File size: 28,712 Bytes
1ae0881
 
 
 
 
 
 
12c72c9
1ae0881
 
 
 
12c72c9
65a8ebe
1ae0881
da23ad3
 
12c72c9
da23ad3
1ae0881
 
 
 
 
 
 
da23ad3
1ae0881
12c72c9
da23ad3
 
 
 
 
 
 
 
12c72c9
da23ad3
1ae0881
 
 
 
 
 
da23ad3
 
 
 
 
 
1ae0881
da23ad3
 
 
 
 
 
1ae0881
12c72c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da23ad3
12c72c9
da23ad3
12c72c9
 
da23ad3
12c72c9
da23ad3
12c72c9
1ae0881
 
12c72c9
 
 
 
da23ad3
12c72c9
 
 
da23ad3
12c72c9
da23ad3
 
 
12c72c9
 
 
da23ad3
12c72c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da23ad3
12c72c9
 
 
 
 
 
 
da23ad3
12c72c9
da23ad3
 
12c72c9
da23ad3
12c72c9
 
 
da23ad3
 
1ae0881
 
da23ad3
1ae0881
da23ad3
 
1ae0881
 
da23ad3
 
 
1ae0881
 
 
 
 
 
 
12c72c9
1ae0881
12c72c9
 
 
 
 
 
 
 
 
 
1ae0881
12c72c9
 
1ae0881
 
 
 
12c72c9
 
 
 
 
1ae0881
 
12c72c9
 
 
 
 
1ae0881
 
 
 
12c72c9
 
 
1ae0881
 
 
 
12c72c9
 
 
1ae0881
da23ad3
12c72c9
1ae0881
 
 
da23ad3
1ae0881
 
12c72c9
 
1ae0881
 
 
 
da23ad3
1ae0881
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da23ad3
 
1ae0881
 
12c72c9
 
 
 
da23ad3
12c72c9
 
da23ad3
 
12c72c9
 
 
 
 
da23ad3
12c72c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da23ad3
12c72c9
 
 
 
 
 
 
 
 
 
da23ad3
12c72c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ae0881
 
38d81b0
 
1ae0881
 
da23ad3
 
12c72c9
da23ad3
1ae0881
 
 
 
 
 
 
 
 
 
 
 
12c72c9
1ae0881
 
12c72c9
1ae0881
 
 
 
 
 
 
 
 
da23ad3
1ae0881
 
 
 
da23ad3
1ae0881
 
 
 
 
da23ad3
12c72c9
da23ad3
1ae0881
 
 
 
 
 
 
 
 
12c72c9
1ae0881
 
 
 
 
 
 
 
 
12c72c9
 
da23ad3
 
 
 
 
 
 
 
12c72c9
da23ad3
 
 
 
12c72c9
 
 
da23ad3
 
 
12c72c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da23ad3
12c72c9
da23ad3
12c72c9
 
 
da23ad3
12c72c9
da23ad3
 
 
 
 
12c72c9
da23ad3
 
 
 
 
 
 
 
 
 
 
12c72c9
da23ad3
 
12c72c9
 
da23ad3
 
 
 
 
 
 
 
12c72c9
 
da23ad3
 
12c72c9
 
da23ad3
 
12c72c9
da23ad3
12c72c9
 
da23ad3
 
 
 
 
1ae0881
da23ad3
 
 
 
12c72c9
da23ad3
 
 
 
1ae0881
 
12c72c9
 
1ae0881
da23ad3
 
 
 
12c72c9
da23ad3
12c72c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da23ad3
12c72c9
 
 
 
da23ad3
 
1ae0881
 
 
12c72c9
da23ad3
4db6206
 
 
 
 
 
1ae0881
4db6206
 
1ae0881
 
da23ad3
 
1ae0881
 
 
 
 
 
 
 
 
da23ad3
1ae0881
 
12c72c9
da23ad3
4db6206
 
da23ad3
 
 
 
1ae0881
 
12c72c9
da23ad3
 
1ae0881
 
da23ad3
1ae0881
da23ad3
4db6206
1ae0881
 
da23ad3
 
 
 
 
 
 
 
 
 
