Spaces:
Sleeping
Sleeping
Update app.py
Browse files
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 |
-
#
|
| 14 |
API_KEY = os.getenv("SILICONFLOW_API_KEY", "").strip()
|
| 15 |
|
|
|
|
|
|
|
| 16 |
|
| 17 |
-
|
| 18 |
-
#
|
| 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 |
-
|
| 38 |
-
|
| 39 |
-
|
|
|
|
|
|
|
| 40 |
finally:
|
| 41 |
-
|
| 42 |
-
doc
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
|
| 44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
|
| 47 |
-
def
|
| 48 |
"""
|
| 49 |
-
|
| 50 |
-
兼容 gr.File(type='filepath', file_count='multiple') 的返回(list[str] 或 None)。
|
| 51 |
"""
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
return ""
|
| 54 |
|
| 55 |
-
#
|
| 56 |
paths = []
|
| 57 |
-
if isinstance(
|
| 58 |
-
for p in
|
| 59 |
if isinstance(p, str) and os.path.exists(p):
|
| 60 |
paths.append(p)
|
| 61 |
-
elif isinstance(
|
| 62 |
-
if os.path.exists(
|
| 63 |
-
paths.append(
|
| 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 =
|
| 73 |
except Exception as e:
|
| 74 |
-
txt = f"[
|
| 75 |
-
sections.append(f"===
|
| 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
|
| 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,
|
| 108 |
if not API_KEY:
|
| 109 |
return pd.DataFrame(
|
| 110 |
-
[{"error": "
|
| 111 |
)
|
| 112 |
|
| 113 |
MAX_CHARS = 8000
|
| 114 |
_text = (text or "").strip()
|
| 115 |
-
|
| 116 |
-
if len(
|
| 117 |
-
|
| 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 |
-
{
|
| 136 |
|
| 137 |
</EMAIL>
|
| 138 |
```
|
| 139 |
|
| 140 |
-
##
|
| 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 |
-
-
|
| 163 |
-
-
|
| 164 |
-
-
|
| 165 |
-
|
| 166 |
-
## `reasoning`
|
| 167 |
-
-
|
| 168 |
-
- `value`
|
| 169 |
-
- `evidence`
|
| 170 |
-
- `reasoning`
|
| 171 |
-
-
|
| 172 |
-
-
|
| 173 |
-
1. **
|
| 174 |
-
2. **
|
| 175 |
-
3. **
|
| 176 |
-
4. **
|
| 177 |
-
|
| 178 |
-
##
|
| 179 |
-
1. **
|
| 180 |
-
2. **
|
| 181 |
-
- `cargo.packages`
|
| 182 |
-
- `cargo.dimensions`
|
| 183 |
-
- `cargo.weight_per_piece`
|
| 184 |
-
-
|
| 185 |
-
3. **
|
| 186 |
-
4. **
|
| 187 |
-
- `cargo.weight_total_gross`
|
| 188 |
-
- `cargo.weight_per_piece`
|
| 189 |
-
5. **
|
| 190 |
-
6. **
|
| 191 |
-
7. **
|
| 192 |
-
- `transport.service_required`
|
| 193 |
-
- `transport.mode_of_transport`
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
-
|
| 197 |
-
- `
|
| 198 |
-
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
-
|
| 207 |
-
-
|
| 208 |
-
-
|
| 209 |
-
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
"""
|
| 211 |
-
|
| 212 |
payload = {
|
| 213 |
-
"model": "Qwen/Qwen3-14B",
|
|
|
|
| 214 |
"temperature": 0.7,
|
| 215 |
"messages": [
|
| 216 |
-
{
|
|
|
|
|
|
|
|
|
|
| 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=
|
| 230 |
)
|
| 231 |
except Exception as e:
|
| 232 |
-
return pd.DataFrame([{"error": f"
|
| 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"
|
| 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(
|
|
|
|
|
|
|
| 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": "
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 274 |
if not text or not str(text).strip():
|
| 275 |
-
return
|
| 276 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 277 |
)
|
| 278 |
try:
|
| 279 |
-
|
| 280 |
except Exception as e:
|
| 281 |
-
return
|
| 282 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 283 |
|
| 284 |
|
| 285 |
CSS = """
|
| 286 |
-
/*
|
| 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 |
-
|
| 314 |
-
flex: 1;
|
| 315 |
-
min-height: 0;
|
| 316 |
-
overflow: auto;
|
|
|
|
|
|
|
|
|
|
| 317 |
}
|
| 318 |
|
| 319 |
-
/*
|
| 320 |
-
|
| 321 |
-
|
| 322 |
border: 1px solid #e5e7eb; padding: 8px; vertical-align: top; text-align: left;
|
| 323 |
}
|
| 324 |
-
|
| 325 |
position: sticky;
|
| 326 |
-
top: 0;
|
| 327 |
background: #fafafa;
|
| 328 |
z-index: 2;
|
| 329 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 330 |
"""
|
| 331 |
|
| 332 |
|
| 333 |
-
with gr.Blocks(title="
|
| 334 |
-
|
| 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="
|
| 340 |
)
|
| 341 |
-
#
|
| 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("
|
| 351 |
-
btn_open = gr.Button("全屏打开表格", variant="secondary")
|
| 352 |
|
| 353 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 354 |
state_records = gr.State(value=None)
|
| 355 |
|
| 356 |
-
#
|
| 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'>
|
| 361 |
-
btn_close = gr.Button("
|
| 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 |
-
|
| 369 |
-
df
|
| 370 |
-
|
| 371 |
-
gr.update(
|
|
|
|
|
|
|
|
|
|
| 372 |
)
|
| 373 |
|
| 374 |
btn_run.click(
|
| 375 |
on_run,
|
| 376 |
inputs=[inp_text, inp_files],
|
| 377 |
-
outputs=[
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 378 |
)
|
| 379 |
|
| 380 |
-
def
|
| 381 |
if not records:
|
| 382 |
-
html = "<div class='table-wrap'>
|
| 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 |
-
|
| 388 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 389 |
)
|
| 390 |
|
| 391 |
-
def
|
| 392 |
return gr.update(visible=False)
|
| 393 |
|
| 394 |
-
|
| 395 |
|
| 396 |
if __name__ == "__main__":
|
| 397 |
-
#
|
| 398 |
-
demo.launch(
|
|
|
|
| 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()
|