File size: 14,275 Bytes
188f4d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
"""ChronoText benchmark inference entry point.

Usage:
    # 1) Local OpenAI-compatible service started by ``vllm serve`` / sglang / lmdeploy
    python infer.py --api_type openai_compat \
        --model_name Qwen2.5-VL-7B-Instruct \
        --base_url http://127.0.0.1:8000/v1 \
        --api_key EMPTY

    # 2) In-process vLLM, point ``--model_path`` to a local checkpoint
    python infer.py --api_type local_vllm \
        --model_path /path/to/checkpoint \
        --tensor_parallel_size 4

    # 3) ⚠️ Internal only — distill backend (delete before release)
    python infer.py --api_type distill --api_name doubao-seed-1-8-251228-nonthinking

Outputs:
    Opensource/infer_results/<model_tag>/results.jsonl
"""

from __future__ import annotations

import argparse
import concurrent.futures
import json
import os
import sys
import time
import traceback
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

import tqdm

REPO_ROOT = Path(__file__).resolve().parent
sys.path.insert(0, str(REPO_ROOT.parent))

from Opensource.apis import API_TYPES, get_api  # noqa: E402
from Opensource.prompts import (  # noqa: E402
    EXTRACT_FUNCS,
    PROMPTS,
    TASK_CLASSIFY,
    TASK_EXTRACT,
    TASK_REFERRING,
    TASK_SPOTTING,
)
from Opensource.prompts.referring import DEFAULT_SEED, prepare_referring_sample  # noqa: E402
from Opensource.utils.io import ResultWriter, get_image_path, read_processed  # noqa: E402
from Opensource.utils.signal_utils import ABORT_EVENT, install_signal_handlers_once  # noqa: E402

# ============================================================
# 配置
# ============================================================
DEFAULT_DATA_FILE = REPO_ROOT / "data" / "Chronicles_OCR.jsonl"
DEFAULT_OUTPUT_DIR = REPO_ROOT / "infer_results"

# 古代三种字体额外执行 spotting / referring;近代字体只跑 classify / extract
ANCIENT_FONTS = {"甲骨文", "金文", "篆书"}
ALL_TASKS = [TASK_CLASSIFY, TASK_EXTRACT, TASK_SPOTTING, TASK_REFERRING]


def parse_args() -> argparse.Namespace:
    p = argparse.ArgumentParser(description="ChronoText inference entry point")

    # API 选择
    p.add_argument(
        "--api_type",
        choices=API_TYPES,
        required=True,
        help="local_vllm: 进程内 vllm.LLM; openai_compat: 标准 OpenAI 协议; distill: 内部专用",
    )

    # OpenAI compat 参数
    p.add_argument("--model_name", type=str, default=None, help="openai_compat 调用时使用的 model 字段")
    p.add_argument("--base_url", type=str, default=None, help="openai_compat 服务地址,例如 http://127.0.0.1:8000/v1")
    p.add_argument("--api_key", type=str, default="EMPTY")

    # local_vllm 参数
    p.add_argument("--model_path", type=str, default=None, help="local_vllm: 本地模型权重路径")
    p.add_argument("--tensor_parallel_size", type=int, default=1)
    p.add_argument("--max_model_len", type=int, default=None)
    p.add_argument("--gpu_memory_utilization", type=float, default=0.9)

    # distill(内部)
    p.add_argument("--api_name", type=str, default=None, help="distill: 内部 API 名称")

    # 数据 / 输出
    p.add_argument(
        "--data_file", type=str, default=str(DEFAULT_DATA_FILE), help=f"benchmark jsonl 路径,默认 {DEFAULT_DATA_FILE}"
    )
    p.add_argument("--output_dir", type=str, default=str(DEFAULT_OUTPUT_DIR))
    p.add_argument(
        "--output_tag", type=str, default=None, help="结果子目录名,默认从 model_name / model_path / api_name 推断"
    )

    # 推理参数
    p.add_argument("--max_workers", type=int, default=64)
    p.add_argument("--max_try", type=int, default=3)
    p.add_argument("--max_rows", type=int, default=-1)
    p.add_argument("--save_interval", type=int, default=1)
    p.add_argument("--seed", type=int, default=DEFAULT_SEED, help="单字识别红框采样的随机种子")
    p.add_argument("--debug", action="store_true")

    return p.parse_args()