12c72c9
da23ad3
 
 
 
 
 
1ae0881
 
 
da23ad3
 
1ae0881
 
 
12c72c9
1ae0881
12c72c9
1ae0881
12c72c9
 
1ae0881
 
 
 
 
da23ad3
1ae0881
12c72c9
da23ad3
 
12c72c9
da23ad3
 
 
 
 
 
 
 
12c72c9
da23ad3
 
 
 
12c72c9
 
 
da23ad3
 
 
 
12c72c9
1ae0881
 
da23ad3
1ae0881
 
12c72c9
da23ad3
1ae0881
 
da23ad3
 
 
 
12c72c9
da23ad3
 
 
 
1ae0881
12c72c9
1ae0881
da23ad3
12c72c9
 
 
 
da23ad3
 
 
 
1ae0881
 
 
 
 
da23ad3
 
 
 
 
 
 
 
 
1ae0881
 
da23ad3
1ae0881
da23ad3
1ae0881
 
 
 
da23ad3
 
 
 
 
 
 
 
 
12c72c9
da23ad3
 
 
 
 
 
 
 
1ae0881
 
da23ad3
1ae0881
 
da23ad3
1ae0881
 
da23ad3
12c72c9
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
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
import os
import io
import json
import requests
import pandas as pd
import gradio as gr

# === OCR dependencies ===
import fitz  # PyMuPDF
from PIL import Image
import pytesseract

# Read environment variable (recommended): export SILICONFLOW_API_KEY=...
API_KEY = os.getenv("SILICONFLOW_API_KEY", "").strip()


# ===============
# PDF → Text (try native text first, fall back to OCR if insufficient)
# ===============
def pdf_to_text(pdf_path: str) -> str:
    if not pdf_path or not os.path.exists(pdf_path):
        return ""

    doc = None
    try:
        doc = fitz.open(pdf_path)
        texts = []

        # 1) Try extracting text directly
        for page in doc:
            t = page.get_text("text") or ""
            if t.strip():
                texts.append(t)
        extracted = "\n".join(texts).strip()
        if extracted:
            return extracted

        # 2) If no usable text, fall back to OCR
        texts = []
        dpi = 400
        zoom = dpi / 72.0
        mat = fitz.Matrix(zoom, zoom)
        for page in doc:
            pix = page.get_pixmap(matrix=mat, alpha=False)
            img = Image.open(io.BytesIO(pix.tobytes("png"))).convert("L")
            txt = pytesseract.image_to_string(img)
            if txt and txt.strip():
                texts.append(txt)
        return "\n".join(texts).strip()
    except Exception as e:
        return f"[OCR failed: {type(e).__name__}: {e}]"
    finally:
        try:
            if doc is not None:
                doc.close()
        except Exception:
            pass


def _safe_json_loads(text: str):
    t = (text or "").strip()
    if t.startswith("```"):
        lines = t.splitlines()[1:]
        buf = []
        for ln in lines:
            if ln.strip().startswith("```"):
                break
            buf.append(ln)
        t = "\n".join(buf).strip()
    return json.loads(t)


def _rows_to_dataframe(rows):
    if not isinstance(rows, list):
        return pd.DataFrame(
            [{"error": "LLM output is not a JSON array", "raw": str(rows)[:2000]}]
        )

    df = pd.DataFrame(rows)
    want = ["field", "value", "evidence", "reasoning"]
    for col in want:
        if col not in df.columns:
            df[col] = ""
    return df[want]


# ===============
# New: General "attachments to plain text" (supports .pdf / .csv / .xlsx / .xls / .txt)
# ===============
def _df_to_text(df: pd.DataFrame) -> str:
    """Convert DataFrame to plain text (CSV format, no index)."""
    try:
        return df.to_csv(index=False)
    except Exception as e:
        return f"[DataFrame to text failed: {type(e).__name__}: {e}]"


def csv_to_text(path: str) -> str:
    """Read CSV and convert to plain text."""
    # Try multiple encodings to avoid decoding failures
    for enc in (None, "utf-8", "utf-8-sig", "gb18030", "latin1"):
        try:
            df = pd.read_csv(path, dtype=str, keep_default_na=False, encoding=enc)
            return _df_to_text(df)
        except Exception:
            continue
    return f"[CSV read failed: {os.path.basename(path)}]"


