boardman7 commited on
Commit
da23ad3
·
verified ·
1 Parent(s): 5fb5347

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +460 -150
app.py CHANGED
@@ -5,62 +5,171 @@ import requests
5
  import pandas as pd
6
  import gradio as gr
7
 
8
- # === OCR 依赖 ===
9
  import fitz # PyMuPDF
10
  from PIL import Image
11
  import pytesseract
12
 
13
- # 读取环境变量(推荐):export SILICONFLOW_API_KEY=...
14
  API_KEY = os.getenv("SILICONFLOW_API_KEY", "").strip()
15
 
 
 
16
 
17
- # ======================
18
- # PDF → 纯文本(OCR)
19
- # ======================
 
20
  def pdf_to_text(pdf_path: str) -> str:
21
  if not pdf_path or not os.path.exists(pdf_path):
22
  return ""
23
 
24
  doc = None
25
- texts = []
26
  try:
27
  doc = fitz.open(pdf_path)
 
28
 
 
 
 
 
 
 
 
 
 
 
 
29
  dpi = 400
30
  zoom = dpi / 72.0
31
  mat = fitz.Matrix(zoom, zoom)
32
-
33
  for page in doc:
34
  pix = page.get_pixmap(matrix=mat, alpha=False)
35
  img = Image.open(io.BytesIO(pix.tobytes("png"))).convert("L")
36
- txt = pytesseract.image_to_string(
37
- img, lang="eng+chi_sim+jpn", config="--psm 6"
38
- )
39
- texts.append(txt.strip())
 
 
40
  finally:
41
- if doc is not None:
42
- doc.close()
 
 
 
 
43
 
44
- return "\n\n==== PAGE BREAK ====\n\n".join(texts)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
 
47
- def pdfs_to_text(pdf_file_paths) -> str:
48
  """
49
- 支持多 PDF:分别 OCR,然后用明确分隔符拼接到一起。
50
- 兼容 gr.File(type='filepath', file_count='multiple') 的返回(list[str] 或 None)。
51
  """
52
- if not pdf_file_paths:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  return ""
54
 
55
- # 统一归一为路径列表
56
  paths = []
57
- if isinstance(pdf_file_paths, (list, tuple)):
58
- for p in pdf_file_paths:
59
  if isinstance(p, str) and os.path.exists(p):
60
  paths.append(p)
61
- elif isinstance(pdf_file_paths, str):
62
- if os.path.exists(pdf_file_paths):
63
- paths.append(pdf_file_paths)
64
 
65
  if not paths:
66
  return ""
@@ -69,10 +178,10 @@ def pdfs_to_text(pdf_file_paths) -> str:
69
  for i, p in enumerate(paths, 1):
70
  base = os.path.basename(p)
71
  try:
72
- txt = pdf_to_text(p)
73
  except Exception as e:
74
- txt = f"[OCR 失败:{type(e).__name__}: {e}]"
75
- sections.append(f"=== 附件 {i}: {base} ===\n{txt}")
76
 
77
  return "\n\n==== ATTACHMENT BREAK ====\n\n".join(sections)
78
 
@@ -93,7 +202,7 @@ def _safe_json_loads(text: str):
93
  def _rows_to_dataframe(rows):
94
  if not isinstance(rows, list):
95
  return pd.DataFrame(
96
- [{"error": "LLM 输出非 JSON 数组", "raw": str(rows)[:2000]}]
97
  )
98
 
99
  df = pd.DataFrame(rows)
@@ -104,40 +213,40 @@ def _rows_to_dataframe(rows):
104
  return df[want]
105
 
106
 
107
- def call_llm(text: str, pdf_text: str) -> pd.DataFrame:
108
  if not API_KEY:
109
  return pd.DataFrame(
110
- [{"error": "未设置 API 密钥:请在环境变量 SILICONFLOW_API_KEY 中配置"}]
111
  )
112
 
113
  MAX_CHARS = 8000
114
  _text = (text or "").strip()
115
- _pdf_text = (pdf_text or "").strip()
116
- if len(_pdf_text) > MAX_CHARS:
117
- _pdf_text = _pdf_text[:MAX_CHARS] + "\n[TRUNCATED]"
118
  if len(_text) > MAX_CHARS:
119
  _text = _text[:MAX_CHARS] + "\n[TRUNCATED]"
120
 
