AmeenAktharT commited on
Commit
f215501
·
verified ·
1 Parent(s): 6e91407

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -58
app.py CHANGED
@@ -3,15 +3,27 @@ import base64
3
  import httpx
4
  import os
5
  import asyncio
 
 
6
  from src.main import app as fastapi_backend
7
 
 
 
 
 
 
 
 
 
 
 
8
  # Configuration
9
- API_URL = "http://0.0.0.0:7860/api/document-analyze"
 
10
  API_KEY = os.getenv("API_KEY", "sk_track2_987654321")
11
 
12
- # --- NEW: Function to clear old results and show success ---
13
  def on_file_upload():
14
- # Returns: (Updated Output Panel, Updated Uploader Label)
15
  return "*Results will appear here...*", gr.update(label="File Uploaded Successfully! ✅")
16
 
17
  async def process_pipeline(file):
@@ -19,12 +31,6 @@ async def process_pipeline(file):
19
  yield "### ⚠️ Please upload a file first."
20
  return
21
 
22
- # NEW: Safety check for Free Tier stability
23
- file_size_mb = os.path.getsize(file.name) / (1024 * 1024)
24
- if file_size_mb > 5:
25
- yield "### ❌ File too large! \nFree tier limit is 5MB to prevent server crash."
26
- return
27
-
28
  file_name = os.path.basename(file.name)
29
  yield f"⏳ **Processing {file_name}...** Analysing content with AI models."
30
 
@@ -37,79 +43,47 @@ async def process_pipeline(file):
37
 
38
  payload = {"fileName": file_name, "fileType": file_type, "fileBase64": encoded_string}
39
 
40
- async with httpx.AsyncClient(timeout=90.0) as client:
41
  headers = {"x-api-key": API_KEY}
42
  response = await client.post(API_URL, json=payload, headers=headers)
43
  res = response.json()
44
 
45
- if res.get("status") == "success":
46
- bullets = "\n".join([f"- {kp}" for kp in res.get('keyPoints', [])])
47
- if not bullets:
48
- bullets = "- No clear key points extracted."
 
49
 
50
  report = f"""
51
- # ✅ Analysis Complete: {res['fileName']}
52
 
53
  ### 📝 Executive Summary
54
- *{res['summary']}*
55
 
56
- ### 🎯 Main Takeaways
57
- {bullets}
58
-
59
- ---
60
  ### 📊 Intelligent Insights
61
- - **Overall Document Tone:** **` {res['sentiment'].upper()} `**
62
- - **👤 Key Names:** {', '.join(res['entities']['names']) or 'None'}
63
- - **🏢 Organizations:** {', '.join(res['entities']['organizations']) or 'None'}
64
- - **📅 Dates:** {', '.join(res['entities']['dates']) or 'None'}
65
- - **💰 Financials/KPIs:** {', '.join(res['entities']['amounts']) or 'None'}
66
-
67
- *Note: OCR was used for image processing to extract text data.*
68
  """
69
  yield report
70
  else:
71
- yield f"### ❌ Backend Error\n{res.get('message')}"
72
  except Exception as e:
73
  yield f"### ❌ System Error\n{str(e)}"
74
 
75
- # UI Design
76
  with gr.Blocks(theme=gr.themes.Soft(primary_hue="indigo"), title="AI IDP Dashboard") as demo:
77
  gr.Markdown("# 🏢 Intelligent Document Processing (IDP) Dashboard")
78
-
79
  with gr.Row():
80
  with gr.Column(scale=1):
81
- # We add a clear label that we can update dynamically
82
  file_uploader = gr.File(label="Upload Document", file_types=[".pdf", ".docx", ".jpg", ".png", ".jpeg"])
83
  submit_btn = gr.Button("🚀 Analyze Document", variant="primary")
84
- clear_btn = gr.Button("🗑️ Clear")
85
-
86
  with gr.Column(scale=2):
87
  output_panel = gr.Markdown(value="*Results will appear here...*")
88
 
