Adarsh-Saurabh commited on
Commit
c11c623
·
1 Parent(s): b225152

Sync with main branch - updated UI and requirements

Browse files
Files changed (2) hide show
  1. app.py +94 -47
  2. requirements.txt +2 -1
app.py CHANGED
@@ -11,18 +11,15 @@ import gradio as gr
11
 
12
  USE_LIVE_BACKEND = os.getenv("USE_LIVE_BACKEND", "false").lower() == "true"
13
  AMD_ENDPOINT = os.getenv("AMD_ENDPOINT", "http://localhost:8000/extract")
14
- ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY", "")
15
  UPLAN_API_KEY = os.getenv("UPLAN_API_KEY", "")
16
  SAMPLE_PATH = Path(__file__).parent / "sample_outputs" / "demo_result.json"
17
  DEMO_RESULT = json.loads(SAMPLE_PATH.read_text(encoding="utf-8")) if SAMPLE_PATH.exists() else {}
18
 
19
 
20
  CSS = """
21
- @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
22
-
23
  .gradio-container {
24
  max-width: 1440px !important;
25
- font-family: 'Inter', sans-serif !important;
26
  }
27
  #uplan-header {
28
  border-bottom: 1px solid rgba(255,255,255,0.08);
@@ -122,16 +119,27 @@ def normalize_result(result: dict[str, Any]) -> dict[str, Any]:
122
  findings = result.get("findings", output.get("findings", []))
123
  full = result.get("full_result", {})
124
  summary = result.get("summary", {})
 
 
 
 
 
 
 
 
 
125
  return {
126
  "applicant_name": fields.get("beneficiary_name") or "Applicant",
127
- "sponsor_name": fields.get("name_variants", {}).get("affidavit", "Sponsor"),
 
128
  "sponsor_relationship": fields.get("spon_relationship"),
129
  "currency_code": fields.get("currency_code"),
130
  "t_req": output.get("t_req", 800000),
131
  "documents_parsed": infer_documents(full, summary),
132
  "reliable_fields": fields,
133
  "agent_findings": findings,
134
- "narrative_synthesis": synthesize(findings),
 
135
  "next_steps": next_steps(findings),
136
  "deletion_cert": full.get("deletion_cert", ""),
137
  }
@@ -195,9 +203,13 @@ def next_steps(findings: list[dict[str, Any]]) -> list[dict[str, str]]:
195
 
196
 
197
  def run_backend(files: list[Any] | None) -> dict[str, Any]:
198
- if not USE_LIVE_BACKEND or not files:
199
- time.sleep(0.8)
200
- return DEMO_RESULT
 
 
 
 
201
 
202
  import requests
203
 
@@ -215,11 +227,59 @@ def run_backend(files: list[Any] | None) -> dict[str, Any]:
215
  response = requests.post(AMD_ENDPOINT, files=upload_files, headers=headers, timeout=300)
216
  response.raise_for_status()
217
  return response.json()
 
 
 
 
218
  finally:
219
  for handle in handles:
220
  handle.close()
221
 
222
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223
  def build_dashboard_html(raw_result: dict[str, Any]) -> str:
224
  result = normalize_result(raw_result)
225
  if not result:
@@ -242,7 +302,7 @@ def build_dashboard_html(raw_result: dict[str, Any]) -> str:
242
  card_border = "rgba(255,255,255,0.08)"
243
 
244
  html = f"""
245
- <div style='font-family:Inter,Arial,sans-serif;font-size:13px;line-height:1.6;color:rgba(255,255,255,0.85)'>
246
  <div style='background:linear-gradient(135deg,rgba(96,165,250,0.08),rgba(167,139,250,0.08));border:1px solid {card_border};border-radius:10px;padding:16px;margin-bottom:12px'>
247
  <div style='display:flex;justify-content:space-between;align-items:center'>
248
  <b style='color:#e2e8f0'>Readiness overview</b>{badge(overall, overall_sev)}
@@ -301,6 +361,15 @@ def build_dashboard_html(raw_result: dict[str, Any]) -> str:
301
  rows = "".join(f"<div style='font-size:12px;padding:4px 0;color:rgba(255,255,255,0.75)'>{item}</div>" for item in synthesis["compound_flags"])
302
  html += card("Cross-document risks", rows, bg="rgba(245,158,11,0.08)", border="rgba(245,158,11,0.2)")
303
 
 
 
 
 
 
 
 
 
 
304
  if result.get("next_steps"):