def build_api(args: argparse.Namespace):
    if args.api_type == "openai_compat":
        if not args.model_name or not args.base_url:
            raise SystemExit("--api_type openai_compat 需要同时提供 --model_name 与 --base_url")
        return get_api(
            "openai_compat",
            model_name=args.model_name,
            base_url=args.base_url,
            api_key=args.api_key,
            max_try=args.max_try,
        )
    if args.api_type == "local_vllm":
        if not args.model_path:
            raise SystemExit("--api_type local_vllm 需要提供 --model_path")
        return get_api(
            "local_vllm",
            model_path=args.model_path,
            tensor_parallel_size=args.tensor_parallel_size,
            max_model_len=args.max_model_len,
            gpu_memory_utilization=args.gpu_memory_utilization,
            max_try=args.max_try,
        )
    # distill
    if not args.api_name:
        raise SystemExit("--api_type distill 需要提供 --api_name")
    return get_api("distill", api_name=args.api_name, max_try=args.max_try)


def derive_output_tag(args: argparse.Namespace) -> str:
    if args.output_tag:
        return args.output_tag
    if args.api_type == "openai_compat" and args.model_name:
        return args.model_name
    if args.api_type == "local_vllm" and args.model_path:
        return Path(args.model_path).name
    if args.api_type == "distill" and args.api_name:
        return args.api_name
    return "default"


def resolve_image_path(row: dict, data_file_dir: Path) -> str:
    """开源 jsonl 里 ``image_path`` 是相对 data 目录的相对路径,需要拼成绝对路径。"""
    rel = get_image_path(row)
    if not rel:
        return ""
    if os.path.isabs(rel):
        return rel
    return str(data_file_dir / rel)


def tasks_for_row(row: dict) -> list[str]:
    """按 font_type 决定该样本应跑的任务列表(古代 4 / 近代 2)。"""
    if str(row.get("font_type", "")).strip() in ANCIENT_FONTS:
        return ALL_TASKS
    return [TASK_CLASSIFY, TASK_EXTRACT]


def process_one_row(
    api_instance,
    row: dict,
    abs_img_path: str,
    existing: dict,
    max_retries: int,
    referring_cache_dir: str,
    seed: int,
) -> dict | None:
    """对单条样本跑所有未完成的任务。返回新 row(包含合并后的 infer_results)。"""
    if not abs_img_path or not os.path.exists(abs_img_path):
        print(f"警告:图片不存在 {abs_img_path}")
        return None

    file_tasks = tasks_for_row(row)
    pending = [t for t in file_tasks if t not in existing]
    if not pending:
        return None

    infer_results = dict(existing)

    for task_name in pending:
        prompt_text = PROMPTS[task_name]
        task_img = abs_img_path
        referring_meta: dict | None = None

        # 单字识别:先采样 + 画红框,再用渲染图调用模型
        if task_name == TASK_REFERRING:
            sample = prepare_referring_sample(row, abs_img_path, seed=seed, out_dir=referring_cache_dir)
            if sample is None:
                infer_results[task_name] = {
                    "thinking": "",
                    "answer": "",
                    "error": "no_referring_target",
                    "skipped": True,
                }
                continue
            task_img = sample["rendered_img_path"]
            referring_meta = {
                "gt_char": sample["target_char"],
                "target_bbox_xyxy": sample["target_bbox_xyxy"],
                "target_index": sample["index"],
                "sample_key": sample["sample_key"],
                "seed": seed,
                "rendered_img_path": sample["rendered_img_path"],
            }

        last_error = None
        for attempt in range(1, max_retries + 1):
            if task_name == TASK_REFERRING and not os.path.exists(task_img):
                # 渲染图被外部清理掉则就地重画
                redrawn = prepare_referring_sample(row, abs_img_path, seed=seed, out_dir=referring_cache_dir)
                if redrawn is not None:
                    task_img = redrawn["rendered_img_path"]
            try:
                ok, thinking, answer = api_instance(task_img, prompt_text)
                if not ok or answer is None:
                    raise RuntimeError("API 调用失败或返回空结果")

                extract_fn = EXTRACT_FUNCS.get(task_name)
                extract_ok, extracted = (False, None)
                if extract_fn is not None:
                    try:
                        extract_ok, extracted = extract_fn(answer)
                    except Exception as e:
                        print(f"  任务 '{task_name}' 提取异常: {e}")
                        extract_ok = False

                if extract_fn is not None and not extract_ok and attempt < max_retries:
                    print(f"  任务 '{task_name}' 提取失败,重试 {attempt}/{max_retries}")
                    time.sleep(2)
                    continue

                rec = {"thinking": thinking or "", "answer": answer}
                if extract_ok:
                    rec["extract"] = extracted
                if referring_meta is not None:
                    rec.update(
                        {
                            k: referring_meta[k]
                            for k in ("gt_char", "target_bbox_xyxy", "target_index", "sample_key", "seed")
                        }
                    )
                infer_results[task_name] = rec
                break
            except Exception as e:
                last_error = str(e)
                if attempt < max_retries:
                    print(f"  任务 '{task_name}' 失败 ({attempt}/{max_retries}): {last_error}")
                    time.sleep(2)
                else:
                    rec = {"thinking": "", "answer": "", "error": last_error}
                    if referring_meta is not None:
                        rec.update(
                            {
                                k: referring_meta[k]
                                for k in ("gt_char", "target_bbox_xyxy", "target_index", "sample_key", "seed")
                            }
                        )
                    infer_results[task_name] = rec

    result = dict(row)
    result["infer_results"] = infer_results
    result["image_path"] = get_image_path(row)  # 保持相对路径作为主键
    return result


