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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import time
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
import gradio as gr
|
| 10 |
+
|
| 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 |
+
.gradio-container { max-width: 1440px !important; }
|
| 22 |
+
#uplan-header {
|
| 23 |
+
border-bottom: 1px solid #e4e4df;
|
| 24 |
+
padding: 10px 0 16px;
|
| 25 |
+
margin-bottom: 14px;
|
| 26 |
+
}
|
| 27 |
+
#uplan-header h1 {
|
| 28 |
+
margin: 0;
|
| 29 |
+
font-size: 24px;
|
| 30 |
+
letter-spacing: 0;
|
| 31 |
+
}
|
| 32 |
+
#uplan-header p {
|
| 33 |
+
margin: 5px 0 0;
|
| 34 |
+
color: #666;
|
| 35 |
+
font-size: 13px;
|
| 36 |
+
}
|
| 37 |
+
.tool-card {
|
| 38 |
+
border: 1px solid #e1e1dc;
|
| 39 |
+
border-radius: 8px;
|
| 40 |
+
padding: 12px;
|
| 41 |
+
background: #ffffff;
|
| 42 |
+
}
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
SEV_COLOR = {
|
| 47 |
+
"critical": ("#FCEBEB", "#A32D2D"),
|
| 48 |
+
"warning": ("#FAEEDA", "#854F0B"),
|
| 49 |
+
"info": ("#E6F1FB", "#0C447C"),
|
| 50 |
+
"pass": ("#E1F5EE", "#085041"),
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def badge(text: str, severity: str) -> str:
|
| 55 |
+
bg, color = SEV_COLOR.get(severity, ("#F1EFE8", "#444441"))
|
| 56 |
+
return (
|
| 57 |
+
f"<span style='display:inline-block;padding:2px 9px;border-radius:999px;"
|
| 58 |
+
f"font-size:11px;font-weight:600;background:{bg};color:{color};"
|
| 59 |
+
f"margin:2px 3px 2px 0'>{text}</span>"
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def money(value: Any, currency: str = "") -> str:
|
| 64 |
+
if value is None:
|
| 65 |
+
return "<span style='color:#999'>not found</span>"
|
| 66 |
+
try:
|
| 67 |
+
return f"<b>{currency} {float(value):,.0f}</b>"
|
| 68 |
+
except (TypeError, ValueError):
|
| 69 |
+
return f"<b>{value}</b>"
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def score_bar(score: float) -> str:
|
| 73 |
+
pct = max(0, min(100, int(score * 100)))
|
| 74 |
+
color = "#A32D2D" if pct < 50 else "#BA7517" if pct < 75 else "#1D9E75"
|
| 75 |
+
return f"""
|
| 76 |
+
<div style='margin-top:8px'>
|
| 77 |
+
<div style='display:flex;justify-content:space-between;font-size:12px;margin-bottom:5px'>
|
| 78 |
+
<span>Narrative coherence</span><b>{pct}%</b>
|
| 79 |
+
</div>
|
| 80 |
+
<div style='height:7px;background:#e8e8e3;border-radius:999px'>
|
| 81 |
+
<div style='height:7px;width:{pct}%;background:{color};border-radius:999px'></div>
|
| 82 |
+
</div>
|
| 83 |
+
</div>
|
| 84 |
+
"""
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def normalize_result(result: dict[str, Any]) -> dict[str, Any]:
|
| 88 |
+
if not result:
|
| 89 |
+
return {}
|
| 90 |
+
|
| 91 |
+
if "agent_output" in result:
|
| 92 |
+
output = result.get("agent_output", {})
|
| 93 |
+
fields = result.get("reliable_fields", {})
|
| 94 |
+
findings = result.get("findings", output.get("findings", []))
|
| 95 |
+
full = result.get("full_result", {})
|
| 96 |
+
summary = result.get("summary", {})
|
| 97 |
+
return {
|
| 98 |
+
"applicant_name": fields.get("beneficiary_name") or "Applicant",
|
| 99 |
+
"sponsor_name": fields.get("name_variants", {}).get("affidavit", "Sponsor"),
|
| 100 |
+
"sponsor_relationship": fields.get("spon_relationship"),
|
| 101 |
+
"currency_code": fields.get("currency_code"),
|
| 102 |
+
"t_req": output.get("t_req", 800000),
|
| 103 |
+
"documents_parsed": infer_documents(full, summary),
|
| 104 |
+
"reliable_fields": fields,
|
| 105 |
+
"agent_findings": findings,
|
| 106 |
+
"narrative_synthesis": synthesize(findings),
|
| 107 |
+
"next_steps": next_steps(findings),
|
| 108 |
+
"deletion_cert": full.get("deletion_cert", ""),
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
if "full_result" in result and "agent_findings" not in result:
|
| 112 |
+
fields = result.get("reliable_fields", {})
|
| 113 |
+
full = result.get("full_result", {})
|
| 114 |
+
return {
|
| 115 |
+
"applicant_name": fields.get("beneficiary_name") or "Applicant",
|
| 116 |
+
"sponsor_name": fields.get("name_variants", {}).get("affidavit", "Sponsor"),
|
| 117 |
+
"sponsor_relationship": fields.get("spon_relationship"),
|
| 118 |
+
"currency_code": fields.get("currency_code"),
|
| 119 |
+
"t_req": 800000,
|
| 120 |
+
"documents_parsed": infer_documents(full, result.get("summary", {})),
|
| 121 |
+
"reliable_fields": fields,
|
| 122 |
+
"agent_findings": [],
|
| 123 |
+
"narrative_synthesis": synthesize([]),
|
| 124 |
+
"next_steps": next_steps([]),
|
| 125 |
+
"deletion_cert": full.get("deletion_cert", ""),
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
return result
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def infer_documents(full: dict[str, Any], summary: dict[str, Any]) -> list[dict[str, Any]]:
|
| 132 |
+
pages = full.get("pages", [])
|
| 133 |
+
if not pages:
|
| 134 |
+
total = summary.get("total_pages", 0)
|
| 135 |
+
return [{"type": "packet", "pages": total, "quality": summary.get("source_quality", "unknown"), "status": "extracted"}]
|
| 136 |
+
docs: dict[str, dict[str, Any]] = {}
|
| 137 |
+
for page in pages:
|
| 138 |
+
ptype = page.get("page_type", "unknown")
|
| 139 |
+
row = docs.setdefault(ptype, {"type": ptype, "pages": 0, "quality": page.get("source_quality", "unknown"), "status": "extracted"})
|
| 140 |
+
row["pages"] += 1
|
| 141 |
+
return list(docs.values())
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def synthesize(findings: list[dict[str, Any]]) -> dict[str, Any]:
|
| 145 |
+
critical = sum(1 for item in findings if item.get("severity") == "critical")
|
| 146 |
+
warning = sum(1 for item in findings if item.get("severity") == "warning")
|
| 147 |
+
score = max(0.2, 0.88 - critical * 0.22 - warning * 0.08)
|
| 148 |
+
return {
|
| 149 |
+
"narrative_score": score,
|
| 150 |
+
"human_review_required": critical > 0 or any(item.get("requires_human_review") for item in findings),
|
| 151 |
+
"compound_flags": [item["message"] for item in findings[:2]],
|
| 152 |
+
"synthesis_trace": "Agents reviewed liquidity, income coherence, and document corroboration. Missing cross-document evidence reduces readiness confidence.",
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def next_steps(findings: list[dict[str, Any]]) -> list[dict[str, str]]:
|
| 157 |
+
if not findings:
|
| 158 |
+
return [
|
| 159 |
+
{"priority": "critical", "action": "Upload bank statements and tax return to enable cross-document checks."},
|
| 160 |
+
{"priority": "warning", "action": "Add bank balance certificate to corroborate closing balances."},
|
| 161 |
+
]
|
| 162 |
+
steps = []
|
| 163 |
+
for finding in findings[:4]:
|
| 164 |
+
sev = finding.get("severity", "info")
|
| 165 |
+
steps.append({"priority": sev, "action": finding.get("message", "Review this finding.")})
|
| 166 |
+
return steps
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def run_backend(files: list[Any] | None) -> dict[str, Any]:
|
| 170 |
+
if not USE_LIVE_BACKEND or not files:
|
| 171 |
+
time.sleep(0.8)
|
| 172 |
+
return DEMO_RESULT
|
| 173 |
+
|
| 174 |
+
import requests
|
| 175 |
+
|
| 176 |
+
upload_files = []
|
| 177 |
+
handles = []
|
| 178 |
+
headers = {}
|
| 179 |
+
if UPLAN_API_KEY:
|
| 180 |
+
headers["X-API-Key"] = UPLAN_API_KEY
|
| 181 |
+
try:
|
| 182 |
+
for file_obj in files:
|
| 183 |
+
path = getattr(file_obj, "name", file_obj)
|
| 184 |
+
handle = open(path, "rb")
|
| 185 |
+
handles.append(handle)
|
| 186 |
+
upload_files.append(("files", (Path(path).name, handle, "application/pdf")))
|
| 187 |
+
response = requests.post(AMD_ENDPOINT, files=upload_files, headers=headers, timeout=300)
|
| 188 |
+
response.raise_for_status()
|
| 189 |
+
return response.json()
|
| 190 |
+
finally:
|
| 191 |
+
for handle in handles:
|
| 192 |
+
handle.close()
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def build_dashboard_html(raw_result: dict[str, Any]) -> str:
|
| 196 |
+
result = normalize_result(raw_result)
|
| 197 |
+
if not result:
|
| 198 |
+
return "<p style='color:#777;padding:16px'>Upload documents or run demo mode to begin.</p>"
|
| 199 |
+
|
| 200 |
+
fields = result.get("reliable_fields", {})
|
| 201 |
+
synthesis = result.get("narrative_synthesis", {})
|
| 202 |
+
findings = result.get("agent_findings", [])
|
| 203 |
+
docs = result.get("documents_parsed", [])
|
| 204 |
+
currency = result.get("currency_code") or fields.get("currency_code") or ""
|
| 205 |
+
t_req = result.get("t_req", 800000)
|
| 206 |
+
score = synthesis.get("narrative_score", 0.0)
|
| 207 |
+
overall = "Critical" if score < 0.5 else "Advisory" if score < 0.75 else "Pass"
|
| 208 |
+
overall_sev = "critical" if score < 0.5 else "warning" if score < 0.75 else "pass"
|
| 209 |
+
account_total = sum(float(item.get("amount") or 0) for item in fields.get("financial_accounts", []))
|
| 210 |
+
income_total = sum(float(item.get("annual_amount") or 0) for item in fields.get("income_sources", []))
|
| 211 |
+
|
| 212 |
+
html = f"""
|
| 213 |
+
<div style='font-family:Inter,Arial,sans-serif;font-size:13px;line-height:1.55'>
|
| 214 |
+
<div style='background:#f8f8f6;border:1px solid #e1e1dc;border-radius:8px;padding:14px;margin-bottom:12px'>
|
| 215 |
+
<div style='display:flex;justify-content:space-between;align-items:center'>
|
| 216 |
+
<b>Readiness overview</b>{badge(overall, overall_sev)}
|
| 217 |
+
</div>
|
| 218 |
+
{score_bar(score)}
|
| 219 |
+
{"<div style='font-size:12px;color:#A32D2D;margin-top:7px'>Human review required</div>" if synthesis.get("human_review_required") else ""}
|
| 220 |
+
</div>
|
| 221 |
+
|
| 222 |
+
<div style='background:#fff;border:1px solid #e1e1dc;border-radius:8px;padding:14px;margin-bottom:12px'>
|
| 223 |
+
<b>Parties</b>
|
| 224 |
+
<div style='display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-top:9px'>
|
| 225 |
+
<div><span style='color:#777;font-size:11px'>Applicant</span><br><b>{result.get("applicant_name") or fields.get("beneficiary_name") or "not found"}</b></div>
|
| 226 |
+
<div><span style='color:#777;font-size:11px'>Sponsor</span><br><b>{result.get("sponsor_name") or "not found"}</b></div>
|
| 227 |
+
</div>
|
| 228 |
+
<div style='margin-top:7px;color:#555'>Relationship: <b>{result.get("sponsor_relationship") or fields.get("spon_relationship") or "not found"}</b></div>
|
| 229 |
+
</div>
|
| 230 |
+
|
| 231 |
+
<div style='background:#fff;border:1px solid #e1e1dc;border-radius:8px;padding:14px;margin-bottom:12px'>
|
| 232 |
+
<b>Financial summary</b>
|
| 233 |
+
<div style='display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-top:9px'>
|
| 234 |
+
<div><span style='color:#777;font-size:11px'>Required funds</span><br>{money(t_req, currency)}</div>
|
| 235 |
+
<div><span style='color:#777;font-size:11px'>Liquid / deposit evidence</span><br>{money(account_total or fields.get("balance_closing"), currency)}</div>
|
| 236 |
+
<div><span style='color:#777;font-size:11px'>Affidavit income</span><br>{money(fields.get("i_aff") or income_total, currency)}</div>
|
| 237 |
+
<div><span style='color:#777;font-size:11px'>Tax verified income</span><br>{money(fields.get("i_tax"), currency)}</div>
|
| 238 |
+
</div>
|
| 239 |
+
</div>
|
| 240 |
+
"""
|
| 241 |
+
|
| 242 |
+
if docs:
|
| 243 |
+
rows = "".join(
|
| 244 |
+
f"<div style='display:flex;justify-content:space-between;padding:5px 0;border-bottom:1px solid #f1f1ed'>"
|
| 245 |
+
f"<span>{doc.get('type','unknown').replace('_',' ').title()}</span>"
|
| 246 |
+
f"<span style='color:#777'>{doc.get('pages',0)}p · {doc.get('quality','unknown')} · {badge(doc.get('status','seen'), 'pass')}</span></div>"
|
| 247 |
+
for doc in docs
|
| 248 |
+
)
|
| 249 |
+
html += card("Documents", rows)
|
| 250 |
+
|
| 251 |
+
if fields.get("name_variants"):
|
| 252 |
+
rows = "".join(
|
| 253 |
+
f"<div style='font-size:12px'><span style='color:#777'>{key.replace('_',' ').title()}</span>: {value}</div>"
|
| 254 |
+
for key, value in fields["name_variants"].items()
|
| 255 |
+
)
|
| 256 |
+
html += card("Name consistency", rows)
|
| 257 |
+
|
| 258 |
+
if findings:
|
| 259 |
+
rows = "".join(
|
| 260 |
+
f"<div style='padding:8px 0;border-bottom:1px solid #f1f1ed'>"
|
| 261 |
+
f"<div><b>{finding.get('rule_id','rule').replace('_',' ').title()}</b> {badge(finding.get('severity','info').title(), finding.get('severity','info'))}</div>"
|
| 262 |
+
f"<div style='font-size:12px;color:#555'>{finding.get('message','')}</div>"
|
| 263 |
+
f"</div>"
|
| 264 |
+
for finding in findings
|
| 265 |
+
)
|
| 266 |
+
html += card("Agent findings", rows)
|
| 267 |
+
|
| 268 |
+
if synthesis.get("compound_flags"):
|
| 269 |
+
rows = "".join(f"<div style='font-size:12px;padding:4px 0'>{item}</div>" for item in synthesis["compound_flags"])
|
| 270 |
+
html += card("Cross-document risks", rows, bg="#FAEEDA", border="#E7C27A")
|
| 271 |
+
|
| 272 |
+
if result.get("next_steps"):
|
| 273 |
+
rows = "".join(
|
| 274 |
+
f"<div style='display:flex;gap:8px;padding:6px 0;border-bottom:1px solid #f1f1ed'>{badge(step.get('priority','info').upper(), step.get('priority','info'))}<span>{step.get('action','')}</span></div>"
|
| 275 |
+
for step in result["next_steps"]
|
| 276 |
+
)
|
| 277 |
+
html += card("Next steps", rows)
|
| 278 |
+
|
| 279 |
+
cert = result.get("deletion_cert") or raw_result.get("full_result", {}).get("deletion_cert")
|
| 280 |
+
if cert:
|
| 281 |
+
html += f"<div style='background:#f4f4f1;border-radius:8px;padding:10px;margin-bottom:4px'><div style='font-size:11px;color:#777'>Deletion certificate</div><pre style='white-space:pre-wrap;font-size:10px;color:#444'>{cert}</pre></div>"
|
| 282 |
+
|
| 283 |
+
html += "</div>"
|
| 284 |
+
return html
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def card(title: str, body: str, bg: str = "#fff", border: str = "#e1e1dc") -> str:
|
| 288 |
+
return f"<div style='background:{bg};border:1px solid {border};border-radius:8px;padding:14px;margin-bottom:12px'><b>{title}</b><div style='margin-top:8px'>{body}</div></div>"
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
SYSTEM_PROMPT = """You are Uplan's immigration document consultant AI.
|
| 292 |
+
|
| 293 |
+
Use the supplied document analysis to explain risks, missing evidence, and next steps.
|
| 294 |
+
Do not give legal advice. Keep replies concise and direct.
|
| 295 |
+
|
| 296 |
+
Analysis:
|
| 297 |
+
{analysis}
|
| 298 |
+
"""
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
def chat_response(message: str, history: list, result_state: dict) -> tuple[list, str]:
|
| 302 |
+
result = normalize_result(result_state)
|
| 303 |
+
if not message:
|
| 304 |
+
return history, ""
|
| 305 |
+
|
| 306 |
+
if not ANTHROPIC_API_KEY:
|
| 307 |
+
findings = result.get("agent_findings", [])
|
| 308 |
+
first = findings[0]["message"] if findings else "Upload bank statements and tax returns to enable cross-document checks."
|
| 309 |
+
reply = (
|
| 310 |
+
"Consultant chat is in local demo mode because ANTHROPIC_API_KEY is not set. "
|
| 311 |
+
f"The main issue I see is: {first} "
|
| 312 |
+
"The dashboard on the right will update as richer packet analysis is loaded."
|
| 313 |
+
)
|
| 314 |
+
else:
|
| 315 |
+
try:
|
| 316 |
+
import anthropic
|
| 317 |
+
|
| 318 |
+
client = anthropic.Anthropic(api_key=ANTHROPIC_API_KEY)
|
| 319 |
+
api_messages = []
|
| 320 |
+
for msg in history:
|
| 321 |
+
if msg.get("role") and msg.get("content"):
|
| 322 |
+
api_messages.append({"role": msg["role"], "content": msg["content"]})
|
| 323 |
+
api_messages.append({"role": "user", "content": message})
|
| 324 |
+
response = client.messages.create(
|
| 325 |
+
model=os.getenv("ANTHROPIC_MODEL", "claude-sonnet-4-20250514"),
|
| 326 |
+
max_tokens=500,
|
| 327 |
+
system=SYSTEM_PROMPT.format(analysis=json.dumps(result, indent=2)[:7000]),
|
| 328 |
+
messages=api_messages,
|
| 329 |
+
)
|
| 330 |
+
reply = response.content[0].text
|
| 331 |
+
except Exception as exc:
|
| 332 |
+
reply = f"Consultant chat is temporarily unavailable: {exc}"
|
| 333 |
+
|
| 334 |
+
return history + [{"role": "user", "content": message}, {"role": "assistant", "content": reply}], ""
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
def handle_upload(files, demo_mode: bool):
|
| 338 |
+
result = DEMO_RESULT if demo_mode else run_backend(files)
|
| 339 |
+
normalized = normalize_result(result)
|
| 340 |
+
findings = normalized.get("agent_findings", [])
|
| 341 |
+
critical = sum(1 for item in findings if item.get("severity") == "critical")
|
| 342 |
+
warning = sum(1 for item in findings if item.get("severity") == "warning")
|
| 343 |
+
intro = (
|
| 344 |
+
f"I analysed the packet and found {critical} critical issue(s) and "
|
| 345 |
+
f"{warning} advisory item(s). The dashboard has been updated. "
|
| 346 |
+
"Ask me about any finding or missing document."
|
| 347 |
+
)
|
| 348 |
+
history = [{"role": "user", "content": "Analysis complete. What are my main issues?"}, {"role": "assistant", "content": intro}]
|
| 349 |
+
return build_dashboard_html(normalized), history, normalized
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
HEADER_HTML = """
|
| 353 |
+
<div id='uplan-header'>
|
| 354 |
+
<h1>Uplan</h1>
|
| 355 |
+
<p>Immigration document intelligence: reads financial packets, audits evidence quality, flags inconsistencies, and builds a readiness roadmap.</p>
|
| 356 |
+
</div>
|
| 357 |
+
"""
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
CHECKLIST_HTML = """
|
| 361 |
+
<div class='tool-card' style='font-size:13px;line-height:1.8'>
|
| 362 |
+
<b>Packet checklist</b><br>
|
| 363 |
+
<span style='color:#A32D2D'>Required:</span> affidavit, bank statement, tax return<br>
|
| 364 |
+
<span style='color:#854F0B'>Recommended:</span> bank balance certificate<br>
|
| 365 |
+
<span style='color:#0C447C'>Optional:</span> passport / identity document<br>
|
| 366 |
+
<hr style='border:0;border-top:1px solid #eee'>
|
| 367 |
+
<b>Agent tools</b><br>
|
| 368 |
+
Auditor: document readiness and quality checks<br>
|
| 369 |
+
Strategist: roadmap and missing-evidence checklist<br>
|
| 370 |
+
Synthesis: cross-document risk narrative
|
| 371 |
+
</div>
|
| 372 |
+
"""
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def build_ui():
|
| 376 |
+
with gr.Blocks(
|
| 377 |
+
title="Uplan - Immigration Document Intelligence",
|
| 378 |
+
) as app:
|
| 379 |
+
result_state = gr.State({})
|
| 380 |
+
gr.HTML(HEADER_HTML)
|
| 381 |
+
|
| 382 |
+
with gr.Row(equal_height=False):
|
| 383 |
+
with gr.Column(scale=1, min_width=270):
|
| 384 |
+
gr.Markdown("### Agent tools")
|
| 385 |
+
demo_toggle = gr.Checkbox(label="Demo mode", value=True, info="Uses sample analysis for HF CPU Space.")
|
| 386 |
+
upload_box = gr.File(label="Upload PDF packet", file_types=[".pdf"], file_count="multiple", visible=False)
|
| 387 |
+
demo_toggle.change(lambda enabled: gr.update(visible=not enabled), demo_toggle, upload_box)
|
| 388 |
+
analyse_btn = gr.Button("Analyse packet", variant="primary")
|
| 389 |
+
gr.HTML(CHECKLIST_HTML)
|
| 390 |
+
gr.Markdown("Raw documents are processed outside the UI in live mode. The extraction layer emits a deletion certificate after purge.")
|
| 391 |
+
|
| 392 |
+
with gr.Column(scale=2, min_width=360):
|
| 393 |
+
gr.Markdown("### Consultant")
|
| 394 |
+
chatbot = gr.Chatbot(
|
| 395 |
+
label="Consultant",
|
| 396 |
+
height=560,
|
| 397 |
+
show_label=False,
|
| 398 |
+
value=[{"role": "assistant", "content": "Welcome to Uplan. Load the demo or upload a packet, and I will walk through the agent findings."}],
|
| 399 |
+
)
|
| 400 |
+
with gr.Row():
|
| 401 |
+
chat_input = gr.Textbox(placeholder="Ask about risks, missing evidence, or next steps...", show_label=False, container=False, scale=5)
|
| 402 |
+
send_btn = gr.Button("Send", variant="secondary", scale=1)
|
| 403 |
+
|
| 404 |
+
with gr.Column(scale=2, min_width=380):
|
| 405 |
+
gr.Markdown("### Readiness dashboard")
|
| 406 |
+
dashboard = gr.HTML("<p style='color:#777;padding:16px'>Load demo or upload documents to begin.</p>")
|
| 407 |
+
|
| 408 |
+
analyse_btn.click(handle_upload, [upload_box, demo_toggle], [dashboard, chatbot, result_state])
|
| 409 |
+
send_btn.click(chat_response, [chat_input, chatbot, result_state], [chatbot, chat_input])
|
| 410 |
+
chat_input.submit(chat_response, [chat_input, chatbot, result_state], [chatbot, chat_input])
|
| 411 |
+
|
| 412 |
+
return app
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
if __name__ == "__main__":
|
| 416 |
+
build_ui().launch(
|
| 417 |
+
server_name="0.0.0.0",
|
| 418 |
+
server_port=7860,
|
| 419 |
+
show_error=True,
|
| 420 |
+
theme=gr.themes.Soft(primary_hue="blue", font=[gr.themes.GoogleFont("Inter"), "Arial", "sans-serif"]),
|
| 421 |
+
css=CSS,
|
| 422 |
+
)
|
requirements.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio>=4.44.0
|
| 2 |
+
requests>=2.32.0
|
| 3 |
+
anthropic>=0.40.0
|
sample_outputs/demo_result.json
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"applicant_name": "Korada SaiKiran",
|
| 3 |
+
"sponsor_name": "KORADA SATYANARAYANA",
|
| 4 |
+
"sponsor_relationship": "Father",
|
| 5 |
+
"currency_code": "INR",
|
| 6 |
+
"t_req": 800000,
|
| 7 |
+
"documents_parsed": [
|
| 8 |
+
{"type": "affidavit", "pages": 2, "quality": "digital", "status": "extracted"},
|
| 9 |
+
{"type": "bank_statement", "pages": 6, "quality": "digital", "status": "pending"},
|
| 10 |
+
{"type": "tax_return", "pages": 3, "quality": "digital", "status": "pending"}
|
| 11 |
+
],
|
| 12 |
+
"reliable_fields": {
|
| 13 |
+
"beneficiary_name": "Korada SaiKiran",
|
| 14 |
+
"currency_code": "INR",
|
| 15 |
+
"declarant_address": "Plot No. 76, SBI Colony, Balaji Nagar, Totapalem area, near Srinivasa College, near Abdul Kalam Park, Vizianagaram",
|
| 16 |
+
"i_aff": 1200000,
|
| 17 |
+
"i_tax": null,
|
| 18 |
+
"i_form": null,
|
| 19 |
+
"i_spon": null,
|
| 20 |
+
"balance_closing": null,
|
| 21 |
+
"spon_relationship": "Father",
|
| 22 |
+
"name_variants": {
|
| 23 |
+
"affidavit": "KORADA SATYANARAYANA"
|
| 24 |
+
},
|
| 25 |
+
"financial_accounts": [
|
| 26 |
+
{"institution_name": "State Bank of India", "account_number": "10576616939", "account_type": "Savings", "amount": 99978.85},
|
| 27 |
+
{"institution_name": "State Bank of India", "account_number": "62214014329", "account_type": "Savings", "amount": 154603.98},
|
| 28 |
+
{"institution_name": "Union Bank of India", "account_number": "253110100033102", "account_type": "Savings", "amount": 140083.88},
|
| 29 |
+
{"institution_name": "State Bank of India", "account_number": "62214014329", "account_type": "Fixed Deposit", "amount": 1023668.4},
|
| 30 |
+
{"institution_name": "LIC of India", "account_number": "808707848", "account_type": "Fixed Deposit", "amount": 162290},
|
| 31 |
+
{"institution_name": "Bajaj Allianz", "account_number": "0039948302", "account_type": "Fixed Deposit", "amount": 158519.55}
|
| 32 |
+
],
|
| 33 |
+
"income_sources": [
|
| 34 |
+
{"source": "salary", "annual_amount": 300000},
|
| 35 |
+
{"source": "business", "annual_amount": 552000},
|
| 36 |
+
{"source": "rent", "annual_amount": 348000}
|
| 37 |
+
],
|
| 38 |
+
"properties": [
|
| 39 |
+
{"description": "Residential flat, vacant sites, agricultural land", "value": 16360000}
|
| 40 |
+
],
|
| 41 |
+
"movable_assets": [
|
| 42 |
+
{"description": "Cash, gold and silver ornaments", "owner": "Korada Venkata Lakshmi", "amount": 25000}
|
| 43 |
+
],
|
| 44 |
+
"family_members": [
|
| 45 |
+
{"name": "Korada Satyanarayana", "relationship": "Father", "date_of_birth": "21/02/1971", "age": 55},
|
| 46 |
+
{"name": "Korada Venkata Lakshmi", "relationship": "Mother", "date_of_birth": "01/07/1979", "age": 46},
|
| 47 |
+
{"name": "Korada Sai Kiran", "relationship": "Son", "date_of_birth": "02/06/2003", "age": 22},
|
| 48 |
+
{"name": "Korada Kusuma Pushpa", "relationship": "Daughter", "date_of_birth": "15/12/1998", "age": 27}
|
| 49 |
+
]
|
| 50 |
+
},
|
| 51 |
+
"agent_findings": [
|
| 52 |
+
{
|
| 53 |
+
"agent_id": "financial_flow",
|
| 54 |
+
"rule_id": "R1_affidavit_liquidity",
|
| 55 |
+
"severity": "warning",
|
| 56 |
+
"message": "Affidavit liquid and fixed-deposit funds appear sufficient on paper, but a six-month statement is still required to prove maintained liquidity.",
|
| 57 |
+
"requires_human_review": false
|
| 58 |
+
},
|
| 59 |
+
{
|
| 60 |
+
"agent_id": "tax_income",
|
| 61 |
+
"rule_id": "R5_tax_baseline_missing",
|
| 62 |
+
"severity": "critical",
|
| 63 |
+
"message": "Tax return data is missing, so the declared affidavit income cannot yet be verified against official income records.",
|
| 64 |
+
"requires_human_review": true
|
| 65 |
+
},
|
| 66 |
+
{
|
| 67 |
+
"agent_id": "identity_consistency",
|
| 68 |
+
"rule_id": "R8_name_review",
|
| 69 |
+
"severity": "warning",
|
| 70 |
+
"message": "Applicant name appears as Korada SaiKiran and Korada Sai Kiran. Confirm spacing across passport, admission letter, and financial documents.",
|
| 71 |
+
"requires_human_review": false
|
| 72 |
+
}
|
| 73 |
+
],
|
| 74 |
+
"narrative_synthesis": {
|
| 75 |
+
"narrative_score": 0.62,
|
| 76 |
+
"human_review_required": true,
|
| 77 |
+
"compound_flags": [
|
| 78 |
+
"Affidavit income and asset claims are present, but tax return and bank statement corroboration are still missing.",
|
| 79 |
+
"Funds exist across multiple instruments; maintained liquidity must be proven month-by-month."
|
| 80 |
+
],
|
| 81 |
+
"synthesis_trace": "The affidavit provides a plausible financial story, but an officer would ask whether the declared income and funds are externally corroborated by tax filings and bank statements."
|
| 82 |
+
},
|
| 83 |
+
"next_steps": [
|
| 84 |
+
{"priority": "critical", "action": "Upload the latest income tax return or computation of returns to establish tax-verified income."},
|
| 85 |
+
{"priority": "critical", "action": "Upload six months of bank statements for all declared savings accounts."},
|
| 86 |
+
{"priority": "warning", "action": "Upload bank balance certificates for fixed deposits and insurance-linked deposits."},
|
| 87 |
+
{"priority": "info", "action": "Verify name spelling and spacing across affidavit, passport, and admission records."}
|
| 88 |
+
],
|
| 89 |
+
"deletion_cert": "UPLAN-CERT:v1\\ndoc=demo\\nnonce=demo\\nts=demo\\nsig=demo"
|
| 90 |
+
}
|