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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
"""

Gradio UI for the Polymer Datasheet Crawler Agent.

Deployable as a HuggingFace Space.

"""

from __future__ import annotations

import json
import logging
import os
import tempfile
from pathlib import Path

import gradio as gr
import pandas as pd

from graph import (
    build_graph,
    db,
    run_search,
    run_upload,
    search_database,
    get_database_summary,
)
from pdf_extractor import extract_text_from_pdf
from models import DatasheetRecord

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s | %(name)s | %(levelname)s | %(message)s",
)
logger = logging.getLogger(__name__)


# ══════════════════════════════════════════════════════════════════════════════
#  Handler Functions
# ══════════════════════════════════════════════════════════════════════════════

def handle_search(

    manufacturer: str,

    polymer_family: str,

    grade: str,

    progress=gr.Progress(),

) -> tuple[str, pd.DataFrame, str]:
    """

    Handle the 'Search & Add' tab: run the full LangGraph workflow

    to search, parse, and store a datasheet.

    """
    if not manufacturer.strip() and not polymer_family.strip():
        return (
            "⚠️ Please provide at least a manufacturer or polymer family.",
            pd.DataFrame(),
            "",
        )

    progress(0.1, desc="Initializing search...")
    try:
        progress(0.3, desc="Searching the web with Tavily...")
        result = run_search(
            manufacturer=manufacturer.strip(),
            polymer_family=polymer_family.strip(),
            grade=grade.strip(),
        )
        progress(0.9, desc="Done!")

        status = result.get("status", "unknown")
        message = result.get("message", "")

        # Build display dataframe from parsed record
        parsed = result.get("parsed_datasheet")
        display_df = pd.DataFrame()
        json_output = ""

        if parsed:
            record = DatasheetRecord(**parsed) if isinstance(parsed, dict) else parsed
            flat = record.to_flat_dict()
            # Filter out empty values and metadata for display
            display_data = {
                k: v for k, v in flat.items()
                if v and k not in ("id", "created_at")
            }
            display_df = pd.DataFrame(
                list(display_data.items()),
                columns=["Property", "Value"],
            )
            json_output = json.dumps(flat, indent=2)

        status_icon = "βœ…" if status == "success" else "❌"
        return f"{status_icon} {message}", display_df, json_output

    except Exception as exc:
        logger.exception("Search handler error")
        return f"❌ Error: {exc}", pd.DataFrame(), ""


def handle_upload(

    file_obj,

    progress=gr.Progress(),

) -> tuple[str, pd.DataFrame, str]:
    """

    Handle the 'Upload Datasheet' tab: extract text from PDF,

    then run the LangGraph workflow in upload mode.

    """
    if file_obj is None:
        return "⚠️ Please upload a PDF file.", pd.DataFrame(), ""

    progress(0.1, desc="Reading PDF...")
    try:
        # Gradio gives us a file path
        file_path = file_obj.name if hasattr(file_obj, "name") else str(file_obj)
        extracted_text = extract_text_from_pdf(file_path)

        if not extracted_text.strip():
            return (
                "⚠️ Could not extract text from the PDF. "
                "It may be image-based (scanned). Try a text-based PDF.",
                pd.DataFrame(),
                "",
            )

        progress(0.4, desc="Parsing with LLM...")
        result = run_upload(uploaded_text=extracted_text)
        progress(0.9, desc="Done!")

        status = result.get("status", "unknown")
        message = result.get("message", "")

        parsed = result.get("parsed_datasheet")
        display_df = pd.DataFrame()
        json_output = ""

        if parsed:
            record = DatasheetRecord(**parsed) if isinstance(parsed, dict) else parsed
            flat = record.to_flat_dict()
            display_data = {
                k: v for k, v in flat.items()
                if v and k not in ("id", "created_at")
            }
            display_df = pd.DataFrame(
                list(display_data.items()),
                columns=["Property", "Value"],
            )
            json_output = json.dumps(flat, indent=2)

        status_icon = "βœ…" if status == "success" else "❌"
        return f"{status_icon} {message}", display_df, json_output

    except Exception as exc:
        logger.exception("Upload handler error")
        return f"❌ Error: {exc}", pd.DataFrame(), ""