121
  prompt = f"""
122
- 你的角色**:你是一名物流询价邮件的信息抽取助手。
123
- **目标**:仅依据客户邮件正文抽取关键信息,并按指定字段与格式输出。
124
- **限制**:只使用**原邮件正文**的信息;**禁止引入外部知识**或凭常识臆测。
125
 
126
- ## 输入
127
- - 原始客户邮件正文,使用以下包裹:
128
  ```
129
  <EMAIL>
130
 
131
- 邮件正文:
132
  {_text or ""}
133
 
134
- 邮件附件
135
- {_pdf_text or ""}
136
 
137
  </EMAIL>
138
  ```
139
 
140
- ## 需要抽取的字段(顺序固定,共 15 个)
141
  ```
142
  cargo.commodity_description
143
  cargo.packages
@@ -156,64 +265,87 @@ trade.pickup_address
156
  trade.delivery_address
157
  trade.port_or_airport_of_loading
158
  trade.port_or_airport_of_discharge
 
 
159
  ```
160
 
161
- ## 严格的输出格式(仅允许如下)
162
- - 直接输出**一个 JSON 数组**(顶层为 `[...]`),不得包含任何解释或多余文字。
163
- - 数组长度 **= 15**,且元素顺序与字段列表一一对应(第 n 个元素即第 n 个字段)。
164
- - 每个元素必须且仅包含 4 个字符串键:`field`、`value`、`evidence`、`reasoning`。
165
-
166
- ## `reasoning` 写作规范(每个字段必填且为非空字符串)
167
- - 若原文**未出现且无法推断**:
168
- - `value`:`""`
169
- - `evidence`:`""`
170
- - `reasoning`:写“未在原文找到”
171
- - 若可由原文**推断**得到(即使无逐字表述):
172
- - 在 `reasoning` 中明确写**“推断成立”**,并包含:
173
- 1. **定位说明**:指出 `evidence`(��字引用片段)来自哪一段/哪一句;
174
- 2. **推断路径**:逐步解释由哪些词句与上下文关系推出该值(如同义改写、指代消解、并列结构、角色线索如“Collection/Delivery/port of …”等);
175
- 3. **规范化说明**(如适用):单位统一、尺寸格式化、去除修饰词;
176
- 4. **边界与排除**:说明放弃的其他可能解释及原因。
177
-
178
- ## 解析与拼接规则
179
- 1. **证据逐字引用**:`evidence` 只能直接引自原文;若需多处证据,用 **`||`** 在**同一字符串**中分隔,不得改写。
180
- 2. **多值字段统一用分号拼接**:
181
- - `cargo.packages` 例:`"1 pallet; 37 boxes"`
182
- - `cargo.dimensions` 例:`"65x55x69 cm; 141x71x228 cm; 116x116x122 cm"`
183
- - `cargo.weight_per_piece` 例:`"18.5 kg; 22 kg"`
184
- - 对应的多处 `evidence` 同样用 `||` 拼接。
185
- 3. **尺寸规范**:输出为**紧凑格式** `LxWxH 单位`;将 “cms” 规范为 “cm”;忽略 “high/height”等修饰词;数字与 `x` 之间不留空格。
186
- 4. **重量字段**:
187
- - `cargo.weight_total_gross`:仅在明确表示总体/总毛重(如 “Total gross weight/总重/GW” 且语义为整体)时填写;
188
- - `cargo.weight_per_piece`:逐件/逐明细重量以分号汇总;单位保持原文。
189
- 5. **堆码性**(`cargo.stackable`):仅在出现明确线索(如 “stackable / not stackable / Stackability: Yes/No”)时填 `Yes/No`;否则置空。
190
- 6. **集装箱规格**(`cargo.container_dimension`):仅在出现如 `20GP/40HQ/40' HC/45HC` 或具体箱型尺寸时填写;不得由“crates/pallets/boxes”等包装外推。
191
- 7. **服务类型与运输方式**:
192
- - `transport.service_required`:当文本明确描述“门到门/门到港/港到港/含报关清关”等,或可由同段出现“Collection …”与“Delivery …”的一次性贯通描述**推断**时填写;否则置空。
193
- - `transport.mode_of_transport`:如 `Air Freight`、`Sea Freight (LCL/FCL)`、`Road` 等;仅当出现直接线索词(“air/flight/airfreight/sea/ocean/vessel/road/truck”等)或可由明确上下文**推断**时填写;仅凭“报价/时效”不得推断。
194
- 8. **Incoterm**(`trade.incoterm`):仅写标准术语(EXW/FCA/FOB/CFR/CIF/CPT/CIP/DAP/DPU/DDP)。若无明确术语且仅有“Collection/Delivery”等操作词,不得外推;在 `reasoning` 说明“线索不足,未推断”。
195
- 9. **地址/港口/机场判定(可推断)**:
196
- - `trade.pickup_address`:出现 “Collection/Pick-up/Collect from …” 等可**推断**为提货地址;值保留原文格式(城市/邮编/国家等)。
197
- - `trade.delivery_address`:出现 “Delivery/Deliver to/Ship to/Consignee address …” 等可**推断**为送货地址。
198
- - `trade.port_or_airport_of_loading` / `trade.port_or_airport_of_discharge`:需出现包含 “port/airport of …” 或等价的明确线索;仅凭城市名或邮编不得外推具体港/机场名称。
199
- 10. **仅使用原文 + 推断边界**:
200
- - 在**原文语义线索充分**的前提下允许推断;**禁止**使用外部知识。
201
- - 若存在多种解释,选择**文本支持最充分、标注最明确**的一种,并在 `reasoning` 写明排除理由。
202
- - 当文本线索不足以支撑推断时,一律置空,并在 `reasoning` 说明“线索不足”。
203
- 11. **去重与一致性**:`value` 去重;`evidence` 可含多处出处(用 `||` 拼接),在 `reasoning` 说明取舍逻辑。
204
-
205
- ## 质量检查(生成前自查)
206
- - 数组元素个数 **= 15**,顺序与字段列表严格一致。
207
- - 每个元素均含 `field`、`value`、`evidence`、`reasoning` 四键且为字符串。
208
- - `evidence` 全部为原文逐字引用;多证据在同一字符串中用 `||` 拼接。
209
- - 对涉及推断的字段,`reasoning` 明确写出:**“推断成立 + 推断路径 + 边界与排除”**。
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
210
  """
211
-
212
  payload = {
213
- "model": "Qwen/Qwen3-14B",
 
214
  "temperature": 0.7,
215
  "messages": [
216
- {"role": "system", "content": "只输出 JSON 数组,不要包含解释或其他文本。"},
 
 
 
217
  {"role": "user", "content": prompt},
218
  ],
219
  }
@@ -226,10 +358,10 @@ trade.port_or_airport_of_discharge
226
  "Content-Type": "application/json",
227
  },
228
  json=payload,
229
- timeout=120,
230
  )
231
  except Exception as e:
232
- return pd.DataFrame([{"error": f"请求异常:{type(e).__name__}: {e}"}])
233
 
234
  if r.status_code != 200:
235
  txt = r.text
@@ -239,18 +371,20 @@ trade.port_or_airport_of_discharge
239
  data = r.json()
240
  except Exception as e:
241
  return pd.DataFrame(
242
- [{"error": f"解析响应 JSON 失败:{e}", "raw": r.text[:2000]}]
243
  )
244
 
245
  content = data.get("choices", [{}])[0].get("message", {}).get("content", "")
246
  if not content:
247
- err = data.get("error", {}).get("message", "LLM 空响应")
248
  return pd.DataFrame([{"error": err}])
249
 
250
  try:
251
  rows = _safe_json_loads(content)
