bonita2026 commited on
Commit
cd38b50
·
verified ·
1 Parent(s): 87dd953

Upload 2 files

Browse files

new versions that in theory should separate two main functions

Files changed (2) hide show
  1. app.py +885 -0
  2. landing.html +64 -0
app.py ADDED
@@ -0,0 +1,885 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ============================================================
2
+ # RailNexus Value — app.py v9
3
+ # ============================================================
4
+ # Merges:
5
+ # - Pablo's V9 route-selective prompt builder (viability vs check)
6
+ # - Production Gradio UI (streaming, survey, HTML output)
7
+ # - Enhanced traceability/citation instructions
8
+ # - Two buttons: Viability + Check (no language selector in Analysis)
9
+ # - Survey tab with 5-language support (independent)
10
+ # - Scripts loaded into system prompt per route
11
+ # - Hide HFS bonita2026 badge via CSS
12
+ # - Disclaimer at bottom, print instruction after results
13
+ # ============================================================
14
+
15
+ import os, csv, json, glob, urllib.parse
16
+ import gradio as gr
17
+ import anthropic
18
+
19
+ # ── Optional doc parsers ─────────────────────────────────────
20
+ try:
21
+ import fitz
22
+ HAS_PYMUPDF = True
23
+ except ImportError:
24
+ HAS_PYMUPDF = False
25
+
26
+ try:
27
+ from docx import Document as DocxDocument
28
+ HAS_DOCX = True
29
+ except ImportError:
30
+ HAS_DOCX = False
31
+
32
+ try:
33
+ import openpyxl
34
+ HAS_XLSX = True
35
+ except ImportError:
36
+ HAS_XLSX = False
37
+
38
+
39
+ # ═══════════════════════════════════════════════════════════════
40
+ # 1. FILE LOADING
41
+ # ═══════════════════════════════════════════════════════════════
42
+
43
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
44
+ LANDING_PATH = os.path.join(BASE_DIR, "landing.html")
45
+
46
+ def _read(path):
47
+ try:
48
+ with open(path, "r", encoding="utf-8") as f:
49
+ return f.read()
50
+ except Exception:
51
+ return ""
52
+
53
+ # Pre-load all files into memory at startup
54
+ SKILL_MD = _read(os.path.join(BASE_DIR, "SKILL.md"))
55
+ PLAYBOOK = _read(os.path.join(BASE_DIR, "re-infra.local.md"))
56
+
57
+ COMMANDS = {}
58
+ cmd_dir = os.path.join(BASE_DIR, "commands")
59
+ if os.path.isdir(cmd_dir):
60
+ for fn in sorted(os.listdir(cmd_dir)):
61
+ if fn.endswith(".md"):
62
+ COMMANDS[fn[:-3]] = _read(os.path.join(cmd_dir, fn))
63
+
64
+ SKILLS = {}
65
+ skills_dir = os.path.join(BASE_DIR, "skills")
66
+ if os.path.isdir(skills_dir):
67
+ for folder in sorted(os.listdir(skills_dir)):
68
+ skill_file = os.path.join(skills_dir, folder, "SKILL.md")
69
+ if os.path.isfile(skill_file):
70
+ SKILLS[folder] = _read(skill_file)
71
+
72
+ SCRIPTS = {}
73
+ scripts_dir = os.path.join(BASE_DIR, "scripts")
74
+ if os.path.isdir(scripts_dir):
75
+ for fn in sorted(os.listdir(scripts_dir)):
76
+ if fn.endswith(".py"):
77
+ SCRIPTS[fn[:-3]] = _read(os.path.join(scripts_dir, fn))
78
+
79
+ REFERENCES = {}
80
+ refs_dir = os.path.join(BASE_DIR, "references")
81
+ if os.path.isdir(refs_dir):
82
+ for root, dirs, files in os.walk(refs_dir):
83
+ for fn in files:
84
+ if fn.endswith(".md"):
85
+ abs_path = os.path.join(root, fn)
86
+ rel_key = os.path.relpath(abs_path, refs_dir).replace(os.sep, "/").replace(".md", "")
87
+ REFERENCES[rel_key] = _read(abs_path)
88
+
89
+
90
+ # ═══════════════════════════════════════════════════════════════
91
+ # 2. ROUTE DEFINITIONS (V9 — from Pablo)
92
+ # ═══════════════════════════════════════════════════════════════
93
+
94
+ VIABILITY_COMMANDS = [
95
+ "analyze-investment", "assess-risk", "stress-test",
96
+ "audit-financials", "build-investment-memo", "evaluate-lending",
97
+ ]
98
+ VIABILITY_SKILLS = [
99
+ "investment-analysis", "risk-categorization", "financial-reporting",
100
+ "investment-memo", "secured-lending", "jurisdiction-router",
101
+ ]
102
+ VIABILITY_SCRIPTS = [
103
+ "validate_jurisdiction", "validate_dscr", "validate_ltv",
104
+ ]
105
+
106
+ CHECK_COMMANDS = [
107
+ "check-visado", "check-zoning", "check-tax-compliance", "track-approvals",
108
+ ]
109
+ CHECK_SKILLS = [
110
+ "pre-visado-checker", "zoning-compliance", "tax-legal-compliance",
111
+ "government-approvals", "jurisdiction-router",
112
+ ]
113
+ CHECK_SCRIPTS = [
114
+ "validate_jurisdiction", "validate_visado",
115
+ "validate_stamp_duty", "validate_tax", "validate_lease",
116
+ ]
117
+
118
+
119
+ # ═══════════════════════════════════════════════════════════════
120
+ # 3. ROUTE-SELECTIVE SYSTEM PROMPT BUILDER + OUTPUT INSTRUCTIONS
121
+ # ═══════════════════════════════════════════════════════════════
122
+
123
+ OUTPUT_INSTRUCTIONS = """
124
+ ---
125
+ ## OUTPUT INSTRUCTIONS
126
+
127
+ For every request:
128
+ 1. Begin with a jurisdiction label: [Analysis under {country} law — {date}]
129
+ 2. Auto-detect jurisdiction from the uploaded documents
130
+ 3. Apply all relevant COMMAND PROTOCOLS and SKILL PROTOCOLS above
131
+ 4. Classify every risk as RED, YELLOW, or GREEN
132
+ 5. Quantify every risk in currency where possible
133
+ 6. End with the standard disclaimer
134
+
135
+ ---
136
+ ## TRACEABILITY AND CITATION RULES (MANDATORY — NEVER SKIP)
137
+
138
+ Every factual assertion about a document MUST include an inline citation.
139
+ This is non-negotiable. Unsourced claims about document content are PROHIBITED.
140
+
141
+ Citation formats — use the one that fits:
142
+ - Clause reference: [Source: filename.pdf, Clause 3.2]
143
+ - Page reference: [Source: filename.pdf, p.7]
144
+ - Cell/row reference: [Source: model.xlsx, Sheet "CF", Row 14]
145
+ - Section reference: [Source: memo.docx, Section 2.1]
146
+ - Multi-document cross-check: [Source: lease.pdf, Clause 7.2 vs. rent_roll.xlsx, Row 3]
147
+
148
+ Rules:
149
+ - If the fact comes from an uploaded document → cite the document with page/clause/row
150
+ - If the fact is derived from training knowledge → mark as [Source: Agent knowledge — verify with local counsel]
151
+ - If the fact is a calculation → show formula AND cite inputs:
152
+ "DSCR = NOI / DS = 850K [Source: cf_model.xlsx, Row 22] / 620K [Source: loan_agreement.pdf, Clause 8.1] = 1.37x"
153
+ - For ABSENCE DETECTION (Move 3) → cite what was searched and NOT found:
154
+ "NO BREAK CLAUSE detected [Source: lease.pdf — Clauses 1-42 searched, no break provision found]"
155
+ - For cross-document discrepancies → cite BOTH documents:
156
+ "Rent discrepancy: 12,500/month [Source: lease.pdf, Clause 4.1] vs 11,800/month [Source: rent_roll.xlsx, Row 7]"
157
+
158
+ EVERY paragraph of analysis must contain at least one [Source: ...] citation.
159
+ If you cannot cite a source for a claim, state explicitly that it is unverified.
160
+
161
+ ---
162
+ ## OUTPUT FORMAT
163
+
164
+ Styled HTML with inline CSS only. No markdown. No code fences. No ```html wrapper.
165
+ Produce a complete HTML fragment (no <html>/<body> tags).
166
+
167
+ RED risk items:
168
+ <div style="background:#fef2f2;border-left:4px solid #dc2626;padding:12px 16px;border-radius:6px;margin:8px 0"><strong style="color:#dc2626">🔴 RED —</strong> [finding with citation]</div>
169
+
170
+ YELLOW risk items:
171
+ <div style="background:#fffbeb;border-left:4px solid #f59e0b;padding:12px 16px;border-radius:6px;margin:8px 0"><strong style="color:#b45309">⚠ YELLOW —</strong> [finding with citation]</div>
172
+
173
+ GREEN items:
174
+ <div style="background:#f0fdf4;border-left:4px solid #16a34a;padding:12px 16px;border-radius:6px;margin:8px 0"><strong style="color:#16a34a">✓ GREEN —</strong> [finding with citation]</div>
175
+
176
+ Section headers:
177
+ <h2 style="color:#5a21d4;border-bottom:2px solid #ebe8f2;padding-bottom:6px;margin-top:28px">[title]</h2>
178
+
179
+ Tables:
180
+ <table style="width:100%;border-collapse:collapse;margin:12px 0"><thead><tr style="background:#5a21d4;color:white"><th style="padding:8px 12px;text-align:left">Header</th></tr></thead><tbody><tr style="background:white"><td style="padding:8px 12px;border-bottom:1px solid #ebe8f2">Cell</td></tr><tr style="background:#f6f6f8"><td style="padding:8px 12px;border-bottom:1px solid #ebe8f2">Cell</td></tr></tbody></table>
181
+
182
+ Blockquotes / citations:
183
+ <blockquote style="border-left:3px solid #5a21d4;padding-left:12px;color:#675194;font-style:italic;margin:8px 0">[cited text with source]</blockquote>
184
+
185
+ Body text:
186
+ <p style="line-height:1.7;color:#1f2937">[text]</p>
187
+
188
+ Subsection headers: <h3 style="color:#120e1a;margin-top:20px">[title]</h3>
189
+
190
+ Executive summary block (MANDATORY at end of every report):
191
+ <div style="background:#ede8fb;border:2px solid #5a21d4;border-radius:8px;padding:16px 20px;margin-top:28px">
192
+ <h3 style="color:#5a21d4;margin:0 0 8px">EXECUTIVE SUMMARY</h3>
193
+ <p style="margin:4px 0"><strong>Viability:</strong> [YES / NO / CONDITIONAL]</p>
194
+ <p style="margin:4px 0"><strong>Principal risk:</strong> [one sentence]</p>
195
+ <p style="margin:4px 0"><strong>Immediate action:</strong> [one sentence]</p>
196
+ </div>
197
+ """
198
+
199
+
200
+ def build_system_prompt(route="viability", jurisdiction=None):
201
+ """
202
+ V9 route-selective prompt builder.
203
+ VIABILITY route: ~73K tokens — financial analysis, IRR/DCF, risk, stress test
204
+ CHECK route: ~58K tokens — visado, zoning, tax compliance, approvals
205
+ """
206
+ parts = [SKILL_MD, "---", PLAYBOOK]
207
+
208
+ # Always load jurisdiction detection
209
+ if "detect-jurisdiction" in COMMANDS:
210
+ parts.append(f"### COMMAND: detect-jurisdiction\n{COMMANDS['detect-jurisdiction']}")
211
+
212
+ if route == "viability":
213
+ parts.append("\n\n## COMMAND PROTOCOLS\n")
214
+ for cmd in VIABILITY_COMMANDS:
215
+ if cmd in COMMANDS:
216
+ parts.append(f"### COMMAND: {cmd}\n{COMMANDS[cmd]}")
217
+ parts.append("\n\n## SKILL PROTOCOLS\n")
218
+ for skill in VIABILITY_SKILLS:
219
+ if skill in SKILLS:
220
+ parts.append(f"### SKILL: {skill}\n{SKILLS[skill]}")
221
+ parts.append("\n\n## VALIDATION SCRIPTS\n")
222
+ for script in VIABILITY_SCRIPTS:
223
+ if script in SCRIPTS:
224
+ parts.append(f"### SCRIPT: {script}\n```python\n{SCRIPTS[script]}\n```")
225
+
226
+ elif route == "check":
227
+ parts.append("\n\n## COMMAND PROTOCOLS\n")
228
+ for cmd in CHECK_COMMANDS:
229
+ if cmd in COMMANDS:
230
+ parts.append(f"### COMMAND: {cmd}\n{COMMANDS[cmd]}")
231
+ parts.append("\n\n## SKILL PROTOCOLS\n")
232
+ for skill in CHECK_SKILLS:
233
+ if skill in SKILLS:
234
+ parts.append(f"### SKILL: {skill}\n{SKILLS[skill]}")
235
+ parts.append("\n\n## VALIDATION SCRIPTS\n")
236
+ for script in CHECK_SCRIPTS:
237
+ if script in SCRIPTS:
238
+ parts.append(f"### SCRIPT: {script}\n```python\n{SCRIPTS[script]}\n```")
239
+ # Load ALL visado references for check route
240
+ parts.append("\n\n## VISADO REFERENCE LIBRARY\n")
241
+ for key, content in sorted(REFERENCES.items()):
242
+ if "visado" in key:
243
+ parts.append(f"### {key}\n{content}")
244
+
245
+ # Load ONLY the detected jurisdiction's references
246
+ if jurisdiction:
247
+ parts.append("\n\n## JURISDICTION REFERENCE\n")
248
+ jl = jurisdiction.lower()
249
+ for key, content in sorted(REFERENCES.items()):
250
+ if jl in key.lower():
251
+ parts.append(f"### {key}\n{content}")
252
+
253
+ # ── Route context instruction (tells Claude which mode it's in) ──
254
+ if route == "viability":
255
+ parts.append("""
256
+ ## ACTIVE ROUTE: VIABILITY
257
+ You are operating in VIABILITY mode. Focus exclusively on:
258
+ - Investment analysis (IRR, DCF, cap rate, NOI, yield, equity multiple)
259
+ - Risk assessment (severity × likelihood matrix, compound risk tracing)
260
+ - Secured lending (DSCR, LTV, ICR, covenant analysis)
261
+ - Stress testing (base / upside / downside / stress scenarios)
262
+ - Investment memo generation (IC-ready)
263
+ - Financial audit and reporting
264
+
265
+ Do NOT produce visado/visa pre-validation, architectural compliance checks, or CTE analysis
266
+ in this mode — those belong to the CHECK route.
267
+ """)
268
+ elif route == "check":
269
+ parts.append("""
270
+ ## ACTIVE ROUTE: CHECK
271
+ You are operating in CHECK mode. Focus exclusively on:
272
+ - Visado / visa pre-validation (COAC, CTE, LOE, Decret 67/2015, ORPIMO)
273
+ - Zoning and planning compliance verification
274
+ - Tax and stamp duty compliance checks
275
+ - Government approvals and regulatory tracking
276
+ - Document completeness for regulatory submissions
277
+
278
+ Do NOT produce full investment analysis (IRR, DCF, stress testing) in this mode
279
+ — those belong to the VIABILITY route.
280
+
281
+ IMPORTANT — DOCUMENT MISMATCH DETECTION:
282
+ If the uploaded documents are NOT relevant to compliance or visado workflows, you MUST:
283
+ 1. State clearly that these documents do not match CHECK mode expectations
284
+ 2. Explain what CHECK mode is designed for (compliance, visado, zoning, tax, approvals)
285
+ 3. List what document types WOULD be appropriate (e.g. architectural project documentation,
286
+ planning permits, lease agreements for compliance review, tax filings, building inspection reports)
287
+ 4. Suggest the user try the VIABILITY button instead if their documents are financial/investment focused
288
+
289
+ Examples of mismatched documents for CHECK mode:
290
+ - US real estate investment analysis → suggest VIABILITY route
291
+ - Financial models / DCF spreadsheets without regulatory content → suggest VIABILITY route
292
+ - Investment memos focused on returns rather than compliance → suggest VIABILITY route
293
+ """)
294
+
295
+ parts.append(OUTPUT_INSTRUCTIONS)
296
+ return "\n\n".join(parts)
297
+
298
+
299
+ # ═══════════════════════════════════════════════════════════════
300
+ # 4. DOCUMENT TEXT EXTRACTION
301
+ # ═══════════════════════════════════════════════════════════════
302
+
303
+ def extract_text(file_path: str) -> str:
304
+ ext = os.path.splitext(file_path.lower())[1]
305
+
306
+ if ext == ".pdf":
307
+ if HAS_PYMUPDF:
308
+ doc = fitz.open(file_path)
309
+ return "\n".join(f"\n--- Page {i+1} ---\n{p.get_text()}" for i, p in enumerate(doc))
310
+ from pypdf import PdfReader
311
+ return "\n".join(p.extract_text() or "" for p in PdfReader(file_path).pages)
312
+
313
+ elif ext == ".docx":
314
+ if HAS_DOCX:
315
+ return "\n".join(p.text for p in DocxDocument(file_path).paragraphs)
316
+ return "[DOCX extraction unavailable]"
317
+
318
+ elif ext == ".csv":
319
+ rows = []
320
+ with open(file_path, newline="", encoding="utf-8", errors="replace") as f:
321
+ for row in csv.reader(f):
322
+ rows.append(", ".join(row))
323
+ return "\n".join(rows)
324
+
325
+ elif ext in (".xlsx", ".xls"):
326
+ if HAS_XLSX:
327
+ wb = openpyxl.load_workbook(file_path, read_only=True, data_only=True)
328
+ lines = []
329
+ for sheet in wb.sheetnames:
330
+ lines.append(f"\n[Sheet: {sheet}]")
331
+ for row in wb[sheet].iter_rows(values_only=True):
332
+ if any(v is not None for v in row):
333
+ lines.append("\t".join("" if v is None else str(v) for v in row))
334
+ return "\n".join(lines)
335
+ return "[XLSX extraction unavailable]"
336
+
337
+ return f"[Unsupported file type: {ext}]"
338
+
339
+
340
+ # ═══════════════════════════════════════════════════════════════
341
+ # 5. BUILD USER MESSAGE (simplified — no language injection)
342
+ # ═══════════════════════════════════════════════════════════════
343
+
344
+ def build_user_message(user_query: str, uploaded_files: list, route: str = "viability") -> str:
345
+ parts = []
346
+
347
+ if user_query.strip():
348
+ # User typed something — prepend route context so Claude knows the mode
349
+ route_context = (
350
+ "[MODE: VIABILITY — financial analysis, IRR/DCF, risk assessment, stress testing]\n\n"
351
+ if route == "viability"
352
+ else "[MODE: CHECK — visado pre-validation, zoning compliance, tax compliance, regulatory approvals]\n\n"
353
+ )
354
+ parts.append(f"## USER REQUEST\n{route_context}{user_query.strip()}")
355
+ else:
356
+ # No user query — send route-specific default instruction
357
+ if route == "check":
358
+ parts.append(
359
+ "## USER REQUEST\n"
360
+ "[MODE: CHECK — visado pre-validation, zoning compliance, tax compliance, regulatory approvals]\n\n"
361
+ "Run a compliance and regulatory check on the uploaded documents. "
362
+ "This includes: visado/visa pre-validation (if applicable to the document type), "
363
+ "zoning and planning verification, tax and stamp duty compliance, "
364
+ "and government approvals tracking. Detect jurisdiction automatically.\n\n"
365
+ "If the uploaded documents are NOT relevant to compliance or visado workflows "
366
+ "(e.g. they are US investment memos, financial models without regulatory content, "
367
+ "or documents from jurisdictions where visado does not apply), state this clearly: "
368
+ "explain what this CHECK mode expects and what document types would be appropriate."
369
+ )
370
+ else:
371
+ parts.append(
372
+ "## USER REQUEST\n"
373
+ "[MODE: VIABILITY — financial analysis, IRR/DCF, risk assessment, stress testing]\n\n"
374
+ "Run a full investment viability analysis on the uploaded documents. "
375
+ "This includes: investment analysis (IRR, DCF, cap rate, NOI, equity multiple), "
376
+ "risk assessment with severity × likelihood scoring, secured lending evaluation "
377
+ "(DSCR, LTV, covenant analysis), stress testing (base/upside/downside/stress scenarios), "
378
+ "and investment memo generation. Detect jurisdiction automatically."
379
+ )
380
+
381
+
382
+ if uploaded_files:
383
+ parts.append("## UPLOADED DOCUMENTS")
384
+ for f in uploaded_files:
385
+ if f is None:
386
+ continue
387
+ path = f.name if hasattr(f, "name") else str(f)
388
+ fname = os.path.basename(path)
389
+ parts.append(f"### Document: {fname}")
390
+ try:
391
+ parts.append(extract_text(path)[:20000])
392
+ except Exception as e:
393
+ parts.append(f"[Error extracting {fname}: {e}]")
394
+
395
+ return "\n\n".join(parts)
396
+
397
+
398
+ # ═══════════════════════════════════════════════════════════════
399
+ # 6. API KEY
400
+ # ═══════════════════════════════════════════════════════════════
401
+
402
+ def get_api_key():
403
+ key = os.environ.get("ANTHROPIC_API_KEY") or os.environ.get("ANTHROPICAPIKEY")
404
+ if not key:
405
+ raise ValueError("ANTHROPIC_API_KEY not set in Space secrets.")
406
+ return key
407
+
408
+
409
+ # ═══════════════════════════════════════════════════════════════
410
+ # 7. STREAMING ANALYSIS (V9 — accepts route, builds prompt per-request)
411
+ # ═══════════════════════════════════════════════════════════════
412
+
413
+ def stream_analysis(user_query, files, route, analysis_state):
414
+ if not files and not user_query.strip():
415
+ yield "⚠️ Please upload at least one document or enter a question.", ""
416
+ return
417
+
418
+ user_msg = build_user_message(user_query, files or [], route=route)
419
+ system_prompt = build_system_prompt(route=route)
420
+
421
+ try:
422
+ client = anthropic.Anthropic(api_key=get_api_key())
423
+ except ValueError as e:
424
+ yield f"❌ {e}", ""
425
+ return
426
+
427
+ accumulated = ""
428
+ try:
429
+ with client.messages.stream(
430
+ model="claude-sonnet-4-20250514",
431
+ max_tokens=16000,
432
+ system=system_prompt,
433
+ messages=[{"role": "user", "content": user_msg}],
434
+ ) as stream:
435
+ for chunk in stream.text_stream:
436
+ accumulated += chunk
437
+ words = len(accumulated.split())
438
+ yield f"✍️ Analysing... ({words} words written)", ""
439
+
440
+ except anthropic.APIError as e:
441
+ yield f"❌ API error: {e}", ""
442
+ return
443
+ except Exception as e:
444
+ yield f"❌ Unexpected error: {e}", ""
445
+ return
446
+
447
+ if not accumulated.strip():
448
+ yield "❌ Claude returned an empty response. Please try again.", ""
449
+ return
450
+
451
+ yield "✅ Analysis complete.", accumulated
452
+
453
+
454
+ # ═══════════════════════════════════════════════════════════════
455
+ # 8. LANDING PAGE HTML
456
+ # ═══════════════════════════════════════════════════════════════
457
+
458
+ _landing_from_file = _read(LANDING_PATH)
459
+
460
+ LANDING_HTML = _landing_from_file if _landing_from_file.strip() else """
461
+ <div style="font-family:sans-serif;max-width:900px;margin:0 auto;padding:32px 24px 0">
462
+ <div style="display:flex;align-items:center;gap:10px;margin-bottom:24px">
463
+ <span style="font-size:26px">📊</span>
464
+ <span style="font-weight:900;font-size:20px;color:#120e1a">RailNexus <span style="color:#5a21d4">Value</span></span>
465
+ </div>
466
+ <h1 style="font-size:32px;font-weight:900;line-height:1.15;color:#120e1a;margin:0 0 12px">
467
+ Upload a deal. <span style="color:#5a21d4">Get institutional</span> analysis.
468
+ </h1>
469
+ </div>
470
+ """
471
+
472
+
473
+ # ═══════════════════════════════════════════════════════════════
474
+ # 9. QUESTIONNAIRE — 5-language mailto composer
475
+ # ═══════════════════════════════════════════════════════════════
476
+
477
+ QUESTIONNAIRE = {
478
+ "Español": {
479
+ "title": "Encuesta de usuario",
480
+ "intro": "Gracias por usar este software. Queremos mejorar vuestra ayuda real. Esto es anónimo y solo nos interesa tu experiencia honesta.",
481
+ "questions": [
482
+ {"id": "freq", "text": "¿Con qué frecuencia usas el agente actualmente?",
483
+ "options": ["Casi diario", "Varias veces por semana", "1-2 veces por semana", "Solo cuando me llega un suelo/promotor", "Una sola vez"]},
484
+ {"id": "workflow", "text": "¿En qué momento del flujo de trabajo usas esta herramienta?",
485
+ "options": ["Viabilidad preliminar de suelo", "Primera reunión con promotor", "Durante el proyecto", "Revisión final antes de visado", "Otro"]},
486
+ {"id": "value", "text": "¿Cuál es el mayor valor que te aporta?",
487
+ "options": ["Ahorro de tiempo brutal (días → minutos)", "Detectar proyectos inviables antes de trabajar gratis", "Análisis financiero que antes no hacía", "Detección de riesgos normativos/técnicos", "Otro"]},
488
+ {"id": "useful_part", "text": "¿Qué parte del informe te parece más útil?",
489
+ "options": ["Semáforo de viabilidad (verde/amarillo/rojo)", "Matriz de riesgos", "Recomendaciones estratégicas", "Detección de documentación ausente", "Otra"]},
490
+ {"id": "improve", "text": "¿Qué debe mejorarse?",
491
+ "options": ["Semáforo demasiado optimista/pesimista", "Falta normativa autonómica/municipal", "No detecta bien ciertos riesgos técnicos", "Otro"]},
492
+ {"id": "new_features", "text": "¿Qué funcionalidades nuevas te harían usarlo más?",
493
+ "options": ["Pre-validación automática para visado COAC", "Cruce con normativa local (POUM, alturas, usos)", "Matriz de documentación ausente", "Informe con tu logo y marca", "Otro"]},
494
+ {"id": "time_saved", "text": "¿Cuánto tiempo te ahorra en viabilidad preliminar?",
495
+ "options": ["Más de 10 horas", "5-10 horas", "2-5 horas", "Menos de 2 horas", "No me ahorra tiempo real"]},
496
+ {"id": "recommend", "text": "¿Lo recomendarías a otros arquitectos colegiados?",
497
+ "options": ["Sí, sin duda", "Sí, pero solo si mejoran...", "Todavía no, falta madurez", "No lo recomendaría"]},
498
+ ],
499
+ "open_q1": "¿Qué patrones recurrentes debería detectar mejor el agente?",
500
+ "open_q2": "¿Qué problema del día a día del arquitecto debería resolver primero?",
501
+ "submit": "Enviar encuesta",
502
+ },
503
+ "Català": {
504
+ "title": "Enquesta d'usuari",
505
+ "intro": "Gràcies per fer servir aquest programari. Volem millorar la vostra ajuda real. Això és anònim i només ens interessa la teva experiència honesta.",
506
+ "questions": [
507
+ {"id": "freq", "text": "Amb quina freqüència fas servir l'agent?",
508
+ "options": ["Gairebé diari", "Diverses vegades per setmana", "1-2 vegades per setmana", "Només quan em ve un sòl/promotor", "Un sol cop"]},
509
+ {"id": "workflow", "text": "En quin moment del flux de treball fas servir l'eina?",
510
+ "options": ["Viabilitat preliminar de sòl", "Primera reunió amb promotor", "Durant el projecte", "Revisió final abans de visat", "Altre"]},
511
+ {"id": "value", "text": "Quin és el major valor que t'aporta?",
512
+ "options": ["Estalvi de temps brutal (dies → minuts)", "Detectar projectes inviables", "Anàlisi financer que abans no feia", "Detecció de riscos normatius/tècnics", "Altre"]},
513
+ {"id": "useful_part", "text": "Quina part de l'informe et sembla més útil?",
514
+ "options": ["Semàfor de viabilitat (verd/groc/vermell)", "Matriu de riscos", "Recomanacions estratègiques", "Detecció de documentació absent", "Altra"]},
515
+ {"id": "improve", "text": "Què s'ha de millorar?",
516
+ "options": ["Semàfor massa optimista/pessimista", "Falta normativa autonòmica/municipal", "No detecta bé certs riscos tècnics", "Altre"]},
517
+ {"id": "new_features", "text": "Quines funcionalitats noves et farien servir-lo més?",
518
+ "options": ["Pre-validació automàtica per a visat COAC", "Encreuament amb normativa local (POUM)", "Matriu de documentació absent", "Informe amb el teu logo", "Altre"]},
519
+ {"id": "time_saved", "text": "Quant temps t'estalvia en viabilitat preliminar?",
520
+ "options": ["Més de 10 hores", "5-10 hores", "2-5 hores", "Menys de 2 hores", "No m'estalvia temps real"]},
521
+ {"id": "recommend", "text": "El recomanaries a altres arquitectes col·legiats?",
522
+ "options": ["Sí, sens dubte", "Sí, però només si milloren...", "Encara no, falta maduresa", "No el recomanaria"]},
523
+ ],
524
+ "open_q1": "Quins patrons recurrents hauria de detectar millor l'agent?",
525
+ "open_q2": "Quin problema del dia a dia de l'arquitecte hauria de resoldre primer?",
526
+ "submit": "Enviar enquesta",
527
+ },
528
+ "English": {
529
+ "title": "User survey",
530
+ "intro": "Thanks for using this software. We want to improve your real-world experience. This is anonymous — we only care about your honest feedback.",
531
+ "questions": [
532
+ {"id": "freq", "text": "How often do you currently use the agent?",
533
+ "options": ["Almost daily", "Several times a week", "1-2 times a week", "Only when a new site/developer comes in", "Just once"]},
534
+ {"id": "workflow", "text": "At what point in your workflow do you use this tool?",
535
+ "options": ["Preliminary site feasibility", "First meeting with developer", "During the project", "Final review before submission", "Other"]},
536
+ {"id": "value", "text": "What's the biggest value it provides?",
537
+ "options": ["Massive time savings (days → minutes)", "Detecting non-viable projects before working for free", "Financial analysis I didn't do before", "Detecting regulatory/technical risks I miss", "Other"]},
538
+ {"id": "useful_part", "text": "Which part of the report is most useful?",
539
+ "options": ["Viability traffic light (green/yellow/red)", "Risk matrix", "Strategic recommendations", "Missing documentation detection", "Other"]},
540
+ {"id": "improve", "text": "What needs to improve?",
541
+ "options": ["Traffic light too optimistic/pessimistic", "Missing local/municipal regulations", "Doesn't detect certain technical risks well", "Other"]},
542
+ {"id": "new_features", "text": "What new features would make you use it more?",
543
+ "options": ["Automatic pre-validation for COAC visa", "Cross-check with local regulations (POUM, heights, uses)", "Missing documentation matrix", "Report with your logo and brand", "Other"]},
544
+ {"id": "time_saved", "text": "How much time does it save on a typical preliminary feasibility?",
545
+ "options": ["More than 10 hours", "5-10 hours", "2-5 hours", "Less than 2 hours", "It doesn't save real time"]},
546
+ {"id": "recommend", "text": "Would you recommend it to other registered architects?",
547
+ "options": ["Yes, absolutely", "Yes, but only if they improve...", "Not yet, needs more maturity", "I wouldn't recommend it"]},
548
+ ],
549
+ "open_q1": "What recurring patterns should the agent detect better?",
550
+ "open_q2": "What daily problem should a tool like this solve first to be essential?",
551
+ "submit": "Submit survey",
552
+ },
553
+ "Deutsch": {
554
+ "title": "Nutzerbefragung",
555
+ "intro": "Danke, dass Sie diese Software nutzen. Wir möchten Ihre Erfahrung verbessern. Dies ist anonym — uns interessiert nur Ihr ehrliches Feedback.",
556
+ "questions": [
557
+ {"id": "freq", "text": "Wie oft nutzen Sie den Agenten derzeit?",
558
+ "options": ["Fast täglich", "Mehrmals pro Woche", "1-2 Mal pro Woche", "Nur bei neuem Grundstück/Bauträger", "Nur einmal"]},
559
+ {"id": "workflow", "text": "An welchem Punkt Ihres Workflows nutzen Sie das Tool?",
560
+ "options": ["Vorläufige Machbarkeit", "Erstes Treffen mit Bauträger", "Während des Projekts", "Abschlussprüfung vor Einreichung", "Andere"]},
561
+ {"id": "value", "text": "Was ist der größte Mehrwert?",
562
+ "options": ["Massive Zeitersparnis (Tage → Minuten)", "Nicht realisierbare Projekte erkennen", "Finanzanalyse, die ich vorher nicht gemacht habe", "Erkennung regulatorischer/technischer Risiken", "Andere"]},
563
+ {"id": "useful_part", "text": "Welcher Teil des Berichts ist am nützlichsten?",
564
+ "options": ["Machbarkeitsampel (grün/gelb/rot)", "Risikomatrix", "Strategische Empfehlungen", "Erkennung fehlender Dokumentation", "Andere"]},
565
+ {"id": "improve", "text": "Was muss verbessert werden?",
566
+ "options": ["Ampel zu optimistisch/pessimistisch", "Fehlende lokale Vorschriften", "Erkennt bestimmte technische Risiken nicht gut", "Andere"]},
567
+ {"id": "new_features", "text": "Welche neuen Funktionen würden Sie öfter nutzen lassen?",
568
+ "options": ["Automatische Vorvalidierung", "Abgleich mit lokalen Vorschriften", "Matrix fehlender Dokumente", "Bericht mit Ihrem Logo", "Andere"]},
569
+ {"id": "time_saved", "text": "Wie viel Zeit spart der Agent bei typischer Vorprüfung?",
570
+ "options": ["Mehr als 10 Stunden", "5-10 Stunden", "2-5 Stunden", "Weniger als 2 Stunden", "Spart keine echte Zeit"]},
571
+ {"id": "recommend", "text": "Würden Sie es anderen Architekten empfehlen?",
572
+ "options": ["Ja, auf jeden Fall", "Ja, aber nur wenn verbessert...", "Noch nicht, braucht mehr Reife", "Würde ich nicht empfehlen"]},
573
+ ],
574
+ "open_q1": "Welche wiederkehrenden Muster sollte der Agent besser erkennen?",
575
+ "open_q2": "Welches tägliche Problem sollte ein solches Tool zuerst lösen?",
576
+ "submit": "Umfrage absenden",
577
+ },
578
+ "Français": {
579
+ "title": "Enquête utilisateur",
580
+ "intro": "Merci d'utiliser ce logiciel. Nous voulons améliorer votre expérience réelle. C'est anonyme — seul votre retour honnête nous intéresse.",
581
+ "questions": [
582
+ {"id": "freq", "text": "À quelle fréquence utilisez-vous l'agent?",
583
+ "options": ["Presque quotidiennement", "Plusieurs fois par semaine", "1-2 fois par semaine", "Uniquement pour un nouveau terrain/promoteur", "Une seule fois"]},
584
+ {"id": "workflow", "text": "À quel moment de votre flux de travail utilisez-vous l'outil?",
585
+ "options": ["Faisabilité préliminaire", "Première réunion avec le promoteur", "Pendant le projet", "Révision finale avant soumission", "Autre"]},
586
+ {"id": "value", "text": "Quelle est la plus grande valeur ajoutée?",
587
+ "options": ["Gain de temps massif (jours → minutes)", "Détecter les projets non viables", "Analyse financière que je ne faisais pas", "Détection de risques réglementaires/techniques", "Autre"]},
588
+ {"id": "useful_part", "text": "Quelle partie du rapport est la plus utile?",
589
+ "options": ["Feu de viabilité (vert/jaune/rouge)", "Matrice de risques", "Recommandations stratégiques", "Détection de documentation manquante", "Autre"]},
590
+ {"id": "improve", "text": "Que faut-il améliorer?",
591
+ "options": ["Feu trop optimiste/pessimiste", "Manque de réglementation locale", "Ne détecte pas bien certains risques techniques", "Autre"]},
592
+ {"id": "new_features", "text": "Quelles nouvelles fonctionnalités vous feraient l'utiliser plus?",
593
+ "options": ["Pré-validation automatique", "Croisement avec réglementation locale", "Matrice de documentation manquante", "Rapport avec votre logo", "Autre"]},
594
+ {"id": "time_saved", "text": "Combien de temps l'agent vous fait-il gagner?",
595
+ "options": ["Plus de 10 heures", "5-10 heures", "2-5 heures", "Moins de 2 heures", "Ne fait pas gagner de temps réel"]},
596
+ {"id": "recommend", "text": "Le recommanderiez-vous à d'autres architectes?",
597
+ "options": ["Oui, sans aucun doute", "Oui, mais seulement s'ils améliorent...", "Pas encore, manque de maturité", "Je ne le recommanderais pas"]},
598
+ ],
599
+ "open_q1": "Quels schémas récurrents l'agent devrait-il mieux détecter?",
600
+ "open_q2": "Quel problème quotidien un tel outil devrait-il résoudre en premier?",
601
+ "submit": "Envoyer l'enquête",
602
+ },
603
+ }
604
+
605
+ def compose_survey_mailto(language, answers_dict, open1, open2):
606
+ q = QUESTIONNAIRE.get(language, QUESTIONNAIRE["Español"])
607
+ lines = [f"RailNexus Value — {q['title']}", ""]
608
+ for question in q["questions"]:
609
+ qid = question["id"]
610
+ answer = answers_dict.get(qid, "(no response)")
611
+ lines.append(f"Q: {question['text']}")
612
+ lines.append(f"A: {answer}")
613
+ lines.append("")
614
+ lines.append(f"Q: {q['open_q1']}")
615
+ lines.append(f"A: {open1 or '(no response)'}")
616
+ lines.append("")
617
+ lines.append(f"Q: {q['open_q2']}")
618
+ lines.append(f"A: {open2 or '(no response)'}")
619
+ body = "\n".join(lines)
620
+ subject = f"RailNexus Value Survey — {language}"
621
+ return (
622
+ f"mailto:jade.zheng@railnexus.io"
623
+ f"?subject={urllib.parse.quote(subject)}"
624
+ f"&body={urllib.parse.quote(body)}"
625
+ )
626
+
627
+
628
+ # ═══════════════════════════════════════════════════════════════
629
+ # 10. GRADIO UI — V9: two route buttons, no language selector
630
+ # ═══════════════════════════════════════════════════════════════
631
+
632
+ css = """
633
+ .huggingface-space-header,
634
+ div[class*="space-header"],
635
+ header.container,
636
+ div[data-testid="space-header"] {
637
+ display: none !important;
638
+ }
639
+ body { font-family: 'Inter', sans-serif !important; }
640
+ .gradio-container { max-width: 1060px !important; margin: 0 auto; }
641
+ .upload-zone { border: 2px dashed #5a21d4 !important; border-radius: 16px !important; }
642
+ .run-btn {
643
+ background: #5a21d4 !important; color: white !important;
644
+ border-radius: 12px !important; font-weight: 700 !important;
645
+ font-size: 16px !important; padding: 14px !important;
646
+ }
647
+ .run-btn:hover { opacity: 0.88 !important; }
648
+ .run-btn:disabled { opacity: 0.5 !important; }
649
+ .check-btn {
650
+ background: white !important; color: #5a21d4 !important;
651
+ border: 2px solid #5a21d4 !important;
652
+ border-radius: 12px !important; font-weight: 700 !important;
653
+ font-size: 16px !important; padding: 14px !important;
654
+ }
655
+ .check-btn:hover { background: #f8f7fc !important; }
656
+ .check-btn:disabled { opacity: 0.5 !important; }
657
+ footer { display: none !important; }
658
+ #results-panel {
659
+ background: white;
660
+ border: 1.5px solid #ebe8f2;
661
+ border-radius: 12px;
662
+ padding: 28px 32px;
663
+ margin-top: 8px;
664
+ min-height: 200px;
665
+ }
666
+ .tab-nav button {
667
+ font-weight: 600 !important;
668
+ font-size: 14px !important;
669
+ }
670
+ .tab-nav button.selected {
671
+ color: #5a21d4 !important;
672
+ border-bottom-color: #5a21d4 !important;
673
+ }
674
+ """
675
+
676
+ with gr.Blocks(title="RailNexus Value", theme=gr.themes.Soft()) as demo:
677
+
678
+ gr.HTML(LANDING_HTML)
679
+
680
+ with gr.Tabs():
681
+
682
+ # ════════════════════════════════════════
683
+ # TAB 1: ANALYSIS (two route buttons)
684
+ # ════════════════════════════════════════
685
+ with gr.TabItem("🔍 Analysis / Análisis"):
686
+
687
+ with gr.Row():
688
+ with gr.Column(scale=1):
689
+ query_box = gr.Textbox(
690
+ label="¿Qué necesitas? / What do you need?",
691
+ placeholder="",
692
+ lines=7,
693
+ max_lines=12,
694
+ )
695
+
696
+ with gr.Column(scale=1):
697
+ file_upload = gr.File(
698
+ label="Subir documentos / Upload documents",
699
+ file_count="multiple",
700
+ file_types=[".pdf", ".docx", ".xlsx", ".csv"],
701
+ elem_classes=["upload-zone"],
702
+ )
703
+ gr.Markdown(
704
+ "<p style='color:#675194;font-size:12px;margin-top:8px'>"
705
+ "PDF · DOCX · XLSX · CSV &nbsp;|&nbsp; "
706
+ "Jurisdicción detectada automáticamente / Jurisdiction detected automatically</p>"
707
+ )
708
+
709
+ # Hidden state for route
710
+ route_state = gr.State("viability")
711
+
712
+ with gr.Row():
713
+ viability_btn = gr.Button(
714
+ "🔍 Viability / Viabilidad",
715
+ variant="primary",
716
+ elem_classes=["run-btn"],
717
+ scale=1,
718
+ )
719
+ check_btn = gr.Button(
720
+ "☑️ Check / Verificación",
721
+ variant="secondary",
722
+ elem_classes=["check-btn"],
723
+ scale=1,
724
+ )
725
+
726
+ analysis_state = gr.State("")
727
+
728
+ status_md = gr.Markdown(
729
+ value="Sube documentos y/o introduce una pregunta, luego elige **Viabilidad** o **Verificación**.\n\n"
730
+ "Upload documents and/or enter a question, then choose **Viability** or **Check**.",
731
+ )
732
+
733
+ results_html = gr.HTML(value="", elem_id="results-panel")
734
+
735
+ # Print instruction below output
736
+ gr.HTML("""
737
+ <div style="text-align:center;margin:12px 0 4px">
738
+ <p style="color:#675194;font-size:13px;font-style:italic">
739
+ 🖨️ Para guardar el informe, use <strong>Ctrl+P</strong> (o <strong>⌘+P</strong> en Mac) para imprimir o guardar como PDF.
740
+ <br>To save the report, use <strong>Ctrl+P</strong> (or <strong>⌘+P</strong> on Mac) to print or save as PDF.
741
+ </p>
742
+ </div>
743
+ """)
744
+
745
+ # ── Wiring for VIABILITY button ──
746
+ (
747
+ viability_btn.click(
748
+ fn=lambda: (gr.Button(interactive=False), gr.Button(interactive=False), "", "", "viability"),
749
+ inputs=[],
750
+ outputs=[viability_btn, check_btn, analysis_state, results_html, route_state],
751
+ queue=False,
752
+ )
753
+ .then(
754
+ fn=stream_analysis,
755
+ inputs=[query_box, file_upload, route_state, analysis_state],
756
+ outputs=[status_md, analysis_state],
757
+ )
758
+ .then(
759
+ fn=lambda state: state,
760
+ inputs=[analysis_state],
761
+ outputs=[results_html],
762
+ queue=False,
763
+ )
764
+ .then(
765
+ fn=lambda: (gr.Button(interactive=True), gr.Button(interactive=True)),
766
+ inputs=[],
767
+ outputs=[viability_btn, check_btn],
768
+ queue=False,
769
+ )
770
+ )
771
+
772
+ # ── Wiring for CHECK button ──
773
+ (
774
+ check_btn.click(
775
+ fn=lambda: (gr.Button(interactive=False), gr.Button(interactive=False), "", "", "check"),
776
+ inputs=[],
777
+ outputs=[viability_btn, check_btn, analysis_state, results_html, route_state],
778
+ queue=False,
779
+ )
780
+ .then(
781
+ fn=stream_analysis,
782
+ inputs=[query_box, file_upload, route_state, analysis_state],
783
+ outputs=[status_md, analysis_state],
784
+ )
785
+ .then(
786
+ fn=lambda state: state,
787
+ inputs=[analysis_state],
788
+ outputs=[results_html],
789
+ queue=False,
790
+ )
791
+ .then(
792
+ fn=lambda: (gr.Button(interactive=True), gr.Button(interactive=True)),
793
+ inputs=[],
794
+ outputs=[viability_btn, check_btn],
795
+ queue=False,
796
+ )
797
+ )
798
+
799
+ # ════════════════════════════════════════
800
+ # TAB 2: SURVEY / ENCUESTA
801
+ # ════════════════════════════════════════
802
+ with gr.TabItem("📋 Survey / Encuesta"):
803
+
804
+ survey_lang = gr.Radio(
805
+ choices=["Español", "Català", "English", "Deutsch", "Français"],
806
+ value="Español",
807
+ label="Idioma de la encuesta / Survey language",
808
+ interactive=True,
809
+ )
810
+
811
+ survey_intro = gr.Markdown(
812
+ value=f"### {QUESTIONNAIRE['Español']['title']}\n\n{QUESTIONNAIRE['Español']['intro']}"
813
+ )
814
+
815
+ es_q = QUESTIONNAIRE["Español"]
816
+ survey_radios = []
817
+ for question in es_q["questions"]:
818
+ survey_radios.append(
819
+ gr.Radio(choices=question["options"], label=question["text"], interactive=True)
820
+ )
821
+
822
+ open_q1 = gr.Textbox(label=es_q["open_q1"], lines=3, placeholder="(opcional / optional)")
823
+ open_q2 = gr.Textbox(label=es_q["open_q2"], lines=3, placeholder="(opcional / optional)")
824
+
825
+ survey_btn = gr.Button(f"📧 {es_q['submit']}", variant="primary", elem_classes=["run-btn"])
826
+ survey_result = gr.HTML(value="")
827
+
828
+ def update_survey_language(lang):
829
+ q = QUESTIONNAIRE.get(lang, QUESTIONNAIRE["Español"])
830
+ updates = [gr.Markdown(value=f"### {q['title']}\n\n{q['intro']}")]
831
+ for question in q["questions"]:
832
+ updates.append(gr.Radio(choices=question["options"], label=question["text"], value=None))
833
+ updates.append(gr.Textbox(label=q["open_q1"]))
834
+ updates.append(gr.Textbox(label=q["open_q2"]))
835
+ updates.append(gr.Button(value=f"📧 {q['submit']}"))
836
+ return updates
837
+
838
+ survey_lang.change(
839
+ fn=update_survey_language,
840
+ inputs=[survey_lang],
841
+ outputs=[survey_intro] + survey_radios + [open_q1, open_q2, survey_btn],
842
+ )
843
+
844
+ def submit_survey(lang, q1, q2, q3, q4, q5, q6, q7, q8, open1, open2):
845
+ q = QUESTIONNAIRE.get(lang, QUESTIONNAIRE["Español"])
846
+ answers = {}
847
+ for i, question in enumerate(q["questions"]):
848
+ answers[question["id"]] = [q1, q2, q3, q4, q5, q6, q7, q8][i] or "(no response)"
849
+ mailto = compose_survey_mailto(lang, answers, open1, open2)
850
+ msg = {"Español": ("Encuesta lista", "Abrir correo para enviar", "Tu cliente de correo se abrirá con las respuestas pre-rellenadas."),
851
+ "Català": ("Enquesta preparada", "Obrir correu per enviar", "El teu client de correu s'obrirà amb les respostes pre-emplenades."),
852
+ "English": ("Survey ready", "Open email to send", "Your email client will open with pre-filled responses."),
853
+ "Deutsch": ("Umfrage bereit", "E-Mail öffnen zum Senden", "Ihr E-Mail-Client öffnet sich mit vorausgefüllten Antworten."),
854
+ "Français": ("Enquête prête", "Ouvrir email pour envoyer", "Votre client email s'ouvrira avec les réponses pré-remplies.")}
855
+ m = msg.get(lang, msg["English"])
856
+ return f"""
857
+ <div style="text-align:center;padding:20px;background:#f0fdf4;border:1px solid #16a34a;border-radius:12px;margin-top:12px">
858
+ <p style="color:#16a34a;font-weight:700;font-size:16px;margin:0 0 12px">✅ {m[0]}!</p>
859
+ <a href="{mailto}" target="_blank"
860
+ style="display:inline-block;background:#5a21d4;color:white;padding:12px 32px;border-radius:10px;font-weight:700;font-size:14px;text-decoration:none">
861
+ 📧 {m[1]}
862
+ </a>
863
+ <p style="color:#675194;font-size:11px;margin-top:10px">{m[2]}</p>
864
+ </div>
865
+ """
866
+
867
+ survey_btn.click(
868
+ fn=submit_survey,
869
+ inputs=[survey_lang] + survey_radios + [open_q1, open_q2],
870
+ outputs=[survey_result],
871
+ )
872
+
873
+ # ── Disclaimer at very bottom ──
874
+ gr.HTML("""
875
+ <p style="font-size:10px;color:#a09ab5;text-align:center;margin:20px 0 8px">
876
+ © 2026 RailNexus Value. AI-generated analysis for review purposes only. Not legal, financial, or investment advice.
877
+ </p>
878
+ """)
879
+
880
+
881
+ # ═══════════════════════════════════════════════════════════════
882
+ # 11. LAUNCH
883
+ # ═══════════════════════════════════════════════════════════════
884
+
885
+ demo.launch(ssr_mode=False, css=css)
landing.html ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- RailNexus Value — landing.html v9 -->
2
+ <div id="rnv-landing" style="font-family:'Inter',system-ui,sans-serif;max-width:940px;margin:0 auto;padding:28px 24px 8px">
3
+
4
+ <!-- Header -->
5
+ <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:28px">
6
+ <div style="display:flex;align-items:center;gap:10px">
7
+ <span style="font-size:26px">📊</span>
8
+ <span style="font-weight:900;font-size:20px;color:#120e1a">RailNexus <span style="color:#5a21d4">Value</span></span>
9
+ </div>
10
+ </div>
11
+
12
+ <!-- Headline -->
13
+ <h1 style="font-size:34px;font-weight:900;line-height:1.12;color:#120e1a;margin:0 0 12px">
14
+ Sube un deal.<br><span style="color:#5a21d4">Análisis institucional.</span> En minutos.
15
+ </h1>
16
+
17
+ <!-- Subtitle -->
18
+ <p style="color:#675194;font-size:15px;line-height:1.6;max-width:640px;margin:0 0 16px">
19
+ Dos modos de análisis. Un agente. Cobertura en <b style="color:#120e1a">España, UK, USA, Alemania, Francia, Canadá, Países Bajos, India y EAU</b>. Automáticamente.
20
+ </p>
21
+
22
+ <!-- Two-route explanation -->
23
+ <div style="display:flex;gap:12px;flex-wrap:wrap;margin-bottom:20px">
24
+ <div style="flex:1;min-width:260px;background:white;border:2px solid #5a21d4;border-radius:12px;padding:14px 16px">
25
+ <div style="font-weight:800;font-size:14px;color:#5a21d4;margin-bottom:6px">🔍 Viability / Viabilidad</div>
26
+ <p style="font-size:12px;color:#675194;margin:0;line-height:1.5">
27
+ IRR · DCF · Cap rate · DSCR · LTV · Stress test · Matriz de riesgos · Investment memo
28
+ </p>
29
+ </div>
30
+ <div style="flex:1;min-width:260px;background:white;border:2px solid #16a34a;border-radius:12px;padding:14px 16px">
31
+ <div style="font-weight:800;font-size:14px;color:#16a34a;margin-bottom:6px">☑️ Check / Verificación</div>
32
+ <p style="font-size:12px;color:#675194;margin:0;line-height:1.5">
33
+ Pre-visado COAC · CTE · Urbanismo · Cumplimiento fiscal · Aprobaciones regulatorias
34
+ </p>
35
+ </div>
36
+ </div>
37
+
38
+ <!-- Privacy banner -->
39
+ <div style="background:#f8f7fc;border:1px solid #ebe8f2;border-radius:8px;padding:8px 14px;margin-bottom:4px;font-size:12px;color:#675194">
40
+ 🔒 Sus documentos no se almacenan. Se procesan en memoria y se eliminan automáticamente.
41
+ </div>
42
+
43
+ </div>
44
+
45
+ <script>
46
+ // Auto-open Survey tab if ?survey=1 is in the URL
47
+ (function() {
48
+ if (window.location.search.indexOf('survey=1') !== -1) {
49
+ var attempts = 0;
50
+ var interval = setInterval(function() {
51
+ var tabs = document.querySelectorAll('.tab-nav button, button[role="tab"]');
52
+ for (var i = 0; i < tabs.length; i++) {
53
+ if (tabs[i].textContent.indexOf('Survey') !== -1 || tabs[i].textContent.indexOf('Encuesta') !== -1) {
54
+ tabs[i].click();
55
+ clearInterval(interval);
56
+ return;
57
+ }
58
+ }
59
+ attempts++;
60
+ if (attempts > 30) clearInterval(interval);
61
+ }, 150);
62
+ }
63
+ })();
64
+ </script>