def handle_db_search(

    query: str,

    manufacturer: str,

    polymer_family: str,

) -> pd.DataFrame:
    """Search the database and return results."""
    try:
        df = search_database(
            query=query.strip(),
            manufacturer=manufacturer.strip(),
            polymer_family=polymer_family.strip(),
        )
        if df.empty:
            return pd.DataFrame({"Info": ["No matching records found."]})
        return df
    except Exception as exc:
        logger.exception("DB search error")
        return pd.DataFrame({"Error": [str(exc)]})


def handle_db_summary() -> tuple[pd.DataFrame, str]:
    """Get the full database summary."""
    try:
        df = get_database_summary()
        count = db.count()
        info = f"πŸ“Š Database contains {count} datasheet(s)."
        if df.empty:
            return pd.DataFrame({"Info": ["Database is empty."]}), info
        return df, info
    except Exception as exc:
        logger.exception("DB summary error")
        return pd.DataFrame({"Error": [str(exc)]}), f"❌ Error: {exc}"


def handle_export_csv() -> str | None:
    """Export the entire database to a CSV file for download."""
    try:
        df = db.get_all_dataframe()
        if df.empty:
            return None
        tmp = tempfile.NamedTemporaryFile(
            suffix=".csv", delete=False, mode="w", encoding="utf-8",
        )
        df.to_csv(tmp.name, index=False)
        tmp.close()
        return tmp.name
    except Exception as exc:
        logger.exception("Export error")
        return None


# ══════════════════════════════════════════════════════════════════════════════
#  Gradio App
# ══════════════════════════════════════════════════════════════════════════════