252
  except Exception as e:
253
- return pd.DataFrame([{"error": f"JSON 解析失败:{e}", "raw": content[:2000]}])
 
 
254
 
255
  return _rows_to_dataframe(rows)
256
 
@@ -260,31 +394,132 @@ def df_to_html_table(records):
260
  df = pd.DataFrame(records)
261
  except Exception:
262
  df = pd.DataFrame(
263
- [{"error": "无法将数据渲染为表格", "raw": str(records)[:1000]}]
264
  )
265
  cols = ["field", "value", "evidence", "reasoning"]
266
  for c in cols:
267
  if c not in df.columns:
268
  df[c] = ""
 
 
 
 
269
  df = df[cols]
270
  return df.to_html(index=False, escape=False)
271
 
272
 
273
- def run_pipeline(text, pdf_files):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
274
  if not text or not str(text).strip():
275
- return pd.DataFrame(
276
- [{"error": "文本为必填项:请在左侧文本框粘贴/输入邮件正文。"}]
 
 
 
 
 
 
 
277
  )
278
  try:
279
- pdf_text = pdfs_to_text(pdf_files) if pdf_files else ""
280
  except Exception as e:
281
- return pd.DataFrame([{"error": f"OCR 失败:{type(e).__name__}: {e}"}])
282
- return call_llm(str(text).strip(), pdf_text or "")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
283
 
284
 
285
  CSS = """
286
- /* 覆盖层:自身不滚动,由内层 table-wrap 滚动 */
287
- #overlay {
288
  position: fixed !important;
289
  inset: 0 !important;
290
  background: #ffffff !important;
@@ -293,11 +528,11 @@ CSS = """
293
  flex-direction: column;
294
  padding: 16px;
295
  gap: 12px;
296
- overflow: hidden; /* 关键:不要在外层滚动 */
297
  }
298
 
299
- /* 顶部工具条(标题 + 关闭按钮)整体吸顶 */
300
- #overlay_bar {
301
  position: sticky;
302
  top: 0;
303
  background: #fff;
@@ -307,92 +542,167 @@ CSS = """
307
  display: flex;
308
  align-items: center;
309
  gap: 8px;
 
310
  }
311
 
312
- /* 表格区域作为唯一滚动容器 */
313
- #overlay .table-wrap {
314
- flex: 1; /* 占满剩余高度 */
315
- min-height: 0; /* 避免 flex 子项高度溢出 */
316
- overflow: auto; /* 只在这里滚动 */
 
 
 
317
  }
318
 
319
- /* 表格与表头吸顶 */
320
- #overlay .table-wrap table { width: 100%; border-collapse: collapse; }
321
- #overlay .table-wrap th, #overlay .table-wrap td {
322
  border: 1px solid #e5e7eb; padding: 8px; vertical-align: top; text-align: left;
323
  }
324
- #overlay .table-wrap thead th {
325
  position: sticky;
326
- top: 0; /* 关键:相对 table-wrap 顶部吸顶 */
327
  background: #fafafa;
328
  z-index: 2;
329
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
330
  """
331
 
332
 
333
- with gr.Blocks(title="邮件回复", css=CSS) as demo:
334
- # gr.Markdown("# 邮件回复")
335
- gr.HTML("<h1 style='text-align:center;margin:0;'>邮件回复</h1>")
336
 
337
  with gr.Row():
338
  inp_text = gr.Textbox(
339
- lines=8, label="文本(必选)", placeholder="粘贴/输入邮件正文"
340
  )
341
- # 允许多选 PDF;使用 type='filepath' 返回路径,兼容旧版 gradio
342
  inp_files = gr.File(
343
- label="PDF 文件(可选,可多选)",
344
- file_types=[".pdf"],
345
  type="filepath",
346
  file_count="multiple",
347
  )
348
 
349
  with gr.Row():
350
- btn_run = gr.Button("运行", variant="primary")
351
- btn_open = gr.Button("全屏打开表格", variant="secondary")
352
 
