Update app.py
Browse files
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
|
| 5 |
-
import
|
| 6 |
-
import
|
| 7 |
-
|
| 8 |
-
import
|
| 9 |
-
import
|
| 10 |
-
import
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
from
|
| 18 |
-
from
|
| 19 |
-
from
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
)
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
#
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
}
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
if
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
if
|
| 151 |
-
st.
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
#
|
| 261 |
-
#
|
| 262 |
-
|
| 263 |
-
if not
|
| 264 |
-
_left, center, _right = st.columns([1, 2, 1])
|
| 265 |
-
with center:
|
| 266 |
-
st.markdown(
|
| 267 |
-
"<h1 style='text-align: center;'>
|
| 268 |
-
unsafe_allow_html=True,
|
| 269 |
-
)
|
| 270 |
-
st.markdown(
|
| 271 |
-
"<p style='text-align: center; color: grey;'>"
|
| 272 |
-
"
|
| 273 |
-
"
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
#
|
| 281 |
-
#
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
# ---------------------------------------------------------------------------
|
| 332 |
-
#
|
| 333 |
-
# ---------------------------------------------------------------------------
|
| 334 |
-
|
| 335 |
-
st.
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
st.
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
# ---------------------------------------------------------------------------
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
st.
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
"
|
| 409 |
-
|
| 410 |
-
"
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
"
|
| 414 |
-
|
| 415 |
-
"
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
"
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
"
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
"
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
|
| 530 |
-
|
| 531 |
-
|
| 532 |
-
|
| 533 |
-
|
| 534 |
-
|
| 535 |
-
|
| 536 |
-
|
| 537 |
-
|
| 538 |
-
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
|
| 547 |
-
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
|
| 574 |
-
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
|
| 586 |
-
|
| 587 |
-
|
| 588 |
-
|
| 589 |
-
|
| 590 |
-
|
| 591 |
-
|
| 592 |
-
|
| 593 |
-
|
| 594 |
-
|
| 595 |
-
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
|
| 602 |
-
|
| 603 |
-
|
| 604 |
-
|
| 605 |
-
|
| 606 |
-
|
| 607 |
-
|
| 608 |
-
|
| 609 |
-
|
| 610 |
-
|
| 611 |
-
|
| 612 |
-
|
| 613 |
-
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
|
| 617 |
-
|
| 618 |
-
|
| 619 |
-
|
| 620 |
-
st.
|
| 621 |
-
|
| 622 |
-
|
| 623 |
-
|
| 624 |
-
|
| 625 |
-
|
| 626 |
-
|
| 627 |
-
|
| 628 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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()
|