305
  rows = "".join(
306
  f"<div style='display:flex;gap:8px;padding:6px 0;border-bottom:1px solid rgba(255,255,255,0.06);align-items:flex-start'>{badge(step.get('priority','info').upper(), step.get('priority','info'))}<span style='color:rgba(255,255,255,0.75)'>{step.get('action','')}</span></div>"
@@ -320,48 +389,26 @@ def card(title: str, body: str, bg: str = "rgba(255,255,255,0.04)", border: str
320
  return f"<div style='background:{bg};border:1px solid {border};border-radius:10px;padding:16px;margin-bottom:12px;backdrop-filter:blur(8px)'><b style='color:#e2e8f0'>{title}</b><div style='margin-top:9px'>{body}</div></div>"
321
 
322
 
323
- SYSTEM_PROMPT = """You are Uplan's immigration document consultant AI.
324
-
325
- Use the supplied document analysis to explain risks, missing evidence, and next steps.
326
- Do not give legal advice. Keep replies concise and direct.
327
-
328
- Analysis:
329
- {analysis}
330
- """
331
-
332
-
333
  def chat_response(message: str, history: list, result_state: dict) -> tuple[list, str]:
334
  result = normalize_result(result_state)
335
  if not message:
336
  return history, ""
337
 
338
- if not ANTHROPIC_API_KEY:
339
- findings = result.get("agent_findings", [])
340
- first = findings[0]["message"] if findings else "Upload bank statements and tax returns to enable cross-document checks."
 
 
341
  reply = (
342
- "Consultant chat is in local demo mode because ANTHROPIC_API_KEY is not set. "
343
- f"The main issue I see is: {first} "
344
- "The dashboard on the right will update as richer packet analysis is loaded."
345
  )
346
  else:
347
- try:
348
- import anthropic
349
-
350
- client = anthropic.Anthropic(api_key=ANTHROPIC_API_KEY)
351
- api_messages = []
352
- for msg in history:
353
- if msg.get("role") and msg.get("content"):
354
- api_messages.append({"role": msg["role"], "content": msg["content"]})
355
- api_messages.append({"role": "user", "content": message})
356
- response = client.messages.create(
357
- model=os.getenv("ANTHROPIC_MODEL", "claude-sonnet-4-20250514"),
358
- max_tokens=500,
359
- system=SYSTEM_PROMPT.format(analysis=json.dumps(result, indent=2)[:7000]),
360
- messages=api_messages,
361
- )
362
- reply = response.content[0].text
363
- except Exception as exc:
364
- reply = f"Consultant chat is temporarily unavailable: {exc}"
365
 
366
  return history + [{"role": "user", "content": message}, {"role": "assistant", "content": reply}], ""
367
 
@@ -414,7 +461,7 @@ def build_ui():
414
  with gr.Row(equal_height=False):
415
  with gr.Column(scale=1, min_width=270):
416
  gr.Markdown("### Agent tools")
417
- demo_toggle = gr.Checkbox(label="Demo mode", value=True, info="Uses sample analysis for HF CPU Space.")
418
  upload_box = gr.File(label="Upload PDF packet", file_types=[".pdf"], file_count="multiple", visible=False)
419
  demo_toggle.change(lambda enabled: gr.update(visible=not enabled), demo_toggle, upload_box)
420
  analyse_btn = gr.Button("Analyse packet", variant="primary")
@@ -427,7 +474,7 @@ def build_ui():
427
  label="Consultant",
428
  height=560,
429
  show_label=False,
430
- value=[{"role": "assistant", "content": "Welcome to Uplan. Load the demo or upload a packet, and I will walk through the agent findings."}],
431
  )
432
  with gr.Row():
433
  chat_input = gr.Textbox(placeholder="Ask about risks, missing evidence, or next steps...", show_label=False, container=False, scale=5)
@@ -449,6 +496,6 @@ if __name__ == "__main__":
449
  server_name="0.0.0.0",
450
  server_port=7860,
451
  show_error=True,
452
- theme=gr.themes.Soft(primary_hue="blue", font=[gr.themes.GoogleFont("Inter"), "Arial", "sans-serif"]),
453
  css=CSS,
454
  )
 
11
 
12
  USE_LIVE_BACKEND = os.getenv("USE_LIVE_BACKEND", "false").lower() == "true"
13
  AMD_ENDPOINT = os.getenv("AMD_ENDPOINT", "http://localhost:8000/extract")
 
14
  UPLAN_API_KEY = os.getenv("UPLAN_API_KEY", "")
15
  SAMPLE_PATH = Path(__file__).parent / "sample_outputs" / "demo_result.json"
16
  DEMO_RESULT = json.loads(SAMPLE_PATH.read_text(encoding="utf-8")) if SAMPLE_PATH.exists() else {}
17
 
18
 