353
- df_compact = gr.Dataframe(label="模型输出表格", interactive=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
354
  state_records = gr.State(value=None)
355
 
356
- # 全屏覆盖层:用 Column + HTML(无脚本),显示时置 visible=True
357
  with gr.Column(visible=False, elem_id="overlay") as overlay:
358
-
359
  with gr.Row(elem_id="overlay_bar"):
360
- _ = gr.HTML("<span class='title'>模型输出表格(全屏)</span>")
361
- btn_close = gr.Button("关闭全屏", variant="secondary")
362
-
363
  overlay_table = gr.HTML(value="<div class='table-wrap'></div>")
364
 
 
 
 
 
 
 
 
 
 
365
  def on_run(text, files):
366
- df = run_pipeline(text, files)
367
  return (
368
- df,
369
- df.to_dict(orient="records"),
370
- gr.update(visible=False),
371
- gr.update(value="<div class='table-wrap'></div>"),
 
 
 
372
  )
373
 
374
  btn_run.click(
375
  on_run,
376
  inputs=[inp_text, inp_files],
377
- outputs=[df_compact, state_records, overlay, overlay_table],
 
 
 
 
 
 
 
 
378
  )
379
 
380
- def open_overlay(records):
381
  if not records:
382
- html = "<div class='table-wrap'>暂无数据</div>"
383
  else:
384
  html = f"<div class='table-wrap'>{df_to_html_table(records)}</div>"
385
  return gr.update(value=html), gr.update(visible=True)
386
 
387
- btn_open.click(
388
- open_overlay, inputs=[state_records], outputs=[overlay_table, overlay]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
389
  )
390
 
391
- def close_overlay():
392
  return gr.update(visible=False)
393
 
394
- btn_close.click(close_overlay, outputs=[overlay])
395
 
396
  if __name__ == "__main__":
397
- # 公共网络
398
- demo.launch(share=True)
 
5
  import pandas as pd
6
  import gradio as gr
7
 
8
+ # === OCR deps ===
9
  import fitz # PyMuPDF
10
  from PIL import Image
11
  import pytesseract
12
 
13
+ # Read from env (recommended): export SILICONFLOW_API_KEY=...
14
  API_KEY = os.getenv("SILICONFLOW_API_KEY", "").strip()
15
 
16
+ # Fields to hide in the display layer
17
+ HIDE_FIELDS = {"request.air_or_sea_demand"}
18
 
19
+
20
+ # ===============
21
+ # PDF → text (extract text first; fallback to OCR when text is insufficient)
22
+ # ===============
23
  def pdf_to_text(pdf_path: str) -> str:
24
  if not pdf_path or not os.path.exists(pdf_path):
25
  return ""
26
 
27
  doc = None
 
28
  try:
29
  doc = fitz.open(pdf_path)
30
+ texts = []
31
 
32
+ # 1) Try direct text extraction
33
+ for page in doc:
34
+ t = page.get_text("text") or ""
35
+ if t.strip():
36
+ texts.append(t)
37
+ extracted = "\n".join(texts).strip()
38
+ if extracted:
39
+ return extracted
40
+
41
+ # 2) Fallback to OCR if no usable text
42
+ texts = []
43
  dpi = 400
44
  zoom = dpi / 72.0
45
  mat = fitz.Matrix(zoom, zoom)
 
46
  for page in doc:
47
  pix = page.get_pixmap(matrix=mat, alpha=False)
48
  img = Image.open(io.BytesIO(pix.tobytes("png"))).convert("L")
49
+ txt = pytesseract.image_to_string(img)
50
+ if txt and txt.strip():
51
+ texts.append(txt)
52
+ return "\n".join(texts).strip()
53
+ except Exception as e:
54
+ return f"[OCR failed: {type(e).__name__}: {e}]"
55
  finally:
56
+ try:
57
+ if doc is not None:
58
+ doc.close()
59
+ except Exception:
60
+ pass
61
+
62
 
63
+ # ===============
64
+ # TXT / CSV / Excel → plain text
65
+ # ===============
66
+ def txt_to_text(path: str, encodings=("utf-8", "gb18030", "latin-1")) -> str:
67
+ """
68
+ Read .txt with best-effort decoding and return as a string.
69
+ """
70
+ for enc in encodings:
71
+ try:
72
+ with open(path, "r", encoding=enc, errors="strict") as f:
73
+ return f.read()
74
+ except Exception:
75
+ continue
76
+ # Last resort: ignore errors
77
+ try:
78
+ with open(path, "r", encoding="utf-8", errors="ignore") as f:
79
+ return f.read()
80
+ except Exception as e:
81
+ return f"[TXT read failed: {type(e).__name__}: {e}]"
82
 
83
 
84
+ def csv_to_text(path: str, encodings=("utf-8", "gb18030", "latin-1")) -> str:
85
  """
86
+ Load CSV to DataFrame and export as TSV text; auto-detect delimiter.
 
87
  """
88
+ last_err = None
89
+ for enc in encodings:
90
+ try:
91
+ df = pd.read_csv(path, dtype=str, sep=None, engine="python", encoding=enc)
92
+ df = df.astype(str).fillna("")
93
+ return df.to_csv(sep="\t", index=False)
94
+ except Exception as e:
95
+ last_err = e
96
+ continue
97
+ # Fallback: raw read, ignore errors, then try pandas
98
+ try:
99
+ with open(path, "r", encoding="utf-8", errors="ignore") as f:
100
+ content = f.read()
101
+ from io import StringIO
102
+
103
+ df = pd.read_csv(StringIO(content), dtype=str, sep=None, engine="python")
104
+ df = df.astype(str).fillna("")
105
+ return df.to_csv(sep="\t", index=False)
106
+ except Exception as e:
107
+ return f"[CSV read failed: {type(e).__name__}: {e if e else last_err}]"
108
+
109
+
110
+ def excel_to_text(path: str) -> str:
111
+ """
112
+ Convert Excel (.xlsx/.xls) sheets to tab-separated plain text;
113
+ prepend each sheet with a header '--- Sheet: <name> ---'.
114
+ """
115
+ try:
116
+ sheets = pd.read_excel(path, sheet_name=None, dtype=str)
117
+ except Exception as e:
118
+ return f"[Excel read failed: {type(e).__name__}: {e}]"
119
+
120
+ out_parts = []
121
+ for sheet_name, df in sheets.items():
122
+ if df is None or df.empty:
123
+ out_parts.append(f"--- Sheet: {sheet_name} ---\n(empty)")
124
+ continue
125
+ df = df.astype(str).fillna("")
126
+ tsv = df.to_csv(sep="\t", index=False)
127
+ out_parts.append(f"--- Sheet: {sheet_name} ---\n{tsv}")
128
+ return "\n\n".join(out_parts).strip()
129
+
130
+
131
+ # ===============
132
+ # Generic attachment → plain text
133
+ # ===============
134
+ def file_to_text(path: str) -> str:
135
+ """
136
+ Choose conversion strategy by extension:
137
+ - .pdf → pdf_to_text (with OCR fallback)
138
+ - .txt → read text
139
+ - .csv → DataFrame → TSV
140
+ - .xlsx/.xls → merge all sheets as TSV
141
+ Unsupported types will return a hint.
142
+ """
143
+ ext = os.path.splitext(path)[1].lower()
144
+ if ext == ".pdf":
145
+ return pdf_to_text(path)
146
+ if ext == ".txt":
147
+ return txt_to_text(path)
148
+ if ext == ".csv":
149
+ return csv_to_text(path)
150
+ if ext in (".xlsx", ".xls"):
151
+ return excel_to_text(path)
152
+ return f"[Unsupported file type: {ext}]"
153
+
154
+
155
+ def attachments_to_text(file_paths) -> str:
156
+ """
157
+ Support multiple types: PDF / TXT / CSV / Excel.
158
+ Convert each to plain text and join with clear separators.
159
+ Compatible with gr.File(type='filepath', file_count='multiple').
160
+ """
161
+ if not file_paths:
162
  return ""
163
 
164
+ # Normalize to a list of paths
165
  paths = []
166
+ if isinstance(file_paths, (list, tuple)):
167
+ for p in file_paths:
168
  if isinstance(p, str) and os.path.exists(p):
169
  paths.append(p)
170
+ elif isinstance(file_paths, str):
171
+ if os.path.exists(file_paths):
172
+ paths.append(file_paths)
173
 
174
  if not paths:
175
  return ""
 
178
  for i, p in enumerate(paths, 1):
179
  base = os.path.basename(p)
180
  try:
181
+ txt = file_to_text(p)
182
  except Exception as e:
183
+ txt = f"[Attachment parse failed: {type(e).__name__}: {e}]"
184
+ sections.append(f"=== Attachment {i}: {base} ===\n{txt}")
185
 
186
  return "\n\n==== ATTACHMENT BREAK ====\n\n".join(sections)
187
 
 
202
  def _rows_to_dataframe(rows):
203
  if not isinstance(rows, list):
204
  return pd.DataFrame(
205
+ [{"error": "LLM output is not a JSON array", "raw": str(rows)[:2000]}]
206
  )
207
 
208
  df = pd.DataFrame(rows)
 
213
  return df[want]
214
 
215
 
216
+ def call_llm(text: str, attach_text: str) -> pd.DataFrame:
217
  if not API_KEY:
218
  return pd.DataFrame(
219
+ [{"error": "API key not set: please configure env var SILICONFLOW_API_KEY"}]
220
  )
221
 
222
  MAX_CHARS = 8000
223
  _text = (text or "").strip()
224
+ _attach_text = (attach_text or "").strip()
225
+ if len(_attach_text) > MAX_CHARS:
226
+ _attach_text = _attach_text[:MAX_CHARS] + "\n[TRUNCATED]"
227
  if len(_text) > MAX_CHARS:
228
  _text = _text[:MAX_CHARS] + "\n[TRUNCATED]"
229
 
230
  prompt = f"""
231
+ Your role: A logistics quotation email information-extraction assistant.
232
+ Goal: Extract key information strictly from the customer's email body and output in the specified fields and format.
233
+ Constraint: Use only the ORIGINAL EMAIL BODY; DO NOT bring in external knowledge or assumptions.
234
 
235
+ ## Input
236
+ Wrap the original customer email as follows:
237
  ```
238
  <EMAIL>
239
 
240
+ Email body:
241
  {_text or ""}
242
 
243
+ Email attachments (PDF/TXT/CSV/Excel converted to plain text):
244
+ {_attach_text or ""}
245
 
246
  </EMAIL>
247
  ```
248
 
249
+ ## Fields to extract (fixed order, total 16)
250
  ```
251
  cargo.commodity_description
252
  cargo.packages
 
265
  trade.delivery_address
266
  trade.port_or_airport_of_loading
267
  trade.port_or_airport_of_discharge
268
+
269
+ request.air_or_sea_demand
270
  ```
271
 
272
+ ## STRICT output format (only this is allowed)
273
+ - Output exactly ONE JSON array (top-level `[...]`), and NOTHING else.
274
+ - The array length must be 16, and the element order must match the field list (the n-th element corresponds to the n-th field).
275
+ - Each element MUST contain ONLY 4 string keys: `field`, `value`, `evidence`, `reasoning`.
276
+
277
+ ## `reasoning` writing rules (each field required and must be a non-empty string)
278
+ - If the info is NOT present and NOT inferable from the text:
279
+ - `value`: `""`
280
+ - `evidence`: `""`
281
+ - `reasoning`: "Not found in the original text"
282
+ - If the value can be INFERRED from the text (even if not verbatim):
283
+ - `reasoning` must explicitly include **"Inference valid"** and contain:
284
+ 1. **Location note**: indicate from which paragraph/sentence the `evidence` (verbatim quotes) comes;
285
+ 2. **Inference path**: step-by-step explanation of which words/phrases and contextual relations lead to the value (e.g., paraphrases, coreference, coordination, cues like "Collection/Delivery/port of …");
286
+ 3. **Normalization note** (if applicable): unit unification, dimension formatting, removing modifiers;
287
+ 4. **Boundaries & exclusions**: which alternative interpretations were discarded and why.
288
+
289
+ ## Parsing & concatenation rules
290
+ 1. **Verbatim evidence**: `evidence` must be quoted VERBATIM from the text; if multiple pieces are needed, join them in the SAME STRING using **`||`** (do not paraphrase).
291
+ 2. **Multi-value fields use semicolons**:
292
+ - `cargo.packages` e.g., "1 pallet; 37 boxes"
293
+ - `cargo.dimensions` e.g., "65x55x69 cm; 141x71x228 cm; 116x116x122 cm"
294
+ - `cargo.weight_per_piece` e.g., "18.5 kg; 22 kg"
295
+ - Corresponding multi-source `evidence` must also be joined with `||`.
296
+ 3. **Dimension normalization**: compact format `LxWxH UNIT`; normalize "cms" to "cm"; ignore modifiers like "high/height"; no spaces around `x`.
297
+ 4. **Weights**:
298
+ - `cargo.weight_total_gross`: fill only when the text clearly indicates a total/overall gross weight ("Total gross weight/GW/总重") with aggregate meaning;
299
+ - `cargo.weight_per_piece`: list per-piece/per-item weights with semicolons; keep original units.
300
+ 5. **Stackability** (`cargo.stackable`): fill with `Yes/No` only if explicit cues appear ("stackable/not stackable/Stackability: Yes/No"); otherwise leave empty.
301
+ 6. **Container dimension** (`cargo.container_dimension`): fill only when explicit codes/sizes appear (e.g., `20GP/40HQ/40' HC/45HC` or exact container sizes); do NOT infer from "crates/pallets/boxes".
302
+ 7. **Service type & transport mode**:
303
+ - `transport.service_required`: fill when the text clearly describes "door-to-door/door-to-port/port-to-port/customs clearance included" etc., or when a one-pass description connects "Collection …" with "Delivery …" in the same context; otherwise leave empty.
304
+ - `transport.mode_of_transport`: e.g., `Air Freight`, `Sea Freight (LCL/FCL)`, `Road`; fill only if direct cue words appear ("air/flight/airfreight/sea/ocean/vessel/road/truck" etc.) or if clearly inferable from context; do NOT infer from "quote/timeframe" alone.
305
+
306
+ 8. **Incoterm** (`trade.incoterm`): only a standard term (EXW/FCA/FOB/CFR/CIF/CPT/CIP/DAP/DPU/DDP). If no explicit term exists, **inference is allowed**:
307
+ - When the text clearly describes **delivery location/responsibility/clearance/freight/insurance** (e.g., "ex works", "seller handles export clearance", "to door with duty & clearance", "to port excluding tax", "freight & insurance by seller/buyer"), you may map to a term;
308
+ - `reasoning` must include "Inference valid" and explain evidence, mapping, and excluded alternatives;
309
+ - Leave empty if cues are insufficient or contradictory;
310
+ - DO NOT guess without evidence.
311
+
312
+ 9. **Address/Port/Airport determination (inference allowed)**:
313
+ - `trade.pickup_address`: "Collection/Pick-up/Collect from …" may be **inferred** as pickup address; keep the original formatting (city/postcode/country etc.).
314
+ - `trade.delivery_address`: "Delivery/Deliver to/Ship to/Consignee address …" may be **inferred** as delivery address.
315
+ - `trade.port_or_airport_of_loading` / `trade.port_or_airport_of_discharge`: must include explicit cues like "port/airport of …" or equivalent; do NOT infer specific port/airport names from city/postcode alone.
316
+ 10. **Original text only + inference boundaries**:
317
+ - Inference is allowed when the textual cues are sufficient; external knowledge is **forbidden**.
318
+ - If multiple interpretations exist, choose the **best-supported** one and explain the exclusions in `reasoning`.
319
+ - When cues are insufficient, leave empty and state "insufficient cues" in `reasoning`.
320
+ 11. **De-dup & consistency**: de-duplicate `value`; `evidence` may include multiple sources (joined by `||`); explain selection in `reasoning`.
321
+ 12. **NEW field: `request.air_or_sea_demand` (yes/no + purpose)**
322
+ - Value:
323
+ - If the email clearly requests AIR or SEA shipping related quote/ETA/booking/arrangement ⇒ set `value` to **"yes"** ONLY;
324
+ - All other cases (road/rail only; general inquiry; after-sale; contract/invoice/payment info, etc.) ⇒ set `value` to **"no: <one-sentence purpose of this email>"**.
325
+ - Purpose writing:
326
+ - Summarize purely from the text, **one sentence**, **concise**, **non-fabricated** (e.g., "requesting invoice", "asking payment method", "following up shipment status", "asking pallet size").
327
+ - `evidence` must quote key phrases verbatim; if from multiple sentences, join with `||`.
328
+ - If air/sea cues and request words ("quote/arrange/ship") are in different lines but combine to one intent, mark **"Inference valid"** in `reasoning` and explain the merge path and exclusions.
329
+ - **Negative boundaries** (output "no"):
330
+ - City/country/ETA appear but **no** air/sea cues;
331
+ - Generic words like "delivery/ship/arrange" appear but **no** "air/sea/ocean/vessel/flight/MAWB/LCL/FCL" cues;
332
+ - Topics like after-sales, contract, invoicing, payment, data supplement, samples, tech spec confirmation, etc., not about transport quotation.
333
+
334
+ ## Quality checks (self-check before output)
335
+ - Array length is **16**, order matches the field list exactly.
336
+ - Each element contains string keys `field`, `value`, `evidence`, `reasoning`.
337
+ - `evidence` is verbatim from the text; multiple pieces joined with `||` in the SAME string.
338
+ - For inferred fields, `reasoning` clearly includes: **"Inference valid + inference path + boundaries & exclusions"**.
339
  """
 
340
  payload = {
341
+ # "model": "Qwen/Qwen3-14B",
342
+ "model": "Qwen/Qwen2.5-7B-Instruct",
343
  "temperature": 0.7,
344
  "messages": [
345
+ {
346
+ "role": "system",
347
+ "content": "Output ONLY a JSON array. No explanations or extra text.",
348
+ },
349
  {"role": "user", "content": prompt},
350
  ],
351
  }
 
358
  "Content-Type": "application/json",
359
  },