def excel_to_text(path: str) -> str:
    """Read Excel (multi-sheet) and convert to plain text, marking boundaries between sheets."""
    out = []
    # Prefer openpyxl (.xlsx), otherwise default engine (may require xlrd for .xls)
    try:
        xls = pd.ExcelFile(path, engine="openpyxl")
    except Exception:
        try:
            xls = pd.ExcelFile(path)
        except Exception as e:
            return f"[Excel read failed: {type(e).__name__}: {e}]"

    for sheet in xls.sheet_names:
        try:
            df = xls.parse(sheet_name=sheet, dtype=str, keep_default_na=False)
            out.append(f"--- Sheet: {sheet} ---\n{_df_to_text(df)}")
        except Exception as e:
            out.append(
                f"--- Sheet: {sheet} ---\n[Read failed: {type(e).__name__}: {e}]"
            )
    return "\n".join(out).strip()


def txt_to_text(path: str) -> str:
    """Read TXT text with tolerant encodings."""
    for enc in ("utf-8", "utf-8-sig", "gb18030", "latin1"):
        try:
            with open(path, "r", encoding=enc, errors="ignore") as f:
                return f.read()
        except Exception:
            continue
    return f"[TXT read failed: {os.path.basename(path)}]"


def files_to_text(file_paths) -> str:
    """
    Support multiple attachment types: convert each to text and join with clear separators.
    Compatible with gr.File(type='filepath', file_count='multiple') return values (list[str] or None).
    Supported suffixes: .pdf/.csv/.xlsx/.xls/.txt
    """
    if not file_paths:
        return ""

    # Normalize to a list of paths
    paths = []
    if isinstance(file_paths, (list, tuple)):
        for p in file_paths:
            if isinstance(p, str) and os.path.exists(p):
                paths.append(p)
    elif isinstance(file_paths, str):
        if os.path.exists(file_paths):
            paths.append(file_paths)

    if not paths:
        return ""

    sections = []
    for i, p in enumerate(paths, 1):
        base = os.path.basename(p)
        ext = os.path.splitext(base)[1].lower()
        try:
            if ext == ".pdf":
                content = pdf_to_text(p)
            elif ext == ".csv":
                content = csv_to_text(p)
            elif ext in (".xlsx", ".xls"):
                content = excel_to_text(p)
            elif ext == ".txt":
                content = txt_to_text(p)
            else:
                content = f"[Unsupported attachment type: {ext}]"
        except Exception as e:
            content = f"[Attachment parse failed: {type(e).__name__}: {e}]"
        sections.append(f"=== Attachment {i}: {base} ===\n{content}")

    return "\n\n==== ATTACHMENT BREAK ====\n\n".join(sections)


