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 body: {_text or ""} Email attachments {_pdf_text or ""} ``` ## 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: "**. - **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("

Email Reply

") 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("
AI-generated email reply
") 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("
Model output table
") 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("Model output table (full screen)") btn_close = gr.Button("Close", variant="secondary") overlay_table = gr.HTML(value="
") # ===== 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( "AI-generated email reply (full screen)" ) btn_close_reply = gr.Button("Close", variant="secondary") overlay_reply_html = gr.HTML(value="
") 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="
"), # -> overlay_table gr.update(visible=False), # -> overlay_reply gr.update(value="
"), # -> 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 = "
No data
" else: html = f"
{df_to_html_table(records)}
" 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"
{text_value or 'No content'}
" 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()