bonita2026 commited on
Commit
2e61dce
·
verified ·
1 Parent(s): 94eab0c

Delete app.py

Browse files

deleting to update with new version that fixes language UI, survey placement

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