19
  CSS = """
 
 
20
  .gradio-container {
21
  max-width: 1440px !important;
22
+ font-family: Georgia, 'Times New Roman', serif !important;
23
  }
24
  #uplan-header {
25
  border-bottom: 1px solid rgba(255,255,255,0.08);
 
119
  findings = result.get("findings", output.get("findings", []))
120
  full = result.get("full_result", {})
121
  summary = result.get("summary", {})
122
+ narrative = result.get("narrative_synthesis") or {
123
+ "narrative_score": output.get("narrative_score"),
124
+ "human_review_required": output.get("human_review_required"),
125
+ "synthesis_trace": output.get("synthesis_trace"),
126
+ }
127
+ adversarial = result.get("adversarial_audit") or {
128
+ "rejection_case": output.get("rejection_case"),
129
+ "rebuttal_case": output.get("rebuttal_case"),
130
+ }
131
  return {
132
  "applicant_name": fields.get("beneficiary_name") or "Applicant",
133
+ "sponsor_name": fields.get("name_variants", {}).get("affidavit")
134
+ or fields.get("name_variants", {}).get("bank_balance_certificate", "Sponsor"),
135
  "sponsor_relationship": fields.get("spon_relationship"),
136
  "currency_code": fields.get("currency_code"),
137
  "t_req": output.get("t_req", 800000),
138
  "documents_parsed": infer_documents(full, summary),
139
  "reliable_fields": fields,
140
  "agent_findings": findings,
141
+ "narrative_synthesis": narrative,
142
+ "adversarial_audit": adversarial,
143
  "next_steps": next_steps(findings),
144
  "deletion_cert": full.get("deletion_cert", ""),
145
  }
 
203
 
204
 
205
  def run_backend(files: list[Any] | None) -> dict[str, Any]:
206
+ if not files:
207
+ return backend_unavailable_result("No files were uploaded.")
208
+
209
+ if not USE_LIVE_BACKEND:
210
+ return backend_unavailable_result(
211
+ "Live backend is disabled. Set USE_LIVE_BACKEND=true and AMD_ENDPOINT to the Flask /extract URL."
212
+ )
213
 
214
  import requests
215
 
 
227
  response = requests.post(AMD_ENDPOINT, files=upload_files, headers=headers, timeout=300)
228
  response.raise_for_status()
229
  return response.json()
230
+ except requests.RequestException as exc:
231
+ return backend_unavailable_result(
232
+ f"Live backend did not respond at {AMD_ENDPOINT}: {exc}"
233
+ )
234
  finally:
235
  for handle in handles:
236
  handle.close()
237
 
238
 
239
+ def backend_unavailable_result(message: str) -> dict[str, Any]:
240
+ return {
241
+ "applicant_name": "Live backend unavailable",
242
+ "sponsor_name": "Not analysed",
243
+ "sponsor_relationship": None,
244
+ "currency_code": "",
245
+ "t_req": 800000,
246
+ "documents_parsed": [
247
+ {"type": "upload_received", "pages": 0, "quality": "not_processed", "status": "backend_offline"}
248
+ ],
249
+ "reliable_fields": {
250
+ "currency_code": None,
251
+ "name_variants": {},
252
+ "financial_accounts": [],
253
+ "income_sources": [],
254
+ "properties": [],
255
+ "movable_assets": [],
256
+ },
257
+ "agent_findings": [
258
+ {
259
+ "agent_id": "system",
260
+ "rule_id": "LIVE_BACKEND_UNAVAILABLE",
261
+ "severity": "critical",
262
+ "message": message,
263
+ "requires_human_review": True,
264
+ }
265
+ ],
266
+ "narrative_synthesis": {
267
+ "narrative_score": 0.0,
268
+ "human_review_required": True,
269
+ "compound_flags": ["Uploaded PDFs were not analysed because the live backend is offline or disabled."],
270
+ "synthesis_trace": "No extraction or agent graph run occurred for this upload.",
271
+ },
272
+ "adversarial_audit": {
273
+ "rejection_case": "No live backend result exists for this upload.",
274
+ "rebuttal_case": "Start the AMD Flask backend and rerun the packet.",
275
+ },
276
+ "next_steps": [
277
+ {"priority": "critical", "action": "Start the AMD Flask backend and set USE_LIVE_BACKEND=true in the HF Space."}
278
+ ],
279
+ "backend_status": "offline",
280
+ }
281
+
282
+
283
  def build_dashboard_html(raw_result: dict[str, Any]) -> str:
284
  result = normalize_result(raw_result)
285
  if not result:
 
302
  card_border = "rgba(255,255,255,0.08)"
303
 
304
  html = f"""
305
+ <div style='font-family:Georgia,"Times New Roman",serif;font-size:13px;line-height:1.6;color:rgba(255,255,255,0.85)'>
306
  <div style='background:linear-gradient(135deg,rgba(96,165,250,0.08),rgba(167,139,250,0.08));border:1px solid {card_border};border-radius:10px;padding:16px;margin-bottom:12px'>