360
  json=payload,
361
+ timeout=240,
362
  )
363
  except Exception as e:
364
+ return pd.DataFrame([{"error": f"Request error: {type(e).__name__}: {e}"}])
365
 
366
  if r.status_code != 200:
367
  txt = r.text
 
371
  data = r.json()
372
  except Exception as e:
373
  return pd.DataFrame(
374
+ [{"error": f"Failed to parse response JSON: {e}", "raw": r.text[:2000]}]
375
  )
376
 
377
  content = data.get("choices", [{}])[0].get("message", {}).get("content", "")
378
  if not content:
379
+ err = data.get("error", {}).get("message", "Empty LLM response")
380
  return pd.DataFrame([{"error": err}])
381
 
382
  try:
383
  rows = _safe_json_loads(content)
384
  except Exception as e:
385
+ return pd.DataFrame(
386
+ [{"error": f"JSON decode error: {e}", "raw": content[:2000]}]
387
+ )
388
 
389
  return _rows_to_dataframe(rows)
390
 
 
394
  df = pd.DataFrame(records)
395
  except Exception:
396
  df = pd.DataFrame(
397
+ [{"error": "Unable to render data as table", "raw": str(records)[:1000]}]
398
  )
399
  cols = ["field", "value", "evidence", "reasoning"]