def call_llm(text: str, pdf_text: str) -> pd.DataFrame:
    """
    Note: The parameter pdf_text now passes in "all attachments converted to plain text" (not limited to PDF).
    To minimize changes to the existing call signature, the parameter name is kept unchanged.
    """
    if not API_KEY:
        return pd.DataFrame(
            [
                {
                    "error": "API key not set: please configure environment variable SILICONFLOW_API_KEY"
                }
            ]
        )

    MAX_CHARS = 8000
    _text = (text or "").strip()
    _pdf_text = (pdf_text or "").strip()
    if len(_pdf_text) > MAX_CHARS:
        _pdf_text = _pdf_text[:MAX_CHARS] + "\n[TRUNCATED]"
    if len(_text) > MAX_CHARS:
        _text = _text[:MAX_CHARS] + "\n[TRUNCATED]"

    prompt = f"""
Your role: You are an information extraction assistant for logistics inquiry emails.
Goal: Extract key information solely from the customer's email body and output in the specified fields and format.
Constraints: Use only the original email body information; do NOT introduce external knowledge or make assumptions.

## Input
- Original customer email body, wrapped as follows:
```
<EMAIL>

Email body:
{_text or ""}

Email attachments
{_pdf_text or ""}

</EMAIL>
```

## Fields to extract (fixed order, total 16)
```
cargo.commodity_description
cargo.packages
cargo.dimensions_unit
cargo.dimensions
cargo.weight_total_gross
cargo.weight_per_piece
cargo.stackable
cargo.container_dimension

transport.service_required
transport.mode_of_transport

trade.incoterm
trade.pickup_address
trade.delivery_address
trade.port_or_airport_of_loading
trade.port_or_airport_of_discharge

request.air_or_sea_demand
```

## Strict output format (must follow exactly)
- Output **a JSON array** directly (top level is `[...]`), with no explanations or extra text.
- Array length **= 16**, and the element order must match the field list one-to-one (the nth element corresponds to the nth field).
- Each element MUST contain exactly 4 string keys: `field`, `value`, `evidence`, `reasoning`.

## `reasoning` writing rules (required and non-empty for every field)
- If the original text **does not contain the info and it cannot be inferred**:
  - `value`: `""`
  - `evidence`: `""`
  - `reasoning`: write "Not found in the original text"
- If it can be **inferred** from the original text (even if not verbatim):
  - In `reasoning`, explicitly write **"Inference valid"**, and include:
    1. **Location note**: indicate where the `evidence` (verbatim quoted fragment) comes from (which paragraph/sentence);
    2. **Inference path**: step-by-step explanation of how the value is derived from words/phrases and context (e.g., synonym normalization, coreference, coordination structures, role cues like "Collection/Delivery/port of …");
    3. **Normalization note** (if applicable): unit unification, dimension formatting, removing modifiers;
    4. **Boundaries & exclusions**: explain alternative interpretations that were discarded and why.

## Parsing and concatenation rules
1. **Evidence verbatim**: `evidence` must be quoted verbatim from the original text; if multiple pieces are needed, use **`||`** to separate them **within the same string**; do not paraphrase.
2. **Multi-value fields use semicolon concatenation**:
   - `cargo.packages` example: "1 pallet; 37 boxes"
   - `cargo.dimensions` example: "65x55x69 cm; 141x71x228 cm; 116x116x122 cm"
   - `cargo.weight_per_piece` example: "18.5 kg; 22 kg"
   - The corresponding multiple `evidence` pieces must also be joined with `||`.
3. **Dimension normalization**: output in compact format `LxWxH UNIT`; normalize “cms” to “cm”; ignore modifiers like “high/height”; no spaces around `x`.
4. **Weight fields**:
   - `cargo.weight_total_gross`: fill only when the text explicitly indicates overall/total gross weight (e.g., “Total gross weight/总重/GW” indicating an overall value);
   - `cargo.weight_per_piece`: per-item/per-line weights aggregated with semicolons; keep the unit as in the original text.
5. **Stackability** (`cargo.stackable`): fill `Yes/No` only when explicit clues appear (e.g., “stackable / not stackable / Stackability: Yes/No”); otherwise leave empty.
6. **Container specification** (`cargo.container_dimension`): fill only when terms like `20GP/40HQ/40' HC/45HC` or specific container dimensions appear; do not infer from “crates/pallets/boxes”.
7. **Service type & mode of transport**:
   - `transport.service_required`: fill when the text clearly describes "door to door/door to port/port to port/customs clearance included", or can be **inferred** from a single coherent description where “Collection …” and “Delivery …” appear in the same context; otherwise leave empty.
   - `transport.mode_of_transport`: e.g., `Air Freight`, `Sea Freight (LCL/FCL)`, `Road`; fill only when direct clue words (“air/flight/airfreight/sea/ocean/vessel/road/truck”, etc.) appear or can be **inferred** from clear context; do not infer merely from “quote/lead time” mentions.
   
8. **Incoterm** (`trade.incoterm`): write only standard terms (EXW/FCA/FOB/CFR/CIF/CPT/CIP/DAP/DPU/DDP). If no explicit term, **inference is allowed**:
   - When the text has clear descriptions about **delivery location/responsibility/clearance/freight/insurance** (e.g., “ex works”, “seller handles export clearance”, “to door including tax & clearance”, “to port excluding tax”, “freight & insurance by seller/buyer”), you may infer the corresponding term;
   - `reasoning` must include “Inference valid” and explain the evidence used, mapping logic, and excluded alternative terms;
   - Leave empty if clues are insufficient or contradictory;
   - Do not make assumptions without evidence.

9. **Address/port/airport determination (inference allowed)**:
   - `trade.pickup_address`: occurrences like “Collection/Pick-up/Collect from …” can be **inferred** as pickup address; keep the original format (city/ZIP/country).
   - `trade.delivery_address`: occurrences like “Delivery/Deliver to/Ship to/Consignee address …” can be **inferred** as delivery address.
   - `trade.port_or_airport_of_loading` / `trade.port_or_airport_of_discharge`: must include terms like “port/airport of …” or equivalent explicit clues; do not infer specific port/airport names from city names or ZIP codes alone.
10. **Original text only + inference boundaries**:
    - Inference is allowed **only when textual cues are sufficient**; **external knowledge is prohibited**.
    - When multiple interpretations exist, choose the one **best supported by the text and most clearly marked**, and state exclusion reasons in `reasoning`.
    - When textual cues are insufficient to support inference, leave it empty and state “insufficient cues” in `reasoning`.
11. **De-duplication & consistency**: de-duplicate `value`; `evidence` may include multiple sources (joined with `||`); explain selection logic in `reasoning`.
12. **New field: `request.air_or_sea_demand` decision rules (yes/no + purpose)**
    - Values:
        - If the email **explicitly requests air or sea freight** quotes/lead time/booking/arrangement, set `value` to **"yes"** only; do not add any other text.
        - In **all other cases** (including road/rail only, general inquiry, after-sales, contract/invoice/payment matters, etc.), set `value` to **"no: <one-sentence summary of the email's purpose>"**.
    - **Purpose writing requirements**:
        - Based only on the original text; **one sentence**, **concise**, and **non-fabricated** (e.g., “asking for an invoice / payment method inquiry / shipment status follow-up / asking pallet size”, etc.).
        - `evidence` must quote key phrases verbatim that support the purpose; if from multiple sentences, join with `||`.
        - If air/sea clues and request words like “quote/arrange/ship” are scattered across different lines but can be combined into a single need, mark **“Inference valid”** in `reasoning` and explain the merge path and exclusions.
    - **Negative boundaries** (should output no):
        - Only cities/countries/lead time appear but **no** air/sea keywords.
        - Only generic words like “delivery/ship/arrange” appear but **no** “air/sea/ocean/vessel/flight/MAWB/LCL/FCL”, etc.
        - Topics only about after-sales, contracts, invoicing, payment, document supplements, samples, technical specs confirmation, etc., not transportation inquiries.

## Quality check (self-check before generating)
- Number of array elements **= 16**, and order strictly matches the field list.
- Every element contains `field`, `value`, `evidence`, `reasoning` and all are strings.
- `evidence` is verbatim from the original text; multiple pieces joined with `||` in the **same string**.
- For inferred fields, `reasoning` must clearly state: **“Inference valid + inference path + boundaries & exclusions”**.
"""
    payload = {
        # "model": "Qwen/Qwen3-14B",
        "model": "Qwen/Qwen2.5-7B-Instruct",
        "temperature": 0.7,
        "messages": [
            {
                "role": "system",
                "content": "Output only a JSON array. Do not include explanations or any other text.",
            },
            {"role": "user", "content": prompt},
        ],
    }

    try:
        r = requests.post(
            "https://api.siliconflow.cn/v1/chat/completions",
            headers={
                "Authorization": f"Bearer {API_KEY}",
                "Content-Type": "application/json",
            },
            json=payload,
            timeout=120,
        )
    except Exception as e:
        return pd.DataFrame([{"error": f"Request exception: {type(e).__name__}: {e}"}])

    if r.status_code != 200:
        txt = r.text
        return pd.DataFrame([{"error": f"HTTP {r.status_code}", "detail": txt[:2000]}])

    try:
        data = r.json()
    except Exception as e:
        return pd.DataFrame(
            [{"error": f"Failed to parse response JSON: {e}", "raw": r.text[:2000]}]
        )

    content = data.get("choices", [{}])[0].get("message", {}).get("content", "")
    if not content:
        err = data.get("error", {}).get("message", "Empty LLM response")
        return pd.DataFrame([{"error": err}])

    try:
        rows = _safe_json_loads(content)
    except Exception as e:
        return pd.DataFrame(
            [{"error": f"JSON parse error: {e}", "raw": content[:2000]}]
        )

    return _rows_to_dataframe(rows)


