AmeenAktharT commited on
Commit
de22381
·
verified ·
1 Parent(s): 40978e4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +11 -60
app.py CHANGED
@@ -3,7 +3,6 @@ import base64
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
@@ -11,49 +10,32 @@ 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
 
34
  with open(file.name, "rb") as f:
35
  encoded_string = base64.b64encode(f.read()).decode('utf-8')
36
 
37
- payload = {
38
- "fileName": file_name,
39
- "fileType": file_type,
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()}**
@@ -61,56 +43,25 @@ async def process_pipeline(file):
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):
81
- file_uploader = gr.File(
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
- # Change the path from "/" to "/docs" or something unique
111
- # This allows Gradio to own the main "/" URL
112
- app = gr.mount_gradio_app(fastapi_backend, demo, path="/api-docs")
113
 
114
- if __name__ == "__main__":
115
- import uvicorn
116
- uvicorn.run(app, host="0.0.0.0", port=7860)
 
3
  import httpx
4
  import os
5
  import asyncio
 
6
  from src.main import app as fastapi_backend
7
 
8
  # Configuration
 
10
  API_KEY = os.getenv("API_KEY", "sk_track2_987654321")
11
 
12
  async def process_pipeline(file):
 
 
 
 
 
 
 
13
  if file is None:
14
  yield "### ⚠️ Please upload a file first.", gr.update(visible=True)
15
+ return
16
 
 
17
  file_name = os.path.basename(file.name)
18
  yield f"⏳ **Processing {file_name}...** Analysing content with AI models.", gr.update(visible=True)
19
 
20
  try:
 
21
  ext = file_name.split('.')[-1].lower()
22
  file_type = "image" if ext in ['jpg', 'jpeg', 'png'] else ext
23
 
24
  with open(file.name, "rb") as f:
25
  encoded_string = base64.b64encode(f.read()).decode('utf-8')
26
 
27
+ payload = {"fileName": file_name, "fileType": file_type, "fileBase64": encoded_string}
 
 
 
 
28
 
 
29
  async with httpx.AsyncClient(timeout=90.0) as client:
30
  headers = {"x-api-key": API_KEY}
31
  response = await client.post(API_URL, json=payload, headers=headers)
32
  res = response.json()
33
 
34
  if res.get("status") == "success":
 
35
  report = f"""
36
  # ✅ Analysis Complete: {res['fileName']}
 
37
  ### 🤖 AI Summary
38
  {res['summary']}
 
39
  ---
40
  ### 📊 Intelligent Insights
41
  - **Sentiment:** **{res['sentiment'].upper()}**
 
43
  - **🏢 Organizations:** {', '.join(res['entities']['organizations']) or 'None'}
44
  - **📅 Dates:** {', '.join(res['entities']['dates']) or 'None'}
45
  - **💰 Financials/KPIs:** {', '.join(res['entities']['amounts']) or 'None'}
 
 
46
  """
47
  yield report, gr.update(visible=True)
48
  else:
49
  yield f"### ❌ Backend Error\n{res.get('message')}", gr.update(visible=True)
 
50
  except Exception as e:
51
+ yield f"### ❌ System Error\n{str(e)}", gr.update(visible=True)
52
 
 
53
  with gr.Blocks(theme=gr.themes.Soft(primary_hue="indigo"), title="AI IDP Dashboard") as demo:
54
  gr.Markdown("# 🏢 Intelligent Document Processing (IDP) Dashboard")
 
 
55
  with gr.Row():
56
  with gr.Column(scale=1):
57
+ file_uploader = gr.File(label="Upload Document", file_types=[".pdf", ".docx", ".jpg", ".png", ".jpeg"])
58
+ submit_btn = gr.Button("🚀 Analyze Document", variant="primary")
59
+ clear_btn = gr.Button("🗑️ Clear")
 
 
 
 
 
60
  with gr.Column(scale=2):
61
+ output_panel = gr.Markdown(value="*Results will appear here...*")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
+ submit_btn.click(fn=process_pipeline, inputs=file_uploader, outputs=[output_panel, output_panel])
64
+ clear_btn.click(fn=lambda: (None, "*Results will appear here...*"), outputs=[file_uploader, output_panel])
 
 
65
 
66
+ # Mount Gradio onto FastAPI
67
+ app = gr.mount_gradio_app(fastapi_backend, demo, path="/")