400
  for c in cols:
401
  if c not in df.columns:
402
  df[c] = ""
403
+ # Hide specified fields
404
+ if "field" in df.columns:
405
+ df["field"] = df["field"].astype(str)
406
+ df = df[~df["field"].isin(HIDE_FIELDS)]
407
  df = df[cols]
408
  return df.to_html(index=False, escape=False)
409
 
410
 
411
+ # ========= Field display names (English) & email reply generation =========
412
+ FIELD_ZH = { # keep variable name to avoid changing logic elsewhere
413
+ "cargo.commodity_description": "Commodity description",
414
+ "cargo.packages": "Packages",
415
+ "cargo.dimensions_unit": "Dimensions unit",
416
+ "cargo.dimensions": "Dimensions",
417
+ "cargo.weight_total_gross": "Total gross weight",
418
+ "cargo.weight_per_piece": "Weight per piece",
419
+ "cargo.stackable": "Stackable",
420
+ "cargo.container_dimension": "Container dimension",
421
+ "transport.service_required": "Service type",
422
+ "transport.mode_of_transport": "Mode of transport",
423
+ "trade.incoterm": "Incoterm",
424
+ "trade.pickup_address": "Pickup address",
425
+ "trade.delivery_address": "Delivery address",
426
+ "trade.port_or_airport_of_loading": "Port/airport of loading",
427
+ "trade.port_or_airport_of_discharge": "Port/airport of discharge",
428
+ "request.air_or_sea_demand": "Air/sea demand judgment",
429
+ }
430
+
431
+
432
+ def build_reply_text(df_or_records) -> str:
433
+ """
434
+ Generate the email reply body text from DataFrame (or list of records).
435
+ Rules:
436
+ - Fields with non-empty `value` go under "Information we have"
437
+ - Empty `value` fields go under "Information needed"
438
+ - Fields in HIDE_FIELDS are skipped
439
+ """
440
+ # Accept list[dict] / DataFrame
441
+ if isinstance(df_or_records, list):
442
+ df = _rows_to_dataframe(df_or_records)
443
+ elif isinstance(df_or_records, pd.DataFrame):
444
+ df = df_or_records.copy()
445
+ else:
446
+ return "# Result not ready."
447
+
448
+ if not {"field", "value"}.issubset(df.columns):
449
+ return "# Result format error; cannot generate."
450
+
451
+ # Normalize
452
+ df["field"] = df["field"].astype(str)
453
+ df["value"] = df["value"].astype(str)
454
+
455
+ known_lines = []
456
+ unknown_lines = []
457
+
458
+ # Keep input order; skip hidden fields
459
+ for _, row in df.iterrows():
460
+ field = row.get("field", "").strip()
461
+ if field in HIDE_FIELDS:
462
+ continue
463
+ value = row.get("value", "").strip()
464
+ name = FIELD_ZH.get(field, field)
465
+
466
+ if value:
467
+ known_lines.append(f"{len(known_lines) + 1}. {name}: {value}")
468
+ else:
469
+ unknown_lines.append(f"{len(unknown_lines) + 1}. {name}")
470
+
471
+ known_block = "\n".join(known_lines) if known_lines else "(none — please provide)"
472
+ unknown_block = "\n".join(unknown_lines) if unknown_lines else "(none)"
473
+
474
+ body = (
475
+ "Dear Customer,\n\n"
476
+ "Based on your email, we have structured the information as follows:\n\n"
477
+ "## Information we have:\n"
478
+ f"{known_block}\n\n"
479
+ "## Information needed:\n"
480
+ f"{unknown_block}\n\n"
481
+ "The above is generated solely from your email content. Please supplement missing items or confirm the known items so we can proceed with a quotation and arrangement."
482
+ )
483
+ return body
484
+
485
+
486
+ def run_pipeline(text, files):
487
  if not text or not str(text).strip():