def df_to_html_table(records):
    try:
        df = pd.DataFrame(records)
    except Exception:
        df = pd.DataFrame(
            [{"error": "Cannot render data as table", "raw": str(records)[:1000]}]
        )
    cols = ["field", "value", "evidence", "reasoning"]
    for c in cols:
        if c not in df.columns:
            df[c] = ""
    df = df[cols]
    return df.to_html(index=False, escape=False)


# ========= Field name mapping (Chinese → English values updated) =========
FIELD_ZH = {
    "cargo.commodity_description": "Commodity description",
    "cargo.packages": "Packages",
    "cargo.dimensions_unit": "Dimensions unit",
    "cargo.dimensions": "Dimensions",
    "cargo.weight_total_gross": "Total gross weight",
    "cargo.weight_per_piece": "Weight per piece",
    "cargo.stackable": "Stackable",
    "cargo.container_dimension": "Container dimension",
    "transport.service_required": "Service required",
    "transport.mode_of_transport": "Mode of transport",
    "trade.incoterm": "Incoterm",
    "trade.pickup_address": "Pickup address",
    "trade.delivery_address": "Delivery address",
    "trade.port_or_airport_of_loading": "Port/Airport of loading",
    "trade.port_or_airport_of_discharge": "Port/Airport of discharge",
    "request.air_or_sea_demand": "Air/Sea demand",
}


