Ryan2219 commited on
Commit
20eb3d7
·
verified ·
1 Parent(s): 2ffd324

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +883 -628
app.py CHANGED
@@ -1,628 +1,883 @@
1
- """Streamlit UI for NYC Code Compliance Bot — with agent discussion panel."""
2
- from __future__ import annotations
3
-
4
- import json
5
- import logging
6
- import tempfile
7
- from pathlib import Path
8
- import os
9
- import sys
10
- import streamlit as st
11
- from PIL import Image
12
-
13
- from config import MAX_INVESTIGATION_ROUNDS
14
- from graph import compile_compliance_graph
15
- from tools.chroma_tools import warmup_collection, is_warmed_up
16
- from tools.crop_cache import CropCache
17
- from tools.image_store import ImageStore
18
- from tools.metadata_cache import MetadataState, get_cached_metadata
19
- from tools.pdf_processor import render_pages
20
-
21
- logger = logging.getLogger(__name__)
22
-
23
- # ---------------------------------------------------------------------------
24
- # Page config
25
- # ---------------------------------------------------------------------------
26
- st.set_page_config(
27
- page_title="NYC Code Compliance Bot",
28
- page_icon=":building_construction:",
29
- layout="wide",
30
- )
31
-
32
- # ---------------------------------------------------------------------------
33
- # Custom CSS for agent discussion panel
34
- # ---------------------------------------------------------------------------
35
- st.markdown("""
36
- <style>
37
- .agent-msg {
38
- padding: 8px 12px;
39
- margin: 4px 0;
40
- border-radius: 8px;
41
- font-size: 0.9em;
42
- }
43
- .agent-planner {
44
- background-color: #e3f2fd;
45
- border-left: 4px solid #1565c0;
46
- }
47
- .agent-code_analyst {
48
- background-color: #fff3e0;
49
- border-left: 4px solid #e65100;
50
- }
51
- .agent-compliance_analyst {
52
- background-color: #e8f5e9;
53
- border-left: 4px solid #2e7d32;
54
- }
55
- .agent-reviewer {
56
- background-color: #f3e5f5;
57
- border-left: 4px solid #6a1b9a;
58
- }
59
- .agent-icon {
60
- font-weight: bold;
61
- margin-right: 6px;
62
- }
63
- .agent-timestamp {
64
- color: #666;
65
- font-size: 0.8em;
66
- }
67
- </style>
68
- """, unsafe_allow_html=True)
69
-
70
- AGENT_ICONS = {
71
- "planner": "\U0001f4cb",
72
- "code_analyst": "\u2696\ufe0f",
73
- "compliance_analyst": "\U0001f50d",
74
- "reviewer": "\U0001f91d",
75
- }
76
-
77
- AGENT_LABELS = {
78
- "planner": "Planner",
79
- "code_analyst": "Code Analyst",
80
- "compliance_analyst": "Compliance Analyst",
81
- "reviewer": "Reviewer",
82
- }
83
-
84
- # ---------------------------------------------------------------------------
85
- # Session state defaults
86
- # ---------------------------------------------------------------------------
87
- if "pdf_loaded" not in st.session_state:
88
- st.session_state.pdf_loaded = False
89
- if "chat_history" not in st.session_state:
90
- st.session_state.chat_history = []
91
- if "image_store" not in st.session_state:
92
- st.session_state.image_store = None
93
- if "ingest_state" not in st.session_state:
94
- st.session_state.ingest_state = {}
95
- if "pdf_bytes" not in st.session_state:
96
- st.session_state.pdf_bytes = None
97
- if "metadata_state" not in st.session_state:
98
- st.session_state.metadata_state = MetadataState()
99
- if "crop_cache" not in st.session_state:
100
- st.session_state.crop_cache = CropCache()
101
- if "discussion_log" not in st.session_state:
102
- st.session_state.discussion_log = []
103
- if "code_report" not in st.session_state:
104
- st.session_state.code_report = ""
105
- if "code_sections" not in st.session_state:
106
- st.session_state.code_sections = []
107
- if "image_refs" not in st.session_state:
108
- st.session_state.image_refs = []
109
- if "db_ready" not in st.session_state:
110
- st.session_state.db_ready = False
111
-
112
- # ---------------------------------------------------------------------------
113
- # Startup: warm up embedding model + ChromaDB
114
- # ---------------------------------------------------------------------------
115
- if not st.session_state.db_ready:
116
- with st.status("Loading NYC Code Database...", expanded=True) as _db_status:
117
- st.write(":brain: Loading embedding model (bge-large-en-v1.5)...")
118
- st.write("_This is a one-time download (~1.3 GB) on first run._")
119
- ok = warmup_collection()
120
- if ok:
121
- st.session_state.db_ready = True
122
- _db_status.update(label="NYC Code Database ready", state="complete")
123
- else:
124
- _db_status.update(
125
- label="NYC Code Database not available — code lookup will be disabled",
126
- state="error",
127
- )
128
- st.session_state.db_ready = False
129
- if st.session_state.db_ready:
130
- st.rerun()
131
-
132
- # ---------------------------------------------------------------------------
133
- # Sidebar
134
- # ---------------------------------------------------------------------------
135
- with st.sidebar:
136
- st.title(":building_construction: NYC Code Compliance Bot")
137
- st.markdown(
138
- "Upload a construction drawing PDF and ask compliance questions. "
139
- "The system uses **agentic vision** + **NYC code database** to "
140
- "verify code compliance."
141
- )
142
-
143
- st.divider()
144
-
145
- # PDF upload
146
- uploaded_file = st.file_uploader("Upload Drawing PDF", type=["pdf"])
147
-
148
- # Default drawing button
149
- _DEFAULT_PDF = Path(__file__).parent / "NorthMaconPark.pdf"
150
- if _DEFAULT_PDF.exists() and not st.session_state.pdf_loaded:
151
- st.markdown("**— or —**")
152
- if st.button("Use Default Drawing", use_container_width=True):
153
- st.session_state._use_default_pdf = True
154
- st.rerun()
155
-
156
- st.divider()
157
-
158
- # Settings
159
- st.subheader("Settings")
160
- enable_consensus = st.checkbox(
161
- "Enable peer review (Gemini + GPT)",
162
- value=False,
163
- help="GPT reviews Gemini's compliance analysis. Slower but more thorough.",
164
- )
165
- enable_annotation = st.checkbox(
166
- "Enable annotation",
167
- value=False,
168
- help="Annotate crops with numbered highlights before analysis.",
169
- )
170
- max_rounds = st.slider(
171
- "Max investigation rounds",
172
- min_value=1,
173
- max_value=5,
174
- value=MAX_INVESTIGATION_ROUNDS,
175
- help="Maximum crop-analyze loops before forcing a final verdict.",
176
- )
177
-
178
- st.divider()
179
- st.caption("Powered by LangGraph + Gemini + GPT + ChromaDB")
180
-
181
- # ---------------------------------------------------------------------------
182
- # PDF ingestion Phase A: render pages
183
- # ---------------------------------------------------------------------------
184
- # Determine if we have a PDF to process (uploaded or default)
185
- _pending_pdf: tuple[str, bytes] | None = None
186
- if not st.session_state.pdf_loaded:
187
- if uploaded_file is not None:
188
- _pending_pdf = (uploaded_file.name, uploaded_file.getvalue())
189
- elif st.session_state.get("_use_default_pdf"):
190
- _default = Path(__file__).parent / "NorthMaconPark.pdf"
191
- if _default.exists():
192
- _pending_pdf = (_default.name, _default.read_bytes())
193
-
194
- if _pending_pdf is not None and not st.session_state.pdf_loaded:
195
- pdf_name, pdf_bytes = _pending_pdf
196
- with st.status("Converting PDF to images...", expanded=True) as status:
197
- tmp_dir = tempfile.mkdtemp(prefix="compliance_bot_")
198
- pdf_path = Path(tmp_dir) / pdf_name
199
- pdf_path.write_bytes(pdf_bytes)
200
-
201
- st.session_state.pdf_bytes = pdf_bytes
202
- st.session_state.crop_cache = CropCache()
203
-
204
- image_store = ImageStore(str(Path(tmp_dir) / "images"))
205
- st.session_state.image_store = image_store
206
- page_image_dir = str(image_store._pages_dir)
207
-
208
- # Check for cached metadata
209
- cached = get_cached_metadata(pdf_bytes)
210
- if cached is not None:
211
- st.session_state.metadata_state.set_ready(json.dumps(cached, indent=2))
212
- st.write("Page index loaded from cache")
213
-
214
- st.write("Rendering pages...")
215
- num_pages = render_pages(str(pdf_path), page_image_dir)
216
-
217
- st.session_state.ingest_state = {
218
- "pdf_path": str(pdf_path),
219
- "page_image_dir": page_image_dir,
220
- "num_pages": num_pages,
221
- }
222
- st.session_state.pdf_loaded = True
223
- st.session_state.pop("_use_default_pdf", None)
224
- st.write(f"Converted {num_pages} pages to images.")
225
- status.update(label=f"PDF ready: {num_pages} pages", state="complete")
226
- st.rerun()
227
-
228
- # ---------------------------------------------------------------------------
229
- # PDF ingestion — Phase B: generate page index
230
- # ---------------------------------------------------------------------------
231
- if st.session_state.pdf_loaded:
232
- meta = st.session_state.metadata_state
233
- if meta.status == "not_started":
234
- if st.session_state.pdf_bytes is not None:
235
- with st.expander(":page_facing_up: PDF Viewer", expanded=False):
236
- st.pdf(st.session_state.pdf_bytes, height=400)
237
-
238
- ingest = st.session_state.ingest_state
239
- num_pages = ingest["num_pages"]
240
-
241
- st.write("**Generating page index...**")
242
- progress_bar = st.progress(0, text="Analyzing pages to build searchable index...")
243
-
244
- def _index_progress(completed: int, total: int, label: str):
245
- pct = completed / total
246
- progress_bar.progress(pct, text=f"Indexing: {label} ({completed}/{total} batches)")
247
-
248
- meta.generate_sync(
249
- ingest["pdf_path"],
250
- num_pages,
251
- st.session_state.pdf_bytes,
252
- progress_callback=_index_progress,
253
- )
254
- if meta.is_ready:
255
- progress_bar.progress(1.0, text="Page index ready!")
256
- else:
257
- progress_bar.progress(1.0, text="Indexing failed — using full PDF mode")
258
- st.rerun()
259
-
260
- # ---------------------------------------------------------------------------
261
- # Main layout (pre-upload welcome)
262
- # ---------------------------------------------------------------------------
263
- if not st.session_state.pdf_loaded:
264
- _left, center, _right = st.columns([1, 2, 1])
265
- with center:
266
- st.markdown(
267
- "<h1 style='text-align: center;'>:building_construction: NYC Code Compliance Bot</h1>",
268
- unsafe_allow_html=True,
269
- )
270
- st.markdown(
271
- "<p style='text-align: center; color: grey;'>"
272
- "Upload a construction drawing PDF in the sidebar to get started.<br>"
273
- "This tool uses <b>agentic vision</b> and the <b>NYC Building Code database</b> "
274
- "to verify code compliance in your drawings."
275
- "</p>",
276
- unsafe_allow_html=True,
277
- )
278
- st.stop()
279
-
280
- # ---------------------------------------------------------------------------
281
- # PDF viewer
282
- # ---------------------------------------------------------------------------
283
- if st.session_state.pdf_bytes is not None:
284
- with st.expander(":page_facing_up: PDF Viewer", expanded=False):
285
- st.pdf(st.session_state.pdf_bytes, height=400)
286
-
287
- # ---------------------------------------------------------------------------
288
- # Three-column layout: chat | discussion | images+code
289
- # ---------------------------------------------------------------------------
290
- chat_col, discuss_col, evidence_col = st.columns([2, 2, 2])
291
-
292
- # ---------------------------------------------------------------------------
293
- # Discussion panel (agent conversation)
294
- # ---------------------------------------------------------------------------
295
- def render_discussion_log(container, discussion_log: list[dict]):
296
- """Render the agent discussion log with styled messages."""
297
- with container:
298
- for msg in discussion_log:
299
- agent = msg.get("agent", "unknown")
300
- icon = AGENT_ICONS.get(agent, "\U0001f916")
301
- label = AGENT_LABELS.get(agent, agent)
302
- css_class = f"agent-{agent}"
303
-
304
- st.markdown(
305
- f'<div class="agent-msg {css_class}">'
306
- f'<span class="agent-timestamp">[{msg.get("timestamp", "")}]</span> '
307
- f'<span class="agent-icon">{icon} {label}</span><br>'
308
- f'{msg.get("summary", "")}'
309
- f'</div>',
310
- unsafe_allow_html=True,
311
- )
312
-
313
- # ---------------------------------------------------------------------------
314
- # Chat history display
315
- # ---------------------------------------------------------------------------
316
- with chat_col:
317
- st.subheader(":speech_balloon: Chat")
318
-
319
- meta = st.session_state.metadata_state
320
- if meta.is_ready:
321
- st.caption("Page index ready — fast planning enabled")
322
- elif meta.status == "failed":
323
- st.caption("Page indexing failed — using full PDF mode")
324
-
325
- for role, content, _refs in st.session_state.chat_history:
326
- with st.chat_message(role):
327
- st.markdown(content)
328
-
329
- question = st.chat_input("Ask a compliance question about the drawing...")
330
-
331
- # ---------------------------------------------------------------------------
332
- # Discussion panel
333
- # ---------------------------------------------------------------------------
334
- with discuss_col:
335
- st.subheader(":busts_in_silhouette: Agent Discussion")
336
- discussion_container = st.container()
337
-
338
- if st.session_state.discussion_log:
339
- render_discussion_log(discussion_container, st.session_state.discussion_log)
340
- else:
341
- st.info("Agent discussions will appear here during analysis.")
342
-
343
- # ---------------------------------------------------------------------------
344
- # Evidence panel (images + code)
345
- # ---------------------------------------------------------------------------
346
- with evidence_col:
347
- st.subheader(":framed_picture: Evidence")
348
-
349
- evidence_tabs = st.tabs(["Drawing Crops", "Code Sections"])
350
-
351
- with evidence_tabs[0]:
352
- if st.session_state.image_refs:
353
- for ref in st.session_state.image_refs:
354
- try:
355
- img = Image.open(ref["path"])
356
- st.image(img, caption=ref["label"], use_container_width=True)
357
- except Exception:
358
- st.warning(f"Could not load: {ref['label']}")
359
- elif st.session_state.chat_history:
360
- st.info("No images for this question.")
361
- else:
362
- st.info("Ask a question to see drawing crops here.")
363
-
364
- with evidence_tabs[1]:
365
- if st.session_state.code_sections:
366
- for sec in st.session_state.code_sections:
367
- with st.expander(
368
- f":balance_scale: {sec.get('code_type', '?')} §{sec.get('section_full', '?')}",
369
- expanded=False,
370
- ):
371
- if sec.get("relevance"):
372
- st.caption(sec["relevance"])
373
- st.markdown(sec.get("text", "")[:1500])
374
- if st.session_state.code_report:
375
- with st.expander(":page_facing_up: Full Code Report", expanded=False):
376
- st.markdown(st.session_state.code_report[:5000])
377
- else:
378
- st.info("Code sections retrieved during analysis will appear here.")
379
-
380
-
381
- # ---------------------------------------------------------------------------
382
- # Question processing
383
- # ---------------------------------------------------------------------------
384
- if question:
385
- # Add user message to history
386
- st.session_state.chat_history.append(("user", question, []))
387
- st.session_state.discussion_log = [] # Reset discussion for new question
388
- st.session_state.code_report = "" # Reset code report for new question
389
- st.session_state.code_sections = [] # Reset code sections for new question
390
- st.session_state.image_refs = [] # Reset image refs for new question
391
-
392
- with chat_col:
393
- with st.chat_message("user"):
394
- st.markdown(question)
395
-
396
- # Build initial state
397
- ingest = st.session_state.ingest_state
398
- image_store = st.session_state.image_store
399
-
400
- meta = st.session_state.metadata_state
401
- metadata_json = meta.data_json if meta.is_ready else ""
402
-
403
- question_state = {
404
- "messages": [],
405
- "question": question,
406
- "pdf_path": ingest.get("pdf_path", ""),
407
- "page_image_dir": ingest.get("page_image_dir", ""),
408
- "num_pages": ingest.get("num_pages", 0),
409
- "page_metadata_json": metadata_json,
410
- "legend_pages": [],
411
- "target_pages": [],
412
- "crop_tasks": [],
413
- "code_queries": [],
414
- "image_refs": [],
415
- "code_sections": [],
416
- "code_report": "",
417
- "code_chapters_fetched": [],
418
- "compliance_analysis": "",
419
- "reviewer_analysis": "",
420
- "final_verdict": "",
421
- "discussion_log": [],
422
- "additional_crop_tasks": [],
423
- "additional_code_queries": [],
424
- "needs_more_investigation": False,
425
- "investigation_round": 0,
426
- "max_rounds": max_rounds,
427
- "enable_consensus": enable_consensus,
428
- "enable_annotation": enable_annotation,
429
- "status_message": [],
430
- }
431
-
432
- # ------------------------------------------------------------------
433
- # Live progress
434
- # ------------------------------------------------------------------
435
- crop_cache = st.session_state.crop_cache
436
-
437
- with evidence_col:
438
- with evidence_tabs[0]:
439
- crop_counter_placeholder = st.empty()
440
- crop_image_container = st.container()
441
-
442
- def on_crop_progress(
443
- completed_ref, crop_task, source: str, completed_count: int, total_count: int,
444
- ) -> None:
445
- source_tag = " (cached)" if source == "cached" else ""
446
- crop_counter_placeholder.markdown(
447
- f"**Crop {completed_count}/{total_count}**{source_tag} \n"
448
- f"Latest: *{crop_task.get('label', 'Crop')}*"
449
- )
450
- with crop_image_container:
451
- try:
452
- img = Image.open(completed_ref["path"])
453
- caption = completed_ref["label"]
454
- if source == "cached":
455
- caption += " (cached)"
456
- st.image(img, caption=caption, use_container_width=True)
457
- except Exception:
458
- st.warning(f"Could not load: {completed_ref['label']}")
459
-
460
- # Compile graph
461
- compliance_graph = compile_compliance_graph(image_store, crop_cache, on_crop_progress)
462
-
463
- # Node progress labels
464
- PROGRESS_LABELS = {
465
- "compliance_planner": "Planning investigation...",
466
- "execute_crops": "Cropping drawing images...",
467
- "annotate_crops": "Annotating crops...",
468
- "initial_code_lookup": "Searching NYC code database...",
469
- "compliance_analyst": "Analyzing compliance...",
470
- "targeted_code_lookup": "Follow-up code search...",
471
- "deliberation": "Running peer review...",
472
- "final_verdict": "Synthesizing verdict...",
473
- }
474
-
475
- with chat_col:
476
- with st.status("Investigating compliance...", expanded=True) as status:
477
- all_image_refs: list[dict] = []
478
- all_discussion: list[dict] = []
479
- final_verdict_text = ""
480
- code_report_text = ""
481
-
482
- st.write(PROGRESS_LABELS["compliance_planner"])
483
-
484
- # Placeholder for parallel-branch status (updated after planner completes)
485
- parallel_status = st.empty()
486
-
487
- for event in compliance_graph.stream(question_state, stream_mode="updates"):
488
- node_name = list(event.keys())[0]
489
- update = event[node_name]
490
-
491
- # Status messages (list, since parallel nodes can both emit)
492
- status_msgs = update.get("status_message", [])
493
- for status_msg in status_msgs:
494
- if status_msg:
495
- st.write(f":white_check_mark: {status_msg}")
496
-
497
- # Collect discussion messages
498
- new_discussion = update.get("discussion_log", [])
499
- if new_discussion:
500
- all_discussion.extend(new_discussion)
501
- st.session_state.discussion_log = all_discussion
502
- # Re-render discussion panel
503
- render_discussion_log(discussion_container, all_discussion)
504
-
505
- # Node-specific handling
506
- if node_name == "compliance_planner":
507
- target_pages = update.get("target_pages", [])
508
- crop_tasks = update.get("crop_tasks", [])
509
- code_queries = update.get("code_queries", [])
510
-
511
- with st.expander(":clipboard: Investigation Plan", expanded=True):
512
- if target_pages:
513
- st.markdown(f"**Target pages:** {', '.join(str(p + 1) for p in target_pages)}")
514
- if crop_tasks:
515
- st.markdown(f"**Image crops ({len(crop_tasks)}):**")
516
- for i, task in enumerate(crop_tasks, 1):
517
- display_page = task.get("page_num", 0) + 1
518
- st.markdown(f" {i}. {task.get('label', 'Crop')} (p.{display_page})")
519
- if code_queries:
520
- st.markdown(f"**Code queries ({len(code_queries)}):**")
521
- for i, q in enumerate(code_queries, 1):
522
- st.markdown(f" {i}. [{q.get('focus_area', '?')}] {q.get('query', '')[:80]}...")
523
-
524
- if crop_tasks:
525
- crop_counter_placeholder.markdown(f"**Crop 0/{len(crop_tasks)}** starting...")
526
-
527
- # Show parallel execution message (this appears while both branches run)
528
- parallel_status.info(
529
- ":arrows_counterclockwise: Running in parallel: "
530
- f"**Cropping {len(crop_tasks)} images** + "
531
- f"**Searching {len(code_queries)} code queries**. "
532
- "This may take 30-60 seconds..."
533
- )
534
-
535
- elif node_name in ("initial_code_lookup", "execute_crops"):
536
- # Clear the parallel status once a branch finishes
537
- parallel_status.empty()
538
-
539
- if node_name in ("initial_code_lookup", "targeted_code_lookup"):
540
- report = update.get("code_report", "")
541
- new_sections = update.get("code_sections", [])
542
- if report:
543
- code_report_text = report
544
- st.session_state.code_report = report
545
- if new_sections:
546
- st.session_state.code_sections.extend(new_sections)
547
- # Render each new section in the evidence panel in real-time
548
- with evidence_col:
549
- with evidence_tabs[1]:
550
- for sec in new_sections:
551
- with st.expander(
552
- f":balance_scale: {sec.get('code_type', '?')} "
553
- f"§{sec.get('section_full', '?')}",
554
- expanded=False,
555
- ):
556
- if sec.get("relevance"):
557
- st.caption(sec["relevance"])
558
- st.markdown(sec.get("text", "")[:1500])
559
-
560
- elif node_name == "compliance_analyst":
561
- analysis = update.get("compliance_analysis", "")
562
- needs_more = update.get("needs_more_investigation", False)
563
- round_num = update.get("investigation_round", 1)
564
-
565
- if analysis:
566
- label = f":mag: Compliance Analysis (Round {round_num})"
567
- if needs_more:
568
- label += " — requesting more evidence"
569
- with st.expander(label, expanded=False):
570
- st.markdown(analysis[:5000])
571
-
572
- elif node_name == "deliberation":
573
- review = update.get("reviewer_analysis", "")
574
- if review:
575
- with st.expander(":handshake: Peer Review", expanded=False):
576
- st.markdown(review[:3000])
577
-
578
- # Collect images persist to session state and render in evidence panel
579
- new_refs = update.get("image_refs", [])
580
- if new_refs:
581
- all_image_refs.extend(new_refs)
582
- st.session_state.image_refs.extend(new_refs)
583
- # Render each new crop in the evidence panel in real-time
584
- with evidence_col:
585
- with evidence_tabs[0]:
586
- for ref in new_refs:
587
- try:
588
- img = Image.open(ref["path"])
589
- st.image(img, caption=ref["label"], use_container_width=True)
590
- except Exception:
591
- st.warning(f"Could not load: {ref['label']}")
592
-
593
- # Capture final verdict
594
- if "final_verdict" in update and update["final_verdict"]:
595
- final_verdict_text = update["final_verdict"]
596
-
597
- # Show next step label
598
- if node_name in PROGRESS_LABELS:
599
- next_labels = {
600
- "compliance_planner": ["execute_crops", "initial_code_lookup"],
601
- "execute_crops": ["compliance_analyst"],
602
- "annotate_crops": ["compliance_analyst"],
603
- "initial_code_lookup": ["compliance_analyst"],
604
- "compliance_analyst": ["final_verdict"],
605
- "targeted_code_lookup": ["compliance_analyst"],
606
- "deliberation": ["final_verdict"],
607
- }
608
- for next_node in next_labels.get(node_name, []):
609
- if next_node in PROGRESS_LABELS:
610
- st.write(PROGRESS_LABELS[next_node])
611
-
612
- if crop_cache.size > 0:
613
- st.caption(f":file_folder: {crop_cache.stats}")
614
- status.update(label="Compliance investigation complete", state="complete")
615
-
616
- # Display final verdict
617
- if final_verdict_text:
618
- with chat_col:
619
- with st.chat_message("assistant"):
620
- st.markdown(final_verdict_text)
621
-
622
- st.session_state.chat_history[-1] = ("user", question, [])
623
- st.session_state.chat_history.append(("assistant", final_verdict_text, all_image_refs))
624
- else:
625
- with chat_col:
626
- st.error("No verdict was generated. Please try again.")
627
-
628
- st.rerun()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Streamlit UI for NYC Code Compliance Bot — with agent discussion panel."""
2
+ from __future__ import annotations
3
+
4
+ import base64
5
+ import hashlib
6
+ import hmac
7
+ import json
8
+ import logging
9
+ import os
10
+ import tempfile
11
+ import time
12
+ from pathlib import Path
13
+
14
+ import pandas as pd
15
+ import requests
16
+ import streamlit as st
17
+ from dotenv import load_dotenv
18
+ from huggingface_hub import HfApi, hf_hub_download
19
+ from huggingface_hub.utils import EntryNotFoundError
20
+ from PIL import Image
21
+
22
+ from config import MAX_INVESTIGATION_ROUNDS
23
+ from graph import compile_compliance_graph
24
+ from tools.chroma_tools import warmup_collection, is_warmed_up
25
+ from tools.crop_cache import CropCache
26
+ from tools.image_store import ImageStore
27
+ from tools.metadata_cache import MetadataState, get_cached_metadata
28
+ from tools.pdf_processor import render_pages
29
+
30
+ load_dotenv()
31
+
32
+ logger = logging.getLogger(__name__)
33
+
34
+ # =============================================================================
35
+ # HF OAuth + Usage Quota Configuration
36
+ # =============================================================================
37
+
38
+ USAGE_DATASET_REPO = "NYSERDA-CRE-Working-Group/nyserda_demo_useage_store"
39
+ USAGE_FILENAME = "usage.csv"
40
+ MAX_RUNS_PER_USER = 10
41
+ HF_TOKEN = os.environ.get("HF_TOKEN")
42
+
43
+ OAUTH_CLIENT_ID = os.environ.get("OAUTH_CLIENT_ID")
44
+ OAUTH_CLIENT_SECRET = os.environ.get("OAUTH_CLIENT_SECRET")
45
+ OPENID_PROVIDER_URL = os.environ.get("OPENID_PROVIDER_URL", "https://huggingface.co")
46
+ SPACE_HOST = os.environ.get("SPACE_HOST", "")
47
+
48
+ _hf_api = HfApi(token=HF_TOKEN) if HF_TOKEN else None
49
+
50
+
51
+ # ---------------------------------------------------------------------------
52
+ # OAuth helpers
53
+ # ---------------------------------------------------------------------------
54
+
55
+ def _get_oauth_state() -> str:
56
+ """Generate a deterministic OAuth state string for CSRF protection."""
57
+ secret = (OAUTH_CLIENT_SECRET or "fallback-secret").encode()
58
+ return hmac.new(secret, b"hf-oauth-state", hashlib.sha256).hexdigest()[:32]
59
+
60
+
61
+ def _get_redirect_uri() -> str:
62
+ """Build the OAuth redirect URI pointing back to this Space."""
63
+ if SPACE_HOST:
64
+ return f"https://{SPACE_HOST}"
65
+ return "http://localhost:7860"
66
+
67
+
68
+ def _exchange_code_for_user(code: str) -> str | None:
69
+ """Exchange the OAuth authorization code for an access token, then fetch username."""
70
+ if not OAUTH_CLIENT_ID or not OAUTH_CLIENT_SECRET:
71
+ st.error("OAuth is not configured. Set hf_oauth: true in your Space's README.md")
72
+ return None
73
+
74
+ redirect_uri = _get_redirect_uri()
75
+ token_url = f"{OPENID_PROVIDER_URL}/oauth/token"
76
+ credentials = base64.b64encode(
77
+ f"{OAUTH_CLIENT_ID}:{OAUTH_CLIENT_SECRET}".encode()
78
+ ).decode()
79
+
80
+ try:
81
+ resp = requests.post(
82
+ token_url,
83
+ headers={"Authorization": f"Basic {credentials}"},
84
+ data={
85
+ "grant_type": "authorization_code",
86
+ "code": code,
87
+ "redirect_uri": redirect_uri,
88
+ "client_id": OAUTH_CLIENT_ID,
89
+ },
90
+ timeout=10,
91
+ )
92
+ resp.raise_for_status()
93
+ token_data = resp.json()
94
+ except Exception as e:
95
+ st.error(f"Token exchange failed: {e}")
96
+ return None
97
+
98
+ access_token = token_data.get("access_token")
99
+ if not access_token:
100
+ st.error("No access token in OAuth response.")
101
+ return None
102
+
103
+ try:
104
+ userinfo_resp = requests.get(
105
+ f"{OPENID_PROVIDER_URL}/oauth/userinfo",
106
+ headers={"Authorization": f"Bearer {access_token}"},
107
+ timeout=10,
108
+ )
109
+ userinfo_resp.raise_for_status()
110
+ userinfo = userinfo_resp.json()
111
+ except Exception as e:
112
+ st.error(f"Failed to fetch user info: {e}")
113
+ return None
114
+
115
+ username = userinfo.get("preferred_username") or userinfo.get("sub")
116
+ if username:
117
+ return username.strip().lower()
118
+ return None
119
+
120
+
121
+ def get_hf_user() -> str | None:
122
+ """Check if user is logged in via HF OAuth (authorization code flow)."""
123
+ if "hf_user" in st.session_state:
124
+ return st.session_state["hf_user"]
125
+
126
+ params = st.query_params
127
+ code = params.get("code")
128
+ returned_state = params.get("state")
129
+
130
+ if code:
131
+ expected_state = _get_oauth_state()
132
+ if returned_state == expected_state:
133
+ user = _exchange_code_for_user(code)
134
+ if user:
135
+ st.session_state["hf_user"] = user
136
+ st.query_params.clear()
137
+ st.rerun()
138
+ else:
139
+ st.error("OAuth login failed could not retrieve user info.")
140
+ st.query_params.clear()
141
+ else:
142
+ st.error("OAuth state mismatch — please try signing in again.")
143
+ st.query_params.clear()
144
+
145
+ return None
146
+
147
+
148
+ def login_button():
149
+ """Show a 'Sign in with Hugging Face' button that starts the OAuth flow."""
150
+ if not OAUTH_CLIENT_ID:
151
+ st.error(
152
+ "OAuth is not configured for this Space. "
153
+ "Add `hf_oauth: true` to your README.md metadata."
154
+ )
155
+ return
156
+
157
+ if st.button("🤗 Sign in with Hugging Face", use_container_width=True, type="primary"):
158
+ state = _get_oauth_state()
159
+ redirect_uri = _get_redirect_uri()
160
+ auth_url = (
161
+ f"{OPENID_PROVIDER_URL}/oauth/authorize"
162
+ f"?client_id={OAUTH_CLIENT_ID}"
163
+ f"&redirect_uri={redirect_uri}"
164
+ f"&scope=openid%20profile"
165
+ f"&response_type=code"
166
+ f"&state={state}"
167
+ )
168
+ st.markdown(
169
+ f'<meta http-equiv="refresh" content="0;url={auth_url}">',
170
+ unsafe_allow_html=True,
171
+ )
172
+ st.stop()
173
+
174
+
175
+ # ---------------------------------------------------------------------------
176
+ # Usage quota helpers
177
+ # ---------------------------------------------------------------------------
178
+
179
+ def _load_usage_df() -> pd.DataFrame:
180
+ """Load the usage CSV from HF dataset repo."""
181
+ if not _hf_api or not USAGE_DATASET_REPO:
182
+ return pd.DataFrame(columns=["user_id", "runs", "first_seen", "last_seen"])
183
+ try:
184
+ local_path = hf_hub_download(
185
+ repo_id=USAGE_DATASET_REPO,
186
+ repo_type="dataset",
187
+ filename=USAGE_FILENAME,
188
+ token=HF_TOKEN,
189
+ )
190
+ return pd.read_csv(local_path)
191
+ except EntryNotFoundError:
192
+ return pd.DataFrame(columns=["user_id", "runs", "first_seen", "last_seen"])
193
+
194
+
195
+ def _save_usage_df(df: pd.DataFrame, commit_message: str) -> None:
196
+ """Save the usage CSV back to HF dataset repo."""
197
+ if not _hf_api or not USAGE_DATASET_REPO:
198
+ return
199
+ tmp_path = "/tmp/usage.csv"
200
+ df.to_csv(tmp_path, index=False)
201
+ _hf_api.upload_file(
202
+ path_or_fileobj=tmp_path,
203
+ path_in_repo=USAGE_FILENAME,
204
+ repo_id=USAGE_DATASET_REPO,
205
+ repo_type="dataset",
206
+ commit_message=commit_message,
207
+ )
208
+
209
+
210
+ def check_and_increment_quota(user_id: str) -> tuple[bool, int]:
211
+ """Check if user has remaining quota and increment usage.
212
+
213
+ Returns (allowed: bool, remaining_runs: int).
214
+ If USAGE_DATASET_REPO is not configured, always allows (unlimited).
215
+ """
216
+ if not USAGE_DATASET_REPO:
217
+ return True, 999
218
+
219
+ now = int(time.time())
220
+ df = _load_usage_df()
221
+
222
+ if df.empty or (df["user_id"] == user_id).sum() == 0:
223
+ runs = 0
224
+ if runs >= MAX_RUNS_PER_USER:
225
+ return False, 0
226
+ new_row = {
227
+ "user_id": user_id,
228
+ "runs": 1,
229
+ "first_seen": now,
230
+ "last_seen": now,
231
+ }
232
+ df = pd.concat([df, pd.DataFrame([new_row])], ignore_index=True)
233
+ _save_usage_df(df, commit_message=f"usage: increment {user_id} to 1")
234
+ return True, MAX_RUNS_PER_USER - 1
235
+
236
+ idx = df.index[df["user_id"] == user_id][0]
237
+ runs = int(df.loc[idx, "runs"])
238
+
239
+ if runs >= MAX_RUNS_PER_USER:
240
+ return False, 0
241
+
242
+ runs += 1
243
+ df.loc[idx, "runs"] = runs
244
+ df.loc[idx, "last_seen"] = now
245
+
246
+ _save_usage_df(df, commit_message=f"usage: increment {user_id} to {runs}")
247
+ return True, MAX_RUNS_PER_USER - runs
248
+
249
+
250
+ # ---------------------------------------------------------------------------
251
+ # Page config
252
+ # ---------------------------------------------------------------------------
253
+ st.set_page_config(
254
+ page_title="NYC Code Compliance Bot",
255
+ page_icon=":building_construction:",
256
+ layout="wide",
257
+ )
258
+
259
+ # ---------------------------------------------------------------------------
260
+ # Authentication gate — must sign in before using the app
261
+ # ---------------------------------------------------------------------------
262
+ uid = get_hf_user()
263
+ if not uid:
264
+ _left, center, _right = st.columns([1, 2, 1])
265
+ with center:
266
+ st.markdown(
267
+ "<h1 style='text-align: center;'>🏗️ NYC Code Compliance Bot</h1>",
268
+ unsafe_allow_html=True,
269
+ )
270
+ st.markdown(
271
+ "<p style='text-align: center; color: grey;'>"
272
+ "Sign in with your Hugging Face account to get started."
273
+ "</p>",
274
+ unsafe_allow_html=True,
275
+ )
276
+ login_button()
277
+ st.stop()
278
+
279
+ # ---------------------------------------------------------------------------
280
+ # Custom CSS for agent discussion panel
281
+ # ---------------------------------------------------------------------------
282
+ st.markdown("""
283
+ <style>
284
+ .agent-msg {
285
+ padding: 8px 12px;
286
+ margin: 4px 0;
287
+ border-radius: 8px;
288
+ font-size: 0.9em;
289
+ }
290
+ .agent-planner {
291
+ background-color: #e3f2fd;
292
+ border-left: 4px solid #1565c0;
293
+ }
294
+ .agent-code_analyst {
295
+ background-color: #fff3e0;
296
+ border-left: 4px solid #e65100;
297
+ }
298
+ .agent-compliance_analyst {
299
+ background-color: #e8f5e9;
300
+ border-left: 4px solid #2e7d32;
301
+ }
302
+ .agent-reviewer {
303
+ background-color: #f3e5f5;
304
+ border-left: 4px solid #6a1b9a;
305
+ }
306
+ .agent-icon {
307
+ font-weight: bold;
308
+ margin-right: 6px;
309
+ }
310
+ .agent-timestamp {
311
+ color: #666;
312
+ font-size: 0.8em;
313
+ }
314
+ </style>
315
+ """, unsafe_allow_html=True)
316
+
317
+ AGENT_ICONS = {
318
+ "planner": "\U0001f4cb",
319
+ "code_analyst": "\u2696\ufe0f",
320
+ "compliance_analyst": "\U0001f50d",
321
+ "reviewer": "\U0001f91d",
322
+ }
323
+
324
+ AGENT_LABELS = {
325
+ "planner": "Planner",
326
+ "code_analyst": "Code Analyst",
327
+ "compliance_analyst": "Compliance Analyst",
328
+ "reviewer": "Reviewer",
329
+ }
330
+
331
+ # ---------------------------------------------------------------------------
332
+ # Session state defaults
333
+ # ---------------------------------------------------------------------------
334
+ if "pdf_loaded" not in st.session_state:
335
+ st.session_state.pdf_loaded = False
336
+ if "chat_history" not in st.session_state:
337
+ st.session_state.chat_history = []
338
+ if "image_store" not in st.session_state:
339
+ st.session_state.image_store = None
340
+ if "ingest_state" not in st.session_state:
341
+ st.session_state.ingest_state = {}
342
+ if "pdf_bytes" not in st.session_state:
343
+ st.session_state.pdf_bytes = None
344
+ if "metadata_state" not in st.session_state:
345
+ st.session_state.metadata_state = MetadataState()
346
+ if "crop_cache" not in st.session_state:
347
+ st.session_state.crop_cache = CropCache()
348
+ if "discussion_log" not in st.session_state:
349
+ st.session_state.discussion_log = []
350
+ if "code_report" not in st.session_state:
351
+ st.session_state.code_report = ""
352
+ if "code_sections" not in st.session_state:
353
+ st.session_state.code_sections = []
354
+ if "image_refs" not in st.session_state:
355
+ st.session_state.image_refs = []
356
+ if "db_ready" not in st.session_state:
357
+ st.session_state.db_ready = False
358
+
359
+ # ---------------------------------------------------------------------------
360
+ # Startup: warm up embedding model + ChromaDB
361
+ # ---------------------------------------------------------------------------
362
+ if not st.session_state.db_ready:
363
+ with st.status("Loading NYC Code Database...", expanded=True) as _db_status:
364
+ st.write(":brain: Loading embedding model (bge-large-en-v1.5)...")
365
+ st.write("_This is a one-time download (~1.3 GB) on first run._")
366
+ ok = warmup_collection()
367
+ if ok:
368
+ st.session_state.db_ready = True
369
+ _db_status.update(label="NYC Code Database ready", state="complete")
370
+ else:
371
+ _db_status.update(
372
+ label="NYC Code Database not available — code lookup will be disabled",
373
+ state="error",
374
+ )
375
+ st.session_state.db_ready = False
376
+ if st.session_state.db_ready:
377
+ st.rerun()
378
+
379
+ # ---------------------------------------------------------------------------
380
+ # Sidebar
381
+ # ---------------------------------------------------------------------------
382
+ with st.sidebar:
383
+ st.title(":building_construction: NYC Code Compliance Bot")
384
+ st.markdown(
385
+ "Upload a construction drawing PDF and ask compliance questions. "
386
+ "The system uses **agentic vision** + **NYC code database** to "
387
+ "verify code compliance."
388
+ )
389
+
390
+ st.divider()
391
+
392
+ # PDF upload
393
+ uploaded_file = st.file_uploader("Upload Drawing PDF", type=["pdf"])
394
+
395
+ # Default drawing button
396
+ _DEFAULT_PDF = Path(__file__).parent / "NorthMaconPark.pdf"
397
+ if _DEFAULT_PDF.exists() and not st.session_state.pdf_loaded:
398
+ st.markdown("**— or —**")
399
+ if st.button("Use Default Drawing", use_container_width=True):
400
+ st.session_state._use_default_pdf = True
401
+ st.rerun()
402
+
403
+ st.divider()
404
+
405
+ # Settings
406
+ st.subheader("Settings")
407
+ enable_consensus = st.checkbox(
408
+ "Enable peer review (Gemini + GPT)",
409
+ value=False,
410
+ help="GPT reviews Gemini's compliance analysis. Slower but more thorough.",
411
+ )
412
+ enable_annotation = st.checkbox(
413
+ "Enable annotation",
414
+ value=False,
415
+ help="Annotate crops with numbered highlights before analysis.",
416
+ )
417
+ max_rounds = st.slider(
418
+ "Max investigation rounds",
419
+ min_value=1,
420
+ max_value=5,
421
+ value=MAX_INVESTIGATION_ROUNDS,
422
+ help="Maximum crop-analyze loops before forcing a final verdict.",
423
+ )
424
+
425
+ st.divider()
426
+
427
+ # --- User info + sign out ---
428
+ st.caption(f"Signed in as: **{uid}**")
429
+ if st.button("Sign out", use_container_width=True):
430
+ st.session_state.pop("hf_user", None)
431
+ st.rerun()
432
+
433
+ st.divider()
434
+ st.caption("Powered by LangGraph + Gemini + GPT + ChromaDB")
435
+
436
+ # ---------------------------------------------------------------------------
437
+ # PDF ingestion — Phase A: render pages
438
+ # ---------------------------------------------------------------------------
439
+ _pending_pdf: tuple[str, bytes] | None = None
440
+ if not st.session_state.pdf_loaded:
441
+ if uploaded_file is not None:
442
+ _pending_pdf = (uploaded_file.name, uploaded_file.getvalue())
443
+ elif st.session_state.get("_use_default_pdf"):
444
+ _default = Path(__file__).parent / "NorthMaconPark.pdf"
445
+ if _default.exists():
446
+ _pending_pdf = (_default.name, _default.read_bytes())
447
+
448
+ if _pending_pdf is not None and not st.session_state.pdf_loaded:
449
+ pdf_name, pdf_bytes = _pending_pdf
450
+ with st.status("Converting PDF to images...", expanded=True) as status:
451
+ tmp_dir = tempfile.mkdtemp(prefix="compliance_bot_")
452
+ pdf_path = Path(tmp_dir) / pdf_name
453
+ pdf_path.write_bytes(pdf_bytes)
454
+
455
+ st.session_state.pdf_bytes = pdf_bytes
456
+ st.session_state.crop_cache = CropCache()
457
+
458
+ image_store = ImageStore(str(Path(tmp_dir) / "images"))
459
+ st.session_state.image_store = image_store
460
+ page_image_dir = str(image_store._pages_dir)
461
+
462
+ cached = get_cached_metadata(pdf_bytes)
463
+ if cached is not None:
464
+ st.session_state.metadata_state.set_ready(json.dumps(cached, indent=2))
465
+ st.write("Page index loaded from cache")
466
+
467
+ st.write("Rendering pages...")
468
+ num_pages = render_pages(str(pdf_path), page_image_dir)
469
+
470
+ st.session_state.ingest_state = {
471
+ "pdf_path": str(pdf_path),
472
+ "page_image_dir": page_image_dir,
473
+ "num_pages": num_pages,
474
+ }
475
+ st.session_state.pdf_loaded = True
476
+ st.session_state.pop("_use_default_pdf", None)
477
+ st.write(f"Converted {num_pages} pages to images.")
478
+ status.update(label=f"PDF ready: {num_pages} pages", state="complete")
479
+ st.rerun()
480
+
481
+ # ---------------------------------------------------------------------------
482
+ # PDF ingestion — Phase B: generate page index
483
+ # ---------------------------------------------------------------------------
484
+ if st.session_state.pdf_loaded:
485
+ meta = st.session_state.metadata_state
486
+ if meta.status == "not_started":
487
+ if st.session_state.pdf_bytes is not None:
488
+ with st.expander(":page_facing_up: PDF Viewer", expanded=False):
489
+ st.pdf(st.session_state.pdf_bytes, height=400)
490
+
491
+ ingest = st.session_state.ingest_state
492
+ num_pages = ingest["num_pages"]
493
+
494
+ st.write("**Generating page index...**")
495
+ progress_bar = st.progress(0, text="Analyzing pages to build searchable index...")
496
+
497
+ def _index_progress(completed: int, total: int, label: str):
498
+ pct = completed / total
499
+ progress_bar.progress(pct, text=f"Indexing: {label} ({completed}/{total} batches)")
500
+
501
+ meta.generate_sync(
502
+ ingest["pdf_path"],
503
+ num_pages,
504
+ st.session_state.pdf_bytes,
505
+ progress_callback=_index_progress,
506
+ )
507
+ if meta.is_ready:
508
+ progress_bar.progress(1.0, text="Page index ready!")
509
+ else:
510
+ progress_bar.progress(1.0, text="Indexing failed — using full PDF mode")
511
+ st.rerun()
512
+
513
+ # ---------------------------------------------------------------------------
514
+ # Main layout (pre-upload welcome)
515
+ # ---------------------------------------------------------------------------
516
+ if not st.session_state.pdf_loaded:
517
+ _left, center, _right = st.columns([1, 2, 1])
518
+ with center:
519
+ st.markdown(
520
+ "<h1 style='text-align: center;'>🏗️ NYC Code Compliance Bot</h1>",
521
+ unsafe_allow_html=True,
522
+ )
523
+ st.markdown(
524
+ "<p style='text-align: center; color: grey;'>"
525
+ "Upload a construction drawing PDF in the sidebar to get started.<br>"
526
+ "This tool uses <b>agentic vision</b> and the <b>NYC Building Code database</b> "
527
+ "to verify code compliance in your drawings."
528
+ "</p>",
529
+ unsafe_allow_html=True,
530
+ )
531
+ st.stop()
532
+
533
+ # ---------------------------------------------------------------------------
534
+ # PDF viewer
535
+ # ---------------------------------------------------------------------------
536
+ if st.session_state.pdf_bytes is not None:
537
+ with st.expander(":page_facing_up: PDF Viewer", expanded=False):
538
+ st.pdf(st.session_state.pdf_bytes, height=400)
539
+
540
+ # ---------------------------------------------------------------------------
541
+ # Three-column layout: chat | discussion | images+code
542
+ # ---------------------------------------------------------------------------
543
+ chat_col, discuss_col, evidence_col = st.columns([2, 2, 2])
544
+
545
+ # ---------------------------------------------------------------------------
546
+ # Discussion panel (agent conversation)
547
+ # ---------------------------------------------------------------------------
548
+ def render_discussion_log(container, discussion_log: list[dict]):
549
+ """Render the agent discussion log with styled messages."""
550
+ with container:
551
+ for msg in discussion_log:
552
+ agent = msg.get("agent", "unknown")
553
+ icon = AGENT_ICONS.get(agent, "\U0001f916")
554
+ label = AGENT_LABELS.get(agent, agent)
555
+ css_class = f"agent-{agent}"
556
+
557
+ st.markdown(
558
+ f'<div class="agent-msg {css_class}">'
559
+ f'<span class="agent-timestamp">[{msg.get("timestamp", "")}]</span> '
560
+ f'<span class="agent-icon">{icon} {label}</span><br>'
561
+ f'{msg.get("summary", "")}'
562
+ f'</div>',
563
+ unsafe_allow_html=True,
564
+ )
565
+
566
+ # ---------------------------------------------------------------------------
567
+ # Chat history display
568
+ # ---------------------------------------------------------------------------
569
+ with chat_col:
570
+ st.subheader(":speech_balloon: Chat")
571
+
572
+ meta = st.session_state.metadata_state
573
+ if meta.is_ready:
574
+ st.caption("Page index ready — fast planning enabled")
575
+ elif meta.status == "failed":
576
+ st.caption("Page indexing failed — using full PDF mode")
577
+
578
+ for role, content, _refs in st.session_state.chat_history:
579
+ with st.chat_message(role):
580
+ st.markdown(content)
581
+
582
+ question = st.chat_input("Ask a compliance question about the drawing...")
583
+
584
+ # ---------------------------------------------------------------------------
585
+ # Discussion panel
586
+ # ---------------------------------------------------------------------------
587
+ with discuss_col:
588
+ st.subheader(":busts_in_silhouette: Agent Discussion")
589
+ discussion_container = st.container()
590
+
591
+ if st.session_state.discussion_log:
592
+ render_discussion_log(discussion_container, st.session_state.discussion_log)
593
+ else:
594
+ st.info("Agent discussions will appear here during analysis.")
595
+
596
+ # ---------------------------------------------------------------------------
597
+ # Evidence panel (images + code)
598
+ # ---------------------------------------------------------------------------
599
+ with evidence_col:
600
+ st.subheader(":framed_picture: Evidence")
601
+
602
+ evidence_tabs = st.tabs(["Drawing Crops", "Code Sections"])
603
+
604
+ with evidence_tabs[0]:
605
+ if st.session_state.image_refs:
606
+ for ref in st.session_state.image_refs:
607
+ try:
608
+ img = Image.open(ref["path"])
609
+ st.image(img, caption=ref["label"], use_container_width=True)
610
+ except Exception:
611
+ st.warning(f"Could not load: {ref['label']}")
612
+ elif st.session_state.chat_history:
613
+ st.info("No images for this question.")
614
+ else:
615
+ st.info("Ask a question to see drawing crops here.")
616
+
617
+ with evidence_tabs[1]:
618
+ if st.session_state.code_sections:
619
+ for sec in st.session_state.code_sections:
620
+ with st.expander(
621
+ f":balance_scale: {sec.get('code_type', '?')} §{sec.get('section_full', '?')}",
622
+ expanded=False,
623
+ ):
624
+ if sec.get("relevance"):
625
+ st.caption(sec["relevance"])
626
+ st.markdown(sec.get("text", "")[:1500])
627
+ if st.session_state.code_report:
628
+ with st.expander(":page_facing_up: Full Code Report", expanded=False):
629
+ st.markdown(st.session_state.code_report[:5000])
630
+ else:
631
+ st.info("Code sections retrieved during analysis will appear here.")
632
+
633
+
634
+ # ---------------------------------------------------------------------------
635
+ # Question processing
636
+ # ---------------------------------------------------------------------------
637
+ if question:
638
+ # === QUOTA CHECK ===
639
+ allowed, remaining = check_and_increment_quota(uid)
640
+ if not allowed:
641
+ with chat_col:
642
+ st.error(
643
+ f"Usage limit reached: {MAX_RUNS_PER_USER} queries per user. "
644
+ "Please contact the admin for additional access."
645
+ )
646
+ st.stop()
647
+
648
+ if remaining <= 2:
649
+ with chat_col:
650
+ st.warning(f"⚠️ Only {remaining} query(ies) left!")
651
+ # === END QUOTA CHECK ===
652
+
653
+ # Add user message to history
654
+ st.session_state.chat_history.append(("user", question, []))
655
+ st.session_state.discussion_log = []
656
+ st.session_state.code_report = ""
657
+ st.session_state.code_sections = []
658
+ st.session_state.image_refs = []
659
+
660
+ with chat_col:
661
+ with st.chat_message("user"):
662
+ st.markdown(question)
663
+
664
+ # Build initial state
665
+ ingest = st.session_state.ingest_state
666
+ image_store = st.session_state.image_store
667
+
668
+ meta = st.session_state.metadata_state
669
+ metadata_json = meta.data_json if meta.is_ready else ""
670
+
671
+ question_state = {
672
+ "messages": [],
673
+ "question": question,
674
+ "pdf_path": ingest.get("pdf_path", ""),
675
+ "page_image_dir": ingest.get("page_image_dir", ""),
676
+ "num_pages": ingest.get("num_pages", 0),
677
+ "page_metadata_json": metadata_json,
678
+ "legend_pages": [],
679
+ "target_pages": [],
680
+ "crop_tasks": [],
681
+ "code_queries": [],
682
+ "image_refs": [],
683
+ "code_sections": [],
684
+ "code_report": "",
685
+ "code_chapters_fetched": [],
686
+ "compliance_analysis": "",
687
+ "reviewer_analysis": "",
688
+ "final_verdict": "",
689
+ "discussion_log": [],
690
+ "additional_crop_tasks": [],
691
+ "additional_code_queries": [],
692
+ "needs_more_investigation": False,
693
+ "investigation_round": 0,
694
+ "max_rounds": max_rounds,
695
+ "enable_consensus": enable_consensus,
696
+ "enable_annotation": enable_annotation,
697
+ "status_message": [],
698
+ }
699
+
700
+ # ------------------------------------------------------------------
701
+ # Live progress
702
+ # ------------------------------------------------------------------
703
+ crop_cache = st.session_state.crop_cache
704
+
705
+ with evidence_col:
706
+ with evidence_tabs[0]:
707
+ crop_counter_placeholder = st.empty()
708
+ crop_image_container = st.container()
709
+
710
+ def on_crop_progress(
711
+ completed_ref, crop_task, source: str, completed_count: int, total_count: int,
712
+ ) -> None:
713
+ source_tag = " (cached)" if source == "cached" else ""
714
+ crop_counter_placeholder.markdown(
715
+ f"**Crop {completed_count}/{total_count}**{source_tag} \n"
716
+ f"Latest: *{crop_task.get('label', 'Crop')}*"
717
+ )
718
+ with crop_image_container:
719
+ try:
720
+ img = Image.open(completed_ref["path"])
721
+ caption = completed_ref["label"]
722
+ if source == "cached":
723
+ caption += " (cached)"
724
+ st.image(img, caption=caption, use_container_width=True)
725
+ except Exception:
726
+ st.warning(f"Could not load: {completed_ref['label']}")
727
+
728
+ # Compile graph
729
+ compliance_graph = compile_compliance_graph(image_store, crop_cache, on_crop_progress)
730
+
731
+ # Node progress labels
732
+ PROGRESS_LABELS = {
733
+ "compliance_planner": "Planning investigation...",
734
+ "execute_crops": "Cropping drawing images...",
735
+ "annotate_crops": "Annotating crops...",
736
+ "initial_code_lookup": "Searching NYC code database...",
737
+ "compliance_analyst": "Analyzing compliance...",
738
+ "targeted_code_lookup": "Follow-up code search...",
739
+ "deliberation": "Running peer review...",
740
+ "final_verdict": "Synthesizing verdict...",
741
+ }
742
+
743
+ with chat_col:
744
+ with st.status("Investigating compliance...", expanded=True) as status:
745
+ all_image_refs: list[dict] = []
746
+ all_discussion: list[dict] = []
747
+ final_verdict_text = ""
748
+ code_report_text = ""
749
+
750
+ st.write(PROGRESS_LABELS["compliance_planner"])
751
+
752
+ parallel_status = st.empty()
753
+
754
+ for event in compliance_graph.stream(question_state, stream_mode="updates"):
755
+ node_name = list(event.keys())[0]
756
+ update = event[node_name]
757
+
758
+ status_msgs = update.get("status_message", [])
759
+ for status_msg in status_msgs:
760
+ if status_msg:
761
+ st.write(f":white_check_mark: {status_msg}")
762
+
763
+ new_discussion = update.get("discussion_log", [])
764
+ if new_discussion:
765
+ all_discussion.extend(new_discussion)
766
+ st.session_state.discussion_log = all_discussion
767
+ render_discussion_log(discussion_container, all_discussion)
768
+
769
+ if node_name == "compliance_planner":
770
+ target_pages = update.get("target_pages", [])
771
+ crop_tasks = update.get("crop_tasks", [])
772
+ code_queries = update.get("code_queries", [])
773
+
774
+ with st.expander(":clipboard: Investigation Plan", expanded=True):
775
+ if target_pages:
776
+ st.markdown(f"**Target pages:** {', '.join(str(p + 1) for p in target_pages)}")
777
+ if crop_tasks:
778
+ st.markdown(f"**Image crops ({len(crop_tasks)}):**")
779
+ for i, task in enumerate(crop_tasks, 1):
780
+ display_page = task.get("page_num", 0) + 1
781
+ st.markdown(f" {i}. {task.get('label', 'Crop')} (p.{display_page})")
782
+ if code_queries:
783
+ st.markdown(f"**Code queries ({len(code_queries)}):**")
784
+ for i, q in enumerate(code_queries, 1):
785
+ st.markdown(f" {i}. [{q.get('focus_area', '?')}] {q.get('query', '')[:80]}...")
786
+
787
+ if crop_tasks:
788
+ crop_counter_placeholder.markdown(f"**Crop 0/{len(crop_tasks)}** — starting...")
789
+
790
+ parallel_status.info(
791
+ ":arrows_counterclockwise: Running in parallel: "
792
+ f"**Cropping {len(crop_tasks)} images** + "
793
+ f"**Searching {len(code_queries)} code queries**. "
794
+ "This may take 30-60 seconds..."
795
+ )
796
+
797
+ elif node_name in ("initial_code_lookup", "execute_crops"):
798
+ parallel_status.empty()
799
+
800
+ if node_name in ("initial_code_lookup", "targeted_code_lookup"):
801
+ report = update.get("code_report", "")
802
+ new_sections = update.get("code_sections", [])
803
+ if report:
804
+ code_report_text = report
805
+ st.session_state.code_report = report
806
+ if new_sections:
807
+ st.session_state.code_sections.extend(new_sections)
808
+ with evidence_col:
809
+ with evidence_tabs[1]:
810
+ for sec in new_sections:
811
+ with st.expander(
812
+ f":balance_scale: {sec.get('code_type', '?')} "
813
+ f"§{sec.get('section_full', '?')}",
814
+ expanded=False,
815
+ ):
816
+ if sec.get("relevance"):
817
+ st.caption(sec["relevance"])
818
+ st.markdown(sec.get("text", "")[:1500])
819
+
820
+ elif node_name == "compliance_analyst":
821
+ analysis = update.get("compliance_analysis", "")
822
+ needs_more = update.get("needs_more_investigation", False)
823
+ round_num = update.get("investigation_round", 1)
824
+
825
+ if analysis:
826
+ label = f":mag: Compliance Analysis (Round {round_num})"
827
+ if needs_more:
828
+ label += " — requesting more evidence"
829
+ with st.expander(label, expanded=False):
830
+ st.markdown(analysis[:5000])
831
+
832
+ elif node_name == "deliberation":
833
+ review = update.get("reviewer_analysis", "")
834
+ if review:
835
+ with st.expander(":handshake: Peer Review", expanded=False):
836
+ st.markdown(review[:3000])
837
+
838
+ new_refs = update.get("image_refs", [])
839
+ if new_refs:
840
+ all_image_refs.extend(new_refs)
841
+ st.session_state.image_refs.extend(new_refs)
842
+ with evidence_col:
843
+ with evidence_tabs[0]:
844
+ for ref in new_refs:
845
+ try:
846
+ img = Image.open(ref["path"])
847
+ st.image(img, caption=ref["label"], use_container_width=True)
848
+ except Exception:
849
+ st.warning(f"Could not load: {ref['label']}")
850
+
851
+ if "final_verdict" in update and update["final_verdict"]:
852
+ final_verdict_text = update["final_verdict"]
853
+
854
+ if node_name in PROGRESS_LABELS:
855
+ next_labels = {
856
+ "compliance_planner": ["execute_crops", "initial_code_lookup"],
857
+ "execute_crops": ["compliance_analyst"],
858
+ "annotate_crops": ["compliance_analyst"],
859
+ "initial_code_lookup": ["compliance_analyst"],
860
+ "compliance_analyst": ["final_verdict"],
861
+ "targeted_code_lookup": ["compliance_analyst"],
862
+ "deliberation": ["final_verdict"],
863
+ }
864
+ for next_node in next_labels.get(node_name, []):
865
+ if next_node in PROGRESS_LABELS:
866
+ st.write(PROGRESS_LABELS[next_node])
867
+
868
+ if crop_cache.size > 0:
869
+ st.caption(f":file_folder: {crop_cache.stats}")
870
+ status.update(label="Compliance investigation complete", state="complete")
871
+
872
+ if final_verdict_text:
873
+ with chat_col:
874
+ with st.chat_message("assistant"):
875
+ st.markdown(final_verdict_text)
876
+
877
+ st.session_state.chat_history[-1] = ("user", question, [])
878
+ st.session_state.chat_history.append(("assistant", final_verdict_text, all_image_refs))
879
+ else:
880
+ with chat_col:
881
+ st.error("No verdict was generated. Please try again.")
882
+
883
+ st.rerun()