488
+ return (
489
+ pd.DataFrame(
490
+ [
491
+ {
492
+ "error": "Text is required: please paste/type the email body on the left."
493
+ }
494
+ ]
495
+ ),
496
+ "# Please enter the email body on the left and click 'Run'.",
497
  )
498
  try:
499
+ attach_text = attachments_to_text(files) if files else ""
500
  except Exception as e:
501
+ return (
502
+ pd.DataFrame(
503
+ [{"error": f"Attachment parsing failed: {type(e).__name__}: {e}"}]
504
+ ),
505
+ "# Attachment parsing failed; cannot generate.",
506
+ )
507
+ df = call_llm(str(text).strip(), attach_text or "")
508
+ # Display-layer filtering: hide specified fields
509
+ if "field" in df.columns:
510
+ df_display = df.copy()
511
+ df_display["field"] = df_display["field"].astype(str)
512
+ df_display = df_display[~df_display["field"].isin(HIDE_FIELDS)]
513
+ else:
514
+ df_display = df
515
+
516
+ reply_text = build_reply_text(df) # build_reply_text also skips hidden fields
517
+ return df_display, reply_text
518
 
519
 
520
  CSS = """
521
+ /* Fullscreen overlay: outer container not scrollable; inner content-wrap scrolls */
522
+ #overlay, #overlay_reply {
523
  position: fixed !important;
524
  inset: 0 !important;
525
  background: #ffffff !important;
 
528
  flex-direction: column;
529
  padding: 16px;
530
  gap: 12px;
531
+ overflow: hidden;
532
  }
533
 
534
+ /* Top toolbar (title + close) sticky */
535
+ #overlay_bar, #overlay_bar_reply {
536
  position: sticky;
537
  top: 0;
538
  background: #fff;
 
542
  display: flex;
543
  align-items: center;
544
  gap: 8px;
545
+ justify-content: space-between;
546
  }
547
 
548
+ /* Scroll containers */
549
+ .table-wrap, .reply-wrap {
550
+ flex: 1;
551
+ min-height: 0;
552
+ overflow: auto;
553
+ border: 1px solid #e5e7eb;
554
+ padding: 8px;
555
+ border-radius: 6px;
556
  }
557
 
558
+ /* Table and sticky header */
559
+ .table-wrap table { width: 100%; border-collapse: collapse; }
560
+ .table-wrap th, .table-wrap td {
561
  border: 1px solid #e5e7eb; padding: 8px; vertical-align: top; text-align: left;
562
  }
563
+ .table-wrap thead th {
564
  position: sticky;
565
+ top: 0;
566
  background: #fafafa;
567
  z-index: 2;
568
  }
569
+
570
+ /* Unified section title style */
571
+ .section-title {
572
+ font-size: 1rem;
573
+ font-weight: 600;
574
+ margin: 8px 0 6px;
575
+ line-height: 1.2;
576
+ display: inline-block;
577
+ }
578
+
579
+ /* Card look */
580
+ .card {
581
+ border: 1px solid #e5e7eb;
582
+ border-radius: 8px;
583
+ padding: 10px;
584
+ background: #fff;
585
+ }
586
  """