def _strip_no_prefix(raw: str) -> str:
    """Remove 'no' (any case) prefix and common delimiters (:, :, -, —, spaces) following it."""
    if not isinstance(raw, str):
        return ""
    tmp = raw.strip()
    # Check if it starts with 'no' (case-insensitive)
    if tmp[:2].lower() == "no":
        tmp = tmp[2:]
    # Remove possible delimiters
    while tmp and tmp[0] in [":", ":", "-", "—", " ", "\t"]:
        tmp = tmp[1:]
    return tmp.strip()


def _parse_air_or_sea_demand(df: pd.DataFrame):
    """Parse the decision and purpose text of request.air_or_sea_demand from the DataFrame."""
    is_yes = False
    purpose = ""
    try:
        row = df[df["field"].astype(str) == "request.air_or_sea_demand"].iloc[0]
        raw_val = str(row.get("value", "")).strip()
        low = raw_val.lower().strip()
        if low[0:3] == "yes":
            is_yes = True
            purpose = ""
        else:
            purpose = _strip_no_prefix(raw_val)
            if not purpose:
                purpose = "(No specific intent identified)"
    except Exception:
        is_yes = False
        purpose = "(No specific intent identified)"
    return is_yes, purpose


def build_reply_text(df_or_records, skip_demand_field: bool = False) -> str:
    """
    Generate the body of the "AI-generated email reply" directly using Python rules based on a DataFrame (or records list).
    Rules:
      - Fields with non-empty `value` go to "Information we have"
      - Fields with empty `value` go to "Information we still need"
      - If skip_demand_field=True, exclude request.air_or_sea_demand from both lists
    """
    # Support list[dict] / DataFrame
    if isinstance(df_or_records, list):
        df = _rows_to_dataframe(df_or_records)
    elif isinstance(df_or_records, pd.DataFrame):
        df = df_or_records.copy()
    else:
        return "# Result not generated yet."

    if not {"field", "value"}.issubset(df.columns):
        return "# Result format error; cannot generate."

    # Normalize
    df["field"] = df["field"].astype(str)
    df["value"] = df["value"].astype(str)

    known_lines = []
    unknown_lines = []

    # Output in input order
    for _, row in df.iterrows():
        field = row.get("field", "").strip()
        if skip_demand_field and field == "request.air_or_sea_demand":
            continue  # hide this field
        value = row.get("value", "").strip()
        name = FIELD_ZH.get(field, field)

        if value:
            known_lines.append(f"{len(known_lines) + 1}. {name}: {value}")
        else:
            unknown_lines.append(f"{len(unknown_lines) + 1}. {name}")

    known_block = "\n".join(known_lines) if known_lines else "(None—please provide)"
    unknown_block = "\n".join(unknown_lines) if unknown_lines else "(None)"

    body = (
        "Dear customer,\n\n"
        "Based on the information you provided, we structured the details as follows:\n\n"
        "## Information we have:\n"
        f"{known_block}\n\n"
        "## Information we still need:\n"
        f"{unknown_block}\n\n"
        "The above is generated solely from your original email content. "
        "Please reply with the missing items or confirm the captured items so that we can quote and arrange promptly."
    )
    return body


