Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,23 +3,31 @@ import base64
|
|
| 3 |
import httpx
|
| 4 |
import os
|
| 5 |
import asyncio
|
|
|
|
|
|
|
| 6 |
|
| 7 |
# Configuration
|
| 8 |
API_URL = "http://0.0.0.0:7860/api/document-analyze"
|
| 9 |
API_KEY = os.getenv("API_KEY", "sk_track2_987654321")
|
| 10 |
|
| 11 |
async def process_pipeline(file):
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
if file is None:
|
| 14 |
-
yield "### ⚠️ Please upload a file first.", gr.update(visible=
|
| 15 |
-
return #
|
| 16 |
|
| 17 |
-
#
|
| 18 |
file_name = os.path.basename(file.name)
|
| 19 |
-
yield f"⏳ **Processing {file_name}...**
|
| 20 |
|
| 21 |
try:
|
| 22 |
-
#
|
| 23 |
ext = file_name.split('.')[-1].lower()
|
| 24 |
file_type = "image" if ext in ['jpg', 'jpeg', 'png'] else ext
|
| 25 |
|
|
@@ -32,39 +40,41 @@ async def process_pipeline(file):
|
|
| 32 |
"fileBase64": encoded_string
|
| 33 |
}
|
| 34 |
|
| 35 |
-
#
|
| 36 |
-
async with httpx.AsyncClient(timeout=
|
| 37 |
headers = {"x-api-key": API_KEY}
|
| 38 |
response = await client.post(API_URL, json=payload, headers=headers)
|
| 39 |
res = response.json()
|
| 40 |
|
| 41 |
if res.get("status") == "success":
|
| 42 |
-
#
|
| 43 |
report = f"""
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
|
|
|
|
|
|
| 57 |
yield report, gr.update(visible=True)
|
| 58 |
else:
|
| 59 |
yield f"### ❌ Backend Error\n{res.get('message')}", gr.update(visible=True)
|
| 60 |
|
| 61 |
except Exception as e:
|
| 62 |
-
yield f"### ❌ System Error\
|
| 63 |
|
| 64 |
-
# --- UI Layout ---
|
| 65 |
-
with gr.Blocks(theme=gr.themes.Soft(primary_hue="indigo"), title="AI IDP
|
| 66 |
gr.Markdown("# 🏢 Intelligent Document Processing (IDP) Dashboard")
|
| 67 |
-
gr.Markdown("
|
| 68 |
|
| 69 |
with gr.Row():
|
| 70 |
with gr.Column(scale=1):
|
|
@@ -72,28 +82,36 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="indigo"), title="AI IDP System"
|
|
| 72 |
label="Step 1: Upload Document",
|
| 73 |
file_types=[".pdf", ".docx", ".jpg", ".png", ".jpeg"]
|
| 74 |
)
|
| 75 |
-
|
| 76 |
-
|
|
|
|
| 77 |
|
| 78 |
with gr.Column(scale=2):
|
| 79 |
output_panel = gr.Markdown(
|
| 80 |
-
value="*
|
| 81 |
elem_id="results-box"
|
| 82 |
)
|
| 83 |
|
| 84 |
-
# Functionality
|
| 85 |
submit_btn.click(
|
| 86 |
fn=process_pipeline,
|
| 87 |
inputs=file_uploader,
|
| 88 |
-
outputs=[output_panel, output_panel]
|
|
|
|
| 89 |
)
|
| 90 |
|
| 91 |
-
# Reset
|
| 92 |
def reset_ui():
|
| 93 |
return None, "*Results will appear here...*"
|
| 94 |
|
| 95 |
clear_btn.click(fn=reset_ui, outputs=[file_uploader, output_panel])
|
| 96 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
if __name__ == "__main__":
|
| 98 |
-
|
| 99 |
-
|
|
|
|
|
|
| 3 |
import httpx
|
| 4 |
import os
|
| 5 |
import asyncio
|
| 6 |
+
# Import your backend FastAPI app from your src folder
|
| 7 |
+
from src.main import app as fastapi_backend
|
| 8 |
|
| 9 |
# Configuration
|
| 10 |
API_URL = "http://0.0.0.0:7860/api/document-analyze"
|
| 11 |
API_KEY = os.getenv("API_KEY", "sk_track2_987654321")
|
| 12 |
|
| 13 |
async def process_pipeline(file):
|
| 14 |
+
"""
|
| 15 |
+
Handles the UI logic:
|
| 16 |
+
1. Acknowledges the upload immediately.
|
| 17 |
+
2. Clears previous results.
|
| 18 |
+
3. Calls the AI backend and displays structured insights.
|
| 19 |
+
"""
|
| 20 |
+
# 1. Validation - Yield error message if no file
|
| 21 |
if file is None:
|
| 22 |
+
yield "### ⚠️ Please upload a file first.", gr.update(visible=True)
|
| 23 |
+
return # Stop the generator
|
| 24 |
|
| 25 |
+
# 2. Instant Acknowledgment & Clearing Previous Results
|
| 26 |
file_name = os.path.basename(file.name)
|
| 27 |
+
yield f"⏳ **Processing {file_name}...** Analysing content with AI models.", gr.update(visible=True)
|
| 28 |
|
| 29 |
try:
|
| 30 |
+
# 3. Prepare File Data
|
| 31 |
ext = file_name.split('.')[-1].lower()
|
| 32 |
file_type = "image" if ext in ['jpg', 'jpeg', 'png'] else ext
|
| 33 |
|
|
|
|
| 40 |
"fileBase64": encoded_string
|
| 41 |
}
|
| 42 |
|
| 43 |
+
# 4. Call Backend API
|
| 44 |
+
async with httpx.AsyncClient(timeout=90.0) as client:
|
| 45 |
headers = {"x-api-key": API_KEY}
|
| 46 |
response = await client.post(API_URL, json=payload, headers=headers)
|
| 47 |
res = response.json()
|
| 48 |
|
| 49 |
if res.get("status") == "success":
|
| 50 |
+
# 5. Success Report Formatting
|
| 51 |
report = f"""
|
| 52 |
+
# ✅ Analysis Complete: {res['fileName']}
|
| 53 |
+
|
| 54 |
+
### 🤖 AI Summary
|
| 55 |
+
{res['summary']}
|
| 56 |
+
|
| 57 |
+
---
|
| 58 |
+
### 📊 Intelligent Insights
|
| 59 |
+
- **Sentiment:** **{res['sentiment'].upper()}**
|
| 60 |
+
- **👤 Key Names:** {', '.join(res['entities']['names']) or 'None'}
|
| 61 |
+
- **🏢 Organizations:** {', '.join(res['entities']['organizations']) or 'None'}
|
| 62 |
+
- **📅 Dates:** {', '.join(res['entities']['dates']) or 'None'}
|
| 63 |
+
- **💰 Financials/KPIs:** {', '.join(res['entities']['amounts']) or 'None'}
|
| 64 |
+
|
| 65 |
+
*Note: OCR was used for image processing to extract text data.*
|
| 66 |
+
"""
|
| 67 |
yield report, gr.update(visible=True)
|
| 68 |
else:
|
| 69 |
yield f"### ❌ Backend Error\n{res.get('message')}", gr.update(visible=True)
|
| 70 |
|
| 71 |
except Exception as e:
|
| 72 |
+
yield f"### ❌ System Error\nCould not connect to AI Engine: {str(e)}", gr.update(visible=True)
|
| 73 |
|
| 74 |
+
# --- UI Layout Design ---
|
| 75 |
+
with gr.Blocks(theme=gr.themes.Soft(primary_hue="indigo"), title="AI IDP Dashboard") as demo:
|
| 76 |
gr.Markdown("# 🏢 Intelligent Document Processing (IDP) Dashboard")
|
| 77 |
+
gr.Markdown("Extract structured intelligence from **PDFs, Word Docs, and Images** using multi-modal AI.")
|
| 78 |
|
| 79 |
with gr.Row():
|
| 80 |
with gr.Column(scale=1):
|
|
|
|
| 82 |
label="Step 1: Upload Document",
|
| 83 |
file_types=[".pdf", ".docx", ".jpg", ".png", ".jpeg"]
|
| 84 |
)
|
| 85 |
+
with gr.Row():
|
| 86 |
+
submit_btn = gr.Button("🚀 Analyze Document", variant="primary")
|
| 87 |
+
clear_btn = gr.Button("🗑️ Clear")
|
| 88 |
|
| 89 |
with gr.Column(scale=2):
|
| 90 |
output_panel = gr.Markdown(
|
| 91 |
+
value="*Upload a file and click analyze to see results...*",
|
| 92 |
elem_id="results-box"
|
| 93 |
)
|
| 94 |
|
| 95 |
+
# Functionality: Link Button to Pipeline
|
| 96 |
submit_btn.click(
|
| 97 |
fn=process_pipeline,
|
| 98 |
inputs=file_uploader,
|
| 99 |
+
outputs=[output_panel, output_panel],
|
| 100 |
+
show_progress="full"
|
| 101 |
)
|
| 102 |
|
| 103 |
+
# Logic to Clear/Reset the UI
|
| 104 |
def reset_ui():
|
| 105 |
return None, "*Results will appear here...*"
|
| 106 |
|
| 107 |
clear_btn.click(fn=reset_ui, outputs=[file_uploader, output_panel])
|
| 108 |
|
| 109 |
+
# --- PRO DEPLOYMENT ---
|
| 110 |
+
# This mounts your FastAPI backend onto the Gradio UI.
|
| 111 |
+
# This makes both the API (for judges) and the Dashboard (for users) live on port 7860.
|
| 112 |
+
app = gr.mount_gradio_app(fastapi_backend, demo, path="/")
|
| 113 |
+
|
| 114 |
if __name__ == "__main__":
|
| 115 |
+
import uvicorn
|
| 116 |
+
# Launch locally if needed
|
| 117 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|