File size: 11,198 Bytes
88bdcff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b08f11
88bdcff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b08f11
88bdcff
 
 
 
3b08f11
88bdcff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b08f11
 
88bdcff
3b08f11
 
 
88bdcff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b08f11
88bdcff
 
 
3b08f11
 
 
88bdcff
 
 
 
 
 
 
3b08f11
88bdcff
 
 
 
 
 
3b08f11
88bdcff
3b08f11
 
 
 
 
 
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
"""Tab 5: Generate Results.

Process all inputs and generate assessment outputs.
"""

import gradio as gr
from typing import Any, Optional
from datetime import datetime
import tempfile

from ui.state import SessionState
from ui.components import create_stats_dict, create_progress_html, image_store
from pipeline import FDAMPipeline, PipelineResult, PDFGenerator


def create_tab() -> dict[str, Any]:
    """Create Tab 5 UI components.

    Returns:
        Dictionary of component references for event wiring.
    """
    gr.Markdown("### Generate Assessment")

    # Pre-flight check summary
    with gr.Row():
        preflight_status = gr.HTML(
            value="",
            elem_id="preflight_status",
        )

    gr.Markdown(
        """
        Click below to process all inputs and generate:
        1. **Cleaning Specification / Scope of Work** (primary output)
        2. **Sampling Plan Recommendations**
        3. **Confidence Report**
        """
    )

    with gr.Row():
        generate_btn = gr.Button(
            "Generate Assessment",
            variant="primary",
            scale=2,
            elem_id="generate_btn",
        )
        processing_status = gr.Textbox(
            label="Status",
            value="Ready",
            interactive=False,
            elem_id="processing_status",
        )

    # Progress display
    with gr.Row():
        progress_html = gr.HTML(
            value="",
            elem_id="progress_html",
        )

    gr.Markdown("---")
    gr.Markdown("### Results")

    with gr.Row():
        with gr.Column():
            gr.Markdown("#### Annotated Images")
            annotated_gallery = gr.Gallery(
                label="AI-Analyzed Images",
                columns=2,
                height="auto",
                elem_id="annotated_gallery",
            )

        with gr.Column():
            gr.Markdown("#### Assessment Summary")
            stats_output = gr.JSON(
                label="Statistics",
                elem_id="stats_output",
            )

    gr.Markdown("### Cleaning Specification / Scope of Work")
    sow_output = gr.Markdown(
        value="*Results will appear here after generation.*",
        elem_id="sow_output",
    )

    gr.Markdown("### Downloads")
    with gr.Row():
        download_md = gr.File(
            label="Download Markdown (.md)",
            elem_id="download_md",
        )
        download_pdf = gr.File(
            label="Download PDF (.pdf)",
            elem_id="download_pdf",
        )

    # Navigation
    with gr.Row():
        back_btn = gr.Button("← Back to Observations")
        regenerate_btn = gr.Button(
            "Regenerate Assessment",
            variant="secondary",
        )

    return {
        "preflight_status": preflight_status,
        "generate_btn": generate_btn,
        "processing_status": processing_status,
        "progress_html": progress_html,
        "annotated_gallery": annotated_gallery,
        "stats_output": stats_output,
        "sow_output": sow_output,
        "download_md": download_md,
        "download_pdf": download_pdf,
        "back_btn": back_btn,
        "regenerate_btn": regenerate_btn,
    }


def check_preflight(session: SessionState) -> str:
    """Check if assessment can be generated.

    Returns:
        HTML string with preflight status.
    """
    can_generate, errors = session.can_generate()

    # Also check if images are in memory
    expected_ids = [img.id for img in session.images]
    missing_ids = image_store.get_missing_ids(expected_ids)
    if missing_ids:
        errors.append(f"{len(missing_ids)} image(s) need to be re-uploaded")
        can_generate = False

    if can_generate:
        # Show summary of what will be processed
        stats = create_stats_dict(session)
        return f"""
        <div style="background: #e8f5e9; border: 1px solid #66bb6a; border-radius: 4px; padding: 15px;">
            <strong style="color: #2e7d32;">✓ Ready to Generate</strong>
            <div style="margin-top: 10px; color: #333;">
                <strong>Room:</strong> {stats['room_name']}<br>
                <strong>Images:</strong> {stats['images']}<br>
                <strong>Total Area:</strong> {stats['total_floor_area_sf']} SF<br>
                <strong>Facility:</strong> {stats['facility_classification']}<br>
                <strong>Era:</strong> {stats['construction_era']}
            </div>
        </div>
        """
    else:
        error_items = "".join(f"<li>{e}</li>" for e in errors)
        return f"""
        <div style="background: #ffebee; border: 1px solid #ef5350; border-radius: 4px; padding: 15px;">
            <strong style="color: #c62828;">Cannot Generate - Please Fix:</strong>
            <ul style="margin: 10px 0 0 0; padding-left: 20px; color: #c62828;">
                {error_items}
            </ul>
        </div>
        """