307
  <div style='display:flex;justify-content:space-between;align-items:center'>
308
  <b style='color:#e2e8f0'>Readiness overview</b>{badge(overall, overall_sev)}
 
361
  rows = "".join(f"<div style='font-size:12px;padding:4px 0;color:rgba(255,255,255,0.75)'>{item}</div>" for item in synthesis["compound_flags"])
362
  html += card("Cross-document risks", rows, bg="rgba(245,158,11,0.08)", border="rgba(245,158,11,0.2)")
363
 
364
+ adversarial = result.get("adversarial_audit", {})
365
+ if adversarial.get("rejection_case") or adversarial.get("rebuttal_case"):
366
+ rows = ""
367
+ if adversarial.get("rejection_case"):
368
+ rows += f"<div style='font-size:12px;padding:4px 0;color:rgba(255,255,255,0.75)'><b>Officer rejection case:</b> {adversarial['rejection_case']}</div>"
369
+ if adversarial.get("rebuttal_case"):
370
+ rows += f"<div style='font-size:12px;padding:4px 0;color:rgba(255,255,255,0.75)'><b>Applicant rebuttal path:</b> {adversarial['rebuttal_case']}</div>"
371
+ html += card("Adversarial audit", rows)
372
+
373
  if result.get("next_steps"):
374
  rows = "".join(
375
  f"<div style='display:flex;gap:8px;padding:6px 0;border-bottom:1px solid rgba(255,255,255,0.06);align-items:flex-start'>{badge(step.get('priority','info').upper(), step.get('priority','info'))}<span style='color:rgba(255,255,255,0.75)'>{step.get('action','')}</span></div>"
 
389
  return f"<div style='background:{bg};border:1px solid {border};border-radius:10px;padding:16px;margin-bottom:12px;backdrop-filter:blur(8px)'><b style='color:#e2e8f0'>{title}</b><div style='margin-top:9px'>{body}</div></div>"
390
 
391
 
 
 
 
 
 
 
 
 
 
 
392
  def chat_response(message: str, history: list, result_state: dict) -> tuple[list, str]:
393
  result = normalize_result(result_state)
394
  if not message:
395
  return history, ""
396
 
397
+ findings = result.get("agent_findings", [])
398
+ synthesis = result.get("narrative_synthesis", {})
399
+ adversarial = result.get("adversarial_audit", {})
400
+ if findings:
401
+ first = findings[0]["message"]
402
  reply = (
403
+ f"The main issue is: {first} "
404
+ f"The current readiness score is {int(float(synthesis.get('narrative_score') or 0) * 100)}%. "
405
+ f"Officer-style concern: {adversarial.get('rejection_case', 'review missing corroborating evidence.')}"
406
  )
407
  else:
408
+ reply = (
409
+ "No agent findings are available yet. Run the demo packet or connect the live AMD backend "
410
+ "so the uploaded documents can be extracted and evaluated."
411
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
412
 
413
  return history + [{"role": "user", "content": message}, {"role": "assistant", "content": reply}], ""
414
 
 
461
  with gr.Row(equal_height=False):
462
  with gr.Column(scale=1, min_width=270):
463
  gr.Markdown("### Agent tools")
464
+ demo_toggle = gr.Checkbox(label="Demo mode", value=True, info="Uses a clearly marked sample analysis. Turn off for live AMD backend.")
465
  upload_box = gr.File(label="Upload PDF packet", file_types=[".pdf"], file_count="multiple", visible=False)
466
  demo_toggle.change(lambda enabled: gr.update(visible=not enabled), demo_toggle, upload_box)
467
  analyse_btn = gr.Button("Analyse packet", variant="primary")
 
474
  label="Consultant",
475
  height=560,
476
  show_label=False,
477
+ value=[{"role": "assistant", "content": "Welcome to Uplan. Load the sample demo or upload a packet when the AMD backend is online. The dashboard will show whether the result is live or backend-offline."}],
478
  )
479
  with gr.Row():
480
  chat_input = gr.Textbox(placeholder="Ask about risks, missing evidence, or next steps...", show_label=False, container=False, scale=5)
 
496
  server_name="0.0.0.0",
497
  server_port=7860,
498
  show_error=True,
499
+ theme=gr.themes.Soft(primary_hue="blue", font=["Georgia", "Times New Roman", "serif"]),
500
  css=CSS,
501
  )
requirements.txt CHANGED
@@ -1,3 +1,4 @@
1
  gradio>=4.44.0
2
  requests>=2.32.0
3
- anthropic>=0.40.0
 
 
1
  gradio>=4.44.0
2
  requests>=2.32.0
3
+ flask>=3.0.0
4
+ flask-cors>=4.0.0