Upload folder using huggingface_hub
Browse files- eval/README.md +180 -0
- eval/README_zh.md +180 -0
- eval/apis/__init__.py +27 -0
- eval/apis/base.py +23 -0
- eval/apis/local_vllm.py +76 -0
- eval/apis/openai_compat.py +84 -0
- eval/data/.gitkeep +0 -0
- eval/infer.py +392 -0
- eval/judge.py +219 -0
- eval/judges/__init__.py +12 -0
- eval/judges/_text.py +23 -0
- eval/judges/classify.py +18 -0
- eval/judges/extract_text.py +63 -0
- eval/judges/referring.py +21 -0
- eval/judges/spotting.py +150 -0
- eval/prompts/__init__.py +26 -0
- eval/prompts/_text.py +115 -0
- eval/prompts/classify.py +65 -0
- eval/prompts/extract_text.py +76 -0
- eval/prompts/referring.py +221 -0
- eval/prompts/spotting.py +133 -0
- eval/requirements.txt +14 -0
- eval/summarize.py +382 -0
- eval/utils/__init__.py +0 -0
- eval/utils/image_utils.py +77 -0
- eval/utils/io.py +107 -0
- eval/utils/signal_utils.py +40 -0
- eval/utils/unk.py +57 -0
eval/README.md
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Chronicles-OCR Benchmark
|
| 2 |
+
|
| 3 |
+
A multi-task benchmark for vision-language models on **Chinese historical script OCR**, covering all seven canonical scripts of Chinese characters: Oracle Bone (甲骨文), Bronze Script (金文), Seal Script (篆书), Clerical Script (隶书), Regular Script (楷书), Running Script (行书), Cursive Script (草书).
|
| 4 |
+
|
| 5 |
+
| Group | Scripts | Tasks |
|
| 6 |
+
| ------- | ------------------------------------------------------------------ | ------------------------------------------------- |
|
| 7 |
+
| Ancient | Oracle Bone / Bronze Script / Seal Script | Spotting · Recognition · Parsing · Classification |
|
| 8 |
+
| Modern | Clerical Script / Regular Script / Running Script / Cursive Script | Parsing · Classification |
|
| 9 |
+
|
| 10 |
+
The four tasks:
|
| 11 |
+
|
| 12 |
+
| Task | Short Name | Metric | Description |
|
| 13 |
+
| ------------------------------------------ | -------------- | --------------------- | -------------------------------------------------------------------------- |
|
| 14 |
+
| Cross-period Character Spotting | Spotting | F1 @ IoU > 0.75 | Detect bounding boxes and identify the modern character for each box |
|
| 15 |
+
| Fine-grained Archaic Character Recognition | Recognition | Exact-match Accuracy | Identify the modern character inside a red bounding box drawn on the image |
|
| 16 |
+
| Ancient Text Parsing | Parsing | 1 − NED (Levenshtein) | Read all characters in reading order; `[UNK]` is filtered before scoring |
|
| 17 |
+
| Script Classification | Classification | Accuracy | Classify the image into one of the seven canonical scripts |
|
| 18 |
+
|
| 19 |
+
All scoring is **rule-based** — no LLM judge is needed.
|
| 20 |
+
|
| 21 |
+
> Note: the Spotting task internally also reports a Detection F1 (bbox-only, IoU > 0.75 without character matching) as a diagnostic; the headline Spotting score requires both IoU and character match.
|
| 22 |
+
|
| 23 |
+
---
|
| 24 |
+
|
| 25 |
+
## 1. Setup
|
| 26 |
+
|
| 27 |
+
```bash
|
| 28 |
+
git clone <this-repo>
|
| 29 |
+
cd ChronoText/Opensource
|
| 30 |
+
pip install -r requirements.txt
|
| 31 |
+
# Optional: only if you plan to use --api_type local_vllm
|
| 32 |
+
pip install vllm
|
| 33 |
+
```
|
| 34 |
+
|
| 35 |
+
## 2. Download benchmark data
|
| 36 |
+
|
| 37 |
+
The dataset (jsonl + images) is released as a single archive. Place the files under `Opensource/data/`:
|
| 38 |
+
|
| 39 |
+
```
|
| 40 |
+
Opensource/data/
|
| 41 |
+
├── Chronicles_OCR.jsonl
|
| 42 |
+
└── images/
|
| 43 |
+
├── 甲骨文/... # Oracle Bone
|
| 44 |
+
├── 金文/... # Bronze Script
|
| 45 |
+
├── 篆书/... # Seal Script
|
| 46 |
+
├── 隶书/... # Clerical Script
|
| 47 |
+
├── 楷书/... # Regular Script
|
| 48 |
+
├── 行书/... # Running Script
|
| 49 |
+
└── 草书/... # Cursive Script
|
| 50 |
+
```
|
| 51 |
+
|
| 52 |
+
Each line of the jsonl looks like:
|
| 53 |
+
|
| 54 |
+
```json
|
| 55 |
+
{
|
| 56 |
+
"image_path": "images/甲骨文/abcdef0123.jpg",
|
| 57 |
+
"font_type": "甲骨文",
|
| 58 |
+
"annotation": "...",
|
| 59 |
+
"spotting": [{"bbox": {"x1":..,"y1":..,"x2":..,"y2":..}, "modern_char": ".."}, ...],
|
| 60 |
+
"width": 800,
|
| 61 |
+
"height": 600
|
| 62 |
+
}
|
| 63 |
+
```
|
| 64 |
+
|
| 65 |
+
`spotting` / `width` / `height` only exist for the three ancient scripts; modern scripts only carry `image_path`, `font_type`, and `annotation`.
|
| 66 |
+
|
| 67 |
+
## 3. Inference
|
| 68 |
+
|
| 69 |
+
Three backends are supported via `--api_type`:
|
| 70 |
+
|
| 71 |
+
### (a) `openai_compat` — any OpenAI-compatible HTTP service
|
| 72 |
+
|
| 73 |
+
Works with locally-served models (`vllm serve`, `sglang`, `lmdeploy`) **or** public APIs that speak the OpenAI Chat Completions protocol (OpenAI, Gemini OpenAI-compat, Claude OpenAI-compat, Together, …).
|
| 74 |
+
|
| 75 |
+
```bash
|
| 76 |
+
python infer.py \
|
| 77 |
+
--api_type openai_compat \
|
| 78 |
+
--model_name Qwen2.5-VL-7B-Instruct \
|
| 79 |
+
--base_url http://127.0.0.1:8000/v1 \
|
| 80 |
+
--api_key EMPTY \
|
| 81 |
+
--max_workers 64
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
### (b) `local_vllm` — in-process vLLM, give it a model path
|
| 85 |
+
|
| 86 |
+
No need to start a server first. The script loads the checkpoint directly with `vllm.LLM`.
|
| 87 |
+
|
| 88 |
+
```bash
|
| 89 |
+
python infer.py \
|
| 90 |
+
--api_type local_vllm \
|
| 91 |
+
--model_path /path/to/Qwen2.5-VL-7B-Instruct \
|
| 92 |
+
--tensor_parallel_size 1 \
|
| 93 |
+
--max_model_len 32768
|
| 94 |
+
```
|
| 95 |
+
|
| 96 |
+
### Output
|
| 97 |
+
|
| 98 |
+
Each run writes one jsonl file:
|
| 99 |
+
|
| 100 |
+
```
|
| 101 |
+
Opensource/infer_results/<model_tag>/results.jsonl
|
| 102 |
+
```
|
| 103 |
+
|
| 104 |
+
`<model_tag>` defaults to `--model_name` / basename of `--model_path` / `--api_name`. You can override it with `--output_tag`.
|
| 105 |
+
|
| 106 |
+
## 4. Judging
|
| 107 |
+
|
| 108 |
+
```bash
|
| 109 |
+
# All models under infer_results/
|
| 110 |
+
python judge.py
|
| 111 |
+
|
| 112 |
+
# Specific models
|
| 113 |
+
python judge.py --models Qwen2.5-VL-7B-Instruct gemini-3.1-pro
|
| 114 |
+
```
|
| 115 |
+
|
| 116 |
+
Outputs to `Opensource/judge_results/<model_tag>/results.jsonl`. The judge step is purely rule-based and **always overwrites** previous output (it is very fast).
|
| 117 |
+
|
| 118 |
+
## 5. Summary report
|
| 119 |
+
|
| 120 |
+
```bash
|
| 121 |
+
python summarize.py
|
| 122 |
+
# → Opensource/judge_results/results_analysis.xlsx
|
| 123 |
+
```
|
| 124 |
+
|
| 125 |
+
The workbook has two sheets, displayed in the canonical task order **Spotting · Recognition · Parsing · Classification**:
|
| 126 |
+
|
| 127 |
+
- **Per-group summary** — per-model averages aggregated by Ancient / Modern groups
|
| 128 |
+
- **Per-script breakdown** — per-model averages broken down by each of the seven scripts
|
| 129 |
+
|
| 130 |
+
Scores are scaled `×100` and shown to 1 decimal (e.g. `87.3` means 0.873).
|
| 131 |
+
|
| 132 |
+
---
|
| 133 |
+
|
| 134 |
+
## 6. End-to-end example
|
| 135 |
+
|
| 136 |
+
```bash
|
| 137 |
+
# 1. Run inference
|
| 138 |
+
python infer.py --api_type openai_compat \
|
| 139 |
+
--model_name Qwen2.5-VL-7B-Instruct \
|
| 140 |
+
--base_url http://127.0.0.1:8000/v1
|
| 141 |
+
|
| 142 |
+
# 2. Score
|
| 143 |
+
python judge.py
|
| 144 |
+
|
| 145 |
+
# 3. Aggregate to Excel
|
| 146 |
+
python summarize.py
|
| 147 |
+
```
|
| 148 |
+
|
| 149 |
+
---
|
| 150 |
+
|
| 151 |
+
## 7. Repo layout
|
| 152 |
+
|
| 153 |
+
```
|
| 154 |
+
Opensource/
|
| 155 |
+
├── README.md / README_zh.md
|
| 156 |
+
├── requirements.txt
|
| 157 |
+
├── data/ # ← download benchmark data here
|
| 158 |
+
├── apis/
|
| 159 |
+
│ ├── base.py # APIBase
|
| 160 |
+
│ ├── openai_compat.py # OpenAI-compatible client
|
| 161 |
+
│ ├── local_vllm.py # in-process vLLM
|
| 162 |
+
├── prompts/
|
| 163 |
+
│ ├── spotting.py # Cross-period Character Spotting
|
| 164 |
+
│ ├── referring.py # Fine-grained Archaic Character Recognition (red-box rendering)
|
| 165 |
+
│ ├── extract_text.py # Ancient Text Parsing
|
| 166 |
+
│ └── classify.py # Script Classification
|
| 167 |
+
├── judges/
|
| 168 |
+
│ ├── spotting.py
|
| 169 |
+
│ ├── referring.py
|
| 170 |
+
│ ├── extract_text.py
|
| 171 |
+
│ └── classify.py
|
| 172 |
+
├── utils/
|
| 173 |
+
│ ├── image_utils.py # base64 encoding for OpenAI-compat
|
| 174 |
+
│ ├── io.py # ResultWriter / read_processed
|
| 175 |
+
│ ├── signal_utils.py # Ctrl+C aware shutdown
|
| 176 |
+
│ └── unk.py # [UNK] / □ / ■ etc.
|
| 177 |
+
├── infer.py # entry: inference
|
| 178 |
+
├── judge.py # entry: rule-based scoring
|
| 179 |
+
└── summarize.py # entry: Excel report
|
| 180 |
+
```
|
eval/README_zh.md
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Chronicles-OCR Benchmark
|
| 2 |
+
|
| 3 |
+
面向视觉语言模型(VLM)的 **中国历代书体 OCR** 多任务评测基准,覆盖全部七种规范汉字书体:甲骨文(Oracle Bone)、金文(Bronze Script)、篆书(Seal Script)、隶书(Clerical Script)、楷书(Regular Script)、行书(Running Script)、草书(Cursive Script)。
|
| 4 |
+
|
| 5 |
+
| 分组 | 书体 | 任务 |
|
| 6 |
+
| ---- | ------------------------- | ------------------------------------------------- |
|
| 7 |
+
| 古代 | 甲骨文 / 金文 / 篆书 | Spotting · Recognition · Parsing · Classification |
|
| 8 |
+
| 近代 | 隶书 / 楷书 / 行书 / 草书 | Parsing · Classification |
|
| 9 |
+
|
| 10 |
+
四个任务:
|
| 11 |
+
|
| 12 |
+
| 任务 | 简称 | 指标 | 说明 |
|
| 13 |
+
| ------------------------------------------ | -------------- | ---------------------- | ------------------------------------------------ |
|
| 14 |
+
| Cross-period Character Spotting | Spotting | F1 @ IoU > 0.75 | 检测每个字符的 bbox 并识别其对应的现代汉字 |
|
| 15 |
+
| Fine-grained Archaic Character Recognition | Recognition | Exact-match Accuracy | 识别图中红色矩形框内单个古文字符所对应的现代汉字 |
|
| 16 |
+
| Ancient Text Parsing | Parsing | 1 − NED(Levenshtein) | 按阅读顺序识别图中所有汉字;评分前会过滤 `[UNK]` |
|
| 17 |
+
| Script Classification | Classification | Accuracy | 将图像分类到七种规范书体中的其中之一 |
|
| 18 |
+
|
| 19 |
+
全部评分均为 **基于规则**,**不需要 LLM 评审**。
|
| 20 |
+
|
| 21 |
+
> 注:Spotting 任务内部还会同时报告一个 Detection F1(仅看 bbox、IoU > 0.75,不要求字符一致)作为诊断指标;Spotting 主指标要求 IoU 与字符同时命中。
|
| 22 |
+
|
| 23 |
+
---
|
| 24 |
+
|
| 25 |
+
## 1. 环境安装
|
| 26 |
+
|
| 27 |
+
```bash
|
| 28 |
+
git clone <this-repo>
|
| 29 |
+
cd ChronoText/Opensource
|
| 30 |
+
pip install -r requirements.txt
|
| 31 |
+
# 可选:仅当使用 --api_type local_vllm 时需要
|
| 32 |
+
pip install vllm
|
| 33 |
+
```
|
| 34 |
+
|
| 35 |
+
## 2. 下载评测数据
|
| 36 |
+
|
| 37 |
+
数据(jsonl + 图片)以单一压缩包发布。请将其解压到 `Opensource/data/` 目录下:
|
| 38 |
+
|
| 39 |
+
```
|
| 40 |
+
Opensource/data/
|
| 41 |
+
├── Chronicles_OCR.jsonl
|
| 42 |
+
└── images/
|
| 43 |
+
├── 甲骨文/... # Oracle Bone
|
| 44 |
+
├── 金文/... # Bronze Script
|
| 45 |
+
├── 篆书/... # Seal Script
|
| 46 |
+
├── 隶书/... # Clerical Script
|
| 47 |
+
├── 楷书/... # Regular Script
|
| 48 |
+
├── 行书/... # Running Script
|
| 49 |
+
└── 草书/... # Cursive Script
|
| 50 |
+
```
|
| 51 |
+
|
| 52 |
+
jsonl 每一行的格式如下:
|
| 53 |
+
|
| 54 |
+
```json
|
| 55 |
+
{
|
| 56 |
+
"image_path": "images/甲骨文/abcdef0123.jpg",
|
| 57 |
+
"font_type": "甲骨文",
|
| 58 |
+
"annotation": "...",
|
| 59 |
+
"spotting": [{"bbox": {"x1":..,"y1":..,"x2":..,"y2":..}, "modern_char": ".."}, ...],
|
| 60 |
+
"width": 800,
|
| 61 |
+
"height": 600
|
| 62 |
+
}
|
| 63 |
+
```
|
| 64 |
+
|
| 65 |
+
`spotting` / `width` / `height` 仅在三种古代书体上存在;近代书体仅包含 `image_path`、`font_type`、`annotation`。
|
| 66 |
+
|
| 67 |
+
## 3. 推理(Inference)
|
| 68 |
+
|
| 69 |
+
通过 `--api_type` 切换三种后端:
|
| 70 |
+
|
| 71 |
+
### (a) `openai_compat` — 任意 OpenAI 兼容 HTTP 服务
|
| 72 |
+
|
| 73 |
+
适用于 `vllm serve` / `sglang` / `lmdeploy` 等本地服务,也适用于符合 OpenAI Chat Completions 协议的公有云接口(OpenAI、Gemini OpenAI-compat、Claude OpenAI-compat、Together 等)。
|
| 74 |
+
|
| 75 |
+
```bash
|
| 76 |
+
python infer.py \
|
| 77 |
+
--api_type openai_compat \
|
| 78 |
+
--model_name Qwen2.5-VL-7B-Instruct \
|
| 79 |
+
--base_url http://127.0.0.1:8000/v1 \
|
| 80 |
+
--api_key EMPTY \
|
| 81 |
+
--max_workers 64
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
### (b) `local_vllm` — 进程内加载 vLLM,直接给本地权重路径
|
| 85 |
+
|
| 86 |
+
不需要先启动服务,脚本会通过 `vllm.LLM` 在进程内加载本地 checkpoint。
|
| 87 |
+
|
| 88 |
+
```bash
|
| 89 |
+
python infer.py \
|
| 90 |
+
--api_type local_vllm \
|
| 91 |
+
--model_path /path/to/Qwen2.5-VL-7B-Instruct \
|
| 92 |
+
--tensor_parallel_size 1 \
|
| 93 |
+
--max_model_len 32768
|
| 94 |
+
```
|
| 95 |
+
|
| 96 |
+
### 输出位置
|
| 97 |
+
|
| 98 |
+
每次运行会写入一个 jsonl:
|
| 99 |
+
|
| 100 |
+
```
|
| 101 |
+
Opensource/infer_results/<model_tag>/results.jsonl
|
| 102 |
+
```
|
| 103 |
+
|
| 104 |
+
`<model_tag>` 默认依次取 `--model_name` / `--model_path` 的 basename / `--api_name`,也可以用 `--output_tag` 显式覆盖。
|
| 105 |
+
|
| 106 |
+
## 4. 评分(Judging)
|
| 107 |
+
|
| 108 |
+
```bash
|
| 109 |
+
# 评分 infer_results/ 下的全部模型
|
| 110 |
+
python judge.py
|
| 111 |
+
|
| 112 |
+
# 只评分指定模型
|
| 113 |
+
python judge.py --models Qwen2.5-VL-7B-Instruct gemini-3.1-pro
|
| 114 |
+
```
|
| 115 |
+
|
| 116 |
+
输出到 `Opensource/judge_results/<model_tag>/results.jsonl`。评分阶段为纯规则计算、速度很快,因此 **始终覆盖** 之前的结果。
|
| 117 |
+
|
| 118 |
+
## 5. 汇总报表(Summary)
|
| 119 |
+
|
| 120 |
+
```bash
|
| 121 |
+
python summarize.py
|
| 122 |
+
# → Opensource/judge_results/results_analysis.xlsx
|
| 123 |
+
```
|
| 124 |
+
|
| 125 |
+
输出的 Excel 含两张表,且任务列均按规范顺序 **Spotting · Recognition · Parsing · Classification** 排列:
|
| 126 |
+
|
| 127 |
+
- **Per-group summary** — 按 Ancient / Modern 两个分组聚合的每模型平均分
|
| 128 |
+
- **Per-script breakdown** — 拆解到七种书体的每模型平均分
|
| 129 |
+
|
| 130 |
+
分数会乘��� `100`,保留 1 位小数(例如 `87.3` 表示 0.873)。
|
| 131 |
+
|
| 132 |
+
---
|
| 133 |
+
|
| 134 |
+
## 6. 完整流程示例
|
| 135 |
+
|
| 136 |
+
```bash
|
| 137 |
+
# 1. 推理
|
| 138 |
+
python infer.py --api_type openai_compat \
|
| 139 |
+
--model_name Qwen2.5-VL-7B-Instruct \
|
| 140 |
+
--base_url http://127.0.0.1:8000/v1
|
| 141 |
+
|
| 142 |
+
# 2. 评分
|
| 143 |
+
python judge.py
|
| 144 |
+
|
| 145 |
+
# 3. 汇总到 Excel
|
| 146 |
+
python summarize.py
|
| 147 |
+
```
|
| 148 |
+
|
| 149 |
+
---
|
| 150 |
+
|
| 151 |
+
## 7. 代码结构
|
| 152 |
+
|
| 153 |
+
```
|
| 154 |
+
Opensource/
|
| 155 |
+
├── README.md / README_zh.md
|
| 156 |
+
├── requirements.txt
|
| 157 |
+
├── data/ # ← 数据下载到这里
|
| 158 |
+
├── apis/
|
| 159 |
+
│ ├── base.py # APIBase
|
| 160 |
+
│ ├── openai_compat.py # OpenAI 兼容客户端
|
| 161 |
+
│ ├── local_vllm.py # 进程内 vLLM
|
| 162 |
+
├── prompts/
|
| 163 |
+
│ ├── spotting.py # Cross-period Character Spotting
|
| 164 |
+
│ ├── referring.py # Fine-grained Archaic Character Recognition(红框采样 + 渲染)
|
| 165 |
+
│ ├── extract_text.py # Ancient Text Parsing
|
| 166 |
+
│ └── classify.py # Script Classification
|
| 167 |
+
├── judges/
|
| 168 |
+
│ ├── spotting.py
|
| 169 |
+
│ ├── referring.py
|
| 170 |
+
│ ├── extract_text.py
|
| 171 |
+
│ └── classify.py
|
| 172 |
+
├── utils/
|
| 173 |
+
│ ├── image_utils.py # OpenAI 兼容 API 的 base64 编码
|
| 174 |
+
│ ├── io.py # ResultWriter / read_processed
|
| 175 |
+
│ ├── signal_utils.py # 友好响应 Ctrl+C
|
| 176 |
+
│ └── unk.py # [UNK] / □ / ■ 等占位归一化
|
| 177 |
+
├── infer.py # 入口:推理
|
| 178 |
+
├── judge.py # 入口:规则评分
|
| 179 |
+
└── summarize.py # 入口:Excel 报表
|
| 180 |
+
```
|
eval/apis/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from .base import APIBase
|
| 4 |
+
|
| 5 |
+
API_TYPES = ("local_vllm", "openai_compat")
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def get_api(api_type: str, **kwargs) -> APIBase:
|
| 9 |
+
"""构造一个 API 实例。
|
| 10 |
+
|
| 11 |
+
Args:
|
| 12 |
+
api_type: 取值 ``"local_vllm"`` / ``"openai_compat"``
|
| 13 |
+
**kwargs: 转发给具体 API 类的参数
|
| 14 |
+
|
| 15 |
+
Returns:
|
| 16 |
+
APIBase 子类实例
|
| 17 |
+
"""
|
| 18 |
+
if api_type == "local_vllm":
|
| 19 |
+
from .local_vllm import LocalVLLMAPI
|
| 20 |
+
|
| 21 |
+
return LocalVLLMAPI(**kwargs)
|
| 22 |
+
if api_type == "openai_compat":
|
| 23 |
+
from .openai_compat import OpenAICompatAPI
|
| 24 |
+
|
| 25 |
+
return OpenAICompatAPI(**kwargs)
|
| 26 |
+
|
| 27 |
+
raise ValueError(f"unsupported api_type: {api_type!r}, expected one of {API_TYPES}")
|
eval/apis/base.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""APIBase:所有 API 实现的最小抽象基类。"""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from abc import ABC, abstractmethod
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class APIBase(ABC):
|
| 9 |
+
@abstractmethod
|
| 10 |
+
def __call__(self, img_path: str | None, question: str, **kwargs) -> tuple[bool, str, str]:
|
| 11 |
+
"""统一调用接口。
|
| 12 |
+
|
| 13 |
+
Args:
|
| 14 |
+
img_path: 本地图片路径(``None`` 表示纯文本任务)
|
| 15 |
+
question: prompt 文本
|
| 16 |
+
|
| 17 |
+
Returns:
|
| 18 |
+
``(success, thinking, answer)`` 三元组:
|
| 19 |
+
- success: 调用是否成功
|
| 20 |
+
- thinking: 模型 think 段(可能为空)
|
| 21 |
+
- answer: 模型最终回复
|
| 22 |
+
"""
|
| 23 |
+
...
|
eval/apis/local_vllm.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""本地 vLLM 进程内推理:``from vllm import LLM`` 加载一个本地模型路径。
|
| 2 |
+
|
| 3 |
+
适用场景:用户提供一个本地权重路径(``--api_type local_vllm --model_path ...``),
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import threading
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
from PIL import Image
|
| 12 |
+
|
| 13 |
+
from .base import APIBase
|
| 14 |
+
|
| 15 |
+
DEFAULT_MAX_TOKENS = 4096
|
| 16 |
+
DEFAULT_TEMPERATURE = 0.0
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class LocalVLLMAPI(APIBase):
|
| 20 |
+
"""vLLM 进程内推理。线程安全:同一个 ``LLM`` 实例可多线程并发调用 ``generate``。"""
|
| 21 |
+
|
| 22 |
+
def __init__(
|
| 23 |
+
self,
|
| 24 |
+
model_path: str,
|
| 25 |
+
tensor_parallel_size: int = 1,
|
| 26 |
+
max_model_len: int | None = None,
|
| 27 |
+
dtype: str = "auto",
|
| 28 |
+
gpu_memory_utilization: float = 0.9,
|
| 29 |
+
trust_remote_code: bool = True,
|
| 30 |
+
max_tokens: int = DEFAULT_MAX_TOKENS,
|
| 31 |
+
temperature: float = DEFAULT_TEMPERATURE,
|
| 32 |
+
max_try: int = 1,
|
| 33 |
+
**engine_kwargs,
|
| 34 |
+
):
|
| 35 |
+
from vllm import LLM, SamplingParams # 延迟导入:openai_compat 用户可能没装 vllm
|
| 36 |
+
|
| 37 |
+
self.model_path = model_path
|
| 38 |
+
self.max_try = max_try
|
| 39 |
+
self.sampling_params = SamplingParams(
|
| 40 |
+
temperature=temperature,
|
| 41 |
+
max_tokens=max_tokens,
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
engine_args = dict(
|
| 45 |
+
model=model_path,
|
| 46 |
+
tensor_parallel_size=tensor_parallel_size,
|
| 47 |
+
dtype=dtype,
|
| 48 |
+
gpu_memory_utilization=gpu_memory_utilization,
|
| 49 |
+
trust_remote_code=trust_remote_code,
|
| 50 |
+
)
|
| 51 |
+
if max_model_len is not None:
|
| 52 |
+
engine_args["max_model_len"] = max_model_len
|
| 53 |
+
engine_args.update(engine_kwargs)
|
| 54 |
+
self.llm = LLM(**engine_args)
|
| 55 |
+
self._lock = threading.Lock() # vLLM 自带异步引擎,但部分版本对 generate 调用串行更稳
|
| 56 |
+
|
| 57 |
+
self._model_name = Path(model_path).name
|
| 58 |
+
|
| 59 |
+
def __call__(self, img_path: str | None, question: str, **kwargs):
|
| 60 |
+
try:
|
| 61 |
+
inputs = self._build_inputs(img_path, question)
|
| 62 |
+
with self._lock:
|
| 63 |
+
outputs = self.llm.generate([inputs], self.sampling_params)
|
| 64 |
+
text = outputs[0].outputs[0].text or ""
|
| 65 |
+
return True, "", text.strip()
|
| 66 |
+
except Exception as e:
|
| 67 |
+
print(f"[LocalVLLMAPI] inference 失败: {e}")
|
| 68 |
+
return False, "", ""
|
| 69 |
+
|
| 70 |
+
def _build_inputs(self, img_path: str | None, question: str) -> dict:
|
| 71 |
+
if not img_path:
|
| 72 |
+
return {"prompt": question}
|
| 73 |
+
# vLLM 多模态格式:使用 ``multi_modal_data``
|
| 74 |
+
image = Image.open(img_path).convert("RGB")
|
| 75 |
+
prompt = f"<|im_start|>user\n<image>\n{question}<|im_end|>\n<|im_start|>assistant\n"
|
| 76 |
+
return {"prompt": prompt, "multi_modal_data": {"image": image}}
|
eval/apis/openai_compat.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""OpenAI 兼容 API 客户端。
|
| 2 |
+
|
| 3 |
+
适用场景:
|
| 4 |
+
1. 用户用 ``vllm serve`` / ``sglang`` / ``lmdeploy`` 等起的本地 OpenAI 兼容服务
|
| 5 |
+
2. OpenAI 官方 / Gemini-OpenAI-compat / Claude-OpenAI-compat 等公有云
|
| 6 |
+
3. 任意自托管的 OpenAI Chat Completions 协议网关
|
| 7 |
+
|
| 8 |
+
只依赖标准 ``openai`` Python 客户端,不引入任何特殊鉴权 / cos url 逻辑。
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import re
|
| 14 |
+
import time
|
| 15 |
+
|
| 16 |
+
from openai import OpenAI
|
| 17 |
+
|
| 18 |
+
from ..utils.image_utils import encode_image
|
| 19 |
+
from .base import APIBase
|
| 20 |
+
|
| 21 |
+
DEFAULT_TIMEOUT = 1200
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _split_think_answer(response: str) -> tuple[str, str]:
|
| 25 |
+
"""从模型输出中拆出 thinking / final answer。"""
|
| 26 |
+
if not response or not response.strip():
|
| 27 |
+
return "", ""
|
| 28 |
+
m = re.search(r"<think>\n(.*?)\n</think>\n<answer>\n(.*?)\n</answer>", response, flags=re.DOTALL)
|
| 29 |
+
if m:
|
| 30 |
+
return m.group(1).strip(), m.group(2).strip()
|
| 31 |
+
return "", response.strip()
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class OpenAICompatAPI(APIBase):
|
| 35 |
+
"""走 OpenAI Chat Completions 协议的通用客户端。"""
|
| 36 |
+
|
| 37 |
+
def __init__(
|
| 38 |
+
self,
|
| 39 |
+
model_name: str,
|
| 40 |
+
base_url: str,
|
| 41 |
+
api_key: str = "EMPTY",
|
| 42 |
+
max_try: int = 3,
|
| 43 |
+
timeout: int = DEFAULT_TIMEOUT,
|
| 44 |
+
image_first: bool = True,
|
| 45 |
+
):
|
| 46 |
+
self.model_name = model_name
|
| 47 |
+
self.base_url = base_url
|
| 48 |
+
self.api_key = api_key
|
| 49 |
+
self.max_try = max_try
|
| 50 |
+
self.timeout = timeout
|
| 51 |
+
self.image_first = image_first
|
| 52 |
+
self.client = OpenAI(base_url=base_url, api_key=api_key)
|
| 53 |
+
|
| 54 |
+
def __call__(self, img_path: str | None, question: str, temperature: float | None = None, **kwargs):
|
| 55 |
+
messages = self._build_messages(img_path, question)
|
| 56 |
+
return self._send(messages, temperature=temperature)
|
| 57 |
+
|
| 58 |
+
def _build_messages(self, img_path: str | None, question: str) -> list[dict]:
|
| 59 |
+
if not img_path:
|
| 60 |
+
assert question, "question is required when img_path is empty"
|
| 61 |
+
return [{"role": "user", "content": [{"type": "text", "text": question}]}]
|
| 62 |
+
data_uri = encode_image(img_path)
|
| 63 |
+
img_part = {"type": "image_url", "image_url": {"url": data_uri}}
|
| 64 |
+
txt_part = {"type": "text", "text": question}
|
| 65 |
+
content = [img_part, txt_part] if self.image_first else [txt_part, img_part]
|
| 66 |
+
return [{"role": "user", "content": content}]
|
| 67 |
+
|
| 68 |
+
def _send(self, messages: list[dict], temperature: float | None = None):
|
| 69 |
+
for attempt in range(1, self.max_try + 1):
|
| 70 |
+
try:
|
| 71 |
+
completion = self.client.chat.completions.create(
|
| 72 |
+
model=self.model_name,
|
| 73 |
+
messages=messages,
|
| 74 |
+
temperature=temperature,
|
| 75 |
+
timeout=self.timeout,
|
| 76 |
+
)
|
| 77 |
+
response = completion.choices[0].message.content or ""
|
| 78 |
+
thinking, answer = _split_think_answer(response)
|
| 79 |
+
return True, thinking, answer
|
| 80 |
+
except Exception as e:
|
| 81 |
+
print(f"[OpenAICompatAPI] 尝试 {attempt}/{self.max_try} 失败: {e}")
|
| 82 |
+
if attempt < self.max_try:
|
| 83 |
+
time.sleep(min(2 * attempt, 10))
|
| 84 |
+
return False, "", ""
|
eval/data/.gitkeep
ADDED
|
File without changes
|
eval/infer.py
ADDED
|
@@ -0,0 +1,392 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ChronoText benchmark inference entry point.
|
| 2 |
+
|
| 3 |
+
Usage:
|
| 4 |
+
# 1) Local OpenAI-compatible service started by ``vllm serve`` / sglang / lmdeploy
|
| 5 |
+
python infer.py --api_type openai_compat \
|
| 6 |
+
--model_name Qwen2.5-VL-7B-Instruct \
|
| 7 |
+
--base_url http://127.0.0.1:8000/v1 \
|
| 8 |
+
--api_key EMPTY
|
| 9 |
+
|
| 10 |
+
# 2) In-process vLLM, point ``--model_path`` to a local checkpoint
|
| 11 |
+
python infer.py --api_type local_vllm \
|
| 12 |
+
--model_path /path/to/checkpoint \
|
| 13 |
+
--tensor_parallel_size 4
|
| 14 |
+
|
| 15 |
+
# 3) ⚠️ Internal only — distill backend (delete before release)
|
| 16 |
+
python infer.py --api_type distill --api_name doubao-seed-1-8-251228-nonthinking
|
| 17 |
+
|
| 18 |
+
Outputs:
|
| 19 |
+
Opensource/infer_results/<model_tag>/results.jsonl
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
from __future__ import annotations
|
| 23 |
+
|
| 24 |
+
import argparse
|
| 25 |
+
import concurrent.futures
|
| 26 |
+
import json
|
| 27 |
+
import os
|
| 28 |
+
import sys
|
| 29 |
+
import time
|
| 30 |
+
import traceback
|
| 31 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 32 |
+
from pathlib import Path
|
| 33 |
+
|
| 34 |
+
import tqdm
|
| 35 |
+
|
| 36 |
+
REPO_ROOT = Path(__file__).resolve().parent
|
| 37 |
+
sys.path.insert(0, str(REPO_ROOT.parent))
|
| 38 |
+
|
| 39 |
+
from Opensource.apis import API_TYPES, get_api # noqa: E402
|
| 40 |
+
from Opensource.prompts import ( # noqa: E402
|
| 41 |
+
EXTRACT_FUNCS,
|
| 42 |
+
PROMPTS,
|
| 43 |
+
TASK_CLASSIFY,
|
| 44 |
+
TASK_EXTRACT,
|
| 45 |
+
TASK_REFERRING,
|
| 46 |
+
TASK_SPOTTING,
|
| 47 |
+
)
|
| 48 |
+
from Opensource.prompts.referring import DEFAULT_SEED, prepare_referring_sample # noqa: E402
|
| 49 |
+
from Opensource.utils.io import ResultWriter, get_image_path, read_processed # noqa: E402
|
| 50 |
+
from Opensource.utils.signal_utils import ABORT_EVENT, install_signal_handlers_once # noqa: E402
|
| 51 |
+
|
| 52 |
+
# ============================================================
|
| 53 |
+
# 配置
|
| 54 |
+
# ============================================================
|
| 55 |
+
DEFAULT_DATA_FILE = REPO_ROOT / "data" / "Chronicles_OCR.jsonl"
|
| 56 |
+
DEFAULT_OUTPUT_DIR = REPO_ROOT / "infer_results"
|
| 57 |
+
|
| 58 |
+
# 古代三种字体额外执行 spotting / referring;近代字体只跑 classify / extract
|
| 59 |
+
ANCIENT_FONTS = {"甲骨文", "金文", "篆书"}
|
| 60 |
+
ALL_TASKS = [TASK_CLASSIFY, TASK_EXTRACT, TASK_SPOTTING, TASK_REFERRING]
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def parse_args() -> argparse.Namespace:
|
| 64 |
+
p = argparse.ArgumentParser(description="ChronoText inference entry point")
|
| 65 |
+
|
| 66 |
+
# API 选择
|
| 67 |
+
p.add_argument(
|
| 68 |
+
"--api_type",
|
| 69 |
+
choices=API_TYPES,
|
| 70 |
+
required=True,
|
| 71 |
+
help="local_vllm: 进程内 vllm.LLM; openai_compat: 标准 OpenAI 协议; distill: 内部专用",
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
# OpenAI compat 参数
|
| 75 |
+
p.add_argument("--model_name", type=str, default=None, help="openai_compat 调用时使用的 model 字段")
|
| 76 |
+
p.add_argument("--base_url", type=str, default=None, help="openai_compat 服务地址,例如 http://127.0.0.1:8000/v1")
|
| 77 |
+
p.add_argument("--api_key", type=str, default="EMPTY")
|
| 78 |
+
|
| 79 |
+
# local_vllm 参数
|
| 80 |
+
p.add_argument("--model_path", type=str, default=None, help="local_vllm: 本地模型权重路径")
|
| 81 |
+
p.add_argument("--tensor_parallel_size", type=int, default=1)
|
| 82 |
+
p.add_argument("--max_model_len", type=int, default=None)
|
| 83 |
+
p.add_argument("--gpu_memory_utilization", type=float, default=0.9)
|
| 84 |
+
|
| 85 |
+
# distill(内部)
|
| 86 |
+
p.add_argument("--api_name", type=str, default=None, help="distill: 内部 API 名称")
|
| 87 |
+
|
| 88 |
+
# 数据 / 输出
|
| 89 |
+
p.add_argument(
|
| 90 |
+
"--data_file", type=str, default=str(DEFAULT_DATA_FILE), help=f"benchmark jsonl 路径,默认 {DEFAULT_DATA_FILE}"
|
| 91 |
+
)
|
| 92 |
+
p.add_argument("--output_dir", type=str, default=str(DEFAULT_OUTPUT_DIR))
|
| 93 |
+
p.add_argument(
|
| 94 |
+
"--output_tag", type=str, default=None, help="结果子目录名,默认从 model_name / model_path / api_name 推断"
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
# 推理参数
|
| 98 |
+
p.add_argument("--max_workers", type=int, default=64)
|
| 99 |
+
p.add_argument("--max_try", type=int, default=3)
|
| 100 |
+
p.add_argument("--max_rows", type=int, default=-1)
|
| 101 |
+
p.add_argument("--save_interval", type=int, default=1)
|
| 102 |
+
p.add_argument("--seed", type=int, default=DEFAULT_SEED, help="单字识别红框采样的随机种子")
|
| 103 |
+
p.add_argument("--debug", action="store_true")
|
| 104 |
+
|
| 105 |
+
return p.parse_args()
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def build_api(args: argparse.Namespace):
|
| 109 |
+
if args.api_type == "openai_compat":
|
| 110 |
+
if not args.model_name or not args.base_url:
|
| 111 |
+
raise SystemExit("--api_type openai_compat 需要同时提供 --model_name 与 --base_url")
|
| 112 |
+
return get_api(
|
| 113 |
+
"openai_compat",
|
| 114 |
+
model_name=args.model_name,
|
| 115 |
+
base_url=args.base_url,
|
| 116 |
+
api_key=args.api_key,
|
| 117 |
+
max_try=args.max_try,
|
| 118 |
+
)
|
| 119 |
+
if args.api_type == "local_vllm":
|
| 120 |
+
if not args.model_path:
|
| 121 |
+
raise SystemExit("--api_type local_vllm 需要提供 --model_path")
|
| 122 |
+
return get_api(
|
| 123 |
+
"local_vllm",
|
| 124 |
+
model_path=args.model_path,
|
| 125 |
+
tensor_parallel_size=args.tensor_parallel_size,
|
| 126 |
+
max_model_len=args.max_model_len,
|
| 127 |
+
gpu_memory_utilization=args.gpu_memory_utilization,
|
| 128 |
+
max_try=args.max_try,
|
| 129 |
+
)
|
| 130 |
+
# distill
|
| 131 |
+
if not args.api_name:
|
| 132 |
+
raise SystemExit("--api_type distill 需要提供 --api_name")
|
| 133 |
+
return get_api("distill", api_name=args.api_name, max_try=args.max_try)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def derive_output_tag(args: argparse.Namespace) -> str:
|
| 137 |
+
if args.output_tag:
|
| 138 |
+
return args.output_tag
|
| 139 |
+
if args.api_type == "openai_compat" and args.model_name:
|
| 140 |
+
return args.model_name
|
| 141 |
+
if args.api_type == "local_vllm" and args.model_path:
|
| 142 |
+
return Path(args.model_path).name
|
| 143 |
+
if args.api_type == "distill" and args.api_name:
|
| 144 |
+
return args.api_name
|
| 145 |
+
return "default"
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def resolve_image_path(row: dict, data_file_dir: Path) -> str:
|
| 149 |
+
"""开源 jsonl 里 ``image_path`` 是相对 data 目录的相对路径,需要拼成绝对路径。"""
|
| 150 |
+
rel = get_image_path(row)
|
| 151 |
+
if not rel:
|
| 152 |
+
return ""
|
| 153 |
+
if os.path.isabs(rel):
|
| 154 |
+
return rel
|
| 155 |
+
return str(data_file_dir / rel)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def tasks_for_row(row: dict) -> list[str]:
|
| 159 |
+
"""按 font_type 决定该样本应跑的任务列表(古代 4 / 近代 2)。"""
|
| 160 |
+
if str(row.get("font_type", "")).strip() in ANCIENT_FONTS:
|
| 161 |
+
return ALL_TASKS
|
| 162 |
+
return [TASK_CLASSIFY, TASK_EXTRACT]
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def process_one_row(
|
| 166 |
+
api_instance,
|
| 167 |
+
row: dict,
|
| 168 |
+
abs_img_path: str,
|
| 169 |
+
existing: dict,
|
| 170 |
+
max_retries: int,
|
| 171 |
+
referring_cache_dir: str,
|
| 172 |
+
seed: int,
|
| 173 |
+
) -> dict | None:
|
| 174 |
+
"""对单条样本跑所有未完成的任务。返回新 row(包含合并后的 infer_results)。"""
|
| 175 |
+
if not abs_img_path or not os.path.exists(abs_img_path):
|
| 176 |
+
print(f"警告:图片不存在 {abs_img_path}")
|
| 177 |
+
return None
|
| 178 |
+
|
| 179 |
+
file_tasks = tasks_for_row(row)
|
| 180 |
+
pending = [t for t in file_tasks if t not in existing]
|
| 181 |
+
if not pending:
|
| 182 |
+
return None
|
| 183 |
+
|
| 184 |
+
infer_results = dict(existing)
|
| 185 |
+
|
| 186 |
+
for task_name in pending:
|
| 187 |
+
prompt_text = PROMPTS[task_name]
|
| 188 |
+
task_img = abs_img_path
|
| 189 |
+
referring_meta: dict | None = None
|
| 190 |
+
|
| 191 |
+
# 单字识别:先采样 + 画红框,再用渲染图调用模型
|
| 192 |
+
if task_name == TASK_REFERRING:
|
| 193 |
+
sample = prepare_referring_sample(row, abs_img_path, seed=seed, out_dir=referring_cache_dir)
|
| 194 |
+
if sample is None:
|
| 195 |
+
infer_results[task_name] = {
|
| 196 |
+
"thinking": "",
|
| 197 |
+
"answer": "",
|
| 198 |
+
"error": "no_referring_target",
|
| 199 |
+
"skipped": True,
|
| 200 |
+
}
|
| 201 |
+
continue
|
| 202 |
+
task_img = sample["rendered_img_path"]
|
| 203 |
+
referring_meta = {
|
| 204 |
+
"gt_char": sample["target_char"],
|
| 205 |
+
"target_bbox_xyxy": sample["target_bbox_xyxy"],
|
| 206 |
+
"target_index": sample["index"],
|
| 207 |
+
"sample_key": sample["sample_key"],
|
| 208 |
+
"seed": seed,
|
| 209 |
+
"rendered_img_path": sample["rendered_img_path"],
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
last_error = None
|
| 213 |
+
for attempt in range(1, max_retries + 1):
|
| 214 |
+
if task_name == TASK_REFERRING and not os.path.exists(task_img):
|
| 215 |
+
# 渲染图被外部清理掉则就地重画
|
| 216 |
+
redrawn = prepare_referring_sample(row, abs_img_path, seed=seed, out_dir=referring_cache_dir)
|
| 217 |
+
if redrawn is not None:
|
| 218 |
+
task_img = redrawn["rendered_img_path"]
|
| 219 |
+
try:
|
| 220 |
+
ok, thinking, answer = api_instance(task_img, prompt_text)
|
| 221 |
+
if not ok or answer is None:
|
| 222 |
+
raise RuntimeError("API 调用失败或返回空结果")
|
| 223 |
+
|
| 224 |
+
extract_fn = EXTRACT_FUNCS.get(task_name)
|
| 225 |
+
extract_ok, extracted = (False, None)
|
| 226 |
+
if extract_fn is not None:
|
| 227 |
+
try:
|
| 228 |
+
extract_ok, extracted = extract_fn(answer)
|
| 229 |
+
except Exception as e:
|
| 230 |
+
print(f" 任务 '{task_name}' 提取异常: {e}")
|
| 231 |
+
extract_ok = False
|
| 232 |
+
|
| 233 |
+
if extract_fn is not None and not extract_ok and attempt < max_retries:
|
| 234 |
+
print(f" 任务 '{task_name}' 提取失败,重试 {attempt}/{max_retries}")
|
| 235 |
+
time.sleep(2)
|
| 236 |
+
continue
|
| 237 |
+
|
| 238 |
+
rec = {"thinking": thinking or "", "answer": answer}
|
| 239 |
+
if extract_ok:
|
| 240 |
+
rec["extract"] = extracted
|
| 241 |
+
if referring_meta is not None:
|
| 242 |
+
rec.update(
|
| 243 |
+
{
|
| 244 |
+
k: referring_meta[k]
|
| 245 |
+
for k in ("gt_char", "target_bbox_xyxy", "target_index", "sample_key", "seed")
|
| 246 |
+
}
|
| 247 |
+
)
|
| 248 |
+
infer_results[task_name] = rec
|
| 249 |
+
break
|
| 250 |
+
except Exception as e:
|
| 251 |
+
last_error = str(e)
|
| 252 |
+
if attempt < max_retries:
|
| 253 |
+
print(f" 任务 '{task_name}' 失败 ({attempt}/{max_retries}): {last_error}")
|
| 254 |
+
time.sleep(2)
|
| 255 |
+
else:
|
| 256 |
+
rec = {"thinking": "", "answer": "", "error": last_error}
|
| 257 |
+
if referring_meta is not None:
|
| 258 |
+
rec.update(
|
| 259 |
+
{
|
| 260 |
+
k: referring_meta[k]
|
| 261 |
+
for k in ("gt_char", "target_bbox_xyxy", "target_index", "sample_key", "seed")
|
| 262 |
+
}
|
| 263 |
+
)
|
| 264 |
+
infer_results[task_name] = rec
|
| 265 |
+
|
| 266 |
+
result = dict(row)
|
| 267 |
+
result["infer_results"] = infer_results
|
| 268 |
+
result["image_path"] = get_image_path(row) # 保持相对路径作为主键
|
| 269 |
+
return result
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def main() -> None:
|
| 273 |
+
args = parse_args()
|
| 274 |
+
|
| 275 |
+
data_file = Path(args.data_file).resolve()
|
| 276 |
+
if not data_file.is_file():
|
| 277 |
+
raise SystemExit(f"benchmark 文件不存在: {data_file}")
|
| 278 |
+
data_dir = data_file.parent
|
| 279 |
+
|
| 280 |
+
output_tag = derive_output_tag(args)
|
| 281 |
+
output_dir = Path(args.output_dir).resolve() / output_tag
|
| 282 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 283 |
+
output_file = output_dir / "results.jsonl"
|
| 284 |
+
referring_cache_dir = str(output_dir / ".referring_cache")
|
| 285 |
+
|
| 286 |
+
print("=" * 72)
|
| 287 |
+
print("ChronoText Inference")
|
| 288 |
+
print("=" * 72)
|
| 289 |
+
print(f"api_type : {args.api_type}")
|
| 290 |
+
print(f"output_tag : {output_tag}")
|
| 291 |
+
print(f"data_file : {data_file}")
|
| 292 |
+
print(f"output_file : {output_file}")
|
| 293 |
+
print(f"max_workers : {args.max_workers}")
|
| 294 |
+
print(f"max_rows : {args.max_rows if args.max_rows > 0 else 'all'}")
|
| 295 |
+
print(f"seed : {args.seed}")
|
| 296 |
+
|
| 297 |
+
# 读 jsonl
|
| 298 |
+
rows: list[dict] = []
|
| 299 |
+
with open(data_file, "r", encoding="utf-8") as f:
|
| 300 |
+
for line in f:
|
| 301 |
+
line = line.strip()
|
| 302 |
+
if not line:
|
| 303 |
+
continue
|
| 304 |
+
rows.append(json.loads(line))
|
| 305 |
+
if args.max_rows > 0:
|
| 306 |
+
rows = rows[: args.max_rows]
|
| 307 |
+
if args.debug:
|
| 308 |
+
rows = rows[: min(5, len(rows))]
|
| 309 |
+
print(f"loaded {len(rows)} rows")
|
| 310 |
+
|
| 311 |
+
# API
|
| 312 |
+
print("\n初始化 API...")
|
| 313 |
+
api_instance = build_api(args)
|
| 314 |
+
print("API 就绪")
|
| 315 |
+
|
| 316 |
+
# 历史结果(增量)
|
| 317 |
+
all_task_set = set(ALL_TASKS)
|
| 318 |
+
processed, _needs = read_processed(str(output_file), all_task_set)
|
| 319 |
+
print(f"历史结果: 已写入 {len(processed)} 条")
|
| 320 |
+
|
| 321 |
+
# 待处理列表
|
| 322 |
+
pending: list[tuple[dict, str, dict]] = []
|
| 323 |
+
fully_done = 0
|
| 324 |
+
for row in rows:
|
| 325 |
+
rel = get_image_path(row)
|
| 326 |
+
if not rel:
|
| 327 |
+
continue
|
| 328 |
+
abs_img = resolve_image_path(row, data_dir)
|
| 329 |
+
existing_infer = processed.get(rel, {}).get("infer_results", {})
|
| 330 |
+
file_tasks = set(tasks_for_row(row))
|
| 331 |
+
if file_tasks.issubset(set(existing_infer.keys())):
|
| 332 |
+
fully_done += 1
|
| 333 |
+
continue
|
| 334 |
+
pending.append((row, abs_img, existing_infer))
|
| 335 |
+
|
| 336 |
+
print(f"完全完成: {fully_done}, 待处理: {len(pending)}\n")
|
| 337 |
+
if not pending:
|
| 338 |
+
print("没有需要处理的数据")
|
| 339 |
+
return
|
| 340 |
+
|
| 341 |
+
install_signal_handlers_once()
|
| 342 |
+
writer = ResultWriter(str(output_file), processed, save_interval=args.save_interval)
|
| 343 |
+
|
| 344 |
+
executor = ThreadPoolExecutor(max_workers=args.max_workers)
|
| 345 |
+
aborted = False
|
| 346 |
+
try:
|
| 347 |
+
futures = {
|
| 348 |
+
executor.submit(
|
| 349 |
+
process_one_row,
|
| 350 |
+
api_instance,
|
| 351 |
+
row,
|
| 352 |
+
abs_img,
|
| 353 |
+
existing,
|
| 354 |
+
args.max_try,
|
| 355 |
+
referring_cache_dir,
|
| 356 |
+
args.seed,
|
| 357 |
+
): row
|
| 358 |
+
for row, abs_img, existing in pending
|
| 359 |
+
}
|
| 360 |
+
pbar = tqdm.tqdm(total=len(futures), desc="inference")
|
| 361 |
+
for fut in concurrent.futures.as_completed(futures):
|
| 362 |
+
if ABORT_EVENT.is_set():
|
| 363 |
+
aborted = True
|
| 364 |
+
break
|
| 365 |
+
try:
|
| 366 |
+
result = fut.result()
|
| 367 |
+
if result:
|
| 368 |
+
writer.update_and_save(result)
|
| 369 |
+
except Exception as e:
|
| 370 |
+
print(f"\n处理失败: {e}")
|
| 371 |
+
traceback.print_exc()
|
| 372 |
+
pbar.update(1)
|
| 373 |
+
pbar.close()
|
| 374 |
+
if aborted:
|
| 375 |
+
for f in futures:
|
| 376 |
+
if not f.done():
|
| 377 |
+
f.cancel()
|
| 378 |
+
finally:
|
| 379 |
+
if ABORT_EVENT.is_set():
|
| 380 |
+
executor.shutdown(wait=False, cancel_futures=True)
|
| 381 |
+
else:
|
| 382 |
+
executor.shutdown(wait=True)
|
| 383 |
+
|
| 384 |
+
print("\n落盘最终结果...")
|
| 385 |
+
writer.finalize()
|
| 386 |
+
print(f"✅ 推理完成: {output_file}")
|
| 387 |
+
if ABORT_EVENT.is_set():
|
| 388 |
+
sys.exit(130)
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
if __name__ == "__main__":
|
| 392 |
+
main()
|
eval/judge.py
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ChronoText benchmark judging entry point.
|
| 2 |
+
|
| 3 |
+
Rule-based scoring only — no LLM / API call needed.
|
| 4 |
+
|
| 5 |
+
Usage:
|
| 6 |
+
# Judge all models under infer_results/
|
| 7 |
+
python judge.py
|
| 8 |
+
|
| 9 |
+
# Judge specific models
|
| 10 |
+
python judge.py --models qwen3-vl-8b gemini-3.1-pro
|
| 11 |
+
|
| 12 |
+
Outputs:
|
| 13 |
+
Opensource/judge_results/<model_tag>/results.jsonl
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import argparse
|
| 19 |
+
import concurrent.futures
|
| 20 |
+
import json
|
| 21 |
+
import sys
|
| 22 |
+
import traceback
|
| 23 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
|
| 26 |
+
import tqdm
|
| 27 |
+
|
| 28 |
+
REPO_ROOT = Path(__file__).resolve().parent
|
| 29 |
+
sys.path.insert(0, str(REPO_ROOT.parent))
|
| 30 |
+
|
| 31 |
+
from Opensource.judges import JUDGE_FUNCS # noqa: E402
|
| 32 |
+
from Opensource.utils.io import ResultWriter, get_image_path # noqa: E402
|
| 33 |
+
|
| 34 |
+
DEFAULT_DATA_FILE = REPO_ROOT / "data" / "Chronicles_OCR.jsonl"
|
| 35 |
+
DEFAULT_INFER_DIR = REPO_ROOT / "infer_results"
|
| 36 |
+
DEFAULT_JUDGE_DIR = REPO_ROOT / "judge_results"
|
| 37 |
+
|
| 38 |
+
ANCIENT_FONTS = {"甲骨文", "金文", "篆书"}
|
| 39 |
+
ALL_TASKS = ["字体分类", "字符提取", "字符检测", "单字识别"]
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def parse_args() -> argparse.Namespace:
|
| 43 |
+
p = argparse.ArgumentParser(description="ChronoText rule-based judging")
|
| 44 |
+
p.add_argument("--data_file", type=str, default=str(DEFAULT_DATA_FILE), help="benchmark jsonl 路径")
|
| 45 |
+
p.add_argument("--infer_dir", type=str, default=str(DEFAULT_INFER_DIR), help="infer_results 目录")
|
| 46 |
+
p.add_argument("--output_dir", type=str, default=str(DEFAULT_JUDGE_DIR), help="judge_results 目录")
|
| 47 |
+
p.add_argument(
|
| 48 |
+
"--models", type=str, nargs="*", default=None, help="只评分指定模型;不传则扫描 infer_dir 下所有子目录"
|
| 49 |
+
)
|
| 50 |
+
p.add_argument("--max_workers", type=int, default=64)
|
| 51 |
+
p.add_argument("--save_interval", type=int, default=1000)
|
| 52 |
+
return p.parse_args()
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def load_gt_index(data_file: Path) -> dict[str, dict]:
|
| 56 |
+
"""加载 GT jsonl,按 image_path 建索引。"""
|
| 57 |
+
index: dict[str, dict] = {}
|
| 58 |
+
with open(data_file, "r", encoding="utf-8") as f:
|
| 59 |
+
for line in f:
|
| 60 |
+
line = line.strip()
|
| 61 |
+
if not line:
|
| 62 |
+
continue
|
| 63 |
+
row = json.loads(line)
|
| 64 |
+
key = get_image_path(row)
|
| 65 |
+
if key:
|
| 66 |
+
index[key] = row
|
| 67 |
+
return index
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def tasks_for_row(gt_row: dict) -> list[str]:
|
| 71 |
+
if str(gt_row.get("font_type", "")).strip() in ANCIENT_FONTS:
|
| 72 |
+
return ALL_TASKS
|
| 73 |
+
return ["字体分类", "字符提取"]
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def judge_one_row(infer_row: dict, gt_row: dict) -> dict:
|
| 77 |
+
"""对单条 infer 结果按对应 GT 评分。"""
|
| 78 |
+
file_tasks = tasks_for_row(gt_row)
|
| 79 |
+
|
| 80 |
+
# 把 GT 字段并入打分上下文
|
| 81 |
+
judge_ctx = dict(gt_row)
|
| 82 |
+
judge_ctx["infer_results"] = infer_row.get("infer_results") or {}
|
| 83 |
+
|
| 84 |
+
judge_results: dict = {}
|
| 85 |
+
for task in file_tasks:
|
| 86 |
+
infer_task = (infer_row.get("infer_results") or {}).get(task)
|
| 87 |
+
if not isinstance(infer_task, dict):
|
| 88 |
+
judge_results[task] = {"score": {"score": 0.0}, "error": "no_infer"}
|
| 89 |
+
continue
|
| 90 |
+
extract = infer_task.get("extract")
|
| 91 |
+
if extract is None:
|
| 92 |
+
judge_results[task] = {"score": {"score": 0.0}, "error": "no_extract"}
|
| 93 |
+
continue
|
| 94 |
+
try:
|
| 95 |
+
score = JUDGE_FUNCS[task](extract, judge_ctx)
|
| 96 |
+
judge_results[task] = {"score": score}
|
| 97 |
+
except Exception as e:
|
| 98 |
+
print(f" 任务 '{task}' 评分异常: {e}")
|
| 99 |
+
judge_results[task] = {"score": 0.0, "error": str(e)}
|
| 100 |
+
|
| 101 |
+
out = dict(infer_row)
|
| 102 |
+
out["judge_results"] = judge_results
|
| 103 |
+
out["font_type"] = gt_row.get("font_type", out.get("font_type", ""))
|
| 104 |
+
out["annotation"] = gt_row.get("annotation", out.get("annotation", ""))
|
| 105 |
+
return out
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def judge_one_model(
|
| 109 |
+
model_tag: str,
|
| 110 |
+
infer_file: Path,
|
| 111 |
+
output_file: Path,
|
| 112 |
+
gt_index: dict[str, dict],
|
| 113 |
+
max_workers: int,
|
| 114 |
+
save_interval: int,
|
| 115 |
+
) -> tuple[int, int, int]:
|
| 116 |
+
"""对单个模型的 infer 结果跑评分。返回 (total, judged, missing_in_gt)。"""
|
| 117 |
+
infer_rows: list[dict] = []
|
| 118 |
+
with open(infer_file, "r", encoding="utf-8") as f:
|
| 119 |
+
for line in f:
|
| 120 |
+
line = line.strip()
|
| 121 |
+
if not line:
|
| 122 |
+
continue
|
| 123 |
+
infer_rows.append(json.loads(line))
|
| 124 |
+
|
| 125 |
+
output_file.parent.mkdir(parents=True, exist_ok=True)
|
| 126 |
+
# 默认覆盖:不读历史 judge 结果
|
| 127 |
+
writer = ResultWriter(str(output_file), processed={}, save_interval=save_interval)
|
| 128 |
+
|
| 129 |
+
pairs: list[tuple[dict, dict]] = []
|
| 130 |
+
missing = 0
|
| 131 |
+
for r in infer_rows:
|
| 132 |
+
key = get_image_path(r)
|
| 133 |
+
gt = gt_index.get(key)
|
| 134 |
+
if gt is None:
|
| 135 |
+
missing += 1
|
| 136 |
+
continue
|
| 137 |
+
pairs.append((r, gt))
|
| 138 |
+
|
| 139 |
+
if not pairs:
|
| 140 |
+
print(f" [{model_tag}] 无可评分样本")
|
| 141 |
+
writer.finalize()
|
| 142 |
+
return len(infer_rows), 0, missing
|
| 143 |
+
|
| 144 |
+
judged = 0
|
| 145 |
+
with ThreadPoolExecutor(max_workers=max_workers) as ex:
|
| 146 |
+
futures = {ex.submit(judge_one_row, ir, gt): ir for ir, gt in pairs}
|
| 147 |
+
pbar = tqdm.tqdm(total=len(futures), desc=f"judge[{model_tag}]")
|
| 148 |
+
for fut in concurrent.futures.as_completed(futures):
|
| 149 |
+
try:
|
| 150 |
+
result = fut.result()
|
| 151 |
+
writer.update_and_save(result)
|
| 152 |
+
judged += 1
|
| 153 |
+
except Exception as e:
|
| 154 |
+
print(f"\n评分失败: {e}")
|
| 155 |
+
traceback.print_exc()
|
| 156 |
+
pbar.update(1)
|
| 157 |
+
pbar.close()
|
| 158 |
+
writer.finalize()
|
| 159 |
+
return len(infer_rows), judged, missing
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def main() -> None:
|
| 163 |
+
args = parse_args()
|
| 164 |
+
|
| 165 |
+
data_file = Path(args.data_file).resolve()
|
| 166 |
+
if not data_file.is_file():
|
| 167 |
+
raise SystemExit(f"benchmark 文件不存在: {data_file}")
|
| 168 |
+
|
| 169 |
+
infer_dir = Path(args.infer_dir).resolve()
|
| 170 |
+
output_dir = Path(args.output_dir).resolve()
|
| 171 |
+
if not infer_dir.is_dir():
|
| 172 |
+
raise SystemExit(f"infer 目录不存在: {infer_dir}")
|
| 173 |
+
|
| 174 |
+
print("=" * 72)
|
| 175 |
+
print("ChronoText Judging")
|
| 176 |
+
print("=" * 72)
|
| 177 |
+
print(f"data_file : {data_file}")
|
| 178 |
+
print(f"infer_dir : {infer_dir}")
|
| 179 |
+
print(f"output_dir : {output_dir}")
|
| 180 |
+
|
| 181 |
+
# 加载 GT
|
| 182 |
+
gt_index = load_gt_index(data_file)
|
| 183 |
+
print(f"GT 样本数 : {len(gt_index)}")
|
| 184 |
+
|
| 185 |
+
# 模型清单
|
| 186 |
+
if args.models:
|
| 187 |
+
model_tags = args.models
|
| 188 |
+
else:
|
| 189 |
+
model_tags = sorted(d.name for d in infer_dir.iterdir() if d.is_dir() and not d.name.startswith("."))
|
| 190 |
+
print(f"模型数量 : {len(model_tags)} -> {model_tags}\n")
|
| 191 |
+
|
| 192 |
+
summary: list[tuple[str, int, int, int]] = []
|
| 193 |
+
for tag in model_tags:
|
| 194 |
+
infer_file = infer_dir / tag / "results.jsonl"
|
| 195 |
+
if not infer_file.is_file():
|
| 196 |
+
print(f"[{tag}] 跳过:找不到 {infer_file}")
|
| 197 |
+
continue
|
| 198 |
+
output_file = output_dir / tag / "results.jsonl"
|
| 199 |
+
total, judged, missing = judge_one_model(
|
| 200 |
+
tag,
|
| 201 |
+
infer_file,
|
| 202 |
+
output_file,
|
| 203 |
+
gt_index,
|
| 204 |
+
max_workers=args.max_workers,
|
| 205 |
+
save_interval=args.save_interval,
|
| 206 |
+
)
|
| 207 |
+
summary.append((tag, total, judged, missing))
|
| 208 |
+
print(f"[{tag}] total={total}, judged={judged}, missing_in_gt={missing}")
|
| 209 |
+
|
| 210 |
+
print("\n" + "=" * 72)
|
| 211 |
+
print("Summary")
|
| 212 |
+
print("=" * 72)
|
| 213 |
+
for tag, total, judged, missing in summary:
|
| 214 |
+
print(f" {tag:40s} total={total:6d} judged={judged:6d} missing={missing:6d}")
|
| 215 |
+
print(f"\n✅ judge 全部完成,结果在 {output_dir}")
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
if __name__ == "__main__":
|
| 219 |
+
main()
|
eval/judges/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import Callable
|
| 4 |
+
|
| 5 |
+
from . import classify, extract_text, referring, spotting
|
| 6 |
+
|
| 7 |
+
JUDGE_FUNCS: dict[str, Callable[[dict, dict], dict]] = {
|
| 8 |
+
"字体分类": classify.judge,
|
| 9 |
+
"字符提取": extract_text.judge,
|
| 10 |
+
"字符检测": spotting.judge,
|
| 11 |
+
"单字识别": referring.judge,
|
| 12 |
+
}
|
eval/judges/_text.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def normalize_text(text: str) -> str:
|
| 5 |
+
if not text:
|
| 6 |
+
return ""
|
| 7 |
+
text = text.replace("\\n", "").replace("\\\n", "")
|
| 8 |
+
return text.replace(" ", "").replace("\u3000", "").replace("\t", "").replace("\r", "").replace("\n", "")
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
_PUNCT_CHARS = (
|
| 12 |
+
r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
|
| 13 |
+
",。、;:「」『』()【】〔〕〈〉《》"
|
| 14 |
+
"!?…—–·.“”‘’「」『』〝〞"
|
| 15 |
+
"¥%#&*@/\|+-=_"
|
| 16 |
+
"~`^"
|
| 17 |
+
)
|
| 18 |
+
_PUNCT_TRANS = str.maketrans("", "", _PUNCT_CHARS)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def normalize_for_parsing(text: str) -> str:
|
| 22 |
+
"""字符提取 / 1-NED 评分专用:基础清洗 + 去标点。"""
|
| 23 |
+
return normalize_text(text).translate(_PUNCT_TRANS)
|
eval/judges/classify.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""字体分类(Classification)打分:exact match。
|
| 2 |
+
|
| 3 |
+
GT 端不做任何归一化(输入 jsonl 保证字体名属于七体之一);
|
| 4 |
+
Pred 端的解析回退已在 ``prompts/classify.py`` 的 ``extract`` 中处理:
|
| 5 |
+
- 严格前缀命中
|
| 6 |
+
- 部分匹配("楷书体" → "楷书")
|
| 7 |
+
- 整段最后一次命中(标记 ``fallback=True``)
|
| 8 |
+
因此这里只做严格相等比较。
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def judge(extract: dict, row: dict) -> dict:
|
| 15 |
+
gt = str(row.get("font_type", "") or "").strip()
|
| 16 |
+
pred = str((extract or {}).get("category", "") or "").strip()
|
| 17 |
+
score = 1.0 if (gt and pred and gt == pred) else 0.0
|
| 18 |
+
return {"score": score, "gt": gt, "pred": pred}
|
eval/judges/extract_text.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""字符提取(Parsing)打分:1 − NED (Normalized Edit Distance)。
|
| 2 |
+
|
| 3 |
+
score = 1 - Levenshtein(pred, gt) / max(|pred|, |gt|)
|
| 4 |
+
|
| 5 |
+
双边都先做 ``normalize_for_parsing``(去空白 / 换行 / 标点),再剔除 ``[UNK]`` 占位。
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
from ..utils.unk import remove_unk
|
| 11 |
+
from ._text import normalize_for_parsing
|
| 12 |
+
|
| 13 |
+
try:
|
| 14 |
+
from rapidfuzz.distance import Levenshtein as _rf_Levenshtein
|
| 15 |
+
|
| 16 |
+
_HAS_RF = True
|
| 17 |
+
except ImportError:
|
| 18 |
+
_rf_Levenshtein = None
|
| 19 |
+
_HAS_RF = False
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _levenshtein(s1: str, s2: str) -> int:
|
| 23 |
+
if s1 == s2:
|
| 24 |
+
return 0
|
| 25 |
+
if not s1:
|
| 26 |
+
return len(s2)
|
| 27 |
+
if not s2:
|
| 28 |
+
return len(s1)
|
| 29 |
+
if _HAS_RF:
|
| 30 |
+
return _rf_Levenshtein.distance(s1, s2)
|
| 31 |
+
# 纯 Python 兜底实现:滚动数组 DP,O(|s1|*|s2|) 时间 / O(|s2|) 空间。
|
| 32 |
+
prev = list(range(len(s2) + 1))
|
| 33 |
+
curr = [0] * (len(s2) + 1)
|
| 34 |
+
for i, c1 in enumerate(s1, start=1):
|
| 35 |
+
curr[0] = i
|
| 36 |
+
for j, c2 in enumerate(s2, start=1):
|
| 37 |
+
curr[j] = prev[j - 1] if c1 == c2 else 1 + min(prev[j], curr[j - 1], prev[j - 1])
|
| 38 |
+
prev, curr = curr, prev
|
| 39 |
+
return prev[len(s2)]
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def judge(extract: dict, row: dict) -> dict:
|
| 43 |
+
gt_raw = normalize_for_parsing(row.get("annotation", "") or "")
|
| 44 |
+
pred_raw = normalize_for_parsing((extract or {}).get("extracted_text", "") or "")
|
| 45 |
+
gt = remove_unk(gt_raw)
|
| 46 |
+
pred = remove_unk(pred_raw)
|
| 47 |
+
|
| 48 |
+
len_gt, len_pred = len(gt), len(pred)
|
| 49 |
+
if len_gt == 0 and len_pred == 0:
|
| 50 |
+
return {"score": 1.0, "metric": "1ned", "edit_distance": 0, "len_pred": 0, "len_gt": 0}
|
| 51 |
+
if len_gt == 0:
|
| 52 |
+
return {"score": 0.0, "metric": "1ned", "edit_distance": len_pred, "len_pred": len_pred, "len_gt": 0}
|
| 53 |
+
|
| 54 |
+
ed = _levenshtein(pred, gt)
|
| 55 |
+
denom = max(len_pred, len_gt)
|
| 56 |
+
score = max(0.0, 1.0 - ed / denom)
|
| 57 |
+
return {
|
| 58 |
+
"score": score,
|
| 59 |
+
"metric": "1ned",
|
| 60 |
+
"edit_distance": ed,
|
| 61 |
+
"len_pred": len_pred,
|
| 62 |
+
"len_gt": len_gt,
|
| 63 |
+
}
|
eval/judges/referring.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""单字识别(Recognition)打分:Exact Match Accuracy。
|
| 2 |
+
|
| 3 |
+
GT 来自 infer 阶段写入 ``infer_results["单字识别"]["gt_char"]``。
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def _norm(s: str) -> str:
|
| 10 |
+
return (s or "").strip().strip("。.;;,,\"'“”‘’《》<>()()【】[]{}!?!?::`·~~")
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def judge(extract: dict, row: dict) -> dict:
|
| 14 |
+
pred = str((extract or {}).get("char", "") or "").strip()
|
| 15 |
+
infer_results = row.get("infer_results") or {}
|
| 16 |
+
task_rec = infer_results.get("单字识别") or {}
|
| 17 |
+
gt = str(task_rec.get("gt_char", "") or "").strip()
|
| 18 |
+
if not gt:
|
| 19 |
+
return {"score": 0.0, "metric": "exact_match", "gt": "", "pred": pred, "error": "no_gt"}
|
| 20 |
+
score = 1.0 if _norm(pred) == _norm(gt) else 0.0
|
| 21 |
+
return {"score": score, "metric": "exact_match", "gt": gt, "pred": pred}
|
eval/judges/spotting.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""字符检测(Detection / End-to-End Spotting)打分。
|
| 2 |
+
|
| 3 |
+
- Detection:仅看 bbox,IoU > 0.75 视为 TP,包含 [UNK]
|
| 4 |
+
- Spotting:IoU > 0.75 且字符匹配视为 TP,排除 [UNK]
|
| 5 |
+
均输出 per-sample F1。GT bbox 像素单位会被归一化到 0-1000 与模型输出对齐。
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
from ..utils.unk import is_unk_char
|
| 11 |
+
|
| 12 |
+
IOU_THRESH = 0.75
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def _iou(a, b) -> float:
|
| 16 |
+
ax1, ay1, ax2, ay2 = a
|
| 17 |
+
bx1, by1, bx2, by2 = b
|
| 18 |
+
if ax2 <= ax1 or ay2 <= ay1 or bx2 <= bx1 or by2 <= by1:
|
| 19 |
+
return 0.0
|
| 20 |
+
ix1, iy1 = max(ax1, bx1), max(ay1, by1)
|
| 21 |
+
ix2, iy2 = min(ax2, bx2), min(ay2, by2)
|
| 22 |
+
iw, ih = ix2 - ix1, iy2 - iy1
|
| 23 |
+
if iw <= 0 or ih <= 0:
|
| 24 |
+
return 0.0
|
| 25 |
+
inter = iw * ih
|
| 26 |
+
union = (ax2 - ax1) * (ay2 - ay1) + (bx2 - bx1) * (by2 - by1) - inter
|
| 27 |
+
return inter / union if union > 0 else 0.0
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _parse_gt(row: dict) -> tuple[list[dict], int, int]:
|
| 31 |
+
"""解析 GT spotting,返回 [{'bbox':[x1,y1,x2,y2],'char':str}, ...] + 图像 W/H。"""
|
| 32 |
+
sp = row.get("spotting") or []
|
| 33 |
+
W = int(row.get("width") or 0)
|
| 34 |
+
H = int(row.get("height") or 0)
|
| 35 |
+
items: list[dict] = []
|
| 36 |
+
for it in sp:
|
| 37 |
+
if not isinstance(it, dict):
|
| 38 |
+
continue
|
| 39 |
+
ch = it.get("modern_char")
|
| 40 |
+
if ch is None:
|
| 41 |
+
ch = it.get("text", "")
|
| 42 |
+
ch = str(ch or "").strip()
|
| 43 |
+
|
| 44 |
+
bbox = it.get("bbox")
|
| 45 |
+
if bbox is None:
|
| 46 |
+
continue
|
| 47 |
+
x1 = y1 = x2 = y2 = None
|
| 48 |
+
if isinstance(bbox, dict):
|
| 49 |
+
try:
|
| 50 |
+
x1, y1, x2, y2 = (float(bbox[k]) for k in ("x1", "y1", "x2", "y2"))
|
| 51 |
+
except (KeyError, TypeError, ValueError):
|
| 52 |
+
continue
|
| 53 |
+
elif isinstance(bbox, (list, tuple)) and len(bbox) == 4:
|
| 54 |
+
try:
|
| 55 |
+
bx = [float(v) for v in bbox]
|
| 56 |
+
except (TypeError, ValueError):
|
| 57 |
+
continue
|
| 58 |
+
if bx[2] < bx[0] or bx[3] < bx[1]:
|
| 59 |
+
x1, y1, x2, y2 = bx[0], bx[1], bx[0] + bx[2], bx[1] + bx[3]
|
| 60 |
+
else:
|
| 61 |
+
if "modern_char" in it:
|
| 62 |
+
x1, y1, x2, y2 = bx[0], bx[1], bx[0] + bx[2], bx[1] + bx[3]
|
| 63 |
+
else:
|
| 64 |
+
x1, y1, x2, y2 = bx
|
| 65 |
+
else:
|
| 66 |
+
continue
|
| 67 |
+
if x2 <= x1 or y2 <= y1:
|
| 68 |
+
continue
|
| 69 |
+
items.append({"bbox": [float(x1), float(y1), float(x2), float(y2)], "char": ch})
|
| 70 |
+
return items, W, H
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _scale_to_1000(items: list[dict], W: int, H: int) -> list[dict]:
|
| 74 |
+
if W <= 0 or H <= 0:
|
| 75 |
+
return []
|
| 76 |
+
sx, sy = 1000.0 / W, 1000.0 / H
|
| 77 |
+
return [
|
| 78 |
+
{"bbox": [it["bbox"][0] * sx, it["bbox"][1] * sy, it["bbox"][2] * sx, it["bbox"][3] * sy], "char": it["char"]}
|
| 79 |
+
for it in items
|
| 80 |
+
]
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _match(preds: list[dict], gts: list[dict], iou_thresh: float, require_char: bool) -> tuple[int, int, int]:
|
| 84 |
+
if not preds or not gts:
|
| 85 |
+
return 0, len(preds), len(gts)
|
| 86 |
+
pairs: list[tuple[float, int, int]] = []
|
| 87 |
+
for pi, p in enumerate(preds):
|
| 88 |
+
for gi, g in enumerate(gts):
|
| 89 |
+
if require_char and p.get("char", "") != g.get("char", ""):
|
| 90 |
+
continue
|
| 91 |
+
iou = _iou(p["bbox"], g["bbox"])
|
| 92 |
+
if iou >= iou_thresh:
|
| 93 |
+
pairs.append((iou, pi, gi))
|
| 94 |
+
pairs.sort(key=lambda x: x[0], reverse=True)
|
| 95 |
+
used_p, used_g, tp = set(), set(), 0
|
| 96 |
+
for _, pi, gi in pairs:
|
| 97 |
+
if pi in used_p or gi in used_g:
|
| 98 |
+
continue
|
| 99 |
+
used_p.add(pi)
|
| 100 |
+
used_g.add(gi)
|
| 101 |
+
tp += 1
|
| 102 |
+
return tp, len(preds) - tp, len(gts) - tp
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def _f1(tp: int, fp: int, fn: int) -> float:
|
| 106 |
+
if tp == 0:
|
| 107 |
+
return 0.0
|
| 108 |
+
p = tp / (tp + fp) if (tp + fp) else 0.0
|
| 109 |
+
r = tp / (tp + fn) if (tp + fn) else 0.0
|
| 110 |
+
return 2 * p * r / (p + r) if (p + r) else 0.0
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def judge(extract: dict, row: dict, iou_thresh: float = IOU_THRESH) -> dict:
|
| 114 |
+
gt_raw, W, H = _parse_gt(row)
|
| 115 |
+
gts = _scale_to_1000(gt_raw, W, H)
|
| 116 |
+
|
| 117 |
+
preds_src = (extract or {}).get("items") or []
|
| 118 |
+
preds: list[dict] = []
|
| 119 |
+
for it in preds_src:
|
| 120 |
+
if not isinstance(it, dict):
|
| 121 |
+
continue
|
| 122 |
+
bb = it.get("bbox")
|
| 123 |
+
if not isinstance(bb, (list, tuple)) or len(bb) != 4:
|
| 124 |
+
continue
|
| 125 |
+
try:
|
| 126 |
+
bb = [float(v) for v in bb]
|
| 127 |
+
except (TypeError, ValueError):
|
| 128 |
+
continue
|
| 129 |
+
if bb[2] <= bb[0] or bb[3] <= bb[1]:
|
| 130 |
+
continue
|
| 131 |
+
preds.append({"bbox": bb, "char": str(it.get("char", "") or "").strip()})
|
| 132 |
+
|
| 133 |
+
det_tp, det_fp, det_fn = _match(preds, gts, iou_thresh, require_char=False)
|
| 134 |
+
det_f1 = _f1(det_tp, det_fp, det_fn)
|
| 135 |
+
|
| 136 |
+
spot_gts = [it for it in gts if not is_unk_char(it["char"])]
|
| 137 |
+
spot_preds = [it for it in preds if not is_unk_char(it["char"])]
|
| 138 |
+
spot_tp, spot_fp, spot_fn = _match(spot_preds, spot_gts, iou_thresh, require_char=True)
|
| 139 |
+
spot_f1 = _f1(spot_tp, spot_fp, spot_fn)
|
| 140 |
+
|
| 141 |
+
return {
|
| 142 |
+
"score": spot_f1,
|
| 143 |
+
"iou_thresh": iou_thresh,
|
| 144 |
+
"detection_f1": det_f1,
|
| 145 |
+
"spotting_f1": spot_f1,
|
| 146 |
+
"detection": {"tp": det_tp, "fp": det_fp, "fn": det_fn},
|
| 147 |
+
"spotting": {"tp": spot_tp, "fp": spot_fp, "fn": spot_fn},
|
| 148 |
+
"n_pred": len(preds),
|
| 149 |
+
"n_gt": len(gts),
|
| 150 |
+
}
|
eval/prompts/__init__.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""4 个任务的 prompt 与 extract 注册表。"""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from typing import Callable
|
| 6 |
+
|
| 7 |
+
from . import classify, extract_text, referring, spotting
|
| 8 |
+
|
| 9 |
+
TASK_CLASSIFY = "字体分类"
|
| 10 |
+
TASK_EXTRACT = "字符提取"
|
| 11 |
+
TASK_SPOTTING = "字符检测"
|
| 12 |
+
TASK_REFERRING = "单字识别"
|
| 13 |
+
|
| 14 |
+
PROMPTS: dict[str, str] = {
|
| 15 |
+
TASK_CLASSIFY: classify.PROMPT,
|
| 16 |
+
TASK_EXTRACT: extract_text.PROMPT,
|
| 17 |
+
TASK_SPOTTING: spotting.PROMPT,
|
| 18 |
+
TASK_REFERRING: referring.PROMPT,
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
EXTRACT_FUNCS: dict[str, Callable[[str], tuple[bool, dict]]] = {
|
| 22 |
+
TASK_CLASSIFY: classify.extract,
|
| 23 |
+
TASK_EXTRACT: extract_text.extract,
|
| 24 |
+
TASK_SPOTTING: spotting.extract,
|
| 25 |
+
TASK_REFERRING: referring.extract,
|
| 26 |
+
}
|
eval/prompts/_text.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Prompt / Extract 共用文本工具。
|
| 2 |
+
|
| 3 |
+
- ``strip_thinking``: 剥离模型输出里的 ``<think>...</think>`` / ``<answer>...</answer>``
|
| 4 |
+
- ``extract_by_prefix``: 按多前缀("字体分类:" / "字体:" / ...)从纯文本中抽取冒号后的内容
|
| 5 |
+
- ``clean_value``: 清理首尾空白、代码块围栏、常见标点引号
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import re
|
| 11 |
+
|
| 12 |
+
_OTHER_PREFIX_RE = re.compile(r"^(?:字体分类|字体|分类|提取文本|提取结果|识别结果|识别文本|文本)\s*[::]")
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def strip_thinking(text: str) -> str:
|
| 16 |
+
"""剥离 thinking 段,只保留最终答案。
|
| 17 |
+
|
| 18 |
+
支持 ``<think>...</think><answer>...</answer>`` / 仅 ``</think>`` / 仅 ``<think>`` 等多种形态。
|
| 19 |
+
"""
|
| 20 |
+
if not text:
|
| 21 |
+
return ""
|
| 22 |
+
s = text
|
| 23 |
+
|
| 24 |
+
ans_m = re.search(r"<\s*answer\s*>([\s\S]*?)<\s*/\s*answer\s*>", s, flags=re.IGNORECASE)
|
| 25 |
+
if ans_m:
|
| 26 |
+
return ans_m.group(1).strip()
|
| 27 |
+
|
| 28 |
+
close_matches = list(re.finditer(r"<\s*/\s*(?:think|thinking|reasoning)\s*>", s, flags=re.IGNORECASE))
|
| 29 |
+
if close_matches:
|
| 30 |
+
last = close_matches[-1]
|
| 31 |
+
tail = s[last.end() :].strip()
|
| 32 |
+
tail = re.sub(r"^\s*<\s*answer\s*>\s*", "", tail, flags=re.IGNORECASE)
|
| 33 |
+
tail = re.sub(r"\s*<\s*/?\s*answer\s*>\s*$", "", tail, flags=re.IGNORECASE)
|
| 34 |
+
return tail.strip()
|
| 35 |
+
|
| 36 |
+
open_m = re.search(r"<\s*(?:think|thinking|reasoning)\s*>", s, flags=re.IGNORECASE)
|
| 37 |
+
if open_m:
|
| 38 |
+
head = s[: open_m.start()].strip()
|
| 39 |
+
return head if head else ""
|
| 40 |
+
|
| 41 |
+
return s.strip()
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def strip_code_fence(s: str) -> str:
|
| 45 |
+
if s is None:
|
| 46 |
+
return ""
|
| 47 |
+
s = s.strip()
|
| 48 |
+
m = re.match(r"^`{3,}[^\n`]*\n?(.*?)\n?`{3,}\s*$", s, re.DOTALL)
|
| 49 |
+
if m:
|
| 50 |
+
return m.group(1).strip()
|
| 51 |
+
return s.strip("`").strip()
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def clean_value(s: str) -> str:
|
| 55 |
+
if not s:
|
| 56 |
+
return ""
|
| 57 |
+
s = strip_code_fence(s)
|
| 58 |
+
s = s.strip().strip("。.;;,,\"'“”‘’")
|
| 59 |
+
return s.strip()
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def extract_by_prefix(text: str, prefixes: list[str], merge_trailing_lines: bool = False) -> str:
|
| 63 |
+
"""按 ``前缀:`` 抽取冒号之后的答案,命中多次取最后一次。
|
| 64 |
+
|
| 65 |
+
``merge_trailing_lines=True`` 时,"同行答案 + 后续多行非空"一并合并,
|
| 66 |
+
用于"字符提取"任务(模型常把多行文本写在前缀之后)。
|
| 67 |
+
"""
|
| 68 |
+
if not text:
|
| 69 |
+
return ""
|
| 70 |
+
|
| 71 |
+
prefix_pattern = "|".join(re.escape(p) for p in prefixes)
|
| 72 |
+
head_pattern = re.compile(rf"(?:{prefix_pattern})\s*[::]")
|
| 73 |
+
matches = list(head_pattern.finditer(text))
|
| 74 |
+
if not matches:
|
| 75 |
+
return ""
|
| 76 |
+
|
| 77 |
+
last = matches[-1]
|
| 78 |
+
tail = text[last.end() :]
|
| 79 |
+
first_line, _nl, rest = tail.partition("\n")
|
| 80 |
+
first_line_stripped = first_line.strip()
|
| 81 |
+
|
| 82 |
+
starts_with_fence = bool(re.match(r"^`{3,}", first_line_stripped))
|
| 83 |
+
first_line_no_fence = re.sub(r"^`{3,}[^\n`]*", "", first_line_stripped).strip("` ").strip()
|
| 84 |
+
|
| 85 |
+
if not starts_with_fence and first_line_no_fence:
|
| 86 |
+
if not merge_trailing_lines:
|
| 87 |
+
return clean_value(first_line_no_fence)
|
| 88 |
+
follow_lines: list[str] = []
|
| 89 |
+
for ln in rest.splitlines():
|
| 90 |
+
ln_s = ln.strip().strip("`").strip()
|
| 91 |
+
if not ln_s:
|
| 92 |
+
continue
|
| 93 |
+
if _OTHER_PREFIX_RE.search(ln_s):
|
| 94 |
+
break
|
| 95 |
+
follow_lines.append(ln_s)
|
| 96 |
+
head_clean = clean_value(first_line_no_fence)
|
| 97 |
+
if not follow_lines:
|
| 98 |
+
return head_clean
|
| 99 |
+
cleaned_follow = [(clean_value(ln) or ln) for ln in follow_lines]
|
| 100 |
+
return "\n".join([head_clean, *cleaned_follow]).strip()
|
| 101 |
+
|
| 102 |
+
multiline_src = rest
|
| 103 |
+
if starts_with_fence:
|
| 104 |
+
close_m = re.search(r"\n?`{3,}\s*(\n|$)", rest)
|
| 105 |
+
if close_m:
|
| 106 |
+
multiline_src = rest[: close_m.start()]
|
| 107 |
+
|
| 108 |
+
lines = [ln.strip().strip("`").strip() for ln in multiline_src.splitlines()]
|
| 109 |
+
lines = [ln for ln in lines if ln]
|
| 110 |
+
if not lines:
|
| 111 |
+
return ""
|
| 112 |
+
if len(lines) == 1:
|
| 113 |
+
return clean_value(lines[0])
|
| 114 |
+
cleaned = [(clean_value(ln) or ln) for ln in lines]
|
| 115 |
+
return "\n".join(cleaned).strip()
|
eval/prompts/classify.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""字体分类(Classification)任务。"""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from ._text import extract_by_prefix, strip_thinking
|
| 6 |
+
|
| 7 |
+
VALID_FONT_CATEGORIES = {"甲骨文", "金文", "篆书", "隶书", "楷书", "行书", "草书"}
|
| 8 |
+
|
| 9 |
+
PROMPT = """你是一名精通中国古文字学与书法史的专家。
|
| 10 |
+
|
| 11 |
+
任务:
|
| 12 |
+
请根据输入的古文字图像,对其中汉字的字体进行分类。
|
| 13 |
+
|
| 14 |
+
分类范围(仅允许从以下七类中选择一个):
|
| 15 |
+
1. 甲骨文
|
| 16 |
+
2. 金文
|
| 17 |
+
3. 篆书
|
| 18 |
+
4. 隶书
|
| 19 |
+
5. 楷书
|
| 20 |
+
6. 行书
|
| 21 |
+
7. 草书
|
| 22 |
+
|
| 23 |
+
要求:
|
| 24 |
+
- 仔细观察字形结构、笔画特征、线条风格和整体布局
|
| 25 |
+
- 只能输出一个最可能的类别
|
| 26 |
+
- 不允许输出多个类别或"无法判断"(除非图像极其模糊)
|
| 27 |
+
- 不要输出解释(除非额外要求)
|
| 28 |
+
|
| 29 |
+
输出格式(必须严格遵守):
|
| 30 |
+
字体分类:<类别名称>
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def extract(answer: str) -> tuple[bool, dict[str, str | bool]]:
|
| 35 |
+
"""三层回退:精确前缀 → 部分匹配("楷书体"→"楷书")→ 整段最后一次命中。"""
|
| 36 |
+
text = strip_thinking(answer)
|
| 37 |
+
category = extract_by_prefix(text, ["字体分类", "字体", "分类"])
|
| 38 |
+
|
| 39 |
+
data: dict[str, str | bool] = {}
|
| 40 |
+
if category and category in VALID_FONT_CATEGORIES:
|
| 41 |
+
data["category"] = category
|
| 42 |
+
return True, data
|
| 43 |
+
|
| 44 |
+
# 部分匹配
|
| 45 |
+
if category:
|
| 46 |
+
for c in VALID_FONT_CATEGORIES:
|
| 47 |
+
if c in category:
|
| 48 |
+
data["category"] = c
|
| 49 |
+
return True, data
|
| 50 |
+
|
| 51 |
+
# 回退:扫整段答案,取最后一次出现的合法字体名
|
| 52 |
+
if text:
|
| 53 |
+
last_pos = -1
|
| 54 |
+
last_hit: str | None = None
|
| 55 |
+
for c in VALID_FONT_CATEGORIES:
|
| 56 |
+
pos = text.rfind(c)
|
| 57 |
+
if pos > last_pos:
|
| 58 |
+
last_pos = pos
|
| 59 |
+
last_hit = c
|
| 60 |
+
if last_hit is not None:
|
| 61 |
+
data["category"] = last_hit
|
| 62 |
+
data["fallback"] = True
|
| 63 |
+
return True, data
|
| 64 |
+
|
| 65 |
+
return False, data
|
eval/prompts/extract_text.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""字符提取(Parsing)任务。"""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import re
|
| 6 |
+
|
| 7 |
+
from ._text import clean_value, extract_by_prefix, strip_code_fence, strip_thinking
|
| 8 |
+
|
| 9 |
+
PROMPT = """你将被提供一张包含汉字字符的图片。请仔细观察图片,并将图片中的所有汉字字符以正确的阅读顺序提取出来。
|
| 10 |
+
|
| 11 |
+
要求:
|
| 12 |
+
- 严格按图片中文字的阅读顺序输出
|
| 13 |
+
- 仅输出识别到的字符本身,不要输出任何解释、标点补充或分析
|
| 14 |
+
|
| 15 |
+
输出格式(必须严格遵守):
|
| 16 |
+
提取文本:<识别到的汉字字符>
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
_OTHER_PREFIX_RE = re.compile(r"(?:字体分类|字体|分类)\s*[::]")
|
| 20 |
+
_PREAMBLE_LINE_RE = re.compile(
|
| 21 |
+
r"^(?:好的|好|没问题|当然|根据(?:图片|图像)|这是|以下是|图片中(?:的)?(?:内容|文字|字符)?(?:为|是|如下)?|无法(?:识别|看清)|抱歉|对不起)"
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _fallback_full_answer(text: str) -> str:
|
| 26 |
+
"""模型不按格式输出时,把整段答案当作字符提取结果,但清理"开场白"与"其它任务前缀"。"""
|
| 27 |
+
if not text:
|
| 28 |
+
return ""
|
| 29 |
+
raw = strip_code_fence(text.strip())
|
| 30 |
+
if not raw:
|
| 31 |
+
return ""
|
| 32 |
+
|
| 33 |
+
cleaned: list[str] = []
|
| 34 |
+
for ln in raw.splitlines():
|
| 35 |
+
s = ln.strip().strip("`").strip()
|
| 36 |
+
if not s:
|
| 37 |
+
continue
|
| 38 |
+
if _OTHER_PREFIX_RE.match(s):
|
| 39 |
+
continue
|
| 40 |
+
if _PREAMBLE_LINE_RE.match(s):
|
| 41 |
+
continue
|
| 42 |
+
m = _OTHER_PREFIX_RE.search(s)
|
| 43 |
+
if m:
|
| 44 |
+
s = s[: m.start()].rstrip()
|
| 45 |
+
if not s:
|
| 46 |
+
continue
|
| 47 |
+
cleaned.append(s)
|
| 48 |
+
|
| 49 |
+
if not cleaned:
|
| 50 |
+
return ""
|
| 51 |
+
candidate = "\n".join(cleaned).strip()
|
| 52 |
+
candidate = clean_value(candidate) or candidate
|
| 53 |
+
if len(candidate) < 2:
|
| 54 |
+
return ""
|
| 55 |
+
return candidate
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def extract(answer: str) -> tuple[bool, dict[str, str | bool]]:
|
| 59 |
+
text = strip_thinking(answer)
|
| 60 |
+
extracted = extract_by_prefix(
|
| 61 |
+
text,
|
| 62 |
+
["提取文本", "提取结果", "识别结果", "识别文本", "文本"],
|
| 63 |
+
merge_trailing_lines=True,
|
| 64 |
+
)
|
| 65 |
+
data: dict[str, str | bool] = {}
|
| 66 |
+
if extracted:
|
| 67 |
+
data["extracted_text"] = extracted
|
| 68 |
+
return True, data
|
| 69 |
+
|
| 70 |
+
fb = _fallback_full_answer(text)
|
| 71 |
+
if fb:
|
| 72 |
+
data["extracted_text"] = fb
|
| 73 |
+
data["fallback"] = True
|
| 74 |
+
return True, data
|
| 75 |
+
|
| 76 |
+
return False, data
|
eval/prompts/referring.py
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""单字识别(Fine-grained Archaic Character Recognition)任务。
|
| 2 |
+
|
| 3 |
+
工作流:
|
| 4 |
+
1. ``prepare_referring_sample`` 从 spotting GT 中按 (seed + sample_key) 确定性采样一个非 [UNK] 字符;
|
| 5 |
+
2. 在原图上绘制红色矩形框,落盘到稳定缓存目录;
|
| 6 |
+
3. 用渲染图调用模型,模型只识别红框内字符;
|
| 7 |
+
4. 评分使用 Exact Match Accuracy。
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import hashlib
|
| 13 |
+
import json
|
| 14 |
+
import os
|
| 15 |
+
import random
|
| 16 |
+
import re
|
| 17 |
+
import tempfile
|
| 18 |
+
import threading
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
from typing import Optional
|
| 21 |
+
|
| 22 |
+
from PIL import Image, ImageDraw
|
| 23 |
+
|
| 24 |
+
from ..utils.unk import is_unk_char
|
| 25 |
+
from ._text import clean_value, extract_by_prefix, strip_thinking
|
| 26 |
+
|
| 27 |
+
# ============================================================
|
| 28 |
+
# Prompt / Extract
|
| 29 |
+
# ============================================================
|
| 30 |
+
PROMPT = """你是一名精通中国古文字学的专家。
|
| 31 |
+
|
| 32 |
+
任务:
|
| 33 |
+
图中有一个**红色矩形框**,框内是一个古文字。请识别该红框内的古文字对应的**现代汉字**。
|
| 34 |
+
|
| 35 |
+
要求:
|
| 36 |
+
- 只识别红框内的单个字符,不要识别图片中其他位置的字符
|
| 37 |
+
- 输出必须是**一个**现代汉字(不要输出多个字,不要加拼音、标点、解释或其他任何字符)
|
| 38 |
+
- 如果无法识别,则输出:[UNK]
|
| 39 |
+
|
| 40 |
+
输出格式(必须严格遵守):
|
| 41 |
+
现代汉字:<单个汉字>
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
_CJK_RE = re.compile(r"[\u4e00-\u9fff\u3400-\u4dbf\U00020000-\U0002a6df\U0002a700-\U0002ebef\U00030000-\U0003134f]")
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def extract(answer: str) -> tuple[bool, dict[str, str]]:
|
| 48 |
+
text = strip_thinking(answer)
|
| 49 |
+
raw = extract_by_prefix(text, ["现代汉字", "汉字", "识别结果", "识别", "答案", "char"])
|
| 50 |
+
if not raw:
|
| 51 |
+
raw = clean_value(text)
|
| 52 |
+
if not raw:
|
| 53 |
+
return False, {}
|
| 54 |
+
|
| 55 |
+
stripped = raw.strip()
|
| 56 |
+
if stripped.upper() in {"[UNK]", "<UNK>", "UNK"}:
|
| 57 |
+
return True, {"char": "[UNK]"}
|
| 58 |
+
|
| 59 |
+
m = _CJK_RE.search(stripped)
|
| 60 |
+
if m:
|
| 61 |
+
return True, {"char": m.group(0)}
|
| 62 |
+
|
| 63 |
+
first = stripped.split()[0] if stripped.split() else ""
|
| 64 |
+
if first:
|
| 65 |
+
return True, {"char": first[:1]}
|
| 66 |
+
return False, {}
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
# ============================================================
|
| 70 |
+
# 红框采样 + 渲染
|
| 71 |
+
# ============================================================
|
| 72 |
+
DEFAULT_SEED = 42
|
| 73 |
+
RED_BOX_COLOR = (255, 0, 0)
|
| 74 |
+
MIN_BOX_WIDTH = 3
|
| 75 |
+
MAX_BOX_WIDTH = 12
|
| 76 |
+
BOX_WIDTH_RATIO = 0.006 # 0.6% of min(W,H)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _bbox_to_xyxy(item: dict) -> Optional[tuple[float, float, float, float]]:
|
| 80 |
+
"""规范化 spotting item 的 bbox 为像素坐标 (x1,y1,x2,y2)。
|
| 81 |
+
|
| 82 |
+
支持:
|
| 83 |
+
- {"bbox":[x,y,w,h], "modern_char": ...}(甲骨文)
|
| 84 |
+
- {"bbox":{"x1","y1","x2","y2"}, "text": ...}(金文/篆文)
|
| 85 |
+
- {"bbox":[x1,y1,x2,y2], "text": ...}(备用格式)
|
| 86 |
+
"""
|
| 87 |
+
bbox = item.get("bbox")
|
| 88 |
+
if bbox is None:
|
| 89 |
+
return None
|
| 90 |
+
|
| 91 |
+
if isinstance(bbox, dict):
|
| 92 |
+
try:
|
| 93 |
+
x1 = float(bbox.get("x1"))
|
| 94 |
+
y1 = float(bbox.get("y1"))
|
| 95 |
+
x2 = float(bbox.get("x2"))
|
| 96 |
+
y2 = float(bbox.get("y2"))
|
| 97 |
+
except (TypeError, ValueError):
|
| 98 |
+
return None
|
| 99 |
+
return (x1, y1, x2, y2) if (x2 > x1 and y2 > y1) else None
|
| 100 |
+
|
| 101 |
+
if isinstance(bbox, (list, tuple)) and len(bbox) == 4:
|
| 102 |
+
try:
|
| 103 |
+
bx = [float(v) for v in bbox]
|
| 104 |
+
except (TypeError, ValueError):
|
| 105 |
+
return None
|
| 106 |
+
if "modern_char" in item:
|
| 107 |
+
x, y, w, h = bx
|
| 108 |
+
x1, y1, x2, y2 = x, y, x + w, y + h
|
| 109 |
+
else:
|
| 110 |
+
if bx[2] < bx[0] or bx[3] < bx[1]:
|
| 111 |
+
x, y, w, h = bx
|
| 112 |
+
x1, y1, x2, y2 = x, y, x + w, y + h
|
| 113 |
+
else:
|
| 114 |
+
x1, y1, x2, y2 = bx
|
| 115 |
+
return (x1, y1, x2, y2) if (x2 > x1 and y2 > y1) else None
|
| 116 |
+
|
| 117 |
+
return None
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def _item_char(item: dict) -> str:
|
| 121 |
+
ch = item.get("modern_char")
|
| 122 |
+
if ch is None:
|
| 123 |
+
ch = item.get("text", "")
|
| 124 |
+
return str(ch or "").strip()
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def _build_sample_key(row: dict) -> str:
|
| 128 |
+
parts: list[str] = []
|
| 129 |
+
for k in ("image_path", "img_path", "image"):
|
| 130 |
+
v = row.get(k)
|
| 131 |
+
if v:
|
| 132 |
+
parts.append(f"{k}={v}")
|
| 133 |
+
sp = row.get("spotting")
|
| 134 |
+
if isinstance(sp, list) and sp:
|
| 135 |
+
fp = hashlib.md5(json.dumps(sp, ensure_ascii=False, sort_keys=True).encode("utf-8")).hexdigest()[:12]
|
| 136 |
+
parts.append(f"sp_fp={fp}")
|
| 137 |
+
return "|".join(parts)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def _seeded_rng(key: str, seed: int) -> random.Random:
|
| 141 |
+
h = hashlib.md5(f"{seed}::{key}".encode("utf-8")).hexdigest()
|
| 142 |
+
return random.Random(int(h[:16], 16))
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def _pick_target(row: dict, seed: int) -> Optional[dict]:
|
| 146 |
+
sp = row.get("spotting") or []
|
| 147 |
+
if not isinstance(sp, list) or not sp:
|
| 148 |
+
return None
|
| 149 |
+
|
| 150 |
+
candidates: list[tuple[int, str, tuple[float, float, float, float]]] = []
|
| 151 |
+
for idx, it in enumerate(sp):
|
| 152 |
+
if not isinstance(it, dict):
|
| 153 |
+
continue
|
| 154 |
+
ch = _item_char(it)
|
| 155 |
+
if is_unk_char(ch):
|
| 156 |
+
continue
|
| 157 |
+
bb = _bbox_to_xyxy(it)
|
| 158 |
+
if bb is None:
|
| 159 |
+
continue
|
| 160 |
+
candidates.append((idx, ch, bb))
|
| 161 |
+
if not candidates:
|
| 162 |
+
return None
|
| 163 |
+
|
| 164 |
+
sample_key = _build_sample_key(row) or "no-key"
|
| 165 |
+
rng = _seeded_rng(sample_key, seed)
|
| 166 |
+
idx, ch, bb = rng.choice(candidates)
|
| 167 |
+
return {"char": ch, "bbox_xyxy": bb, "index": idx, "sample_key": sample_key}
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def _box_width(W: int, H: int) -> int:
|
| 171 |
+
short = max(1, min(W, H))
|
| 172 |
+
w = int(round(short * BOX_WIDTH_RATIO))
|
| 173 |
+
return max(MIN_BOX_WIDTH, min(MAX_BOX_WIDTH, w))
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def _draw_box(img_path: str, bbox_xyxy, out_dir: Optional[str]) -> str:
|
| 177 |
+
with Image.open(img_path) as im:
|
| 178 |
+
im = im.convert("RGB")
|
| 179 |
+
W, H = im.size
|
| 180 |
+
x1, y1, x2, y2 = [
|
| 181 |
+
max(0.0, min(float(W - 1) if i % 2 == 0 else float(H - 1), float(v))) for i, v in enumerate(bbox_xyxy)
|
| 182 |
+
]
|
| 183 |
+
bw = _box_width(W, H)
|
| 184 |
+
ImageDraw.Draw(im).rectangle([x1, y1, x2, y2], outline=RED_BOX_COLOR, width=bw)
|
| 185 |
+
|
| 186 |
+
if out_dir is None:
|
| 187 |
+
out_dir = os.path.join(tempfile.gettempdir(), "chronotext_referring")
|
| 188 |
+
os.makedirs(out_dir, exist_ok=True)
|
| 189 |
+
stem = Path(img_path).stem
|
| 190 |
+
tag = hashlib.md5(f"{img_path}|{x1:.2f},{y1:.2f},{x2:.2f},{y2:.2f}".encode("utf-8")).hexdigest()[:8]
|
| 191 |
+
out_path = os.path.join(out_dir, f"{stem}_redbox_{tag}_{os.getpid()}_{threading.get_ident()}.png")
|
| 192 |
+
|
| 193 |
+
tmp = f"{out_path}.tmp"
|
| 194 |
+
im.save(tmp, format="PNG")
|
| 195 |
+
os.replace(tmp, out_path)
|
| 196 |
+
return out_path
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def prepare_referring_sample(
|
| 200 |
+
row: dict,
|
| 201 |
+
img_path: str,
|
| 202 |
+
seed: int = DEFAULT_SEED,
|
| 203 |
+
out_dir: Optional[str] = None,
|
| 204 |
+
) -> Optional[dict]:
|
| 205 |
+
"""采样 + 画框 + 落盘。任一步失败返回 None。"""
|
| 206 |
+
picked = _pick_target(row, seed=seed)
|
| 207 |
+
if picked is None:
|
| 208 |
+
return None
|
| 209 |
+
if not img_path or not os.path.exists(img_path):
|
| 210 |
+
return None
|
| 211 |
+
|
| 212 |
+
rendered = _draw_box(img_path, picked["bbox_xyxy"], out_dir)
|
| 213 |
+
if not (rendered and os.path.exists(rendered)):
|
| 214 |
+
rendered = _draw_box(img_path, picked["bbox_xyxy"], out_dir)
|
| 215 |
+
return {
|
| 216 |
+
"rendered_img_path": rendered,
|
| 217 |
+
"target_char": picked["char"],
|
| 218 |
+
"target_bbox_xyxy": [float(v) for v in picked["bbox_xyxy"]],
|
| 219 |
+
"index": picked["index"],
|
| 220 |
+
"sample_key": picked["sample_key"],
|
| 221 |
+
}
|
eval/prompts/spotting.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""字符检测(Detection / End-to-End Spotting)任务。
|
| 2 |
+
|
| 3 |
+
模型输出 JSON 数组,bbox 归一化到 0-1000,char 是该 bbox 对应的现代汉字。
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import json
|
| 9 |
+
import re
|
| 10 |
+
|
| 11 |
+
from ._text import strip_thinking
|
| 12 |
+
|
| 13 |
+
PROMPT = """你是一名古文字图像检测与识别专家。
|
| 14 |
+
|
| 15 |
+
任务:
|
| 16 |
+
请检测输入图像中所有可见的古文单字符,并为每个单字符同时给出边界框 bbox 和该字符本身。
|
| 17 |
+
|
| 18 |
+
检测对象:
|
| 19 |
+
- 每个独立古文字符作为一个目标
|
| 20 |
+
- 不要检测标点、背景纹理、裂纹、装饰线、器物边缘或非文字区域
|
| 21 |
+
- 如果一个字符残缺但仍可辨认为字符,也应检测
|
| 22 |
+
- 如果多个笔画明显属于同一个字符,只输出一个 bbox
|
| 23 |
+
|
| 24 |
+
坐标要求:
|
| 25 |
+
- bbox 格式为 [x1, y1, x2, y2]
|
| 26 |
+
- x1, y1 表示左上角坐标
|
| 27 |
+
- x2, y2 表示右下角坐标
|
| 28 |
+
- 所有坐标必须基于整张输入图像归一化到 0–1000 的整数范围
|
| 29 |
+
- x1 < x2,y1 < y2
|
| 30 |
+
- 不要输出小数
|
| 31 |
+
|
| 32 |
+
字符要求:
|
| 33 |
+
- char 字段填写该 bbox 区域对应的字符本身(使用现代汉字写出)
|
| 34 |
+
- 每个 bbox 只对应一个字符
|
| 35 |
+
- 如果字符无法识别,可以使用 "[UNK]" 代替,但仍需要输出该字符的 bbox
|
| 36 |
+
|
| 37 |
+
排序要求:
|
| 38 |
+
- 按从上到下、从左到右的顺序排输出
|
| 39 |
+
- idx 从 1 开始连续编号
|
| 40 |
+
|
| 41 |
+
输出要求:
|
| 42 |
+
- 只输出合法 JSON
|
| 43 |
+
- 不要输出解释、Markdown、代码块或多余文字
|
| 44 |
+
|
| 45 |
+
JSON 输出格式:
|
| 46 |
+
[
|
| 47 |
+
{"idx": 1, "bbox": [x1, y1, x2, y2], "char": "<该bbox对应的字符>"},
|
| 48 |
+
{"idx": 2, "bbox": [x1, y1, x2, y2], "char": "<该bbox对应的字符>"}
|
| 49 |
+
]
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _strip_json_fence(text: str) -> str:
|
| 54 |
+
if not text:
|
| 55 |
+
return ""
|
| 56 |
+
s = text.strip()
|
| 57 |
+
m = re.match(r"^```(?:json|JSON)?\s*\n?(.*?)\n?```\s*$", s, flags=re.DOTALL)
|
| 58 |
+
return m.group(1).strip() if m else s
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def extract(answer: str) -> tuple[bool, dict]:
|
| 62 |
+
data: dict = {"items": []}
|
| 63 |
+
if not answer:
|
| 64 |
+
return False, data
|
| 65 |
+
|
| 66 |
+
s = _strip_json_fence(strip_thinking(answer))
|
| 67 |
+
|
| 68 |
+
parsed = None
|
| 69 |
+
try:
|
| 70 |
+
parsed = json.loads(s)
|
| 71 |
+
except Exception:
|
| 72 |
+
parsed = None
|
| 73 |
+
|
| 74 |
+
if parsed is None:
|
| 75 |
+
lb, rb = s.find("["), s.rfind("]")
|
| 76 |
+
if lb != -1 and rb != -1 and rb > lb:
|
| 77 |
+
try:
|
| 78 |
+
parsed = json.loads(s[lb : rb + 1])
|
| 79 |
+
except Exception:
|
| 80 |
+
parsed = None
|
| 81 |
+
|
| 82 |
+
if parsed is None:
|
| 83 |
+
for m in re.finditer(r"\[[\s\S]*?\]", s):
|
| 84 |
+
try:
|
| 85 |
+
cand = json.loads(m.group(0))
|
| 86 |
+
if isinstance(cand, list):
|
| 87 |
+
parsed = cand
|
| 88 |
+
break
|
| 89 |
+
except Exception:
|
| 90 |
+
continue
|
| 91 |
+
|
| 92 |
+
if parsed is None or not isinstance(parsed, list):
|
| 93 |
+
return False, data
|
| 94 |
+
|
| 95 |
+
items: list[dict] = []
|
| 96 |
+
valid_all = True
|
| 97 |
+
for i, it in enumerate(parsed, start=1):
|
| 98 |
+
if not isinstance(it, dict):
|
| 99 |
+
valid_all = False
|
| 100 |
+
continue
|
| 101 |
+
bbox = it.get("bbox")
|
| 102 |
+
if not isinstance(bbox, list) or len(bbox) != 4 or not all(isinstance(v, (int, float)) for v in bbox):
|
| 103 |
+
valid_all = False
|
| 104 |
+
continue
|
| 105 |
+
x1, y1, x2, y2 = [int(round(float(v))) for v in bbox]
|
| 106 |
+
x1 = max(0, min(1000, x1))
|
| 107 |
+
y1 = max(0, min(1000, y1))
|
| 108 |
+
x2 = max(0, min(1000, x2))
|
| 109 |
+
y2 = max(0, min(1000, y2))
|
| 110 |
+
if not (x1 < x2 and y1 < y2):
|
| 111 |
+
valid_all = False
|
| 112 |
+
continue
|
| 113 |
+
|
| 114 |
+
char = it.get("char", "")
|
| 115 |
+
if not isinstance(char, str):
|
| 116 |
+
char = str(char) if char is not None else ""
|
| 117 |
+
char = char.strip()
|
| 118 |
+
|
| 119 |
+
idx = it.get("idx", i)
|
| 120 |
+
items.append(
|
| 121 |
+
{
|
| 122 |
+
"idx": int(idx) if isinstance(idx, (int, float)) else i,
|
| 123 |
+
"bbox": [x1, y1, x2, y2],
|
| 124 |
+
"char": char,
|
| 125 |
+
}
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
data["items"] = items
|
| 129 |
+
if len(parsed) == 0:
|
| 130 |
+
return True, data
|
| 131 |
+
if not items:
|
| 132 |
+
return False, data
|
| 133 |
+
return valid_all, data
|
eval/requirements.txt
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Core
|
| 2 |
+
openai>=1.30.0
|
| 3 |
+
Pillow>=9.0.0
|
| 4 |
+
tqdm>=4.60.0
|
| 5 |
+
|
| 6 |
+
# Optional but strongly recommended (C++ Levenshtein, ~10x faster than pure-Python fallback)
|
| 7 |
+
rapidfuzz>=3.0.0
|
| 8 |
+
|
| 9 |
+
# For summarize.py (Excel output)
|
| 10 |
+
pandas>=1.5.0
|
| 11 |
+
openpyxl>=3.1.0
|
| 12 |
+
|
| 13 |
+
# Only required when --api_type local_vllm
|
| 14 |
+
# vllm>=0.5.0
|
eval/summarize.py
ADDED
|
@@ -0,0 +1,382 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ChronoText benchmark scoring summary.
|
| 2 |
+
|
| 3 |
+
Aggregates rule-based judging results from ``judge_results/<model>/results.jsonl``
|
| 4 |
+
into a multi-sheet Excel workbook with per-model x per-task / per-font-type breakdowns.
|
| 5 |
+
|
| 6 |
+
Usage:
|
| 7 |
+
python summarize.py # default: scan judge_results/
|
| 8 |
+
python summarize.py --input_dir judge_results
|
| 9 |
+
python summarize.py --output results_analysis.xlsx --num_workers 64
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import argparse
|
| 15 |
+
import json
|
| 16 |
+
import os
|
| 17 |
+
import sys
|
| 18 |
+
from collections import defaultdict
|
| 19 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
|
| 22 |
+
import pandas as pd
|
| 23 |
+
from openpyxl.styles import Alignment, Font, PatternFill
|
| 24 |
+
from openpyxl.utils import get_column_letter
|
| 25 |
+
from tqdm import tqdm
|
| 26 |
+
|
| 27 |
+
REPO_ROOT = Path(__file__).resolve().parent
|
| 28 |
+
sys.path.insert(0, str(REPO_ROOT.parent))
|
| 29 |
+
|
| 30 |
+
DEFAULT_INPUT_DIR = REPO_ROOT / "judge_results"
|
| 31 |
+
DEFAULT_OUTPUT_FILE = REPO_ROOT / "judge_results" / "results_analysis.xlsx"
|
| 32 |
+
|
| 33 |
+
# 数值格式:x100 保留 1 位(不加 %)
|
| 34 |
+
SCORE_SCALE = 100
|
| 35 |
+
SCORE_DECIMALS = 1
|
| 36 |
+
AVG_HEADER = "Average"
|
| 37 |
+
|
| 38 |
+
# 任务展示名:jsonl 中的 task key 用中文,输出表头统一映射为英文
|
| 39 |
+
TASK_DISPLAY = {
|
| 40 |
+
"字体分类": "Classification",
|
| 41 |
+
"字符提取": "Parsing",
|
| 42 |
+
"字符检测_Detection": "Detection",
|
| 43 |
+
"字符检测_Spotting": "Spotting",
|
| 44 |
+
"单字识别": "Recognition",
|
| 45 |
+
}
|
| 46 |
+
DETECTION_TASK = "字符检测_Detection"
|
| 47 |
+
SPOTTING_TASK = "字符检测_Spotting"
|
| 48 |
+
RECOGNITION_TASK = "单字识别"
|
| 49 |
+
|
| 50 |
+
# 字体顺序:学术顺序,不要按字典序
|
| 51 |
+
FONT_TYPE_PRIORITY = ["甲骨文", "金文", "篆书", "隶书", "楷书", "行书", "草书"]
|
| 52 |
+
ANCIENT_FONTS = {"甲骨文", "金文", "篆书"}
|
| 53 |
+
|
| 54 |
+
ANCIENT_TASKS = ["字体分类", "字符提取", DETECTION_TASK, SPOTTING_TASK, RECOGNITION_TASK]
|
| 55 |
+
MODERN_TASKS = ["字体分类", "字符提取"]
|
| 56 |
+
DISPLAY_TASKS = [SPOTTING_TASK, RECOGNITION_TASK, "字符提取", "字体分类"]
|
| 57 |
+
_DISPLAY_ORDER = {t: i for i, t in enumerate(DISPLAY_TASKS)}
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def display(t: str) -> str:
|
| 61 |
+
return TASK_DISPLAY.get(t, t)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def filter_display(tasks: list[str]) -> list[str]:
|
| 65 |
+
inter = [t for t in tasks if t in _DISPLAY_ORDER]
|
| 66 |
+
inter.sort(key=lambda x: _DISPLAY_ORDER[x])
|
| 67 |
+
return inter
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def fmt(v) -> float | str:
|
| 71 |
+
if v is None or v == "":
|
| 72 |
+
return ""
|
| 73 |
+
try:
|
| 74 |
+
return round(float(v) * SCORE_SCALE, SCORE_DECIMALS)
|
| 75 |
+
except (TypeError, ValueError):
|
| 76 |
+
return ""
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def parse_judge_file(file_path: str) -> tuple[dict[str, list[float]], dict[str, dict[str, list[float]]]]:
|
| 80 |
+
"""单次遍历同时返回整体分数 + 按字体分组的分数。"""
|
| 81 |
+
task_scores: dict[str, list[float]] = defaultdict(list)
|
| 82 |
+
type_task_scores: dict[str, dict[str, list[float]]] = defaultdict(lambda: defaultdict(list))
|
| 83 |
+
try:
|
| 84 |
+
with open(file_path, "r", encoding="utf-8") as f:
|
| 85 |
+
for line in f:
|
| 86 |
+
line = line.strip()
|
| 87 |
+
if not line:
|
| 88 |
+
continue
|
| 89 |
+
try:
|
| 90 |
+
data = json.loads(line)
|
| 91 |
+
except json.JSONDecodeError:
|
| 92 |
+
continue
|
| 93 |
+
jr = data.get("judge_results") or {}
|
| 94 |
+
if not jr:
|
| 95 |
+
continue
|
| 96 |
+
font_type = str(data.get("font_type", "") or "").strip() or "未知"
|
| 97 |
+
for task_name, task_result in jr.items():
|
| 98 |
+
# 字符检测拆成 Detection / Spotting 两个虚拟任务
|
| 99 |
+
if task_name == "字符检测":
|
| 100 |
+
inner = task_result.get("score", task_result) if isinstance(task_result, dict) else None
|
| 101 |
+
det = inner.get("detection_f1") if isinstance(inner, dict) else None
|
| 102 |
+
spot = inner.get("spotting_f1") if isinstance(inner, dict) else None
|
| 103 |
+
if det is not None:
|
| 104 |
+
task_scores[DETECTION_TASK].append(det)
|
| 105 |
+
type_task_scores[font_type][DETECTION_TASK].append(det)
|
| 106 |
+
if spot is not None:
|
| 107 |
+
task_scores[SPOTTING_TASK].append(spot)
|
| 108 |
+
type_task_scores[font_type][SPOTTING_TASK].append(spot)
|
| 109 |
+
continue
|
| 110 |
+
score = task_result.get("score", 0.0) if isinstance(task_result, dict) else 0.0
|
| 111 |
+
if isinstance(score, dict) and "score" in score:
|
| 112 |
+
score = score["score"]
|
| 113 |
+
task_scores[task_name].append(score)
|
| 114 |
+
type_task_scores[font_type][task_name].append(score)
|
| 115 |
+
except Exception as e:
|
| 116 |
+
print(f"读取文件 {file_path} 时出错: {e}")
|
| 117 |
+
return task_scores, type_task_scores
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def calc_avg(task_scores: dict[str, list]) -> dict[str, float | None]:
|
| 121 |
+
out: dict[str, float | None] = {}
|
| 122 |
+
for k, scores in task_scores.items():
|
| 123 |
+
cleaned = []
|
| 124 |
+
for s in scores:
|
| 125 |
+
if isinstance(s, dict) and "score" in s:
|
| 126 |
+
s = s["score"]
|
| 127 |
+
if s is None:
|
| 128 |
+
continue
|
| 129 |
+
try:
|
| 130 |
+
cleaned.append(float(s))
|
| 131 |
+
except (TypeError, ValueError):
|
| 132 |
+
continue
|
| 133 |
+
out[k] = sum(cleaned) / len(cleaned) if cleaned else None
|
| 134 |
+
return out
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def font_allowed_tasks(font_type: str, available_tasks: list[str]) -> list[str]:
|
| 138 |
+
allowed = ANCIENT_TASKS if font_type in ANCIENT_FONTS else MODERN_TASKS
|
| 139 |
+
inter = [t for t in available_tasks if t in allowed]
|
| 140 |
+
return filter_display(inter)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def get_group_tasks(group: str) -> list[str]:
|
| 144 |
+
base = ANCIENT_TASKS if group == "ancient" else MODERN_TASKS if group == "modern" else []
|
| 145 |
+
return filter_display(base)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def analyze(input_dir: str, output_file: str, num_workers: int) -> None:
|
| 149 |
+
print("=" * 72)
|
| 150 |
+
print("ChronoText Summarize")
|
| 151 |
+
print("=" * 72)
|
| 152 |
+
print(f"input_dir : {input_dir}")
|
| 153 |
+
print(f"output_file : {output_file}")
|
| 154 |
+
print(f"num_workers : {num_workers}\n")
|
| 155 |
+
|
| 156 |
+
if not os.path.isdir(input_dir):
|
| 157 |
+
raise SystemExit(f"输入目录不存在: {input_dir}")
|
| 158 |
+
|
| 159 |
+
model_tags = sorted(d for d in os.listdir(input_dir) if os.path.isdir(os.path.join(input_dir, d)))
|
| 160 |
+
print(f"找到 {len(model_tags)} 个模型: {model_tags}\n")
|
| 161 |
+
|
| 162 |
+
tasks: list[tuple[str, str]] = []
|
| 163 |
+
for tag in model_tags:
|
| 164 |
+
f = os.path.join(input_dir, tag, "results.jsonl")
|
| 165 |
+
if os.path.isfile(f):
|
| 166 |
+
tasks.append((tag, f))
|
| 167 |
+
else:
|
| 168 |
+
print(f" 跳过 {tag}:找不到 {f}")
|
| 169 |
+
|
| 170 |
+
per_model_overall: dict[str, dict[str, float | None]] = {}
|
| 171 |
+
per_model_by_font: dict[str, dict[str, dict[str, float | None]]] = {}
|
| 172 |
+
per_model_count: dict[str, dict[str, int]] = {}
|
| 173 |
+
all_tasks: set[str] = set()
|
| 174 |
+
all_fonts: set[str] = set()
|
| 175 |
+
|
| 176 |
+
def _worker(item):
|
| 177 |
+
tag, fpath = item
|
| 178 |
+
ts, tts = parse_judge_file(fpath)
|
| 179 |
+
return tag, calc_avg(ts), tts
|
| 180 |
+
|
| 181 |
+
workers = max(1, min(num_workers, len(tasks))) if tasks else 1
|
| 182 |
+
with ThreadPoolExecutor(max_workers=workers) as ex:
|
| 183 |
+
futs = [ex.submit(_worker, t) for t in tasks]
|
| 184 |
+
for fut in tqdm(as_completed(futs), total=len(futs), desc="parse jsonl"):
|
| 185 |
+
tag, overall, tts = fut.result()
|
| 186 |
+
per_model_overall[tag] = overall
|
| 187 |
+
all_tasks.update(overall.keys())
|
| 188 |
+
font_avg: dict[str, dict[str, float | None]] = {}
|
| 189 |
+
cnt: dict[str, int] = {}
|
| 190 |
+
for ft, tmap in tts.items():
|
| 191 |
+
font_avg[ft] = {tn: (sum(v) / len(v) if v else None) for tn, v in tmap.items()}
|
| 192 |
+
cnt[ft] = max((len(v) for v in tmap.values()), default=0)
|
| 193 |
+
per_model_by_font[tag] = font_avg
|
| 194 |
+
per_model_count[tag] = cnt
|
| 195 |
+
all_fonts.update(tts.keys())
|
| 196 |
+
|
| 197 |
+
sorted_models = sorted(per_model_overall.keys()) # 按字典序展示
|
| 198 |
+
sorted_fonts = [f for f in FONT_TYPE_PRIORITY if f in all_fonts] + sorted(all_fonts - set(FONT_TYPE_PRIORITY))
|
| 199 |
+
|
| 200 |
+
ancient_tasks = get_group_tasks("ancient")
|
| 201 |
+
modern_tasks = get_group_tasks("modern")
|
| 202 |
+
|
| 203 |
+
# ==================== Sheet 1: 评分分析(古代 / 近代汇总) ====================
|
| 204 |
+
rows = []
|
| 205 |
+
for tag in sorted_models:
|
| 206 |
+
font_avg = per_model_by_font.get(tag, {})
|
| 207 |
+
|
| 208 |
+
row: dict[str, object] = {"模型名称": tag}
|
| 209 |
+
|
| 210 |
+
# 古代区块:只取古代字体下的 per-font 均分,再对字体求平均
|
| 211 |
+
anc_scores: dict[str, list[float]] = defaultdict(list)
|
| 212 |
+
for ft in sorted_fonts:
|
| 213 |
+
if ft not in ANCIENT_FONTS:
|
| 214 |
+
continue
|
| 215 |
+
for t, v in font_avg.get(ft, {}).items():
|
| 216 |
+
if t in ancient_tasks and v is not None:
|
| 217 |
+
anc_scores[t].append(v)
|
| 218 |
+
anc_per = {t: (sum(v) / len(v) if v else None) for t, v in anc_scores.items()}
|
| 219 |
+
anc_valid = [anc_per.get(t) for t in ancient_tasks if anc_per.get(t) is not None]
|
| 220 |
+
row["平均分古代_avg"] = fmt(sum(anc_valid) / len(anc_valid) if anc_valid else None)
|
| 221 |
+
for t in ancient_tasks:
|
| 222 |
+
row[f"平均分古代_{t}"] = fmt(anc_per.get(t))
|
| 223 |
+
|
| 224 |
+
# 近代区块:只取近代字体下的 per-font 均分,再对字体求平均
|
| 225 |
+
mod_scores: dict[str, list[float]] = defaultdict(list)
|
| 226 |
+
for ft in sorted_fonts:
|
| 227 |
+
if ft in ANCIENT_FONTS:
|
| 228 |
+
continue
|
| 229 |
+
for t, v in font_avg.get(ft, {}).items():
|
| 230 |
+
if t in modern_tasks and v is not None:
|
| 231 |
+
mod_scores[t].append(v)
|
| 232 |
+
mod_per = {t: (sum(v) / len(v) if v else None) for t, v in mod_scores.items()}
|
| 233 |
+
mod_valid = [mod_per.get(t) for t in modern_tasks if mod_per.get(t) is not None]
|
| 234 |
+
row["平均分近代_avg"] = fmt(sum(mod_valid) / len(mod_valid) if mod_valid else None)
|
| 235 |
+
for t in modern_tasks:
|
| 236 |
+
row[f"平均分近代_{t}"] = fmt(mod_per.get(t))
|
| 237 |
+
|
| 238 |
+
rows.append(row)
|
| 239 |
+
|
| 240 |
+
df = pd.DataFrame(rows)
|
| 241 |
+
header1 = ["模型名称"] + ["平均分_古代"] * (len(ancient_tasks) + 1) + ["平均分_近代"] * (len(modern_tasks) + 1)
|
| 242 |
+
header2 = (
|
| 243 |
+
["模型名称", AVG_HEADER]
|
| 244 |
+
+ [display(t) for t in ancient_tasks]
|
| 245 |
+
+ [AVG_HEADER]
|
| 246 |
+
+ [display(t) for t in modern_tasks]
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
+
column_order = (
|
| 250 |
+
["模型名称", "平均分古代_avg"]
|
| 251 |
+
+ [f"平均分古代_{t}" for t in ancient_tasks]
|
| 252 |
+
+ ["平均分近代_avg"]
|
| 253 |
+
+ [f"平均分近代_{t}" for t in modern_tasks]
|
| 254 |
+
)
|
| 255 |
+
for col in column_order:
|
| 256 |
+
if col not in df.columns:
|
| 257 |
+
df[col] = ""
|
| 258 |
+
df = df[column_order]
|
| 259 |
+
|
| 260 |
+
os.makedirs(os.path.dirname(output_file) or ".", exist_ok=True)
|
| 261 |
+
with pd.ExcelWriter(output_file, engine="openpyxl") as writer:
|
| 262 |
+
df.to_excel(writer, sheet_name="评分分析", index=False, startrow=2, header=False)
|
| 263 |
+
ws = writer.sheets["评分分析"]
|
| 264 |
+
for ci, v in enumerate(header1, start=1):
|
| 265 |
+
ws.cell(row=1, column=ci, value=v)
|
| 266 |
+
for ci, v in enumerate(header2, start=1):
|
| 267 |
+
ws.cell(row=2, column=ci, value=v)
|
| 268 |
+
ws.merge_cells(start_row=1, start_column=1, end_row=2, end_column=1)
|
| 269 |
+
ci = 2
|
| 270 |
+
ws.merge_cells(start_row=1, start_column=ci, end_row=1, end_column=ci + len(ancient_tasks))
|
| 271 |
+
ci += len(ancient_tasks) + 1
|
| 272 |
+
ws.merge_cells(start_row=1, start_column=ci, end_row=1, end_column=ci + len(modern_tasks))
|
| 273 |
+
|
| 274 |
+
head_fill = PatternFill(start_color="CCE5FF", end_color="CCE5FF", fill_type="solid")
|
| 275 |
+
head_font = Font(bold=True)
|
| 276 |
+
center = Alignment(horizontal="center", vertical="center")
|
| 277 |
+
for r in (1, 2):
|
| 278 |
+
for c in range(1, len(header2) + 1):
|
| 279 |
+
cell = ws.cell(row=r, column=c)
|
| 280 |
+
cell.fill = head_fill
|
| 281 |
+
cell.font = head_font
|
| 282 |
+
cell.alignment = center
|
| 283 |
+
ws.column_dimensions["A"].width = 30
|
| 284 |
+
for c in range(2, len(header2) + 1):
|
| 285 |
+
ws.column_dimensions[get_column_letter(c)].width = 12
|
| 286 |
+
|
| 287 |
+
# ==================== Sheet 2: 按字体分析 ====================
|
| 288 |
+
if sorted_fonts:
|
| 289 |
+
# 顶部 Average 区域只展示出现过的、属于古代∪近代任一组、且在 DISPLAY_TASKS 内的任务
|
| 290 |
+
all_visible = filter_display([t for t in all_tasks if t in (set(ANCIENT_TASKS) | set(MODERN_TASKS))])
|
| 291 |
+
|
| 292 |
+
type_rows = []
|
| 293 |
+
for tag in sorted_models:
|
| 294 |
+
font_avg = per_model_by_font.get(tag, {})
|
| 295 |
+
cnt = per_model_count.get(tag, {})
|
| 296 |
+
row: dict[str, object] = {"模型名称": tag}
|
| 297 |
+
|
| 298 |
+
scores_by_task: dict[str, list[float]] = defaultdict(list)
|
| 299 |
+
all_for_avg: list[float] = []
|
| 300 |
+
for ft, tmap in font_avg.items():
|
| 301 |
+
allowed = set(font_allowed_tasks(ft, sorted(all_tasks)))
|
| 302 |
+
for t, v in tmap.items():
|
| 303 |
+
if t.startswith("_") or t not in allowed or v is None:
|
| 304 |
+
continue
|
| 305 |
+
scores_by_task[t].append(v)
|
| 306 |
+
all_for_avg.append(v)
|
| 307 |
+
row["平均分_avg"] = fmt(sum(all_for_avg) / len(all_for_avg) if all_for_avg else None)
|
| 308 |
+
for t in all_visible:
|
| 309 |
+
vs = scores_by_task.get(t, [])
|
| 310 |
+
row[f"平均分_{t}"] = fmt(sum(vs) / len(vs) if vs else None)
|
| 311 |
+
|
| 312 |
+
for ft in sorted_fonts:
|
| 313 |
+
tmap = font_avg.get(ft, {})
|
| 314 |
+
ft_tasks = font_allowed_tasks(ft, sorted(all_tasks))
|
| 315 |
+
allowed_set = set(ft_tasks)
|
| 316 |
+
valid = [v for k, v in tmap.items() if k in allowed_set and v is not None]
|
| 317 |
+
row[f"{ft}_avg"] = fmt(sum(valid) / len(valid) if valid else None)
|
| 318 |
+
for t in ft_tasks:
|
| 319 |
+
v = tmap.get(t)
|
| 320 |
+
row[f"{ft}_{t}"] = fmt(v) if v is not None else ""
|
| 321 |
+
type_rows.append(row)
|
| 322 |
+
|
| 323 |
+
df_t = pd.DataFrame(type_rows)
|
| 324 |
+
type_header1 = ["模型名称"] + ["平均分"] * (len(all_visible) + 1)
|
| 325 |
+
for ft in sorted_fonts:
|
| 326 |
+
type_header1.extend([ft] * (len(font_allowed_tasks(ft, sorted(all_tasks))) + 1))
|
| 327 |
+
type_header2 = ["模型名称", AVG_HEADER] + [display(t) for t in all_visible]
|
| 328 |
+
for ft in sorted_fonts:
|
| 329 |
+
ft_tasks = font_allowed_tasks(ft, sorted(all_tasks))
|
| 330 |
+
type_header2.append(AVG_HEADER)
|
| 331 |
+
type_header2.extend(display(t) for t in ft_tasks)
|
| 332 |
+
|
| 333 |
+
type_columns = ["模型名称", "平均分_avg"] + [f"平均分_{t}" for t in all_visible]
|
| 334 |
+
for ft in sorted_fonts:
|
| 335 |
+
ft_tasks = font_allowed_tasks(ft, sorted(all_tasks))
|
| 336 |
+
type_columns.append(f"{ft}_avg")
|
| 337 |
+
type_columns.extend(f"{ft}_{t}" for t in ft_tasks)
|
| 338 |
+
for col in type_columns:
|
| 339 |
+
if col not in df_t.columns:
|
| 340 |
+
df_t[col] = ""
|
| 341 |
+
df_t = df_t[type_columns]
|
| 342 |
+
|
| 343 |
+
with pd.ExcelWriter(output_file, engine="openpyxl", mode="a", if_sheet_exists="replace") as writer:
|
| 344 |
+
df_t.to_excel(writer, sheet_name="按字体分析", index=False, startrow=2, header=False)
|
| 345 |
+
ws_t = writer.sheets["按字体分析"]
|
| 346 |
+
for ci, v in enumerate(type_header1, start=1):
|
| 347 |
+
ws_t.cell(row=1, column=ci, value=v)
|
| 348 |
+
for ci, v in enumerate(type_header2, start=1):
|
| 349 |
+
ws_t.cell(row=2, column=ci, value=v)
|
| 350 |
+
ws_t.merge_cells(start_row=1, start_column=1, end_row=2, end_column=1)
|
| 351 |
+
ci = 2
|
| 352 |
+
ws_t.merge_cells(start_row=1, start_column=ci, end_row=1, end_column=ci + len(all_visible))
|
| 353 |
+
ci += len(all_visible) + 1
|
| 354 |
+
for ft in sorted_fonts:
|
| 355 |
+
span = len(font_allowed_tasks(ft, sorted(all_tasks))) + 1
|
| 356 |
+
ws_t.merge_cells(start_row=1, start_column=ci, end_row=1, end_column=ci + span - 1)
|
| 357 |
+
ci += span
|
| 358 |
+
head_fill_t = PatternFill(start_color="D5F5E3", end_color="D5F5E3", fill_type="solid")
|
| 359 |
+
for r in (1, 2):
|
| 360 |
+
for c in range(1, len(type_header2) + 1):
|
| 361 |
+
cell = ws_t.cell(row=r, column=c)
|
| 362 |
+
cell.fill = head_fill_t
|
| 363 |
+
cell.font = head_font
|
| 364 |
+
cell.alignment = center
|
| 365 |
+
ws_t.column_dimensions["A"].width = 30
|
| 366 |
+
for c in range(2, len(type_header2) + 1):
|
| 367 |
+
ws_t.column_dimensions[get_column_letter(c)].width = 12
|
| 368 |
+
|
| 369 |
+
print(f"\n✅ 已写入 {output_file}")
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
def main() -> None:
|
| 373 |
+
p = argparse.ArgumentParser(description="ChronoText scoring summary")
|
| 374 |
+
p.add_argument("--input_dir", type=str, default=str(DEFAULT_INPUT_DIR))
|
| 375 |
+
p.add_argument("--output", type=str, default=str(DEFAULT_OUTPUT_FILE))
|
| 376 |
+
p.add_argument("--num_workers", type=int, default=32)
|
| 377 |
+
args = p.parse_args()
|
| 378 |
+
analyze(args.input_dir, args.output, args.num_workers)
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
if __name__ == "__main__":
|
| 382 |
+
main()
|
eval/utils/__init__.py
ADDED
|
File without changes
|
eval/utils/image_utils.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
图像编码:把本地图片读成 OpenAI / Anthropic 等通用网关接受的 data URI。
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
import base64
|
| 8 |
+
import os
|
| 9 |
+
from io import BytesIO
|
| 10 |
+
|
| 11 |
+
from PIL import Image
|
| 12 |
+
|
| 13 |
+
MAX_IMAGE_SIZE = 8 * 1024 * 1024 # 8MB,超过则压缩
|
| 14 |
+
|
| 15 |
+
try:
|
| 16 |
+
import imghdr
|
| 17 |
+
|
| 18 |
+
def _detect_format(image_bytes: bytes) -> str | None:
|
| 19 |
+
return imghdr.what(None, image_bytes)
|
| 20 |
+
except ImportError:
|
| 21 |
+
|
| 22 |
+
def _detect_format(image_bytes: bytes) -> str | None:
|
| 23 |
+
try:
|
| 24 |
+
with Image.open(BytesIO(image_bytes)) as img:
|
| 25 |
+
return (img.format or "").lower() or None
|
| 26 |
+
except Exception:
|
| 27 |
+
return None
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _compress(image_bytes: bytes, max_size: int = MAX_IMAGE_SIZE) -> tuple[bytes, str]:
|
| 31 |
+
with Image.open(BytesIO(image_bytes)) as img:
|
| 32 |
+
if img.mode in ("RGBA", "P"):
|
| 33 |
+
img = img.convert("RGB")
|
| 34 |
+
for quality in (95, 90, 85, 80, 75, 70, 60):
|
| 35 |
+
buf = BytesIO()
|
| 36 |
+
img.save(buf, format="JPEG", quality=quality)
|
| 37 |
+
if buf.tell() <= max_size:
|
| 38 |
+
return buf.getvalue(), "jpeg"
|
| 39 |
+
# 仍超限:缩小分辨率
|
| 40 |
+
scale = 0.95
|
| 41 |
+
while scale > 0.1:
|
| 42 |
+
new_size = (int(img.width * scale), int(img.height * scale))
|
| 43 |
+
resized = img.resize(new_size, Image.LANCZOS)
|
| 44 |
+
buf = BytesIO()
|
| 45 |
+
resized.save(buf, format="JPEG", quality=50)
|
| 46 |
+
if buf.tell() <= max_size:
|
| 47 |
+
return buf.getvalue(), "jpeg"
|
| 48 |
+
scale -= 0.05
|
| 49 |
+
return buf.getvalue(), "jpeg"
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def encode_image(image_path: str) -> str:
|
| 53 |
+
"""把本地图片文件读成 ``data:image/<fmt>;base64,<b64>`` data URI。"""
|
| 54 |
+
if not isinstance(image_path, str) or not image_path:
|
| 55 |
+
raise ValueError(f"invalid image path: {image_path!r}")
|
| 56 |
+
if not os.path.isfile(image_path):
|
| 57 |
+
raise FileNotFoundError(image_path)
|
| 58 |
+
|
| 59 |
+
with open(image_path, "rb") as f:
|
| 60 |
+
image_bytes = f.read()
|
| 61 |
+
|
| 62 |
+
fmt = None
|
| 63 |
+
try:
|
| 64 |
+
with Image.open(BytesIO(image_bytes)) as img:
|
| 65 |
+
fmt = (img.format or "").lower() or None
|
| 66 |
+
except Exception:
|
| 67 |
+
fmt = _detect_format(image_bytes)
|
| 68 |
+
if not fmt:
|
| 69 |
+
raise ValueError(f"无法识别图像格式: {image_path}")
|
| 70 |
+
|
| 71 |
+
if len(image_bytes) > MAX_IMAGE_SIZE:
|
| 72 |
+
image_bytes, fmt = _compress(image_bytes)
|
| 73 |
+
|
| 74 |
+
if fmt == "jpeg":
|
| 75 |
+
fmt = "jpg"
|
| 76 |
+
b64 = base64.b64encode(image_bytes).decode("utf-8")
|
| 77 |
+
return f"data:image/{fmt};base64,{b64}"
|
eval/utils/io.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""线程安全的增量结果写入器 + 历史结果读取。
|
| 2 |
+
|
| 3 |
+
用于 infer / judge 场景:把每条样本以 ``image_path`` 为主键写入同一个 jsonl,
|
| 4 |
+
在并发 worker 提交结果时按 ``save_interval`` 周期性落盘,崩溃也不会丢全量进度。
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import json
|
| 10 |
+
import os
|
| 11 |
+
import traceback
|
| 12 |
+
from threading import Lock
|
| 13 |
+
|
| 14 |
+
from .signal_utils import install_signal_handlers_once
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def get_image_path(row: dict) -> str:
|
| 18 |
+
"""从一条 row 中取规范化后的图片相对路径(开源 jsonl 唯一字段:image_path)。"""
|
| 19 |
+
for k in ("image_path", "img_path", "image"):
|
| 20 |
+
v = row.get(k)
|
| 21 |
+
if v:
|
| 22 |
+
return v
|
| 23 |
+
return ""
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def read_processed(output_file: str, current_tasks: set[str]) -> tuple[dict[str, dict], set[str]]:
|
| 27 |
+
"""读历史落盘结果,返回 (image_path -> row, 需要重跑的 image_path 集合)。
|
| 28 |
+
|
| 29 |
+
缺任意一个 ``current_tasks`` 中的 task 就视为需要补跑。
|
| 30 |
+
"""
|
| 31 |
+
processed: dict[str, dict] = {}
|
| 32 |
+
needs: set[str] = set()
|
| 33 |
+
if not os.path.isfile(output_file):
|
| 34 |
+
return processed, needs
|
| 35 |
+
try:
|
| 36 |
+
with open(output_file, "r", encoding="utf-8") as f:
|
| 37 |
+
for line in f:
|
| 38 |
+
line = line.strip()
|
| 39 |
+
if not line:
|
| 40 |
+
continue
|
| 41 |
+
try:
|
| 42 |
+
item = json.loads(line)
|
| 43 |
+
except json.JSONDecodeError:
|
| 44 |
+
continue
|
| 45 |
+
key = get_image_path(item)
|
| 46 |
+
if not key:
|
| 47 |
+
continue
|
| 48 |
+
infer_results = item.get("infer_results") or item.get("judge_results") or {}
|
| 49 |
+
completed = set(infer_results.keys())
|
| 50 |
+
if not current_tasks.issubset(completed):
|
| 51 |
+
needs.add(key)
|
| 52 |
+
processed[key] = item
|
| 53 |
+
except Exception as e:
|
| 54 |
+
print(f"读取已处理数据时出错: {e}")
|
| 55 |
+
return processed, needs
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class ResultWriter:
|
| 59 |
+
"""周期性落盘 + 全量替换写入;失败回退到 .tmp 文件。"""
|
| 60 |
+
|
| 61 |
+
def __init__(self, output_file: str, processed: dict[str, dict], save_interval: int = 1):
|
| 62 |
+
self.output_file = output_file
|
| 63 |
+
self.processed = processed
|
| 64 |
+
self.lock = Lock()
|
| 65 |
+
self.tmp_file = output_file + ".tmp"
|
| 66 |
+
self.save_interval = save_interval
|
| 67 |
+
self.update_count = 0
|
| 68 |
+
self.last_save_count = 0
|
| 69 |
+
install_signal_handlers_once()
|
| 70 |
+
|
| 71 |
+
def update_and_save(self, result: dict, force_save: bool = False) -> None:
|
| 72 |
+
with self.lock:
|
| 73 |
+
key = get_image_path(result)
|
| 74 |
+
if not key:
|
| 75 |
+
return
|
| 76 |
+
self.processed[key] = result
|
| 77 |
+
self.update_count += 1
|
| 78 |
+
if force_save or (self.update_count - self.last_save_count >= self.save_interval):
|
| 79 |
+
self._save_to_disk()
|
| 80 |
+
self.last_save_count = self.update_count
|
| 81 |
+
|
| 82 |
+
def _save_to_disk(self) -> None:
|
| 83 |
+
try:
|
| 84 |
+
os.makedirs(os.path.dirname(self.output_file) or ".", exist_ok=True)
|
| 85 |
+
with open(self.tmp_file, "w", encoding="utf-8") as f:
|
| 86 |
+
for data in self.processed.values():
|
| 87 |
+
f.write(json.dumps(data, ensure_ascii=False) + "\n")
|
| 88 |
+
if os.path.exists(self.output_file):
|
| 89 |
+
os.remove(self.output_file)
|
| 90 |
+
os.rename(self.tmp_file, self.output_file)
|
| 91 |
+
except Exception as e:
|
| 92 |
+
print(f"保存到磁盘时出错: {e}")
|
| 93 |
+
traceback.print_exc()
|
| 94 |
+
|
| 95 |
+
def finalize(self) -> None:
|
| 96 |
+
with self.lock:
|
| 97 |
+
try:
|
| 98 |
+
self._save_to_disk()
|
| 99 |
+
except Exception as e:
|
| 100 |
+
print(f"保存最终结果时出错: {e}")
|
| 101 |
+
traceback.print_exc()
|
| 102 |
+
finally:
|
| 103 |
+
if os.path.exists(self.tmp_file):
|
| 104 |
+
try:
|
| 105 |
+
os.remove(self.tmp_file)
|
| 106 |
+
except Exception:
|
| 107 |
+
pass
|
eval/utils/signal_utils.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""全局中止信号:第一次 Ctrl+C 设标志位优雅退出,第二次直接强退。"""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
import signal
|
| 7 |
+
import threading
|
| 8 |
+
|
| 9 |
+
ABORT_EVENT = threading.Event()
|
| 10 |
+
_INSTALLED = False
|
| 11 |
+
_SIGINT_COUNT = 0
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _handler(signum, frame):
|
| 15 |
+
global _SIGINT_COUNT
|
| 16 |
+
_SIGINT_COUNT += 1
|
| 17 |
+
ABORT_EVENT.set()
|
| 18 |
+
msg = (
|
| 19 |
+
"\n[中止] 收到 Ctrl+C,正在请求主循环退出并落盘,再次按 Ctrl+C 将强制退出...\n"
|
| 20 |
+
if _SIGINT_COUNT == 1
|
| 21 |
+
else "\n[中止] 再次收到 Ctrl+C,立即强制退出(可能丢失最近未落盘数据)。\n"
|
| 22 |
+
)
|
| 23 |
+
try:
|
| 24 |
+
os.write(2, msg.encode("utf-8", errors="replace"))
|
| 25 |
+
except Exception:
|
| 26 |
+
pass
|
| 27 |
+
if _SIGINT_COUNT >= 2:
|
| 28 |
+
os._exit(130)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def install_signal_handlers_once() -> None:
|
| 32 |
+
global _INSTALLED
|
| 33 |
+
if _INSTALLED:
|
| 34 |
+
return
|
| 35 |
+
try:
|
| 36 |
+
signal.signal(signal.SIGINT, _handler)
|
| 37 |
+
signal.signal(signal.SIGTERM, _handler)
|
| 38 |
+
except Exception:
|
| 39 |
+
pass
|
| 40 |
+
_INSTALLED = True
|
eval/utils/unk.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""UNK 占位符的统一定义与处理。
|
| 2 |
+
|
| 3 |
+
数据集与模型预测里 "无法辨识的字符" 有多种写法,全部归一化到 ``[UNK]``:
|
| 4 |
+
1. token 形态:``[UNK]`` / ``<UNK>`` / 裸 ``UNK``(不区分大小写)
|
| 5 |
+
2. 方块占位 :``□ ■ ▢ ◻ ◼``
|
| 6 |
+
|
| 7 |
+
注意:全角/半角问号属于标点,不在本模块的处理范围内(由打分时的标点剥离统一处理)。
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import re
|
| 13 |
+
|
| 14 |
+
UNK_CANONICAL = "[UNK]"
|
| 15 |
+
|
| 16 |
+
UNK_BLOCK_CHARS: frozenset[str] = frozenset(
|
| 17 |
+
{
|
| 18 |
+
"\u25a1", # □
|
| 19 |
+
"\u25a0", # ■
|
| 20 |
+
"\u25a2", # ▢
|
| 21 |
+
"\u25fb", # ◻
|
| 22 |
+
"\u25fc", # ◼
|
| 23 |
+
}
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
UNK_TOKEN_FORMS: frozenset[str] = frozenset({"[unk]", "<unk>", "unk"})
|
| 27 |
+
|
| 28 |
+
# 1-NED 等场景"剔除"用:[UNK] / <UNK> / 方块整体替换为空
|
| 29 |
+
_UNK_STRIP_PATTERN = re.compile(
|
| 30 |
+
r"\[UNK\]|<UNK>|[" + "".join(UNK_BLOCK_CHARS) + r"]",
|
| 31 |
+
flags=re.IGNORECASE,
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def is_unk_char(ch: str | None) -> bool:
|
| 36 |
+
"""单 char 字段是否表示 UNK。
|
| 37 |
+
|
| 38 |
+
覆盖:空字符串、[UNK]/<UNK>/裸 UNK(不区分大小写、忽略首尾空白)、
|
| 39 |
+
以及 □ ■ ▢ ◻ ◼ 等方块占位(无论是单独一个还是包在空白里)。
|
| 40 |
+
"""
|
| 41 |
+
if not ch:
|
| 42 |
+
return True
|
| 43 |
+
s = ch.strip()
|
| 44 |
+
if not s:
|
| 45 |
+
return True
|
| 46 |
+
if s.lower() in UNK_TOKEN_FORMS:
|
| 47 |
+
return True
|
| 48 |
+
if all(c in UNK_BLOCK_CHARS for c in s):
|
| 49 |
+
return True
|
| 50 |
+
return False
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def remove_unk(text: str) -> str:
|
| 54 |
+
"""剔除文本中所有 UNK 占位(用于 1-NED 等需要"忽略 UNK"的指标)。"""
|
| 55 |
+
if not text:
|
| 56 |
+
return ""
|
| 57 |
+
return _UNK_STRIP_PATTERN.sub("", text)
|