Spaces:
Paused
Paused
File size: 22,148 Bytes
88bdcff 78caafb 88bdcff f3ebc82 88bdcff f3ebc82 88bdcff 0699c5f 88bdcff 78caafb f3ebc82 78caafb f3ebc82 78caafb f3ebc82 78caafb f3ebc82 78caafb f3ebc82 88bdcff 78caafb 88bdcff 78caafb 88bdcff f3ebc82 78caafb 88bdcff 3b08f11 88bdcff f3ebc82 78caafb 88bdcff 78caafb f3ebc82 78caafb 88bdcff f3ebc82 78caafb f3ebc82 78caafb f3ebc82 78caafb f3ebc82 78caafb f3ebc82 78caafb f3ebc82 78caafb 3b08f11 f3ebc82 78caafb f3ebc82 78caafb 3b08f11 78caafb 3b08f11 78caafb 3b08f11 78caafb 3b08f11 78caafb 3b08f11 78caafb 3b08f11 78caafb 88bdcff 78caafb 88bdcff 78caafb 88bdcff 78caafb 88bdcff 78caafb 88bdcff 78caafb 88bdcff 78caafb 88bdcff 78caafb 88bdcff 78caafb 88bdcff 78caafb 88bdcff 78caafb 88bdcff 78caafb 88bdcff 78caafb 88bdcff 78caafb 88bdcff 78caafb 88bdcff f3ebc82 88bdcff 78caafb 88bdcff 78caafb 88bdcff 78caafb 88bdcff 78caafb 88bdcff 78caafb 88bdcff 78caafb 88bdcff 78caafb 88bdcff 78caafb 88bdcff 78caafb 88bdcff 78caafb 88bdcff 78caafb 88bdcff 78caafb f3ebc82 88bdcff 78caafb 3b08f11 88bdcff 78caafb 88bdcff 78caafb f3ebc82 78caafb f3ebc82 88bdcff 78caafb 88bdcff f3ebc82 88bdcff |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 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 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 151 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 264 265 266 267 268 269 270 271 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 336 337 338 339 340 341 342 343 344 345 346 347 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 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 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 |
"""FDAM AI Pipeline - Fire Damage Assessment Methodology v4.0.1
Main Gradio application entry point with session state and chat functionality.
Simplified UI: 2 tabs (Input + Results/Chat).
"""
import gradio as gr
from config.logging import setup_logging
from config.settings import settings
# Initialize logging before any other imports that might log
setup_logging(settings.log_level)
import logging
logger = logging.getLogger(__name__)
from models.loader import get_models
from ui.state import SessionState, create_new_session
from ui.storage import get_head_html
from ui.tabs import input_tab, results_tab
from ui import samples
from pipeline.chat import ChatHandler, get_quick_action_message
# Keyboard shortcuts JavaScript (Ctrl+1-2 for tab navigation)
KEYBOARD_JS = """
<script>
document.addEventListener('keydown', (e) => {
if (e.ctrlKey && e.key >= '1' && e.key <= '2') {
e.preventDefault();
const tabIds = ['tab-input-button', 'tab-results-button'];
const tabIndex = parseInt(e.key) - 1;
const tabButton = document.getElementById(tabIds[tabIndex]);
if (tabButton) {
tabButton.click();
}
}
});
</script>
"""
# Validation CSS classes
VALIDATION_CSS = """
.valid-field input, .valid-field textarea {
border-color: #66bb6a !important;
}
.invalid-field input, .invalid-field textarea {
border-color: #ef5350 !important;
}
"""
def ensure_rag_index():
"""Ensure RAG index is built. Builds on first run if empty."""
from pathlib import Path
try:
# Check if index exists and has content
chroma_path = Path(__file__).parent / "chroma_db"
if not chroma_path.exists() or not any(chroma_path.iterdir()):
logger.info("RAG index empty or missing - building from RAG-KB...")
from rag.index_builder import build_index
stats = build_index(rebuild=False)
logger.info(f"RAG index built: {stats['chunks_created']} chunks from {stats['documents_processed']} documents")
else:
logger.info("RAG index found")
except Exception as e:
logger.warning(f"RAG index build failed (will use fallback): {e}")
def create_app() -> gr.Blocks:
"""Create the main Gradio application."""
# Initialize models at startup
model_stack = get_models()
# Ensure RAG index is built (builds on first run)
ensure_rag_index()
# Initialize chat handler
chat_handler = ChatHandler(model_stack)
with gr.Blocks(
title="FDAM AI Pipeline - Fire Damage Assessment",
css=VALIDATION_CSS,
head=get_head_html(KEYBOARD_JS),
) as app:
# Session state (stored in Gradio State component)
session_state = gr.State(value=create_new_session())
# Header
gr.Markdown(
"""
# FDAM AI Pipeline
## Fire Damage Assessment Methodology v4.0.1
Upload images and room information to generate a professional
Cleaning Specification / Scope of Work.
"""
)
# Mode indicator
if settings.mock_models:
gr.Markdown(
"""
> **Development Mode**: Using mock models for testing.
> Set `MOCK_MODELS=false` for production inference.
"""
)
# Sample loader dropdown
with gr.Row():
sample_dropdown = gr.Dropdown(
label="Load Sample",
choices=samples.get_sample_choices(),
value="",
elem_id="sample_dropdown",
scale=2,
)
sample_status = gr.HTML(
value="",
elem_id="sample_status",
)
# Tab navigation (2 tabs)
with gr.Tabs() as tabs:
# Tab 1: Input (combined room + images + observations)
tab_input = gr.Tab("1. Input", id=0, elem_id="tab-input")
with tab_input:
tab1 = input_tab.create_tab()
# Tab 2: Results + Chat
tab_results = gr.Tab("2. Results", id=1, elem_id="tab-results")
with tab_results:
tab2 = results_tab.create_tab()
# --- Event Handlers ---
# Sample Loader
def handle_sample_load(scenario_id: str, current_session: SessionState):
"""Handle sample dropdown selection."""
if not scenario_id:
return (
current_session,
*input_tab.load_room_from_session(current_session),
*input_tab.load_images_from_session(current_session),
*input_tab.load_observations_from_session(current_session),
gr.update(),
"",
"",
)
# Load the sample
new_session = samples.load_sample(scenario_id)
if not new_session:
return (
current_session,
*input_tab.load_room_from_session(current_session),
*input_tab.load_images_from_session(current_session),
*input_tab.load_observations_from_session(current_session),
gr.update(),
'<span style="color: #c62828;">Error: Sample not found</span>',
"",
)
# Get scenario name for status message
scenario = samples.get_scenario_by_id(scenario_id)
name = scenario.name if scenario else scenario_id
# Load form values from new session
room_values = input_tab.load_room_from_session(new_session)
image_values = input_tab.load_images_from_session(new_session)
obs_values = input_tab.load_observations_from_session(new_session)
return (
new_session,
*room_values,
*image_values,
*obs_values,
gr.update(selected=0), # Stay on Input tab
f'<span style="color: #2e7d32;">Loaded sample: {name}</span>',
"", # reset dropdown
)
sample_dropdown.change(
fn=handle_sample_load,
inputs=[sample_dropdown, session_state],
outputs=[
session_state,
# Room outputs (9)
tab1["room_name"],
tab1["room_length"],
tab1["room_width"],
tab1["room_height_preset"],
tab1["room_height_custom"],
tab1["floor_area"],
tab1["room_volume"],
tab1["facility_classification"],
tab1["construction_era"],
# Image outputs (3)
tab1["images_gallery"],
tab1["image_count"],
tab1["resume_warning"],
# Observation outputs (15)
tab1["smoke_odor"],
tab1["odor_intensity"],
tab1["visible_soot"],
tab1["soot_description"],
tab1["large_char"],
tab1["char_density"],
tab1["ash_residue"],
tab1["ash_description"],
tab1["surface_discoloration"],
tab1["discoloration_description"],
tab1["dust_interference"],
tab1["dust_notes"],
tab1["wildfire_indicators"],
tab1["wildfire_notes"],
tab1["additional_notes"],
# Navigation
tabs,
sample_status,
sample_dropdown,
],
)
# --- Tab 1: Input ---
# Room field changes - save to session and update calculations
def on_room_field_change(
session: SessionState,
name: str,
length: float | None,
width: float | None,
height_preset: int | None,
height_custom: float | None,
facility_classification: str,
construction_era: str,
):
"""Save room data and update calculated values."""
updated_session = input_tab.save_room_to_session(
session, name, length, width, height_preset, height_custom,
facility_classification, construction_era
)
floor_area, volume = input_tab.update_calculated_values(
length, width, height_preset, height_custom
)
return updated_session, floor_area, volume
room_inputs = [
session_state,
tab1["room_name"],
tab1["room_length"],
tab1["room_width"],
tab1["room_height_preset"],
tab1["room_height_custom"],
tab1["facility_classification"],
tab1["construction_era"],
]
room_outputs = [session_state, tab1["floor_area"], tab1["room_volume"]]
for input_component in [
tab1["room_name"],
tab1["room_length"],
tab1["room_width"],
tab1["room_height_preset"],
tab1["room_height_custom"],
tab1["facility_classification"],
tab1["construction_era"],
]:
input_component.change(
fn=on_room_field_change,
inputs=room_inputs,
outputs=room_outputs,
)
# Show/hide custom height input
tab1["room_height_preset"].change(
fn=input_tab.on_height_preset_change,
inputs=[tab1["room_height_preset"]],
outputs=[tab1["room_height_custom"]],
)
# Image handling
tab1["add_image_btn"].click(
fn=input_tab.add_image,
inputs=[
session_state,
tab1["image_upload"],
tab1["image_description"],
],
outputs=[
session_state,
tab1["images_gallery"],
tab1["validation_status"],
tab1["image_count"],
tab1["image_upload"],
tab1["image_description"],
],
)
tab1["clear_upload_btn"].click(
fn=lambda: (None, ""),
outputs=[
tab1["image_upload"],
tab1["image_description"],
],
)
tab1["remove_last_btn"].click(
fn=input_tab.remove_last_image,
inputs=[session_state],
outputs=[
session_state,
tab1["images_gallery"],
tab1["validation_status"],
tab1["image_count"],
],
)
tab1["clear_all_btn"].click(
fn=input_tab.clear_all_images,
inputs=[session_state],
outputs=[
session_state,
tab1["images_gallery"],
tab1["validation_status"],
tab1["image_count"],
],
)
# Generate button - validate and switch to results
def on_generate_click(
session: SessionState,
smoke_odor: bool,
odor_intensity: str,
visible_soot: bool,
soot_description: str,
large_char: bool,
char_density: str,
ash_residue: bool,
ash_description: str,
surface_discoloration: bool,
discoloration_description: str,
dust_interference: bool,
dust_notes: str,
wildfire_indicators: bool,
wildfire_notes: str,
additional_notes: str,
):
"""Save observations and validate before generating."""
# Save observations first
session = input_tab.save_observations_to_session(
session,
smoke_odor, odor_intensity, visible_soot, soot_description,
large_char, char_density, ash_residue, ash_description,
surface_discoloration, discoloration_description,
dust_interference, dust_notes, wildfire_indicators,
wildfire_notes, additional_notes,
)
# Validate and potentially switch tabs
return input_tab.validate_and_generate(session)
tab1["generate_btn"].click(
fn=on_generate_click,
inputs=[
session_state,
tab1["smoke_odor"],
tab1["odor_intensity"],
tab1["visible_soot"],
tab1["soot_description"],
tab1["large_char"],
tab1["char_density"],
tab1["ash_residue"],
tab1["ash_description"],
tab1["surface_discoloration"],
tab1["discoloration_description"],
tab1["dust_interference"],
tab1["dust_notes"],
tab1["wildfire_indicators"],
tab1["wildfire_notes"],
tab1["additional_notes"],
],
outputs=[
session_state,
tab1["validation_status"],
tabs,
],
)
# --- Tab 2: Results + Chat ---
# Generate assessment
tab2["generate_btn"].click(
fn=results_tab.generate_assessment,
inputs=[session_state],
outputs=[
session_state,
tab2["processing_status"],
tab2["progress_html"],
tab2["annotated_gallery"],
tab2["stats_output"],
tab2["sow_output"],
tab2["download_md"],
tab2["download_pdf"],
tab2["chatbot"],
],
)
tab2["regenerate_btn"].click(
fn=results_tab.generate_assessment,
inputs=[session_state],
outputs=[
session_state,
tab2["processing_status"],
tab2["progress_html"],
tab2["annotated_gallery"],
tab2["stats_output"],
tab2["sow_output"],
tab2["download_md"],
tab2["download_pdf"],
tab2["chatbot"],
],
)
# Back to input
tab2["back_btn"].click(
fn=lambda: gr.update(selected=0),
outputs=[tabs],
)
# Reset document
def on_reset_document(session: SessionState):
"""Reset document to original and regenerate downloads."""
session, doc = results_tab.reset_document(session)
md_path, pdf_path = results_tab.regenerate_downloads(session)
return session, doc, md_path, pdf_path
tab2["reset_doc_btn"].click(
fn=on_reset_document,
inputs=[session_state],
outputs=[
session_state,
tab2["sow_output"],
tab2["download_md"],
tab2["download_pdf"],
],
)
# Chat functionality
def handle_chat_message(
message: str,
session: SessionState,
chat_history: list[dict],
):
"""Process chat message and update UI."""
if not message.strip():
return session, chat_history, "", session.generated_document or "", None, None
response, edit, updated_history = chat_handler.process_message(
message, session, chat_history
)
# Apply document edit if present
if edit and session.generated_document:
session.generated_document = chat_handler.apply_document_edit(
session.generated_document, edit
)
session.update_timestamp()
# Regenerate downloads
md_path, pdf_path = results_tab.regenerate_downloads(session)
else:
md_path, pdf_path = None, None
# Store chat history in session
session.chat_history = updated_history
return (
session,
updated_history,
"", # Clear input
session.generated_document or "",
md_path,
pdf_path,
)
# Chat send button
tab2["chat_send_btn"].click(
fn=handle_chat_message,
inputs=[tab2["chat_input"], session_state, tab2["chatbot"]],
outputs=[
session_state,
tab2["chatbot"],
tab2["chat_input"],
tab2["sow_output"],
tab2["download_md"],
tab2["download_pdf"],
],
)
# Chat input enter key
tab2["chat_input"].submit(
fn=handle_chat_message,
inputs=[tab2["chat_input"], session_state, tab2["chatbot"]],
outputs=[
session_state,
tab2["chatbot"],
tab2["chat_input"],
tab2["sow_output"],
tab2["download_md"],
tab2["download_pdf"],
],
)
# Quick action buttons
def send_quick_action(action_key: str, session: SessionState, chat_history: list[dict]):
"""Send a quick action message."""
message = get_quick_action_message(action_key)
return handle_chat_message(message, session, chat_history)
tab2["quick_explain_zones"].click(
fn=lambda s, h: send_quick_action("explain_zones", s, h),
inputs=[session_state, tab2["chatbot"]],
outputs=[
session_state,
tab2["chatbot"],
tab2["chat_input"],
tab2["sow_output"],
tab2["download_md"],
tab2["download_pdf"],
],
)
tab2["quick_explain_materials"].click(
fn=lambda s, h: send_quick_action("explain_materials", s, h),
inputs=[session_state, tab2["chatbot"]],
outputs=[
session_state,
tab2["chatbot"],
tab2["chat_input"],
tab2["sow_output"],
tab2["download_md"],
tab2["download_pdf"],
],
)
tab2["quick_sampling"].click(
fn=lambda s, h: send_quick_action("explain_sampling", s, h),
inputs=[session_state, tab2["chatbot"]],
outputs=[
session_state,
tab2["chatbot"],
tab2["chat_input"],
tab2["sow_output"],
tab2["download_md"],
tab2["download_pdf"],
],
)
tab2["quick_add_note"].click(
fn=lambda s, h: send_quick_action("add_note", s, h),
inputs=[session_state, tab2["chatbot"]],
outputs=[
session_state,
tab2["chatbot"],
tab2["chat_input"],
tab2["sow_output"],
tab2["download_md"],
tab2["download_pdf"],
],
)
# --- Tab Select Handlers ---
# Load data when switching to Input tab
def load_input_tab(session: SessionState):
"""Load all input data when tab is selected."""
room_values = input_tab.load_room_from_session(session)
image_values = input_tab.load_images_from_session(session)
obs_values = input_tab.load_observations_from_session(session)
return (*room_values, *image_values, *obs_values)
tab_input.select(
fn=load_input_tab,
inputs=[session_state],
outputs=[
# Room (9)
tab1["room_name"],
tab1["room_length"],
tab1["room_width"],
tab1["room_height_preset"],
tab1["room_height_custom"],
tab1["floor_area"],
tab1["room_volume"],
tab1["facility_classification"],
tab1["construction_era"],
# Images (3)
tab1["images_gallery"],
tab1["image_count"],
tab1["resume_warning"],
# Observations (15)
tab1["smoke_odor"],
tab1["odor_intensity"],
tab1["visible_soot"],
tab1["soot_description"],
tab1["large_char"],
tab1["char_density"],
tab1["ash_residue"],
tab1["ash_description"],
tab1["surface_discoloration"],
tab1["discoloration_description"],
tab1["dust_interference"],
tab1["dust_notes"],
tab1["wildfire_indicators"],
tab1["wildfire_notes"],
tab1["additional_notes"],
],
)
# Load data when switching to Results tab
def load_results_tab(session: SessionState):
"""Load results data when tab is selected."""
doc = session.generated_document or "*Generate an assessment to see results here.*"
chat = session.chat_history or []
return doc, chat
tab_results.select(
fn=load_results_tab,
inputs=[session_state],
outputs=[
tab2["sow_output"],
tab2["chatbot"],
],
)
return app
def main():
"""Entry point for the application."""
logger.info("Starting FDAM AI Pipeline v4.0.1")
logger.info(f"Mock models: {settings.mock_models}")
logger.info(f"Log level: {settings.log_level}")
logger.info(f"Server: {settings.server_host}:{settings.server_port}")
app = create_app()
app.launch(
server_name=settings.server_host,
server_port=settings.server_port,
share=False,
)
if __name__ == "__main__":
main()
|