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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import io
|
| 3 |
+
import json
|
| 4 |
+
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 |
+
API_KEY = "sk-goqgnnbymargzjjiwlruhwkuvfbcfqmhcophnwwfnjrblxgs"
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
# ======================
|
| 19 |
+
# PDF → 纯文本(OCR)
|
| 20 |
+
# ======================
|
| 21 |
+
def pdf_to_text(pdf_path: str) -> str:
|
| 22 |
+
if not pdf_path or not os.path.exists(pdf_path):
|
| 23 |
+
return ""
|
| 24 |
+
|
| 25 |
+
doc = None
|
| 26 |
+
texts = []
|
| 27 |
+
try:
|
| 28 |
+
doc = fitz.open(pdf_path)
|
| 29 |
+
|
| 30 |
+
dpi = 400
|
| 31 |
+
zoom = dpi / 72.0
|
| 32 |
+
mat = fitz.Matrix(zoom, zoom)
|
| 33 |
+
|
| 34 |
+
for page in doc:
|
| 35 |
+
pix = page.get_pixmap(matrix=mat, alpha=False)
|
| 36 |
+
img = Image.open(io.BytesIO(pix.tobytes("png"))).convert("L")
|
| 37 |
+
txt = pytesseract.image_to_string(
|
| 38 |
+
img, lang="eng+chi_sim+jpn", config="--psm 6"
|
| 39 |
+
)
|
| 40 |
+
texts.append(txt.strip())
|
| 41 |
+
finally:
|
| 42 |
+
if doc is not None:
|
| 43 |
+
doc.close()
|
| 44 |
+
|
| 45 |
+
return "\n\n==== PAGE BREAK ====\n\n".join(texts)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def pdfs_to_text(pdf_file_paths) -> str:
|
| 49 |
+
"""
|
| 50 |
+
支持多 PDF:分别 OCR,然后用明确分隔符拼接到一起。
|
| 51 |
+
兼容 gr.File(type='filepath', file_count='multiple') 的返回(list[str] 或 None)。
|
| 52 |
+
"""
|
| 53 |
+
if not pdf_file_paths:
|
| 54 |
+
return ""
|
| 55 |
+
|
| 56 |
+
# 统一归一为路径列表
|
| 57 |
+
paths = []
|
| 58 |
+
if isinstance(pdf_file_paths, (list, tuple)):
|
| 59 |
+
for p in pdf_file_paths:
|
| 60 |
+
if isinstance(p, str) and os.path.exists(p):
|
| 61 |
+
paths.append(p)
|
| 62 |
+
elif isinstance(pdf_file_paths, str):
|
| 63 |
+
if os.path.exists(pdf_file_paths):
|
| 64 |
+
paths.append(pdf_file_paths)
|
| 65 |
+
|
| 66 |
+
if not paths:
|
| 67 |
+
return ""
|
| 68 |
+
|
| 69 |
+
sections = []
|
| 70 |
+
for i, p in enumerate(paths, 1):
|
| 71 |
+
base = os.path.basename(p)
|
| 72 |
+
try:
|
| 73 |
+
txt = pdf_to_text(p)
|
| 74 |
+
except Exception as e:
|
| 75 |
+
txt = f"[OCR 失败:{type(e).__name__}: {e}]"
|
| 76 |
+
sections.append(f"=== 附件 {i}: {base} ===\n{txt}")
|
| 77 |
+
|
| 78 |
+
return "\n\n==== ATTACHMENT BREAK ====\n\n".join(sections)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _safe_json_loads(text: str):
|
| 82 |
+
t = (text or "").strip()
|
| 83 |
+
if t.startswith("```"):
|
| 84 |
+
lines = t.splitlines()[1:]
|
| 85 |
+
buf = []
|
| 86 |
+
for ln in lines:
|
| 87 |
+
if ln.strip().startswith("```"):
|
| 88 |
+
break
|
| 89 |
+
buf.append(ln)
|
| 90 |
+
t = "\n".join(buf).strip()
|
| 91 |
+
return json.loads(t)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def _rows_to_dataframe(rows):
|
| 95 |
+
if not isinstance(rows, list):
|
| 96 |
+
return pd.DataFrame(
|
| 97 |
+
[{"error": "LLM 输出非 JSON 数组", "raw": str(rows)[:2000]}]
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
df = pd.DataFrame(rows)
|
| 101 |
+
want = ["field", "value", "evidence", "reasoning"]
|
| 102 |
+
for col in want:
|
| 103 |
+
if col not in df.columns:
|
| 104 |
+
df[col] = ""
|
| 105 |
+
return df[want]
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def call_llm(text: str, pdf_text: str) -> pd.DataFrame:
|
| 109 |
+
if not API_KEY:
|
| 110 |
+
return pd.DataFrame(
|
| 111 |
+
[{"error": "未设置 API 密钥:请在环境变量 SILICONFLOW_API_KEY 中配置"}]
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
MAX_CHARS = 8000
|
| 115 |
+
_text = (text or "").strip()
|
| 116 |
+
_pdf_text = (pdf_text or "").strip()
|
| 117 |
+
if len(_pdf_text) > MAX_CHARS:
|
| 118 |
+
_pdf_text = _pdf_text[:MAX_CHARS] + "\n[TRUNCATED]"
|
| 119 |
+
if len(_text) > MAX_CHARS:
|
| 120 |
+
_text = _text[:MAX_CHARS] + "\n[TRUNCATED]"
|
| 121 |
+
|
| 122 |
+
prompt = f"""
|
| 123 |
+
你的角色**:你是一名物流询价邮件的信息抽取助手。
|
| 124 |
+
**目标**:仅依据客户邮件正文抽取关键信息,并按指定字段与格式输出。
|
| 125 |
+
**限制**:只使用**原邮件正文**的信息;**禁止引入外部知识**或凭常识臆测。
|
| 126 |
+
|
| 127 |
+
## 输入
|
| 128 |
+
- 原始客户邮件正文,使用以下包裹:
|
| 129 |
+
```
|
| 130 |
+
<EMAIL>
|
| 131 |
+
|
| 132 |
+
邮件正文:
|
| 133 |
+
{_text or ""}
|
| 134 |
+
|
| 135 |
+
邮件附件
|
| 136 |
+
{_pdf_text or ""}
|
| 137 |
+
|
| 138 |
+
</EMAIL>
|
| 139 |
+
```
|
| 140 |
+
|
| 141 |
+
## 需要抽取的字段(顺序固定,共 15 个)
|
| 142 |
+
```
|
| 143 |
+
cargo.commodity_description
|
| 144 |
+
cargo.packages
|
| 145 |
+
cargo.dimensions_unit
|
| 146 |
+
cargo.dimensions
|
| 147 |
+
cargo.weight_total_gross
|
| 148 |
+
cargo.weight_per_piece
|
| 149 |
+
cargo.stackable
|
| 150 |
+
cargo.container_dimension
|
| 151 |
+
|
| 152 |
+
transport.service_required
|
| 153 |
+
transport.mode_of_transport
|
| 154 |
+
|
| 155 |
+
trade.incoterm
|
| 156 |
+
trade.pickup_address
|
| 157 |
+
trade.delivery_address
|
| 158 |
+
trade.port_or_airport_of_loading
|
| 159 |
+
trade.port_or_airport_of_discharge
|
| 160 |
+
```
|
| 161 |
+
|
| 162 |
+
## 严格的输出格式(仅允许如下)
|
| 163 |
+
- 直接输出**一个 JSON 数组**(顶层为 `[...]`),不得包含任何解释或多余文字。
|
| 164 |
+
- 数组长度 **= 15**,且元素顺序与字段列表一一对应(第 n 个元素即第 n 个字段)。
|
| 165 |
+
- 每个元素必须且仅包含 4 个字符串键:`field`、`value`、`evidence`、`reasoning`。
|
| 166 |
+
|
| 167 |
+
## `reasoning` 写作规范(每个字段必填且为非空字符串)
|
| 168 |
+
- 若原文**未出现且无法推断**:
|
| 169 |
+
- `value`:`""`
|
| 170 |
+
- `evidence`:`""`
|
| 171 |
+
- `reasoning`:写“未在原文找到”
|
| 172 |
+
- 若可由原文**推断**得到(即使无逐字表述):
|
| 173 |
+
- 在 `reasoning` 中明确写**“推断成立”**,并包含:
|
| 174 |
+
1. **定位���明**:指出 `evidence`(逐字引用片段)来自哪一段/哪一句;
|
| 175 |
+
2. **推断路径**:逐步解释由哪些词句与上下文关系推出该值(如同义改写、指代消解、并列结构、角色线索如“Collection/Delivery/port of …”等);
|
| 176 |
+
3. **规范化说明**(如适用):单位统一、尺寸格式化、去除修饰词;
|
| 177 |
+
4. **边界与排除**:说明放弃的其他可能解释及原因。
|
| 178 |
+
|
| 179 |
+
## 解析与拼接规则
|
| 180 |
+
1. **证据逐字引用**:`evidence` 只能直接引自原文;若需多处证据,用 **`||`** 在**同一字符串**中分隔,不得改写。
|
| 181 |
+
2. **多值字段统一用分号拼接**:
|
| 182 |
+
- `cargo.packages` 例:`"1 pallet; 37 boxes"`
|
| 183 |
+
- `cargo.dimensions` 例:`"65x55x69 cm; 141x71x228 cm; 116x116x122 cm"`
|
| 184 |
+
- `cargo.weight_per_piece` 例:`"18.5 kg; 22 kg"`
|
| 185 |
+
- 对应的多处 `evidence` 同样用 `||` 拼接。
|
| 186 |
+
3. **尺寸规范**:输出为**紧凑格式** `LxWxH 单位`;将 “cms” 规范为 “cm”;忽略 “high/height”等修饰词;数字与 `x` 之间不留空格。
|
| 187 |
+
4. **重量字段**:
|
| 188 |
+
- `cargo.weight_total_gross`:仅在明确表示总体/总毛重(如 “Total gross weight/总重/GW” 且语义为整体)时填写;
|
| 189 |
+
- `cargo.weight_per_piece`:逐件/逐明细重量以分号汇总;单位保持原文。
|
| 190 |
+
5. **堆码性**(`cargo.stackable`):仅在出现明确线索(如 “stackable / not stackable / Stackability: Yes/No”)时填 `Yes/No`;否则置空。
|
| 191 |
+
6. **集装箱规格**(`cargo.container_dimension`):仅在出现如 `20GP/40HQ/40' HC/45HC` 或具体箱型尺寸时填写;不得由“crates/pallets/boxes”等包装外推。
|
| 192 |
+
7. **服务类型与运输方式**:
|
| 193 |
+
- `transport.service_required`:当文本明确描述“门到门/门到港/港到港/含报关清关”等,或可由同段出现“Collection …”与“Delivery …”的一次性贯通描述**推断**时填写;否则置空。
|
| 194 |
+
- `transport.mode_of_transport`:如 `Air Freight`、`Sea Freight (LCL/FCL)`、`Road` 等;仅当出现直接线索词(“air/flight/airfreight/sea/ocean/vessel/road/truck”等)或可由明确上下文**推断**时填写;仅凭“报价/时效”不得推断。
|
| 195 |
+
8. **Incoterm**(`trade.incoterm`):仅写标准术语(EXW/FCA/FOB/CFR/CIF/CPT/CIP/DAP/DPU/DDP)。若无明确术语且仅有“Collection/Delivery”等操作词,不得外推;在 `reasoning` 说明“线索不足,未推断”。
|
| 196 |
+
9. **地址/港口/机场判定(可推断)**:
|
| 197 |
+
- `trade.pickup_address`:出现 “Collection/Pick-up/Collect from …” 等可**推断**为提货地址;值保留原文格式(城市/邮编/国家等)。
|
| 198 |
+
- `trade.delivery_address`:出现 “Delivery/Deliver to/Ship to/Consignee address …” 等可**推断**为送货地址。
|
| 199 |
+
- `trade.port_or_airport_of_loading` / `trade.port_or_airport_of_discharge`:需出现包含 “port/airport of …” 或等价的明确线索;仅凭城市名或邮编不得外推具体港/机场名称。
|
| 200 |
+
10. **仅使用原文 + 推断边界**:
|
| 201 |
+
- 在**原文语义线索充分**的前提下允许推断;**禁止**使用外部知识。
|
| 202 |
+
- 若存在多种解释,选择**文本支持最充分、标注最明确**的一种,并在 `reasoning` 写明排除理由。
|
| 203 |
+
- 当文本线索不足以支撑推断时,一律置空,并在 `reasoning` 说明“线索不足”。
|
| 204 |
+
11. **去重与一致性**:`value` 去重;`evidence` 可含多处出处(用 `||` 拼接),在 `reasoning` 说明取舍逻辑。
|
| 205 |
+
|
| 206 |
+
## 质量检查(生成前自查)
|
| 207 |
+
- 数组元素个数 **= 15**,顺序与字段列表严格一致。
|
| 208 |
+
- 每个元素均含 `field`、`value`、`evidence`、`reasoning` 四键且为字符串。
|
| 209 |
+
- `evidence` 全部为原文逐字引用;多证据在同一字符串中用 `||` 拼接。
|
| 210 |
+
- 对涉及推断的字段,`reasoning` 明确写出:**“推断成立 + 推断路径 + 边界与排除”**。
|
| 211 |
+
"""
|
| 212 |
+
|
| 213 |
+
payload = {
|
| 214 |
+
"model": "Qwen/Qwen3-14B",
|
| 215 |
+
"temperature": 0.7,
|
| 216 |
+
"messages": [
|
| 217 |
+
{"role": "system", "content": "只输出 JSON 数组,不要包含解释或其他文本。"},
|
| 218 |
+
{"role": "user", "content": prompt},
|
| 219 |
+
],
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
try:
|
| 223 |
+
r = requests.post(
|
| 224 |
+
"https://api.siliconflow.cn/v1/chat/completions",
|
| 225 |
+
headers={
|
| 226 |
+
"Authorization": f"Bearer {API_KEY}",
|
| 227 |
+
"Content-Type": "application/json",
|
| 228 |
+
},
|
| 229 |
+
json=payload,
|
| 230 |
+
timeout=120,
|
| 231 |
+
)
|
| 232 |
+
except Exception as e:
|
| 233 |
+
return pd.DataFrame([{"error": f"请求异常:{type(e).__name__}: {e}"}])
|
| 234 |
+
|
| 235 |
+
if r.status_code != 200:
|
| 236 |
+
txt = r.text
|
| 237 |
+
return pd.DataFrame([{"error": f"HTTP {r.status_code}", "detail": txt[:2000]}])
|
| 238 |
+
|
| 239 |
+
try:
|
| 240 |
+
data = r.json()
|
| 241 |
+
except Exception as e:
|
| 242 |
+
return pd.DataFrame(
|
| 243 |
+
[{"error": f"解析响应 JSON 失败:{e}", "raw": r.text[:2000]}]
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
content = data.get("choices", [{}])[0].get("message", {}).get("content", "")
|
| 247 |
+
if not content:
|
| 248 |
+
err = data.get("error", {}).get("message", "LLM 空响应")
|
| 249 |
+
return pd.DataFrame([{"error": err}])
|
| 250 |
+
|
| 251 |
+
try:
|
| 252 |
+
rows = _safe_json_loads(content)
|
| 253 |
+
except Exception as e:
|
| 254 |
+
return pd.DataFrame([{"error": f"JSON 解析失败:{e}", "raw": content[:2000]}])
|
| 255 |
+
|
| 256 |
+
return _rows_to_dataframe(rows)
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def df_to_html_table(records):
|
| 260 |
+
try:
|
| 261 |
+
df = pd.DataFrame(records)
|
| 262 |
+
except Exception:
|
| 263 |
+
df = pd.DataFrame(
|
| 264 |
+
[{"error": "无法将数据渲染为表格", "raw": str(records)[:1000]}]
|
| 265 |
+
)
|
| 266 |
+
cols = ["field", "value", "evidence", "reasoning"]
|
| 267 |
+
for c in cols:
|
| 268 |
+
if c not in df.columns:
|
| 269 |
+
df[c] = ""
|
| 270 |
+
df = df[cols]
|
| 271 |
+
return df.to_html(index=False, escape=False)
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
def run_pipeline(text, pdf_files):
|
| 275 |
+
if not text or not str(text).strip():
|
| 276 |
+
return pd.DataFrame(
|
| 277 |
+
[{"error": "文本为必填项:请在左侧文本框粘贴/输入邮件正文。"}]
|
| 278 |
+
)
|
| 279 |
+
try:
|
| 280 |
+
pdf_text = pdfs_to_text(pdf_files) if pdf_files else ""
|
| 281 |
+
except Exception as e:
|
| 282 |
+
return pd.DataFrame([{"error": f"OCR 失败:{type(e).__name__}: {e}"}])
|
| 283 |
+
return call_llm(str(text).strip(), pdf_text or "")
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
CSS = """
|
| 287 |
+
/* 覆盖层:自身不滚动,由内层 table-wrap 滚动 */
|
| 288 |
+
#overlay {
|
| 289 |
+
position: fixed !important;
|
| 290 |
+
inset: 0 !important;
|
| 291 |
+
background: #ffffff !important;
|
| 292 |
+
z-index: 9999 !important;
|
| 293 |
+
display: flex;
|
| 294 |
+
flex-direction: column;
|
| 295 |
+
padding: 16px;
|
| 296 |
+
gap: 12px;
|
| 297 |
+
overflow: hidden; /* 关键:不要在外层滚动 */
|
| 298 |
+
}
|
| 299 |
+
|
| 300 |
+
/* 顶部工具条(标题 + 关闭按钮)整体吸顶 */
|
| 301 |
+
#overlay_bar {
|
| 302 |
+
position: sticky;
|
| 303 |
+
top: 0;
|
| 304 |
+
background: #fff;
|
| 305 |
+
padding: 8px 0;
|
| 306 |
+
border-bottom: 1px solid #eee;
|
| 307 |
+
z-index: 3;
|
| 308 |
+
display: flex;
|
| 309 |
+
align-items: center;
|
| 310 |
+
gap: 8px;
|
| 311 |
+
}
|
| 312 |
+
|
| 313 |
+
/* 表格区域作为唯一滚动容器 */
|
| 314 |
+
#overlay .table-wrap {
|
| 315 |
+
flex: 1; /* 占满剩余高度 */
|
| 316 |
+
min-height: 0; /* 避免 flex 子项高度溢出 */
|
| 317 |
+
overflow: auto; /* 只在这里滚动 */
|
| 318 |
+
}
|
| 319 |
+
|
| 320 |
+
/* 表格与表头吸顶 */
|
| 321 |
+
#overlay .table-wrap table { width: 100%; border-collapse: collapse; }
|
| 322 |
+
#overlay .table-wrap th, #overlay .table-wrap td {
|
| 323 |
+
border: 1px solid #e5e7eb; padding: 8px; vertical-align: top; text-align: left;
|
| 324 |
+
}
|
| 325 |
+
#overlay .table-wrap thead th {
|
| 326 |
+
position: sticky;
|
| 327 |
+
top: 0; /* 关键:相对 table-wrap 顶部吸顶 */
|
| 328 |
+
background: #fafafa;
|
| 329 |
+
z-index: 2;
|
| 330 |
+
}
|
| 331 |
+
"""
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
with gr.Blocks(title="邮件回复", css=CSS) as demo:
|
| 335 |
+
# gr.Markdown("# 邮件回复")
|
| 336 |
+
gr.HTML("<h1 style='text-align:center;margin:0;'>邮件回复</h1>")
|
| 337 |
+
|
| 338 |
+
with gr.Row():
|
| 339 |
+
inp_text = gr.Textbox(
|
| 340 |
+
lines=8, label="文本(必选)", placeholder="粘贴/输入邮件正文"
|
| 341 |
+
)
|
| 342 |
+
# 允许多选 PDF;使用 type='filepath' 返回路径,兼容旧版 gradio
|
| 343 |
+
inp_files = gr.File(
|
| 344 |
+
label="PDF 文件(可选,可多选)",
|
| 345 |
+
file_types=[".pdf"],
|
| 346 |
+
type="filepath",
|
| 347 |
+
file_count="multiple",
|
| 348 |
+
)
|
| 349 |
+
|
| 350 |
+
with gr.Row():
|
| 351 |
+
btn_run = gr.Button("运行", variant="primary")
|
| 352 |
+
btn_open = gr.Button("全屏打开表格", variant="secondary")
|
| 353 |
+
|
| 354 |
+
df_compact = gr.Dataframe(label="模型输出表格", interactive=False)
|
| 355 |
+
state_records = gr.State(value=None)
|
| 356 |
+
|
| 357 |
+
# 全屏覆盖层:用 Column + HTML(无脚本),显示时置 visible=True
|
| 358 |
+
with gr.Column(visible=False, elem_id="overlay") as overlay:
|
| 359 |
+
|
| 360 |
+
with gr.Row(elem_id="overlay_bar"):
|
| 361 |
+
_ = gr.HTML("<span class='title'>模型输出表格(全屏)</span>")
|
| 362 |
+
btn_close = gr.Button("关闭全屏", variant="secondary")
|
| 363 |
+
|
| 364 |
+
overlay_table = gr.HTML(value="<div class='table-wrap'></div>")
|
| 365 |
+
|
| 366 |
+
def on_run(text, files):
|
| 367 |
+
df = run_pipeline(text, files)
|
| 368 |
+
return (
|
| 369 |
+
df,
|
| 370 |
+
df.to_dict(orient="records"),
|
| 371 |
+
gr.update(visible=False),
|
| 372 |
+
gr.update(value="<div class='table-wrap'></div>"),
|
| 373 |
+
)
|
| 374 |
+
|
| 375 |
+
btn_run.click(
|
| 376 |
+
on_run,
|
| 377 |
+
inputs=[inp_text, inp_files],
|
| 378 |
+
outputs=[df_compact, state_records, overlay, overlay_table],
|
| 379 |
+
)
|
| 380 |
+
|
| 381 |
+
def open_overlay(records):
|
| 382 |
+
if not records:
|
| 383 |
+
html = "<div class='table-wrap'>暂无数据</div>"
|
| 384 |
+
else:
|
| 385 |
+
html = f"<div class='table-wrap'>{df_to_html_table(records)}</div>"
|
| 386 |
+
return gr.update(value=html), gr.update(visible=True)
|
| 387 |
+
|
| 388 |
+
btn_open.click(
|
| 389 |
+
open_overlay, inputs=[state_records], outputs=[overlay_table, overlay]
|
| 390 |
+
)
|
| 391 |
+
|
| 392 |
+
def close_overlay():
|
| 393 |
+
return gr.update(visible=False)
|
| 394 |
+
|
| 395 |
+
btn_close.click(close_overlay, outputs=[overlay])
|
| 396 |
+
|
| 397 |
+
if __name__ == "__main__":
|
| 398 |
+
# 公共网络
|
| 399 |
+
demo.launch(share=True)
|
packages.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
tesseract-ocr
|
| 2 |
+
tesseract-ocr-eng
|
| 3 |
+
tesseract-ocr-chi-sim
|
| 4 |
+
tesseract-ocr-jpn
|
| 5 |
+
libgl1
|
requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
pandas
|
| 3 |
+
requests
|
| 4 |
+
pymupdf
|
| 5 |
+
pillow
|
| 6 |
+
pytesseract
|