def run_pipeline(text, files):
    if not text or not str(text).strip():
        return (
            pd.DataFrame(
                [
                    {
                        "error": "Text is required: please paste/type the email body in the left text box."
                    }
                ]
            ),
            "# Please enter the email body on the left and click 'Run'.",
        )
    try:
        # New: support multi-type attachments
        attachments_text = files_to_text(files) if files else ""
    except Exception as e:
        return (
            pd.DataFrame(
                [{"error": f"Attachment parsing failed: {type(e).__name__}: {e}"}]
            ),
            "# Attachment parsing failed; cannot generate for now.",
        )
    # Pass to LLM (reuse original parameter name pdf_text)
    df = call_llm(str(text).strip(), attachments_text or "")

    # Read air/sea demand decision
    is_yes, purpose = _parse_air_or_sea_demand(df)

    # === Display logic per new requirement ===
    if is_yes:
        # Table: show normally but remove request.air_or_sea_demand
        if "field" in df.columns:
            df_display = df.copy()
            df_display["field"] = df_display["field"].astype(str)
            df_display = df_display[df_display["field"] != "request.air_or_sea_demand"]
        else:
            df_display = df

        # Reply: generate normally without that field
        reply_text = build_reply_text(df, skip_demand_field=True)
    else:
        # Table: show nothing (empty table)
        df_display = pd.DataFrame(columns=["field", "value", "evidence", "reasoning"])
        # Reply: show only one sentence
        reply_text = f"Based on model recognition, the original email is not an air/sea freight request; it is about {purpose}."

    return df_display, reply_text


CSS = """
/* Overlay: outer container not scrollable; inner content-wrap scrolls */
#overlay, #overlay_reply {
  position: fixed !important;
  inset: 0 !important;
  background: #ffffff !important;
  z-index: 9999 !important;
  display: flex;
  flex-direction: column;
  padding: 16px;
  gap: 12px;
  overflow: hidden;
}

/* Top toolbar (title + close) sticky */
#overlay_bar, #overlay_bar_reply {
  position: sticky;
  top: 0;
  background: #fff;
  padding: 8px 0;
  border-bottom: 1px solid #eee;
  z-index: 3;
  display: flex;
  align-items: center;
  gap: 8px;
  justify-content: space-between;
}

/* Fullscreen table/reply scroll containers */
.table-wrap, .reply-wrap {
  flex: 1;
  min-height: 0;
  overflow: auto;
  border: 1px solid #e5e7eb;
  padding: 8px;
  border-radius: 6px;
}

/* Table & sticky header */
.table-wrap table { width: 100%; border-collapse: collapse; }
.table-wrap th, .table-wrap td {
  border: 1px solid #e5e7eb; padding: 8px; vertical-align: top; text-align: left;
}
.table-wrap thead th {
  position: sticky;
  top: 0;
  background: #fafafa; 
  z-index: 2;
}

/* Unified section title style */
.section-title {
  font-size: 1rem;
  font-weight: 600;
  margin: 8px 0 6px;
  line-height: 1.2;
  display: inline-block;
}

/* Card appearance */
.card {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 10px;
  background: #fff;
}
"""