def create_app() -> gr.Blocks:
    """Build the Gradio Blocks application."""

    with gr.Blocks(
        title="πŸ§ͺ Polymer Datasheet Agent",
        theme=gr.themes.Soft(),
        css="""

        .header { text-align: center; margin-bottom: 1em; }

        .status-box { font-size: 1.1em; font-weight: 600; padding: 0.5em; }

        """,
    ) as app:

        # ── Header ───────────────────────────────────────────────────────
        gr.Markdown(
            """

            # πŸ§ͺ Polymer Datasheet Crawler Agent

            **Build a searchable database of commercial polymer datasheets.**



            This agent uses **Tavily** to search the web for technical datasheets,

            **LLaMA 3.1** to extract structured properties, and stores results in

            a local **SQLite** database.



            ---

            """,
            elem_classes=["header"],
        )

        # ── Tab 1: Search & Add ──────────────────────────────────────────
        with gr.Tab("πŸ” Search & Add Datasheet"):
            gr.Markdown(
                "Enter a manufacturer and/or polymer family to search for "
                "datasheets online and add them to the database."
            )

            with gr.Row():
                manufacturer_input = gr.Textbox(
                    label="Manufacturer",
                    placeholder="e.g., SABIC, BASF, DuPont",
                    scale=2,
                )
                polymer_input = gr.Textbox(
                    label="Polymer Family",
                    placeholder="e.g., Polycarbonate, Nylon 6,6, PEEK",
                    scale=2,
                )
                grade_input = gr.Textbox(
                    label="Grade (optional)",
                    placeholder="e.g., Lexan 141R, Ultramid A3K",
                    scale=2,
                )

            search_btn = gr.Button("πŸ” Search & Add", variant="primary", size="lg")

            search_status = gr.Textbox(
                label="Status",
                interactive=False,
                elem_classes=["status-box"],
            )

            with gr.Accordion("Extracted Properties", open=True):
                search_table = gr.Dataframe(
                    label="Parsed Datasheet",
                    interactive=False,
                    wrap=True,
                )

            with gr.Accordion("Raw JSON Output", open=False):
                search_json = gr.Code(
                    label="JSON",
                    language="json",
                    interactive=False,
                )

            search_btn.click(
                fn=handle_search,
                inputs=[manufacturer_input, polymer_input, grade_input],
                outputs=[search_status, search_table, search_json],
            )

        # ── Tab 2: Upload Datasheet ──────────────────────────────────────
        with gr.Tab("πŸ“„ Upload Datasheet"):
            gr.Markdown(
                "Upload a PDF datasheet to extract properties and add to the database."
            )

            file_input = gr.File(
                label="Upload PDF Datasheet",
                file_types=[".pdf"],
                type="filepath",
            )
            upload_btn = gr.Button("πŸ“„ Parse & Add", variant="primary", size="lg")

            upload_status = gr.Textbox(
                label="Status",
                interactive=False,
                elem_classes=["status-box"],
            )

            with gr.Accordion("Extracted Properties", open=True):
                upload_table = gr.Dataframe(
                    label="Parsed Datasheet",
                    interactive=False,
                    wrap=True,
                )

            with gr.Accordion("Raw JSON Output", open=False):
                upload_json = gr.Code(
                    label="JSON",
                    language="json",
                    interactive=False,
                )

            upload_btn.click(
                fn=handle_upload,
                inputs=[file_input],
                outputs=[upload_status, upload_table, upload_json],
            )

        # ── Tab 3: Database Browser ──────────────────────────────────────
        with gr.Tab("πŸ—„οΈ Database Browser"):
            gr.Markdown("Search and browse the existing datasheet database.")

            with gr.Row():
                db_query = gr.Textbox(
                    label="Search query",
                    placeholder="Free text search across all fields...",
                    scale=3,
                )
                db_manufacturer = gr.Textbox(
                    label="Filter: Manufacturer",
                    placeholder="e.g., BASF",
                    scale=2,
                )
                db_polymer = gr.Textbox(
                    label="Filter: Polymer Family",
                    placeholder="e.g., Polyamide",
                    scale=2,
                )

            with gr.Row():
                db_search_btn = gr.Button("πŸ” Search Database", variant="primary")
                db_refresh_btn = gr.Button("πŸ”„ Show All Records")
                db_export_btn = gr.Button("πŸ“₯ Export to CSV")

            db_info = gr.Textbox(label="Info", interactive=False)

            db_results = gr.Dataframe(
                label="Database Records",
                interactive=False,
                wrap=True,
            )

            export_file = gr.File(label="Download CSV", visible=True)

            db_search_btn.click(
                fn=handle_db_search,
                inputs=[db_query, db_manufacturer, db_polymer],
                outputs=[db_results],
            )

            db_refresh_btn.click(
                fn=handle_db_summary,
                inputs=[],
                outputs=[db_results, db_info],
            )

            db_export_btn.click(
                fn=handle_export_csv,
                inputs=[],
                outputs=[export_file],
            )

        # ── Tab 4: About / Help ──────────────────────────────────────────
        with gr.Tab("ℹ️ About"):
            gr.Markdown(
                """

                ## Architecture



                This application is built with:



                - **[LangGraph](https://github.com/langchain-ai/langgraph)** β€”

                  Orchestrates the agent workflow as a directed state graph.

                - **[Tavily](https://tavily.com)** β€”

                  AI-optimized web search API for finding datasheets.

                - **[LLaMA 3.1](https://huggingface.co/meta-llama/Meta-Llama-3.1-8B-Instruct)** β€”

                  Open-source LLM via HuggingFace Inference API for structured extraction.

                - **SQLite + SQLAlchemy** β€” Local relational database.

                - **[Gradio](https://gradio.app)** β€” Web UI, deployable on HuggingFace Spaces.



                ## Workflow



                ```

                User Input ──► Router ──► Web Search (Tavily) ──► LLM Parse (LLaMA 3.1) ──► Store DB ──► Output

                                  β”‚                                          β–²

                                  └──► Process Upload (PDF) β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

                ```



                ## Property Categories



                The agent extracts properties across these categories:

                - **General**: Material name, trade name, manufacturer, grade, applications

                - **Mechanical**: Tensile/flexural strength, modulus, impact, hardness

                - **Thermal**: Tm, Tg, HDT, Vicat, CTE, thermal conductivity

                - **Physical**: Density, MFI, water absorption, specific gravity

                - **Electrical**: Dielectric strength/constant, resistivity

                - **Chemical Resistance**: Acid, alkali, solvent, UV resistance

                - **Regulatory**: FDA, RoHS, REACH, UL94



                ## Data Sources



                The crawler prioritizes trusted sources including:

                MatWeb, Omnexus, UL Prospector, Campus Plastics,

                and official manufacturer portals (SABIC, BASF, DuPont, Dow, etc.)



                ---

                *Built for Plinity β€” Infinite Recyclable Polymers Project*

                """
            )

    return app


# ══════════════════════════════════════════════════════════════════════════════
#  Main
# ══════════════════════════════════════════════════════════════════════════════

if __name__ == "__main__":
    app = create_app()
    app.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False,
    )