587
 
588
 
589
+ with gr.Blocks(title="Email Reply", css=CSS) as demo:
590
+ gr.HTML("<h1 style='text-align:center;margin:0;'>Email Reply</h1>")
 
591
 
592
  with gr.Row():
593
  inp_text = gr.Textbox(
594
+ lines=8, label="Text (required)", placeholder="Paste/type the email body"
595
  )
596
+ # Allow multiple files (PDF/TXT/CSV/Excel); type='filepath' returns paths; compatible with older gradio
597
  inp_files = gr.File(
598
+ label="Attachments (PDF / TXT / CSV / Excel; optional, multiple)",
599
+ file_types=[".pdf", ".txt", ".csv", ".xlsx", ".xls"],
600
  type="filepath",
601
  file_count="multiple",
602
  )
603
 
604
  with gr.Row():
605
+ btn_run = gr.Button("Run", variant="primary")
 
606
 
607
+ # ===== Reply area: custom title + fullscreen button + textbox (hide default label) =====
608
+ with gr.Row():
609
+ gr.HTML("<div class='section-title'>AI-generated email reply</div>")
610
+ btn_open_reply = gr.Button("Open fullscreen", variant="secondary")
611
+ reply_box = gr.Textbox(
612
+ label="",
613
+ value="",
614
+ lines=16,
615
+ show_copy_button=True,
616
+ show_label=False,
617
+ )
618
+
619
+ # ===== Table area: compact table only (left column), with title + fullscreen button =====
620
+ with gr.Row():
621
+ with gr.Column(scale=1, min_width=300):
622
+ with gr.Row():
623
+ gr.HTML("<div class='section-title'>Model output table</div>")
624
+ btn_open_table = gr.Button("Open fullscreen", variant="secondary")
625
+ df_compact = gr.Dataframe(
626
+ label="", interactive=False, show_label=False, elem_classes=["card"]
627
+ )
628
+
629
+ # Keep records for fullscreen reuse
630
  state_records = gr.State(value=None)
631
 
632
+ # ===== Fullscreen overlay: table =====
633
  with gr.Column(visible=False, elem_id="overlay") as overlay:
 
634
  with gr.Row(elem_id="overlay_bar"):
635
+ _ = gr.HTML("<span class='title'>Model output table (fullscreen)</span>")
636
+ btn_close = gr.Button("Close", variant="secondary")
 
637
  overlay_table = gr.HTML(value="<div class='table-wrap'></div>")
638
 
639
+ # ===== Fullscreen overlay: reply =====
640
+ with gr.Column(visible=False, elem_id="overlay_reply") as overlay_reply:
641
+ with gr.Row(elem_id="overlay_bar_reply"):
642
+ _ = gr.HTML(
643
+ "<span class='title'>AI-generated email reply (fullscreen)</span>"
644
+ )
645
+ btn_close_reply = gr.Button("Close", variant="secondary")
646
+ overlay_reply_html = gr.HTML(value="<div class='reply-wrap'></div>")
647
+
648
  def on_run(text, files):
649
+ df, reply_text = run_pipeline(text, files)
650
  return (
651
+ reply_text, # -> reply_box
652
+ df, # -> df_compact (with hidden fields filtered)
653
+ df.to_dict(orient="records"), # -> state_records (filtered)
654
+ gr.update(visible=False), # -> overlay (table)
655
+ gr.update(value="<div class='table-wrap'></div>"), # -> overlay_table
656
+ gr.update(visible=False), # -> overlay_reply
657
+ gr.update(value="<div class='reply-wrap'></div>"), # -> overlay_reply_html
658
  )
659
 
660
  btn_run.click(
661
  on_run,
662
  inputs=[inp_text, inp_files],
663
+ outputs=[
664
+ reply_box,
665
+ df_compact,
666
+ state_records,
667
+ overlay,
668
+ overlay_table,
669
+ overlay_reply,
670
+ overlay_reply_html,
671
+ ],
672
  )
673
 
674
+ def open_table_overlay(records):
675
  if not records:
676
+ html = "<div class='table-wrap'>No data</div>"
677
  else:
678
  html = f"<div class='table-wrap'>{df_to_html_table(records)}</div>"
679
  return gr.update(value=html), gr.update(visible=True)
680
 
681
+ btn_open_table.click(
682
+ open_table_overlay, inputs=[state_records], outputs=[overlay_table, overlay]
683
+ )
684
+
685
+ def close_table_overlay():
686
+ return gr.update(visible=False)
687
+
688
+ btn_close.click(close_table_overlay, outputs=[overlay])
689
+
690
+ # ===== Reply fullscreen toggle =====
691
+ def open_reply_overlay(text_value):
692
+ html = f"<div class='reply-wrap'><pre style='white-space:pre-wrap;margin:0;'>{text_value or 'No content'}</pre></div>"
693
+ return gr.update(value=html), gr.update(visible=True)
694
+
695
+ btn_open_reply.click(
696
+ open_reply_overlay,
697
+ inputs=[reply_box],
698
+ outputs=[overlay_reply_html, overlay_reply],
699
  )
700
 
701
+ def close_reply_overlay():
702
  return gr.update(visible=False)
703
 
704
+ btn_close_reply.click(close_reply_overlay, outputs=[overlay_reply])
705
 
706
  if __name__ == "__main__":
707
+ # Public network
708
+ demo.launch()