def generate_assessment(
    session: SessionState,
    progress: Optional[gr.Progress] = None,
) -> tuple[SessionState, str, str, list[tuple], dict, str, Optional[str], Optional[str]]:
    """Generate the assessment using the FDAM pipeline.

    Returns:
        Tuple of (session, status, progress_html, annotated_images,
                  stats, sow_markdown, md_file_path, pdf_file_path).
    """
    # Create pipeline instance
    pipeline = FDAMPipeline()

    # Define progress callback for Gradio
    def progress_callback(prog):
        if progress:
            progress(prog.percent, desc=prog.message)

    # Execute pipeline
    result: PipelineResult = pipeline.execute(
        session=session,
        progress_callback=progress_callback,
    )

    # Handle errors
    if not result.success:
        error_msg = "**Error:** Please fix the following before generating:\n\n"
        error_msg += "\n".join(f"- {e}" for e in result.errors)
        return (
            result.session,
            "Error: Cannot generate",
            "",
            [],
            {},
            error_msg,
            None,
            None,
        )

    # Generate stats dictionary for UI
    stats = pipeline.generate_stats_dict(result)

    # Get markdown content
    sow_markdown = result.document.markdown if result.document else ""

    # Save markdown file
    md_path = None
    pdf_path = None

    try:
        if sow_markdown:
            # Save Markdown file
            room_name_safe = session.room.name.replace(' ', '_') if session.room.name else "Room"
            with tempfile.NamedTemporaryFile(
                mode='w',
                suffix='.md',
                delete=False,
                prefix=f"SOW_{room_name_safe}_",
            ) as f:
                f.write(sow_markdown)
                md_path = f.name

            # Generate PDF
            pdf_generator = PDFGenerator()
            pdf_result = pdf_generator.generate_pdf(sow_markdown)
            if pdf_result.success:
                pdf_path = pdf_result.pdf_path
            else:
                result.warnings.append(f"PDF generation failed: {pdf_result.error_message}")

    except Exception as e:
        print(f"Error saving files: {e}")

    # Add warnings to status if any
    status = "Complete"
    if result.warnings:
        status = f"Complete ({len(result.warnings)} warnings)"

    return (
        result.session,
        status,
        create_progress_html(6, 6, f"Complete! ({result.execution_time_seconds:.1f}s)"),
        result.annotated_images,
        stats,
        sow_markdown,
        md_path,
        pdf_path,
    )


def _generate_sow_markdown(
    session: SessionState,
    stats: dict,
    vision_results: dict,
) -> str:
    """Generate Scope of Work markdown document.

    This is a placeholder - real implementation uses DocumentGenerator.
    Kept for backwards compatibility but should not be called directly.
    """
    r = session.room
    area = r.length_ft * r.width_ft
    volume = area * r.ceiling_height_ft

    # Build vision summary
    vision_lines = []
    for img_meta in session.images:
        result = vision_results.get(img_meta.id, {})
        zone = result.get("zone", {}).get("classification", "N/A")
        condition = result.get("condition", {}).get("level", "N/A")
        vision_lines.append(f"- **{img_meta.filename}**: Zone={zone}, Condition={condition}")
    vision_summary = "\n".join(vision_lines) if vision_lines else "No images analyzed."

    # Build observations summary
    obs = session.observations
    obs_items = []
    if obs.smoke_fire_odor:
        obs_items.append(f"- Smoke/fire odor: {obs.odor_intensity}")
    if obs.visible_soot_deposits:
        obs_items.append(f"- Visible soot deposits: {obs.soot_pattern_description or 'Yes'}")
    if obs.large_char_particles:
        obs_items.append(f"- Large char particles: {obs.char_density_estimate or 'Yes'}")
    if obs.ash_like_residue:
        obs_items.append(f"- Ash residue: {obs.ash_color_texture or 'Yes'}")
    if obs.surface_discoloration:
        obs_items.append(f"- Surface discoloration: {obs.discoloration_description or 'Yes'}")
    if obs.wildfire_indicators:
        obs_items.append(f"- Wildfire indicators: {obs.wildfire_notes or 'Yes'}")
    obs_summary = "\n".join(obs_items) if obs_items else "No significant observations noted."

    # Regulatory flags
    reg_flags = "\n".join(f"- {f}" for f in stats.get("regulatory_flags", [])) or "None identified."

    markdown = f"""# Cleaning Specification / Scope of Work

## Room Information

| Field | Value |
|-------|-------|
| **Room Name** | {r.name} |
| **Facility Classification** | {r.facility_classification or 'Not specified'} |
| **Construction Era** | {r.construction_era or 'Not specified'} |

---

## Scope Summary

| Metric | Value |
|--------|-------|
| Room | {r.name} |
| Total Floor Area | {stats['total_floor_area_sf']} SF |
| Total Volume | {stats['total_volume_cf']} CF |
| Images Analyzed | {stats['total_images']} |

---

## Room Details

| Property | Value |
|----------|-------|
| **Room Name** | {r.name} |
| **Dimensions** | {r.length_ft:.0f}' x {r.width_ft:.0f}' x {r.ceiling_height_ft:.0f}' |
| **Floor Area** | {area:,.0f} SF |
| **Volume** | {volume:,.0f} CF |

---

## AI Vision Analysis Summary

{vision_summary}

---

## Field Observations

{obs_summary}

---

## Air Filtration Requirements

Per NADCA ACR 2021, Section 3.6:

- **Required ACH**: 4 air changes per hour
- **Total Volume**: {stats['total_volume_cf']} CF
- **Air Scrubbers Required**: {stats['air_scrubbers_required']} units (2000 CFM each)
- **Calculation**: ({stats['total_volume_cf']} CF × 4 ACH) / (2000 CFM × 60) = {stats['air_scrubbers_required']} units

---

## Regulatory Flags

{reg_flags}

---

## Sampling Recommendations

*Detailed sampling plan to be generated based on surface inventory and zone classifications.*

---

## Disclaimer

This document was generated using AI-assisted analysis and should be reviewed by a qualified
industrial hygienist before implementation. Visual assessments require laboratory confirmation
for definitive particle identification.

---

*Generated by FDAM AI Pipeline v4.0.1*
*{datetime.now().strftime('%Y-%m-%d %H:%M')}*
"""
    return markdown