Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import base64 | |
| import httpx | |
| import os | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from src.main import app as fastapi_backend | |
| # 1. Configuration | |
| API_URL = "http://127.0.0.1:7860/api/document-analyze" | |
| API_KEY = os.getenv("API_KEY", "sk_track2_987654321") | |
| # 2. UI Helper Functions (The "Usual" Logic) | |
| def on_file_upload(): | |
| return "*Results will appear here...*", gr.update(label="File Uploaded Successfully! ✅") | |
| async def process_pipeline(file): | |
| if file is None: | |
| yield "### ⚠️ Please upload a file first." | |
| return | |
| file_name = os.path.basename(file.name) | |
| yield f"⏳ **Processing {file_name}...** Analysing content." | |
| try: | |
| with open(file.name, "rb") as f: | |
| encoded_string = base64.b64encode(f.read()).decode('utf-8') | |
| payload = { | |
| "fileName": file_name, | |
| "fileType": file_name.split('.')[-1].lower(), | |
| "fileBase64": encoded_string | |
| } | |
| async with httpx.AsyncClient(timeout=120.0) as client: | |
| response = await client.post(API_URL, json=payload, headers={"x-api-key": API_KEY}) | |
| res = response.json() | |
| if response.status_code == 200: | |
| report = f""" | |
| # ✅ Analysis Complete: {res.get('fileName')} | |
| ### 🤖 AI Summary | |
| {res.get('summary')} | |
| ### 📊 Sentiment: {res.get('sentiment')} | |
| """ | |
| yield report | |
| else: | |
| yield f"### ❌ Error: {res.get('detail')}" | |
| except Exception as e: | |
| yield f"### ❌ System Error: {str(e)}" | |
| # 3. The "Usual" UI Design (Indigo Theme) | |
| with gr.Blocks(theme=gr.themes.Soft(primary_hue="indigo"), title="AI IDP Dashboard") as demo: | |
| gr.Markdown("# 🏢 Intelligent Document Processing (IDP) Dashboard") | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| file_uploader = gr.File(label="Upload Document", file_types=[".pdf", ".docx", ".jpg", ".png", ".jpeg"]) | |
| submit_btn = gr.Button("🚀 Analyze Document", variant="primary") | |
| with gr.Column(scale=2): | |
| output_panel = gr.Markdown(value="*Results will appear here...*") | |
| file_uploader.upload(fn=on_file_upload, inputs=None, outputs=[output_panel, file_uploader]) | |
| submit_btn.click(fn=process_pipeline, inputs=file_uploader, outputs=output_panel) | |
| # 4. The Mount (Crucial Step) | |
| # This removes any accidental root routes and attaches the Indigo GUI | |
| for route in fastapi_backend.routes: | |
| if getattr(route, "path", None) == "/": | |
| fastapi_backend.routes.remove(route) | |
| fastapi_backend.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"]) | |
| app = gr.mount_gradio_app(fastapi_backend, demo, path="/") |