def main() -> None:
    args = parse_args()

    data_file = Path(args.data_file).resolve()
    if not data_file.is_file():
        raise SystemExit(f"benchmark 文件不存在: {data_file}")
    data_dir = data_file.parent

    output_tag = derive_output_tag(args)
    output_dir = Path(args.output_dir).resolve() / output_tag
    output_dir.mkdir(parents=True, exist_ok=True)
    output_file = output_dir / "results.jsonl"
    referring_cache_dir = str(output_dir / ".referring_cache")

    print("=" * 72)
    print("ChronoText Inference")
    print("=" * 72)
    print(f"api_type     : {args.api_type}")
    print(f"output_tag   : {output_tag}")
    print(f"data_file    : {data_file}")
    print(f"output_file  : {output_file}")
    print(f"max_workers  : {args.max_workers}")
    print(f"max_rows     : {args.max_rows if args.max_rows > 0 else 'all'}")
    print(f"seed         : {args.seed}")

    # 读 jsonl
    rows: list[dict] = []
    with open(data_file, "r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            rows.append(json.loads(line))
    if args.max_rows > 0:
        rows = rows[: args.max_rows]
    if args.debug:
        rows = rows[: min(5, len(rows))]
    print(f"loaded {len(rows)} rows")

    # API
    print("\n初始化 API...")
    api_instance = build_api(args)
    print("API 就绪")

    # 历史结果(增量)
    all_task_set = set(ALL_TASKS)
    processed, _needs = read_processed(str(output_file), all_task_set)
    print(f"历史结果: 已写入 {len(processed)} 条")

    # 待处理列表
    pending: list[tuple[dict, str, dict]] = []
    fully_done = 0
    for row in rows:
        rel = get_image_path(row)
        if not rel:
            continue
        abs_img = resolve_image_path(row, data_dir)
        existing_infer = processed.get(rel, {}).get("infer_results", {})
        file_tasks = set(tasks_for_row(row))
        if file_tasks.issubset(set(existing_infer.keys())):
            fully_done += 1
            continue
        pending.append((row, abs_img, existing_infer))

    print(f"完全完成: {fully_done}, 待处理: {len(pending)}\n")
    if not pending:
        print("没有需要处理的数据")
        return

    install_signal_handlers_once()
    writer = ResultWriter(str(output_file), processed, save_interval=args.save_interval)

    executor = ThreadPoolExecutor(max_workers=args.max_workers)
    aborted = False
    try:
        futures = {
            executor.submit(
                process_one_row,
                api_instance,
                row,
                abs_img,
                existing,
                args.max_try,
                referring_cache_dir,
                args.seed,
            ): row
            for row, abs_img, existing in pending
        }
        pbar = tqdm.tqdm(total=len(futures), desc="inference")
        for fut in concurrent.futures.as_completed(futures):
            if ABORT_EVENT.is_set():
                aborted = True
                break
            try:
                result = fut.result()
                if result:
                    writer.update_and_save(result)
            except Exception as e:
                print(f"\n处理失败: {e}")
                traceback.print_exc()
            pbar.update(1)
        pbar.close()
        if aborted:
            for f in futures:
                if not f.done():
                    f.cancel()
    finally:
        if ABORT_EVENT.is_set():
            executor.shutdown(wait=False, cancel_futures=True)
        else:
            executor.shutdown(wait=True)

    print("\n落盘最终结果...")
    writer.finalize()
    print(f"✅ 推理完成: {output_file}")
    if ABORT_EVENT.is_set():
        sys.exit(130)


if __name__ == "__main__":
    main()