bonita2026 commited on
Commit
f4f83b3
·
verified ·
1 Parent(s): 746a90a

Delete app.py

Browse files

deleting to add new app.py

Files changed (1) hide show
  1. app.py +0 -849
app.py DELETED
@@ -1,849 +0,0 @@
1
- # =============================================================================
2
- # InvestVerify — Real Estate & Infrastructure Investment Analysis Tool
3
- # Deployed on HuggingFace Spaces
4
- # Model: claude-sonnet-4-20250514 | API: Anthropic
5
- # =============================================================================
6
-
7
- import os
8
- import time
9
- import logging
10
- import traceback
11
-
12
- import gradio as gr
13
- import fitz # PyMuPDF
14
- import anthropic
15
- from docx import Document
16
- from docx.shared import RGBColor, Pt, Inches
17
- from docx.enum.text import WD_ALIGN_PARAGRAPH
18
-
19
- # ---------------------------------------------------------------------------
20
- # Logging
21
- # ---------------------------------------------------------------------------
22
- logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
23
- logger = logging.getLogger(__name__)
24
-
25
- # ---------------------------------------------------------------------------
26
- # Constants
27
- # ---------------------------------------------------------------------------
28
- MODEL_ID = "claude-sonnet-4-20250514"
29
- MAX_TOKENS = 8000
30
- MAX_TEXT_CHARS = 150_000
31
-
32
- # ---------------------------------------------------------------------------
33
- # Prompt loader
34
- # ---------------------------------------------------------------------------
35
- _MISSING_PROMPTS: list[str] = []
36
-
37
- def load_prompt(filename: str) -> str:
38
- """Load a prompt from the prompts/ directory next to this file."""
39
- filepath = os.path.join(os.path.dirname(__file__), filename)
40
- try:
41
- with open(filepath, "r", encoding="utf-8") as f:
42
- return f.read()
43
- except FileNotFoundError:
44
- logger.warning("Prompt file not found: %s", filepath)
45
- _MISSING_PROMPTS.append(filename)
46
- return ""
47
-
48
- # Load all prompts at startup
49
- SYSTEM_PROMPT = load_prompt("system_prompt.txt")
50
- PLAYBOOK = load_prompt("playbook.txt")
51
- INVESTMENT_MEMO_PROMPT = load_prompt("investment_memo.txt")
52
- RISK_ASSESSMENT_PROMPT = load_prompt("risk_assessment.txt")
53
- DISCREPANCIES_PROMPT = load_prompt("discrepancies.txt")
54
- LEASE_ABSTRACT_PROMPT = load_prompt("lease_abstract.txt")
55
-
56
- # ---------------------------------------------------------------------------
57
- # PDF extraction
58
- # ---------------------------------------------------------------------------
59
-
60
- def extract_text_from_pdfs(file_list) -> tuple[str, list[str]]:
61
- """
62
- Extract text from a list of uploaded PDF file objects.
63
- Returns (combined_text, warnings_list).
64
- """
65
- if not file_list:
66
- return "", []
67
-
68
- parts: list[str] = []
69
- warnings: list[str] = []
70
-
71
- for file_obj in file_list:
72
- # Gradio passes either a filepath string or a NamedString / tempfile object
73
- filepath = file_obj if isinstance(file_obj, str) else file_obj.name
74
- filename = os.path.basename(filepath)
75
- try:
76
- doc = fitz.open(filepath)
77
- pages_text = []
78
- for page in doc:
79
- pages_text.append(page.get_text())
80
- doc.close()
81
- file_text = "\n".join(pages_text).strip()
82
- if not file_text:
83
- warnings.append(
84
- f"⚠️ Could not extract text from **{filename}** — "
85
- "the file may be scanned or image-based."
86
- )
87
- else:
88
- separator = f"\n\n---DOCUMENT: {filename}---\n\n"
89
- parts.append(separator + file_text)
90
- except Exception as exc:
91
- logger.error("PDF extraction failed for %s: %s", filename, exc)
92
- warnings.append(
93
- f"⚠️ Could not extract text from **{filename}**: {exc}"
94
- )
95
-
96
- combined = "\n".join(parts)
97
-
98
- # Truncate if necessary
99
- if len(combined) > MAX_TEXT_CHARS:
100
- combined = combined[:MAX_TEXT_CHARS]
101
- warnings.append(
102
- f"\n\n⚠️ **Note:** Extracted text exceeded {MAX_TEXT_CHARS:,} characters "
103
- "and has been truncated. Some document content may not be included in the analysis."
104
- )
105
-
106
- return combined, warnings
107
-
108
-
109
- # ---------------------------------------------------------------------------
110
- # Anthropic streaming helper
111
- # ---------------------------------------------------------------------------
112
-
113
- def stream_claude(system_text: str, user_text: str):
114
- """
115
- Generator that yields incremental text chunks from the Claude API.
116
- Raises on API / key errors.
117
- """
118
- api_key = os.environ.get("ANTHROPICAPIKEY", "")
119
- if not api_key:
120
- raise ValueError(
121
- "API key not configured. Please add ANTHROPIC_API_KEY to your Space Secrets."
122
- )
123
-
124
- client = anthropic.Anthropic(api_key=api_key)
125
-
126
- with client.messages.stream(
127
- model=MODEL_ID,
128
- max_tokens=MAX_TOKENS,
129
- system=system_text,
130
- messages=[{"role": "user", "content": user_text}],
131
- ) as stream:
132
- for text_chunk in stream.text_stream:
133
- yield text_chunk
134
-
135
-
136
- # ---------------------------------------------------------------------------
137
- # Shared analysis runner (used by all four buttons)
138
- # ---------------------------------------------------------------------------
139
-
140
- def _build_system(prompt_name: str, prompt_text: str) -> tuple[str, str | None]:
141
- """
142
- Returns (system_text, error_message).
143
- error_message is None if everything is fine.
144
- """
145
- if not prompt_text:
146
- return "", (
147
- f"⚠️ **Configuration Error:** The prompt file for **{prompt_name}** is missing. "
148
- "Please contact the administrator to restore the `prompts/` directory."
149
- )
150
- system_text = SYSTEM_PROMPT + "\n\n" + PLAYBOOK
151
- return system_text, None
152
-
153
-
154
- def run_analysis(file_list, command_prompt: str, prompt_name: str):
155
- """
156
- Core generator used by Investment Memo, Risk Assessment, and Lease Abstract buttons.
157
- Yields (markdown_text, download_file_update) tuples.
158
- """
159
- # --- Guard: missing prompt ---
160
- system_text, err = _build_system(prompt_name, command_prompt)
161
- if err:
162
- yield err, gr.File(value=None, visible=False)
163
- return
164
-
165
- # --- Guard: no files ---
166
- if not file_list:
167
- yield (
168
- "⚠️ **Please upload at least one PDF document before running analysis.**",
169
- gr.File(value=None, visible=False),
170
- )
171
- return
172
-
173
- # --- Extract PDF text ---
174
- doc_text, warnings = extract_text_from_pdfs(file_list)
175
- warning_block = "\n".join(warnings) + "\n\n" if warnings else ""
176
-
177
- if not doc_text.strip():
178
- yield (
179
- warning_block
180
- + "⚠️ **No text could be extracted from the uploaded documents.** "
181
- "Please ensure the PDFs contain selectable text (not scanned images).",
182
- gr.File(value=None, visible=False),
183
- )
184
- return
185
-
186
- # --- Build user message ---
187
- user_message = (
188
- command_prompt
189
- + "\n\n"
190
- + "---UPLOADED DOCUMENTS---"
191
- + "\n\n"
192
- + doc_text
193
- )
194
-
195
- # --- Stream from Claude ---
196
- accumulated = warning_block
197
- try:
198
- for chunk in stream_claude(system_text, user_message):
199
- accumulated += chunk
200
- yield accumulated, gr.File(value=None, visible=False)
201
- except ValueError as ve:
202
- yield (
203
- f"⚠️ **{ve}**",
204
- gr.File(value=None, visible=False),
205
- )
206
- except anthropic.APIError as ae:
207
- yield (
208
- f"⚠️ **API Error:** {ae}\n\nPlease try again. "
209
- "If the problem persists, check your API key and quota.",
210
- gr.File(value=None, visible=False),
211
- )
212
- except Exception as exc:
213
- logger.error("Unexpected error during analysis: %s", traceback.format_exc())
214
- yield (
215
- f"⚠️ **Unexpected Error:** {exc}\n\nPlease try again.",
216
- gr.File(value=None, visible=False),
217
- )
218
-
219
-
220
- # ---------------------------------------------------------------------------
221
- # Button handlers — Investment Memo, Risk Assessment, Lease Abstract
222
- # ---------------------------------------------------------------------------
223
-
224
- def run_investment_memo(file_list):
225
- yield from run_analysis(file_list, INVESTMENT_MEMO_PROMPT, "investment_memo")
226
-
227
-
228
- def run_risk_assessment(file_list):
229
- yield from run_analysis(file_list, RISK_ASSESSMENT_PROMPT, "risk_assessment")
230
-
231
-
232
- def run_lease_abstract(file_list):
233
- yield from run_analysis(file_list, LEASE_ABSTRACT_PROMPT, "lease_abstract")
234
-
235
-
236
- # ---------------------------------------------------------------------------
237
- # Discrepancies — Step 1: stream + accumulate into gr.State
238
- # ---------------------------------------------------------------------------
239
-
240
- def run_discrepancy_analysis(file_list, _state):
241
- """
242
- Step 1 of the discrepancy flow.
243
- Streams the analysis and accumulates the full response into gr.State.
244
- Yields (markdown_text, accumulated_state).
245
- """
246
- system_text, err = _build_system("discrepancies", DISCREPANCIES_PROMPT)
247
- if err:
248
- yield err, ""
249
- return
250
-
251
- if not file_list:
252
- yield (
253
- "⚠️ **Please upload at least one PDF document before running analysis.**",
254
- "",
255
- )
256
- return
257
-
258
- doc_text, warnings = extract_text_from_pdfs(file_list)
259
- warning_block = "\n".join(warnings) + "\n\n" if warnings else ""
260
-
261
- if not doc_text.strip():
262
- yield (
263
- warning_block
264
- + "⚠️ **No text could be extracted from the uploaded documents.**",
265
- "",
266
- )
267
- return
268
-
269
- user_message = (
270
- DISCREPANCIES_PROMPT
271
- + "\n\n"
272
- + "---UPLOADED DOCUMENTS---"
273
- + "\n\n"
274
- + doc_text
275
- )
276
-
277
- accumulated = warning_block
278
- try:
279
- for chunk in stream_claude(system_text, user_message):
280
- accumulated += chunk
281
- yield accumulated, accumulated
282
- except ValueError as ve:
283
- yield f"⚠️ **{ve}**", ""
284
- except anthropic.APIError as ae:
285
- yield (
286
- f"⚠️ **API Error:** {ae}\n\nPlease try again.",
287
- "",
288
- )
289
- except Exception as exc:
290
- logger.error("Discrepancy analysis error: %s", traceback.format_exc())
291
- yield f"⚠️ **Unexpected Error:** {exc}", ""
292
-
293
-
294
- # ---------------------------------------------------------------------------
295
- # Discrepancies — Step 2: generate DOCX from accumulated state
296
- # ---------------------------------------------------------------------------
297
-
298
- def _get_doc_names(file_list) -> list[str]:
299
- if not file_list:
300
- return []
301
- names = []
302
- for f in file_list:
303
- fp = f if isinstance(f, str) else f.name
304
- names.append(os.path.basename(fp))
305
- return names
306
-
307
-
308
- def _severity_color(block_text: str) -> RGBColor:
309
- """Infer severity color from emoji in the block header."""
310
- if "🔴" in block_text or "🔺" in block_text:
311
- return RGBColor(0xDC, 0x26, 0x26) # red
312
- if "🟡" in block_text or "⚠" in block_text:
313
- return RGBColor(0xF5, 0x9E, 0x0B) # amber
314
- if "🟢" in block_text or "✅" in block_text:
315
- return RGBColor(0x16, 0xA3, 0x4A) # green
316
- return RGBColor(0x1F, 0x29, 0x37) # default near-black
317
-
318
-
319
- def generate_docx(full_response: str, file_list) -> gr.File:
320
- """
321
- Step 2 of the discrepancy flow.
322
- Parses the markdown response and generates a .docx report.
323
- Returns a gr.File update object.
324
- """
325
- if not full_response or not full_response.strip():
326
- logger.warning("generate_docx called with empty response; skipping.")
327
- return gr.File(value=None, visible=False)
328
-
329
- timestamp = int(time.time())
330
- output_path = f"/tmp/discrepancy_report_{timestamp}.docx"
331
-
332
- try:
333
- doc_names = _get_doc_names(file_list)
334
- doc_names_str = ", ".join(doc_names) if doc_names else "Uploaded Documents"
335
-
336
- doc = Document()
337
-
338
- # ---- Title block ----
339
- title_para = doc.add_paragraph()
340
- title_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
341
- run = title_para.add_run("RailNexus Value — Key Discrepancy Report")
342
- run.bold = True
343
- run.font.size = Pt(18)
344
- run.font.color.rgb = RGBColor(0x25, 0x63, 0xEB)
345
-
346
- subtitle = doc.add_paragraph()
347
- subtitle.alignment = WD_ALIGN_PARAGRAPH.CENTER
348
- sub_run = subtitle.add_run(
349
- f"Generated: {time.strftime('%Y-%m-%d %H:%M UTC', time.gmtime(timestamp))}\n"
350
- f"Documents: {doc_names_str}"
351
- )
352
- sub_run.font.size = Pt(10)
353
- sub_run.font.color.rgb = RGBColor(0x6B, 0x72, 0x80)
354
-
355
- doc.add_paragraph() # spacer
356
-
357
- # ---- Parse discrepancy blocks ----
358
- # Split on severity emoji patterns that typically start a new finding
359
- # We look for lines that start with a severity emoji or a numbered heading
360
- severity_markers = ["🔴", "🟡", "🟢", "🔺", "⚠️", "##"]
361
- lines = full_response.split("\n")
362
-
363
- blocks: list[list[str]] = []
364
- current_block: list[str] = []
365
-
366
- for line in lines:
367
- stripped = line.strip()
368
- is_new_block = any(stripped.startswith(m) for m in severity_markers)
369
- if is_new_block and current_block:
370
- blocks.append(current_block)
371
- current_block = [line]
372
- else:
373
- current_block.append(line)
374
-
375
- if current_block:
376
- blocks.append(current_block)
377
-
378
- # If no blocks were parsed, treat the whole response as one block
379
- if not blocks or (len(blocks) == 1 and not any(
380
- any(l.strip().startswith(m) for m in severity_markers)
381
- for l in blocks[0]
382
- )):
383
- # Fallback: dump the full text as a single section
384
- doc.add_heading("Analysis Output", level=1)
385
- doc.add_paragraph(full_response)
386
- else:
387
- severity_counts = {"High": 0, "Medium": 0, "Low": 0, "Other": 0}
388
-
389
- for block_lines in blocks:
390
- if not any(l.strip() for l in block_lines):
391
- continue
392
-
393
- block_text = "\n".join(block_lines)
394
- header_line = block_lines[0].strip() if block_lines else ""
395
-
396
- # Determine severity for color
397
- color = _severity_color(block_text)
398
-
399
- # Add heading
400
- heading = doc.add_heading(level=2)
401
- heading_run = heading.add_run(
402
- header_line.lstrip("#").strip() or "Finding"
403
- )
404
- heading_run.font.color.rgb = color
405
-
406
- # Track severity counts
407
- upper = block_text.upper()
408
- if "HIGH" in upper or "🔴" in block_text or "🔺" in block_text:
409
- severity_counts["High"] += 1
410
- elif "MEDIUM" in upper or "MODERATE" in upper or "🟡" in block_text:
411
- severity_counts["Medium"] += 1
412
- elif "LOW" in upper or "MINOR" in upper or "🟢" in block_text:
413
- severity_counts["Low"] += 1
414
- else:
415
- severity_counts["Other"] += 1
416
-
417
- # Add body lines as paragraphs
418
- for body_line in block_lines[1:]:
419
- stripped_body = body_line.strip()
420
- if not stripped_body:
421
- doc.add_paragraph()
422
- continue
423
- # Detect field labels like "Document A:", "Variance:", etc.
424
- if ":" in stripped_body and stripped_body.index(":") < 30:
425
- label, _, value = stripped_body.partition(":")
426
- p = doc.add_paragraph()
427
- label_run = p.add_run(label.strip() + ": ")
428
- label_run.bold = True
429
- label_run.font.color.rgb = RGBColor(0x1F, 0x29, 0x37)
430
- p.add_run(value.strip())
431
- else:
432
- doc.add_paragraph(stripped_body)
433
-
434
- doc.add_paragraph() # spacer between blocks
435
-
436
- # ---- Summary table ----
437
- doc.add_page_break()
438
- doc.add_heading("Summary", level=1)
439
-
440
- table = doc.add_table(rows=1, cols=2)
441
- table.style = "Table Grid"
442
- hdr_cells = table.rows[0].cells
443
- hdr_cells[0].text = "Severity"
444
- hdr_cells[1].text = "Count"
445
- for cell in hdr_cells:
446
- for para in cell.paragraphs:
447
- for run in para.runs:
448
- run.bold = True
449
-
450
- severity_color_map = {
451
- "High": RGBColor(0xDC, 0x26, 0x26),
452
- "Medium": RGBColor(0xF5, 0x9E, 0x0B),
453
- "Low": RGBColor(0x16, 0xA3, 0x4A),
454
- "Other": RGBColor(0x6B, 0x72, 0x80),
455
- }
456
- for sev, count in severity_counts.items():
457
- row_cells = table.add_row().cells
458
- row_cells[0].text = sev
459
- row_cells[1].text = str(count)
460
- for para in row_cells[0].paragraphs:
461
- for run in para.runs:
462
- run.font.color.rgb = severity_color_map[sev]
463
-
464
- # ---- Disclaimer footer ----
465
- doc.add_paragraph()
466
- footer_para = doc.add_paragraph()
467
- footer_run = footer_para.add_run(
468
- "DISCLAIMER: This report is AI-generated for review purposes only. "
469
- "It does not constitute legal, financial, or investment advice. "
470
- "All outputs require professional verification."
471
- )
472
- footer_run.italic = True
473
- footer_run.font.size = Pt(8)
474
- footer_run.font.color.rgb = RGBColor(0x6B, 0x72, 0x80)
475
-
476
- # ---- Save ----
477
- doc.save(output_path)
478
-
479
- if not os.path.isfile(output_path):
480
- logger.error("DOCX file was not created at %s", output_path)
481
- return gr.File(value=None, visible=False)
482
-
483
- logger.info("DOCX report saved to %s", output_path)
484
- return gr.File(value=output_path, visible=True)
485
-
486
- except Exception as exc:
487
- logger.error("DOCX generation failed: %s", traceback.format_exc())
488
- return gr.File(value=None, visible=False)
489
-
490
-
491
- # ---------------------------------------------------------------------------
492
- # Custom CSS
493
- # ---------------------------------------------------------------------------
494
-
495
- CUSTOM_CSS = """
496
- /* ── Global reset & font ── */
497
- body, .gradio-container {
498
- background-color: #FAFBFC !important;
499
- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
500
- "Helvetica Neue", Arial, sans-serif !important;
501
- }
502
- /* ── Max-width centred container ── */
503
- .gradio-container {
504
- max-width: 1200px !important;
505
- margin: 0 auto !important;
506
- padding: 0 24px 48px 24px !important;
507
- }
508
- /* ── Hide Gradio default footer ── */
509
- footer { display: none !important; }
510
- .svelte-1ipelgc { display: none !important; }
511
- /* ── Disclaimer banner ── */
512
- #disclaimer-banner {
513
- background-color: #FEF3C7 !important;
514
- border-left: 4px solid #F59E0B !important;
515
- border-radius: 6px !important;
516
- padding: 10px 16px !important;
517
- margin-bottom: 8px !important;
518
- }
519
- #disclaimer-banner p {
520
- color: #92400E !important;
521
- font-size: 0.82rem !important;
522
- margin: 0 !important;
523
- }
524
- /* ── Header ── */
525
- #app-header {
526
- padding: 24px 0 16px 0 !important;
527
- border-bottom: 1px solid #E5E7EB !important;
528
- margin-bottom: 24px !important;
529
- }
530
- #app-title {
531
- font-size: 1.9rem !important;
532
- font-weight: 700 !important;
533
- color: #2563EB !important;
534
- margin: 0 !important;
535
- line-height: 1.2 !important;
536
- }
537
- #app-subtitle {
538
- font-size: 0.95rem !important;
539
- color: #6B7280 !important;
540
- margin: 4px 0 0 0 !important;
541
- }
542
- /* ── Upload area ── */
543
- #upload-area {
544
- border: 2px dashed #D1D5DB !important;
545
- border-radius: 12px !important;
546
- background: #FFFFFF !important;
547
- padding: 8px !important;
548
- transition: border-color 0.2s ease !important;
549
- }
550
- #upload-area:hover {
551
- border-color: #2563EB !important;
552
- }
553
- /* ── Action buttons row ── */
554
- #action-row {
555
- gap: 12px !important;
556
- margin: 20px 0 !important;
557
- }
558
- /* Base button style */
559
- #btn-memo, #btn-risk, #btn-discrepancies, #btn-lease {
560
- background-color: #FFFFFF !important;
561
- color: #1F2937 !important;
562
- border: 1.5px solid #D1D5DB !important;
563
- border-radius: 8px !important;
564
- font-weight: 500 !important;
565
- font-size: 0.9rem !important;
566
- padding: 10px 16px !important;
567
- transition: background-color 0.15s ease, border-color 0.15s ease,
568
- box-shadow 0.15s ease !important;
569
- cursor: pointer !important;
570
- }
571
- #btn-memo:hover, #btn-risk:hover,
572
- #btn-discrepancies:hover, #btn-lease:hover {
573
- background-color: #EFF6FF !important;
574
- border-color: #2563EB !important;
575
- box-shadow: 0 1px 4px rgba(37,99,235,0.15) !important;
576
- }
577
- #btn-memo:active, #btn-risk:active,
578
- #btn-discrepancies:active, #btn-lease:active {
579
- background-color: #DBEAFE !important;
580
- }
581
- /* ── Results panel ── */
582
- #results-panel {
583
- background: #FFFFFF !important;
584
- border: 1.5px solid #E5E7EB !important;
585
- border-radius: 12px !important;
586
- padding: 24px !important;
587
- min-height: 400px !important;
588
- overflow-y: auto !important;
589
- margin-top: 8px !important;
590
- }
591
- #results-panel p, #results-panel li {
592
- color: #1F2937 !important;
593
- line-height: 1.7 !important;
594
- }
595
- #results-panel h1, #results-panel h2, #results-panel h3 {
596
- color: #111827 !important;
597
- margin-top: 1.2em !important;
598
- }
599
- /* ── Download area ── */
600
- #download-area {
601
- margin-top: 16px !important;
602
- padding: 12px 16px !important;
603
- background: #F0FDF4 !important;
604
- border: 1.5px solid #86EFAC !important;
605
- border-radius: 10px !important;
606
- }
607
- /* ── Footer ── */
608
- #app-footer {
609
- text-align: center !important;
610
- color: #9CA3AF !important;
611
- font-size: 0.78rem !important;
612
- padding: 24px 0 8px 0 !important;
613
- border-top: 1px solid #F3F4F6 !important;
614
- margin-top: 32px !important;
615
- }
616
- /* ── Missing prompt warning ── */
617
- #missing-prompt-warning {
618
- background-color: #FEF2F2 !important;
619
- border-left: 4px solid #DC2626 !important;
620
- border-radius: 6px !important;
621
- padding: 10px 16px !important;
622
- margin-bottom: 12px !important;
623
- }
624
- #missing-prompt-warning p {
625
- color: #991B1B !important;
626
- font-size: 0.85rem !important;
627
- margin: 0 !important;
628
- }
629
- """
630
-
631
- # ---------------------------------------------------------------------------
632
- # Build the Gradio UI
633
- # ---------------------------------------------------------------------------
634
-
635
- def build_missing_prompt_warning() -> str:
636
- if not _MISSING_PROMPTS:
637
- return ""
638
- files = ", ".join(f"`{p}`" for p in _MISSING_PROMPTS)
639
- return (
640
- f"⚠️ **Missing prompt files detected:** {files}. "
641
- "Some analysis functions may not work correctly. "
642
- "Please ensure all files exist in the `prompts/` directory."
643
- )
644
-
645
-
646
- with gr.Blocks(title="RailNexus Value") as demo:
647
-
648
- # ── State ──────────────────────────────────────────────────────────────
649
- discrepancy_state = gr.State("") # holds full discrepancy response text
650
-
651
- # ── SECTION 1: Disclaimer banner ───────────────────────────────────────
652
- gr.HTML(
653
- """
654
- <div id="disclaimer-banner">
655
- <p>
656
- <strong>Beta</strong> — AI-generated analysis for review purposes only.
657
- Does not constitute legal, financial, or investment advice.
658
- All outputs require professional verification.
659
- </p>
660
- </div>
661
- """
662
- )
663
-
664
- # ── Missing prompt warning (only shown if files are absent) ────────────
665
- missing_warning_text = build_missing_prompt_warning()
666
- if missing_warning_text:
667
- gr.HTML(
668
- f'<div id="missing-prompt-warning"><p>{missing_warning_text}</p></div>'
669
- )
670
-
671
- # ── SECTION 2: Header ──────────────────────────────────────────────────
672
- gr.HTML(
673
- """
674
- <div id="app-header">
675
- <div id="app-title">RailNexus Value</div>
676
- <div id="app-subtitle">AI-Powered Investment Analysis</div>
677
- </div>
678
- """
679
- )
680
-
681
- # ── SECTION 3: Upload ──────────────────────────────────────────────────
682
- file_upload = gr.File(
683
- label="Upload Documents",
684
- file_types=[".pdf"],
685
- file_count="multiple",
686
- elem_id="upload-area",
687
- )
688
-
689
- # ── SECTION 4: Action buttons ──────────────────────────────────────────
690
- with gr.Row(elem_id="action-row"):
691
- btn_memo = gr.Button(
692
- "📋 Investment Memo",
693
- elem_id="btn-memo",
694
- scale=1,
695
- )
696
- btn_risk = gr.Button(
697
- "⚠️ Risk Assessment",
698
- elem_id="btn-risk",
699
- scale=1,
700
- )
701
- btn_discrepancies = gr.Button(
702
- "🔍 Key Discrepancies",
703
- elem_id="btn-discrepancies",
704
- scale=1,
705
- )
706
- btn_lease = gr.Button(
707
- "📄 Lease Abstract",
708
- elem_id="btn-lease",
709
- scale=1,
710
- )
711
-
712
- # ── SECTION 5: Results panel ───────────────────────────────────────────
713
- results_md = gr.Markdown(
714
- value="*Upload documents and select an analysis type to begin.*",
715
- elem_id="results-panel",
716
- )
717
-
718
- # ── SECTION 6: Download area ───────────────────────────────────────────
719
- download_file = gr.File(
720
- label="Download Discrepancy Report",
721
- visible=False,
722
- interactive=False,
723
- elem_id="download-area",
724
- )
725
-
726
- # ── SECTION 7: Footer ──────────────────────────────────────────────────
727
- gr.HTML(
728
- """
729
- <div id="app-footer">
730
- © 2025 RailNexus Value. For review purposes only.
731
- </div>
732
- """
733
- )
734
-
735
- # -----------------------------------------------------------------------
736
- # Event wiring
737
- # -----------------------------------------------------------------------
738
-
739
- # Shared list of all buttons (for disabling during processing)
740
- all_buttons = [btn_memo, btn_risk, btn_discrepancies, btn_lease]
741
-
742
- # Helper: returns gr.update dicts to disable / re-enable all buttons
743
- def _disable_buttons():
744
- return [gr.Button(interactive=False)] * 4
745
-
746
- def _enable_buttons():
747
- return [gr.Button(interactive=True)] * 4
748
-
749
- # ── Investment Memo ────────────────────────────────────────────────────
750
- (
751
- btn_memo.click(
752
- fn=lambda: _disable_buttons(),
753
- inputs=[],
754
- outputs=all_buttons,
755
- queue=False,
756
- )
757
- .then(
758
- fn=run_investment_memo,
759
- inputs=[file_upload],
760
- outputs=[results_md, download_file],
761
- )
762
- .then(
763
- fn=lambda: _enable_buttons(),
764
- inputs=[],
765
- outputs=all_buttons,
766
- queue=False,
767
- )
768
- )
769
-
770
- # ── Risk Assessment ────────────────────────────────────────────────────
771
- (
772
- btn_risk.click(
773
- fn=lambda: _disable_buttons(),
774
- inputs=[],
775
- outputs=all_buttons,
776
- queue=False,
777
- )
778
- .then(
779
- fn=run_risk_assessment,
780
- inputs=[file_upload],
781
- outputs=[results_md, download_file],
782
- )
783
- .then(
784
- fn=lambda: _enable_buttons(),
785
- inputs=[],
786
- outputs=all_buttons,
787
- queue=False,
788
- )
789
- )
790
-
791
- # ── Key Discrepancies (two-step: stream → docx) ────────────────────────
792
- (
793
- btn_discrepancies.click(
794
- fn=lambda: _disable_buttons(),
795
- inputs=[],
796
- outputs=all_buttons,
797
- queue=False,
798
- )
799
- .then(
800
- fn=run_discrepancy_analysis,
801
- inputs=[file_upload, discrepancy_state],
802
- outputs=[results_md, discrepancy_state],
803
- )
804
- .then(
805
- fn=generate_docx,
806
- inputs=[discrepancy_state, file_upload],
807
- outputs=[download_file],
808
- )
809
- .then(
810
- fn=lambda: _enable_buttons(),
811
- inputs=[],
812
- outputs=all_buttons,
813
- queue=False,
814
- )
815
- )
816
-
817
- # ── Lease Abstract ─────────────────────────────────────────────────────
818
- (
819
- btn_lease.click(
820
- fn=lambda: _disable_buttons(),
821
- inputs=[],
822
- outputs=all_buttons,
823
- queue=False,
824
- )
825
- .then(
826
- fn=run_lease_abstract,
827
- inputs=[file_upload],
828
- outputs=[results_md, download_file],
829
- )
830
- .then(
831
- fn=lambda: _enable_buttons(),
832
- inputs=[],
833
- outputs=all_buttons,
834
- queue=False,
835
- )
836
- )
837
-
838
-
839
- # ---------------------------------------------------------------------------
840
- # Launch
841
- # ---------------------------------------------------------------------------
842
- demo.launch(
843
- server_name="0.0.0.0",
844
- server_port=7860,
845
- ssr_mode=False,
846
- css=CUSTOM_CSS,
847
- share=False,
848
- show_error=True
849
- )