with gr.Blocks(title="Email Reply", css=CSS) as demo:
    gr.HTML("<h1 style='text-align:center;margin:0;'>Email Reply</h1>")

    with gr.Row():
        inp_text = gr.Textbox(
            lines=8, label="Text (required)", placeholder="Paste/type email body"
        )
        # Allow multiple attachments; use type='filepath' to return paths, compatible with older gradio
        inp_files = gr.File(
            label="Attachments (PDF/CSV/Excel/TXT, optional, multiple)",
            file_types=[".pdf", ".csv", ".xlsx", ".xls", ".txt"],
            type="filepath",
            file_count="multiple",
        )

    with gr.Row():
        btn_run = gr.Button("Run", variant="primary")

    # ====== Reply area: custom title + fullscreen button + textbox (hide default label) ======
    with gr.Row():
        gr.HTML("<div class='section-title'>AI-generated email reply</div>")
        btn_open_reply = gr.Button("Full screen", variant="secondary")
    reply_box = gr.Textbox(
        label="",
        value="",
        lines=16,
        show_copy_button=True,
        show_label=False,
    )

    # ====== Table area: keep on its own row, reply first then table ======
    with gr.Row():
        with gr.Column(scale=1, min_width=300):
            with gr.Row():
                gr.HTML("<div class='section-title'>Model output table</div>")
                btn_open_table = gr.Button(
                    "Full screen", variant="secondary"
                )
            df_compact = gr.Dataframe(
                label="", interactive=False, show_label=False, elem_classes=["card"]
            )

    # Save records for fullscreen reuse
    state_records = gr.State(value=None)

    # ===== Fullscreen overlay: table =====
    with gr.Column(visible=False, elem_id="overlay") as overlay:
        with gr.Row(elem_id="overlay_bar"):
            _ = gr.HTML("<span class='title'>Model output table (full screen)</span>")
            btn_close = gr.Button("Close", variant="secondary")
        overlay_table = gr.HTML(value="<div class='table-wrap'></div>")

    # ===== Fullscreen overlay: reply =====
    with gr.Column(visible=False, elem_id="overlay_reply") as overlay_reply:
        with gr.Row(elem_id="overlay_bar_reply"):
            _ = gr.HTML(
                "<span class='title'>AI-generated email reply (full screen)</span>"
            )
            btn_close_reply = gr.Button("Close", variant="secondary")
        overlay_reply_html = gr.HTML(value="<div class='reply-wrap'></div>")

    def on_run(text, files):
        df_display, reply_text = run_pipeline(text, files)
        return (
            reply_text,  # -> reply_box
            df_display,  # -> df_compact
            (
                df_display.to_dict(orient="records") if not df_display.empty else []
            ),  # -> state_records
            gr.update(visible=False),  # -> overlay (table)
            gr.update(value="<div class='table-wrap'></div>"),  # -> overlay_table
            gr.update(visible=False),  # -> overlay_reply
            gr.update(value="<div class='reply-wrap'></div>"),  # -> overlay_reply_html
        )

    btn_run.click(
        on_run,
        inputs=[inp_text, inp_files],
        outputs=[
            reply_box,
            df_compact,
            state_records,
            overlay,
            overlay_table,
            overlay_reply,
            overlay_reply_html,
        ],
    )

    def open_table_overlay(records):
        if not records:
            html = "<div class='table-wrap'>No data</div>"
        else:
            html = f"<div class='table-wrap'>{df_to_html_table(records)}</div>"
        return gr.update(value=html), gr.update(visible=True)

    btn_open_table.click(
        open_table_overlay, inputs=[state_records], outputs=[overlay_table, overlay]
    )

    def close_table_overlay():
        return gr.update(visible=False)

    btn_close.click(close_table_overlay, outputs=[overlay])

    # ===== Reply fullscreen toggles =====
    def open_reply_overlay(text_value):
        html = f"<div class='reply-wrap'><pre style='white-space:pre-wrap;margin:0;'>{text_value or 'No content'}</pre></div>"
        return gr.update(value=html), gr.update(visible=True)

    btn_open_reply.click(
        open_reply_overlay,
        inputs=[reply_box],
        outputs=[overlay_reply_html, overlay_reply],
    )

    def close_reply_overlay():
        return gr.update(visible=False)

    btn_close_reply.click(close_reply_overlay, outputs=[overlay_reply])

if __name__ == "__main__":
    # Public network
    demo.launch()