89
- # --- LOGIC UPDATES ---
90
-
91
- # 1. When a file is uploaded: Clear output AND change uploader label
92
- file_uploader.upload(
93
- fn=on_file_upload,
94
- inputs=None,
95
- outputs=[output_panel, file_uploader]
96
- )
97
-
98
- # 2. When analyzing: Reset the label back to default while it works
99
- submit_btn.click(
100
- fn=lambda: gr.update(label="Upload Document"),
101
- outputs=file_uploader
102
- ).then(
103
- fn=process_pipeline,
104
- inputs=file_uploader,
105
- outputs=output_panel
106
- )
107
-
108
- # 3. Manual Clear Button
109
- clear_btn.click(
110
- fn=lambda: (None, "*Results will appear here...*", gr.update(label="Upload Document")),
111
- outputs=[file_uploader, output_panel, file_uploader]
112
- )
113
 
114
- # Mount Gradio onto FastAPI
 
115
  app = gr.mount_gradio_app(fastapi_backend, demo, path="/")
 
3
  import httpx
4
  import os
5
  import asyncio
6
+ from fastapi.middleware.cors import CORSMiddleware
7
+ # Ensure your main.py is inside a folder named 'src'
8
  from src.main import app as fastapi_backend
9
 
10
+ # 1. ADD CORS MIDDLEWARE TO THE BACKEND
11
+ # This is mandatory to pass the external task site's API test
12
+ fastapi_backend.add_middleware(
13
+ CORSMiddleware,
14
+ allow_origins=["*"],
15
+ allow_credentials=True,
16
+ allow_methods=["*"],
17
+ allow_headers=["*"],
18
+ )
19
+
20
  # Configuration
21
+ # Internal URL for Gradio to talk to FastAPI within the same container
22
+ API_URL = "http://127.0.0.1:7860/api/document-analyze"
23
  API_KEY = os.getenv("API_KEY", "sk_track2_987654321")
24
 
25
+ # --- UI Logic ---
26
  def on_file_upload():
 
27
  return "*Results will appear here...*", gr.update(label="File Uploaded Successfully! ✅")
28
 
29
  async def process_pipeline(file):
 
31
  yield "### ⚠️ Please upload a file first."
32
  return
33
 
 
 
 
 
 
 
34
  file_name = os.path.basename(file.name)
35
  yield f"⏳ **Processing {file_name}...** Analysing content with AI models."
36
 
 
43
 
44
  payload = {"fileName": file_name, "fileType": file_type, "fileBase64": encoded_string}
45
 
46
+ async with httpx.AsyncClient(timeout=120.0) as client:
47
  headers = {"x-api-key": API_KEY}
48
  response = await client.post(API_URL, json=payload, headers=headers)
49
  res = response.json()
50
 
51
+ # Using .get() safely in case the backend returns a different structure
52
+ if response.status_code == 200:
53
+ # We handle both formats (with or without keyPoints) for the UI
54
+ kps = res.get('keyPoints', [])
55
+ bullets = "\n".join([f"- {kp}" for kp in kps]) if kps else "- Key points processed."
56
 
57
  report = f"""
58
+ # ✅ Analysis Complete: {res.get('fileName', 'Document')}
59
 
60
  ### 📝 Executive Summary
61
+ *{res.get('summary', 'No summary available.')}*
62
 
 
 
 
 
63
  ### 📊 Intelligent Insights
64
+ - **Overall Tone:** **` {res.get('sentiment', 'N/A').upper()} `**
65
+ - **👤 Names:** {', '.join(res.get('entities', {}).get('names', [])) or 'None'}
66
+ - **🏢 Orgs:** {', '.join(res.get('entities', {}).get('organizations', [])) or 'None'}
 
 
 
 
67
  """
68
  yield report
69
  else:
70
+ yield f"### ❌ Error {response.status_code}\n{res.get('detail', 'Unknown Error')}"
71
  except Exception as e:
72
  yield f"### ❌ System Error\n{str(e)}"
73
 
74
+ # --- Gradio UI 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
  with gr.Row():
78
  with gr.Column(scale=1):
 
79
  file_uploader = gr.File(label="Upload Document", file_types=[".pdf", ".docx", ".jpg", ".png", ".jpeg"])
80
  submit_btn = gr.Button("🚀 Analyze Document", variant="primary")
 
 
81
  with gr.Column(scale=2):
82
  output_panel = gr.Markdown(value="*Results will appear here...*")
83
 
84
+ file_uploader.upload(fn=on_file_upload, inputs=None, outputs=[output_panel, file_uploader])
85
+ submit_btn.click(fn=process_pipeline, inputs=file_uploader, outputs=output_panel)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
+ # --- THE MOUNT ---
88
+ # This makes the API and the UI live on the same link
89
  app = gr.mount_gradio_app(fastapi_backend, demo, path="/")