Datasets:
Commit ·
efa0e35
0
Parent(s):
Release LongLongTextBench
Browse filesFiles changed (15)
- .gitattributesAdded+4
- .gitignoreAdded+11
- CODE_LICENSEAdded+201
- LICENSE.mdAdded+11
- README.mdAdded+138
- README_zh.mdAdded+103
- evaluation/README.mdAdded+47
- evaluation/bench.pyAdded+291
- evaluation/local_inference.pyAdded+39
- evaluation/metrics.pyAdded+95
- evaluation/requirements.txtAdded+7
- evaluation/vendor/X-Omni-LICENSEAdded+201
- evaluation/vendor/textbench/evaluate_text_reward.pyAdded+141
- text_prompts.jsonlAdded
- text_prompts_zh.jsonlAdded
1234*.jsonl text eol=lf*.json text eol=lf*.md text eol=lf*.py text eol=lf1234567891011__pycache__/*.py[cod].venv/.cache/.pytest_cache/images/score/jobs.jsonl*.sqlite3*.env*.log123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.1234567891011# License scope
## Literary texts
The passages in `text_prompts.jsonl` and `text_prompts_zh.jsonl` follow the terms of their respective works, translations, and editions. Titles and author names accompany each prompt.
The dataset draws from 40 Project Gutenberg records, 20 chinese-poetry records, and 20 Chinese Wikisource records.
## Evaluation software
LLTB generation and evaluation tools are provided under [Apache License 2.0](CODE_LICENSE). Bundled X-Omni code retains its [Apache License 2.0](evaluation/vendor/X-Omni-LICENSE).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138---language:- en- zhtask_categories:- text-to-imagesize_categories:- n<1Klicense: otherlicense_name: mixed-source-literary-textslicense_link: LICENSE.mdpretty_name: LongLongTextBench (LLTB)tags:- benchmark- text-rendering- long-text- ocrconfigs:- config_name: default default: true data_files: - split: test path: - text_prompts.jsonl - text_prompts_zh.jsonl- config_name: en data_files: - split: test path: text_prompts.jsonl- config_name: zh data_files: - split: test path: text_prompts_zh.jsonl---
# LongLongTextBench (LLTB)
**English** | [简体中文](README_zh.md)
LLTB is a benchmark from the [MOSS-Image](https://github.com/OpenMOSS/MOSS-Image) project for rendering long English and Chinese passages in generated images. It contains **240 prompts**: 120 English and 120 Chinese, each asking for a page with a title, author, and literary excerpt.
We follow the evaluation setup of [X-Omni's LongText-Bench](https://huggingface.co/datasets/X-Omni/LongText-Bench): generate four images per prompt and measure text coverage with OCR.
## Dataset
| Language | Length group | Prompts | Target text length | Unit ||---|---|---:|---:|---|| English | short | 40 | 69–93 | words || English | medium | 40 | 191–246 | words || English | long | 40 | 470–570 | words || Chinese | short | 40 | 330–393 | characters || Chinese | medium | 40 | 923–1,078 | characters || Chinese | long | 40 | 1,284–1,601 | characters |
Lengths count the normalized title, author, and passage used for scoring. Each language/length group contains 20 `classical` and 20 `modern` excerpts. The 240 prompts come from 80 excerpts, each presented at three lengths.
## Load
```bashpip install datasets```
```pythonfrom datasets import load_dataset
ds = load_dataset("OpenMOSS-Team/LongLongTextBench", "default", split="test")prompt = ds[0]["prompt"]ground_truth = ds[0]["gt_text"]```
The `default`, `en`, and `zh` configurations contain 240, 120, and 120 rows in their `test` splits.
| Field | Meaning ||---|---|| `prompt_id`, `sample_id` | Numeric and descriptive task identifiers || `language` | `en` or `zh` || `style` | `classical` or `modern` || `length` | `short`, `medium`, or `long` || `prompt` | Full generation input, including instructions and line breaks || `gt_text` | Target title, author, and passage for scoring || `text` | A one-element list containing `gt_text` || `text_length`, `text_length_unit` | Normalized target length and unit (`word` or `character`) || `title`, `author` | Title and author attribution |
## Generate
With Python 3.10+ and Pillow, run from the repository root:
```bashpython evaluation/bench.py export --output jobs.jsonl --n-samples 4 --seed 42python evaluation/local_inference.py --adapter my_adapter:generate \ --jobs jobs.jsonl --images images```
Export produces 960 jobs with the full prompt, image dimensions, seed, and output filename. Provide `generate(*, prompt, seed, width, height)` in `my_adapter.py`, returning a PIL image. Generation uses 1024×1024 canvases; outputs are saved as `images/<prompt_id>/samples/<sample_index>.png`, with both IDs padded to five digits.
## Evaluate
Use a CUDA-compatible PyTorch/torchvision environment and a local [Qwen2.5-VL-7B-Instruct](https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct) checkpoint:
```bashpython -m pip install -r evaluation/requirements.txtpython evaluation/bench.py check --images images --n-samples 4python evaluation/bench.py score \ --images images --output score \ --ocr-model /path/to/Qwen2.5-VL-7B-Instruct \ --workers 1 --n-samples 4```
OCR processes RGB images resized to 1024×1024 with LANCZOS and uses a maximum of 4,096 output tokens. Coverage matches normalized target and OCR text as multisets: English uses words and Chinese uses characters. Repeated units count up to their frequency in the target text.
```textmatched = sum_u min(count_target(u), count_ocr(u))group coverage = sum_image(matched) / sum_image(target_units)Mean-6 = mean(EN-short, EN-medium, EN-long, ZH-short, ZH-medium, ZH-long)```
The main result is `score/summary.json` → `macro_overall_mean6`, the mean of the six language/length group scores. Scores range from 0 to 1. Per-image OCR and scores are saved in `score/en/results.jsonl` and `score/zh/results.jsonl`. See [evaluation usage](evaluation/README.md) for additional options.
## Citation
If you use LLTB, please cite the [MOSS-Image technical report](https://arxiv.org/abs/2610.23374):
```bibtex@misc{ai2026mossimagetechnicalreport, title={MOSS-Image Technical Report}, author={MOSI. AI}, year={2026}, eprint={2610.23374}, archivePrefix={arXiv}, primaryClass={cs.CV}, url={https://arxiv.org/abs/2610.23374},}```
## License
Evaluation tools use [Apache-2.0](CODE_LICENSE), including the bundled [X-Omni license](evaluation/vendor/X-Omni-LICENSE). Text attribution and license scope are described in [LICENSE.md](LICENSE.md).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103# LongLongTextBench (LLTB)
[English](README.md) | **简体中文**
LLTB 是 [MOSS-Image](https://github.com/OpenMOSS/MOSS-Image) 项目用于评估生成图像中中英文长文本渲染能力的基准,包含 **240 条提示词**,英文和中文各 120 条。每条提示词要求生成包含标题、作者和文学节选的页面。
我们遵循 [X-Omni 的 LongText-Bench](https://huggingface.co/datasets/X-Omni/LongText-Bench) 评测设置:每条提示词生成四张图像,通过 OCR 计算文本覆盖率。
## 数据集
| 语言 | 长度组 | 提示词数量 | 目标文本长度 | 单位 ||---|---|---:|---:|---|| 英文 | short | 40 | 69–93 | 单词 || 英文 | medium | 40 | 191–246 | 单词 || 英文 | long | 40 | 470–570 | 单词 || 中文 | short | 40 | 330–393 | 字符 || 中文 | medium | 40 | 923–1,078 | 字符 || 中文 | long | 40 | 1,284–1,601 | 字符 |
上表长度按计分归一化后的标题、作者和正文统计。每个语言与长度组合包含 20 条 `classical` 和 20 条 `modern` 节选。240 条提示词来自 80 段节选,每段对应三个长度版本。
## 加载数据
```bashpip install datasets```
```pythonfrom datasets import load_dataset
ds = load_dataset("OpenMOSS-Team/LongLongTextBench", "default", split="test")prompt = ds[0]["prompt"]ground_truth = ds[0]["gt_text"]```
`default`、`en` 和 `zh` 配置的 `test` 划分分别包含 240、120 和 120 条数据。
| 字段 | 含义 ||---|---|| `prompt_id`, `sample_id` | 数值与描述性任务标识 || `language` | `en` 或 `zh` || `style` | `classical` 或 `modern` || `length` | `short`、`medium` 或 `long` || `prompt` | 完整生成输入,包含指令与换行 || `gt_text` | 用于计分的目标标题、作者和正文 || `text` | 包含 `gt_text` 的单元素列表 || `text_length`, `text_length_unit` | 归一化后的目标长度及单位(`word` 或 `character`) || `title`, `author` | 标题和作者署名 |
## 生成图像
使用 Python 3.10+ 和 Pillow,在仓库根目录运行:
```bashpython evaluation/bench.py export --output jobs.jsonl --n-samples 4 --seed 42python evaluation/local_inference.py --adapter my_adapter:generate \ --jobs jobs.jsonl --images images```
导出结果包含 960 个任务,每个任务提供完整提示词、图像尺寸、种子和输出文件名。在 `my_adapter.py` 中提供 `generate(*, prompt, seed, width, height)`,返回一张 PIL 图像。生成画布为 1024×1024,图像保存为 `images/<prompt_id>/samples/<sample_index>.png`,两个编号均补零至五位。
## 评测
使用兼容 CUDA 的 PyTorch/torchvision 环境,以及本地 [Qwen2.5-VL-7B-Instruct](https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct) 模型:
```bashpython -m pip install -r evaluation/requirements.txtpython evaluation/bench.py check --images images --n-samples 4python evaluation/bench.py score \ --images images --output score \ --ocr-model /path/to/Qwen2.5-VL-7B-Instruct \ --workers 1 --n-samples 4```
OCR 使用经 LANCZOS 缩放至 1024×1024 的 RGB 图像,输出上限为 4,096 tokens。覆盖率将归一化后的目标文本与 OCR 文本按多重集匹配:英文按单词计数,中文按字符计数,重复单位最多计入其在目标文本中出现的次数。
```textmatched = sum_u min(count_target(u), count_ocr(u))group coverage = sum_image(matched) / sum_image(target_units)Mean-6 = mean(EN-short, EN-medium, EN-long, ZH-short, ZH-medium, ZH-long)```
主要结果为 `score/summary.json` 中的 `macro_overall_mean6`,即六个语言与长度组分数的平均值。分数范围为 0 到 1。逐图像 OCR 和分数保存在 `score/en/results.jsonl` 与 `score/zh/results.jsonl`。其他选项见[评测用法](evaluation/README.md)。
## 引用
使用 LLTB 时,请引用 [MOSS-Image 技术报告](https://arxiv.org/abs/2610.23374):
```bibtex@misc{ai2026mossimagetechnicalreport, title={MOSS-Image Technical Report}, author={MOSI. AI}, year={2026}, eprint={2610.23374}, archivePrefix={arXiv}, primaryClass={cs.CV}, url={https://arxiv.org/abs/2610.23374},}```
## 许可证
评测工具采用 [Apache-2.0](CODE_LICENSE),并保留所附 [X-Omni 许可证](evaluation/vendor/X-Omni-LICENSE)。文本署名及许可范围见 [LICENSE.md](LICENSE.md)。1234567891011121314151617181920212223242526272829303132333435363738394041424344454647# Evaluation
The CLI reads `text_prompts.jsonl` and `text_prompts_zh.jsonl` from the repository root. Use Python 3.10+ and Pillow, and run the commands below from that directory.
## Generate images
```bashpython evaluation/bench.py export --output jobs.jsonl --n-samples 4 --seed 42python evaluation/local_inference.py --adapter my_adapter:generate \ --jobs jobs.jsonl --images imagespython evaluation/bench.py check --images images --n-samples 4```
Provide `generate(*, prompt, seed, width, height)` in `my_adapter.py`, returning a PIL image. The 960 exported jobs use 1024×1024 canvases and seeds computed as `base_seed + prompt_id * n_samples + sample_index`. Outputs follow `images/<prompt_id>/samples/<sample_index>.png`, with both IDs padded to five digits.
The adapter supports `--num-shards N --shard-index I`. For another dataset directory containing the two prompt files, pass `--data-dir` to `bench.py`.
## OCR and coverage
Install a CUDA-compatible PyTorch/torchvision pair and the evaluation dependencies:
```bashpython -m pip install -r evaluation/requirements.txtpython evaluation/bench.py score --images images --n-samples 4 \ --output scores --ocr-model /path/to/Qwen2.5-VL-7B-Instruct --workers 1```
`--ocr-model` points to a local Qwen2.5-VL-7B-Instruct checkpoint, including its tokenizer and processor. `--workers` sets the number of OCR GPU workers. Images are processed as 1024×1024 RGB inputs using LANCZOS resizing; OCR generates up to 4,096 tokens.
The main score is `scores/summary.json` → `macro_overall_mean6`, the equal mean of the six language/length group coverage scores. Each group uses total matched units divided by total target units. English units are words; Chinese units are characters. Matching retains repeated-unit counts. The target includes the title, author, and passage.
The X-Omni normalization removes punctuation, lowercases English, and removes Chinese whitespace while retaining Latin-letter case in Chinese text. Images with empty OCR text receive zero matched units. Results are stored in `scores/en/results.jsonl` and `scores/zh/results.jsonl`.
For one image per prompt, use `--n-samples 1` for export, image checks, and scoring.
## Reuse OCR results
```bashpython evaluation/bench.py summarize --results scores \ --output rescored --n-samples 4```
This recomputes coverage from saved OCR text and dataset targets. Use the same sample count and language selection as the original run.
## Attribution
The OCR and coverage evaluation follows [X-Omni](https://github.com/X-Omni-Team/X-Omni). The bundled evaluation code retains its [Apache-2.0 license](vendor/X-Omni-LICENSE).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291#!/usr/bin/env python3"""Export generation jobs and evaluate LongLongTextBench text coverage."""import argparsefrom datetime import datetime, timezoneimport hashlibimport jsonimport osfrom pathlib import Pathimport shutilimport subprocessimport sys
from metrics import LANGUAGES, strip_instruction, summarize as aggregate
ROOT = Path(__file__).resolve().parentDATA_DIR = ROOT.parent
def data_paths(data_dir=None): directory = Path(data_dir or DATA_DIR) return [directory / name for name in ("text_prompts.jsonl", "text_prompts_zh.jsonl")]
def data_hashes(data_dir=None): return {path.name: hashlib.sha256(path.read_bytes()).hexdigest() for path in data_paths(data_dir)}
def read_jsonl(path): with Path(path).open(encoding="utf-8") as handle: return [json.loads(line) for line in handle if line.strip()]
def write_json(path, value): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
def write_jsonl(path, rows): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) path.write_text("".join(json.dumps(row, ensure_ascii=False) + "\n" for row in rows), encoding="utf-8")
def select_metadata(language="both", limit=0, data_dir=None): rows = [{**row, "language": row["language"].upper(), "render_text": row["prompt"], "target_text": row["gt_text"]} for path in data_paths(data_dir) for row in read_jsonl(path)] selected = [] for lang in LANGUAGES if language == "both" else (language.upper(),): group = [row for row in rows if row["language"] == lang] selected.extend(group[:limit] if limit else group) return selected
def export(args): jobs = [] for item in select_metadata(args.language, args.limit, args.data_dir): for sample in range(args.n_samples): pid = int(item["prompt_id"]) jobs.append({"prompt_id": pid, "sample_id": item["sample_id"], "sample_index": sample, "language": item["language"], "style": item["style"], "length": item["length"], "prompt": item["render_text"], "width": 1024, "height": 1024, "seed": args.seed + pid * args.n_samples + sample, "output_relpath": f"{pid:05d}/samples/{sample:05d}.png"}) write_jsonl(args.output, jobs) print(json.dumps({"jobs": len(jobs), "output": str(Path(args.output).resolve())}))
def inspect_images(metadata, image_root, *, n_samples, image_manifest=None, data_dir=None): from PIL import Image image_root = Path(image_root).resolve() mapping = {} if image_manifest: valid_ids = {int(row["prompt_id"]) for row in select_metadata(data_dir=data_dir)} for row in read_jsonl(image_manifest): key = int(row["prompt_id"]), int(row["sample_index"]) if key in mapping: raise ValueError(f"duplicate image mapping: {key}") if key[0] not in valid_ids or not 0 <= key[1] < n_samples: raise ValueError(f"Invalid image mapping: {key}") path = Path(row["image_path"]) mapping[key] = path if path.is_absolute() else image_root / path report = {"expected_images": len(metadata) * n_samples, "found_images": 0, "missing": [], "invalid": [], "non_1024_images": 0, "sizes": {}} images = [] for item in metadata: pid = int(item["prompt_id"]) for sample in range(n_samples): path = (mapping.get((pid, sample)) if image_manifest else image_root / f"{pid:05d}/samples/{sample:05d}.png") if path is None or not path.is_file(): report["missing"].append({"prompt_id": pid, "sample_index": sample}) continue try: with Image.open(path) as image: image.load() size = image.size report["non_1024_images"] += size != (1024, 1024) name = f"{size[0]}x{size[1]}" report["sizes"][name] = report["sizes"].get(name, 0) + 1 images.append((item, sample, path)) except (OSError, ValueError) as exc: report["invalid"].append({"path": str(path), "error": str(exc)}) report["found_images"] = len(images) return images, report
def checked_images(args): metadata = select_metadata(args.language, args.limit, args.data_dir) images, report = inspect_images(metadata, args.images, n_samples=args.n_samples, image_manifest=args.image_manifest, data_dir=args.data_dir) if report["invalid"] or (report["missing"] and not args.allow_missing): raise ValueError("Image preflight failed: " + json.dumps(report, ensure_ascii=False)) if not images: raise ValueError("No valid images found") return metadata, images, report
def check(args): _, report = inspect_images(select_metadata(args.language, args.limit, args.data_dir), args.images, n_samples=args.n_samples, image_manifest=args.image_manifest, data_dir=args.data_dir) if args.output: write_json(args.output, report) print(json.dumps(report, ensure_ascii=False, indent=2)) if report["invalid"] or (report["missing"] and not args.allow_missing) or not report["found_images"]: raise ValueError("Image preflight failed; see the report above")
def save_scores(output, results, metadata, args): summary, rows = aggregate(results, metadata, n_samples=args.n_samples, allow_missing=args.allow_missing) for language in LANGUAGES: if not any(item["language"] == language for item in metadata): continue directory = output / language.lower() directory.mkdir(parents=True, exist_ok=True) write_jsonl(directory / "results.jsonl", [row for row in rows if row["language"] == language]) coverage = summary[language.lower()]["coverage"] (directory / "scores.txt").write_text( f"Text Score: {coverage:.4f}\n" if coverage is not None else "Text Score: unavailable\n") write_json(output / "summary.json", summary) print(json.dumps(summary, ensure_ascii=False, indent=2)) return summary
def fresh_output(path): output = Path(path).resolve() if output.exists() and (not output.is_dir() or any(output.iterdir())): raise ValueError(f"Output must be a new or empty directory: {output}") output.mkdir(parents=True, exist_ok=True) return output
def score(args): from PIL import Image model = Path(args.ocr_model).resolve() if not (model / "config.json").is_file(): raise ValueError(f"--ocr-model must point to a local HF checkpoint with config.json: {model}") metadata, images, report = checked_images(args) output = fresh_output(args.output) env = os.environ.copy() env.update({"LONGTEXT_QWEN_MODEL_PATH": str(model), "LONGTEXT_MAX_NEW_TOKENS": "4096", "HF_HUB_OFFLINE": "1", "TRANSFORMERS_OFFLINE": "1", "TOKENIZERS_PARALLELISM": "false"}) write_json(output / "run_config.json", { "created_utc": datetime.now(timezone.utc).isoformat(), "data_sha256": data_hashes(args.data_dir), "ocr_model": str(model), "ocr_max_new_tokens": 4096, "requested_workers": args.workers, "n_samples": args.n_samples, "language": args.language, "limit_per_language": args.limit, "allow_missing": args.allow_missing, "image_root": str(Path(args.images).resolve()), "image_manifest": str(Path(args.image_manifest).resolve()) if args.image_manifest else None, "image_preflight": report, "ocr_input_size": [1024, 1024], "resize": "LANCZOS"}) results = [] image_records = [] for language in LANGUAGES: selected = [image for image in images if image[0]["language"] == language] if not selected: continue directory = output / language.lower() samples = directory / "samples" samples.mkdir(parents=True) for item, sample, source in selected: target = samples / f"{int(item['prompt_id'])}_{sample + 1}.png" with Image.open(source) as image: size = image.size if size == (1024, 1024) and source.suffix.lower() == ".png": shutil.copyfile(source, target) else: image.convert("RGB").resize((1024, 1024), Image.Resampling.LANCZOS).save(target) image_records.append({"prompt_id": int(item["prompt_id"]), "sample_index": sample, "source": str(source.resolve()), "source_size": list(size), "ocr_image": str(target.relative_to(output))}) prompt_file = directory / "prompt_file.jsonl" write_jsonl(prompt_file, [{"prompt_id": int(item["prompt_id"]), "prompt": "A paper writes:", "target_text": strip_instruction(item["target_text"]), "text": strip_instruction(item["target_text"]).splitlines()} for item in metadata if item["language"] == language]) workers = min(args.workers, len(selected)) command = [sys.executable, "-m", "torch.distributed.run", "--standalone", f"--nproc_per_node={workers}", str(ROOT / "vendor/textbench/evaluate_text_reward.py"), "--sample_dir", str(samples), "--output_dir", str(directory), "--mode", language.lower(), "--prompt_file", str(prompt_file)] print(f"OCR {language}: {len(selected)} images, {workers} workers", flush=True) subprocess.run(command, cwd=str(ROOT), env=env, check=True) language_results = [] for rank in range(workers): language_results.extend(read_jsonl(directory / f"results_chunk{rank}.jsonl")) expected_keys = {(int(item["prompt_id"]), sample) for item, sample, _ in selected} from metrics import result_key actual_keys = [result_key(row) for row in language_results] if set(actual_keys) != expected_keys or len(actual_keys) != len(expected_keys): raise ValueError(f"OCR results do not cover the staged {language} images exactly") results.extend(language_results) write_jsonl(output / "image_manifest.jsonl", image_records) save_scores(output, results, metadata, args)
def summarize(args): result_dir = Path(args.results).resolve() metadata = select_metadata(args.language, args.limit, args.data_dir) rows = [] for language in LANGUAGES if args.language == "both" else (args.language.upper(),): file = result_dir / language.lower() / "results.jsonl" if file.is_file(): rows.extend(read_jsonl(file)) if not rows: raise ValueError("No en/results.jsonl or zh/results.jsonl found") output = fresh_output(args.output) save_scores(output, rows, metadata, args) write_json(output / "run_config.json", {"mode": "reuse_ocr", "source": str(result_dir), "data_sha256": data_hashes(args.data_dir), "n_samples": args.n_samples, "language": args.language, "limit_per_language": args.limit, "allow_missing": args.allow_missing})
def positive(value): number = int(value) if number < 1: raise argparse.ArgumentTypeError("must be >= 1") return number
def nonnegative(value): number = int(value) if number < 0: raise argparse.ArgumentTypeError("must be >= 0") return number
def parser(): cli = argparse.ArgumentParser(description=__doc__) cli.add_argument("--data-dir", type=Path, default=DATA_DIR, help="directory containing text_prompts.jsonl and text_prompts_zh.jsonl (default: repository root)") commands = cli.add_subparsers(dest="command", required=True) for name, handler in (("export", export), ("check", check), ("score", score), ("summarize", summarize)): cmd = commands.add_parser(name) cmd.add_argument("--data-dir", type=Path, default=argparse.SUPPRESS) cmd.set_defaults(handler=handler) cmd.add_argument("--language", choices=("both", "en", "zh"), default="both") cmd.add_argument("--limit", type=nonnegative, default=0, help="first N prompts per language; 0 = all") cmd.add_argument("--n-samples", type=positive, default=4) cmd.add_argument("--output", required=name != "check") if name == "export": cmd.add_argument("--seed", type=int, default=42) else: cmd.add_argument("--allow-missing", action="store_true") if name in ("check", "score"): cmd.add_argument("--images", required=True) cmd.add_argument("--image-manifest", help="JSONL: prompt_id, sample_index (0-based), image_path") if name == "score": cmd.add_argument("--ocr-model", required=True, help="local Qwen2.5-VL-7B-Instruct HF directory") cmd.add_argument("--workers", type=positive, default=1) if name == "summarize": cmd.add_argument("--results", required=True, help="directory containing en/zh/results.jsonl") return cli
def main(): args = parser().parse_args() try: args.handler(args) except (ValueError, OSError, ImportError, subprocess.CalledProcessError) as exc: print(f"ERROR: {exc}", file=sys.stderr) return 1 return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839#!/usr/bin/env python3"""Adapt an existing inference function returning PIL.Image to the exported jobs."""import argparseimport importlibimport jsonfrom pathlib import Pathimport sys
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--adapter", required=True, help="importable module:function returning PIL.Image") parser.add_argument("--jobs", required=True) parser.add_argument("--images", required=True) parser.add_argument("--num-shards", type=int, default=1) parser.add_argument("--shard-index", type=int, default=0) args = parser.parse_args() if args.num_shards < 1 or not 0 <= args.shard_index < args.num_shards: parser.error("require 0 <= shard-index < num-shards") module, name = args.adapter.split(":", 1) generate = getattr(importlib.import_module(module), name) root = Path(args.images).resolve() jobs = [json.loads(line) for line in Path(args.jobs).read_text(encoding="utf-8").splitlines() if line.strip()] for index, job in enumerate(jobs): if index % args.num_shards != args.shard_index: continue target = (root / job["output_relpath"]).resolve() if not target.is_relative_to(root): raise ValueError(f"Output path escapes image root: {target}") target.parent.mkdir(parents=True, exist_ok=True) image = generate(prompt=job["prompt"], seed=job["seed"], width=job["width"], height=job["height"]) image.save(target, format="PNG") print(f"[{index + 1}/{len(jobs)}] {target}", flush=True)
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495"""Text normalization and coverage aggregation following X-Omni."""from collections import Counterfrom pathlib import Pathimport re
LANGUAGES = ("EN", "ZH")LENGTHS = ("short", "medium", "long")ALLOWED = r"\u4e00-\u9fa5a-zA-Z0-9àâäéèêëîïôöùûüçÀÂÄÉÈÊËÎÏÔÖÙÛÜÇ"
def strip_instruction(text): lines = str(text).splitlines() if lines and lines[0].strip() == "A paper writes:": return "\n".join(lines[1:]).lstrip("\n") return str(text)
def normalize(text, language): if language == "EN": cleaned = re.sub(f"[^{ALLOWED}\\s]", "", str(text)) return re.sub(r"\s+", " ", cleaned).strip().lower() if language == "ZH": return "".join(re.findall(f"[{ALLOWED}]", str(text))).strip() raise ValueError(f"Unknown language: {language}")
def measure(target, recognized, language): gt = normalize(target, language) ocr = normalize(recognized, language) gt_units = gt.split() if language == "EN" else gt ocr_units = ocr.split() if language == "EN" else ocr if not gt_units: raise ValueError("Ground truth contains no scoring units") matched = sum((Counter(gt_units) & Counter(ocr_units)).values()) return {"ocr_gt": gt, "ocr_results": ocr, "match_word_count": matched, "gt_word_count": len(gt_units), "text_accuray": matched / len(gt_units)}
def result_key(row): if "prompt_id" in row and "sample_index" in row: return int(row["prompt_id"]), int(row["sample_index"]) match = re.fullmatch(r"(\d+)_(\d+)", Path(row["image"]).stem) if not match: raise ValueError(f"Cannot identify OCR image: {row['image']}") return int(match[1]), int(match[2]) - 1
def summarize(results, metadata, *, n_samples=4, allow_missing=False): by_id = {int(item["prompt_id"]): item for item in metadata} expected = {(pid, sample) for pid in by_id for sample in range(n_samples)} rows, seen = [], set() for original in results: key = result_key(original) if key in seen: raise ValueError(f"duplicate OCR result: {key}") if key not in expected: raise ValueError(f"Unexpected OCR result: {key}") seen.add(key) item = by_id[key[0]] rows.append({**original, "prompt_id": key[0], "sample_index": key[1], "sample_id": item.get("sample_id"), "language": item["language"], "length": item["length"], "style": item.get("style"), **measure(strip_instruction(item["target_text"]), original["ocr_results"], item["language"])}) missing = sorted(expected - seen) if missing and not allow_missing: raise ValueError(f"missing OCR results: {len(missing)}; first: {missing[:5]}")
def stats(selected, prompts): matched = sum(row["match_word_count"] for row in selected) gt = sum(row["gt_word_count"] for row in selected) return {"coverage": matched / gt if gt else None, "images": len(selected), "expected_images": prompts * n_samples, "matched_units": matched, "gt_units": gt}
summary = {"protocol": "longlongtext-official-v1", "n_samples": n_samples, "prompts": len(metadata), "images": len(rows), "expected_images": len(expected), "complete": not missing, "missing": [{"prompt_id": pid, "sample_index": sample} for pid, sample in missing]} coverages = [] for language in LANGUAGES: selected = [row for row in rows if row["language"] == language] prompts = [item for item in metadata if item["language"] == language] groups = {length: stats([row for row in selected if row["length"] == length], sum(item["length"] == length for item in prompts)) for length in LENGTHS} values = [groups[length]["coverage"] for length in LENGTHS] summary[language.lower()] = {**stats(selected, len(prompts)), "by_length": groups, "mean3": sum(values) / 3 if all(v is not None for v in values) else None} coverages.extend(values) summary["macro_overall_mean6"] = (sum(coverages) / 6 if all(v is not None for v in coverages) else None) summary["total_coverage"] = stats(rows, len(metadata))["coverage"] summary["benchmark_scope"] = "full" if len(metadata) == 240 else "subset" return summary, rows1234567# Pinned OCR dependencies.# Install a CUDA-compatible torch + torchvision pair FIRST; see README.md.transformers==4.56.2accelerate==1.4.0qwen-vl-utils==0.0.14Pillow==11.2.1tqdm==4.67.1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141import osimport globimport jsonimport argparseimport warningswarnings.filterwarnings("ignore")
import torchimport torch.distributed as dist
from tqdm import tqdmfrom datetime import timedelta
from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessorfrom qwen_vl_utils import process_vision_info
def clean_and_remove_hallucinations(text): # keywords_list can be added to process ocr results to a cleaner version keywords_list = ["addCriterion", "No text recognized."] for keyword in keywords_list: s = text.replace(keyword, "").replace(f"\n{keyword}", "").replace(f"{keyword}\n", "")
return s
class ImageEvaluator: def __init__(self, device): self.device = device
model_id = os.environ.get("LONGTEXT_QWEN_MODEL_PATH", "Qwen/Qwen2.5-VL-7B-Instruct") self.qwen_model = Qwen2_5_VLForConditionalGeneration.from_pretrained( model_id, torch_dtype=torch.bfloat16, device_map=device, ) self.qwen_processor = AutoProcessor.from_pretrained(model_id) self.qwen_prompt = ( "Recognize the text in the image, only reply with the text content, " "but avoid repeating previously mentioned content. " "If no text is recognized, please reply with 'No text recognized'." )
def qwen_ocr(self, image): message = [{"role": "user", "content": [{"type": "image", "image": image}, {"type": "text", "text": self.qwen_prompt}],}] texts = self.qwen_processor.apply_chat_template(message, tokenize=False, add_generation_prompt=True) image_inputs, _ = process_vision_info(message) inputs = self.qwen_processor( text=texts, images=image_inputs, padding=True, return_tensors="pt", ).to(self.device) max_new_tokens = int(os.environ.get("LONGTEXT_MAX_NEW_TOKENS", "1024")) generated_ids = self.qwen_model.generate(**inputs, max_new_tokens=max_new_tokens) generated_ids_trimmed = [out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)] outputs = self.qwen_processor.batch_decode( generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False, ) qwen_results = clean_and_remove_hallucinations(outputs[0]) return qwen_results
def evaluate(self, data_chunk): assert len(data_chunk) >= 1, f'At least one document is required.' eval_results = [] with torch.no_grad(): for data in tqdm(data_chunk): ocr_results = self.qwen_ocr(data['image']) final_result = {'image': data['image'], 'prompt': data['prompt'], 'ocr_gt': data['text'], 'ocr_results': ocr_results} eval_results.append(final_result)
return eval_results
def split_list(x, n): k, m = divmod(len(x), n) return [x[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] for i in range(n)]
def main(args): # Setup PyTorch: torch.set_grad_enabled(False) dist.init_process_group("nccl", timeout=timedelta(hours=1)) rank = dist.get_rank() device = rank % torch.cuda.device_count() world_size = dist.get_world_size() seed = args.global_seed * world_size + rank torch.manual_seed(seed)
os.makedirs(args.output_dir, exist_ok=True)
prompt_file = args.prompt_file or ('text_prompts.jsonl' if args.mode == 'en' else 'text_prompts_zh.jsonl') prompts = [json.loads(line) for line in open(prompt_file)] prompt_map = {} for prompt in prompts: # LLTB metadata uses target_text instead of the upstream # LongText-Bench text list. if "text" not in prompt and "target_text" in prompt: prompt = dict(prompt) prompt["text"] = str(prompt["target_text"]).splitlines() prompt_map[prompt["prompt_id"]] = prompt
data = [] for image_file in sorted(glob.glob(f'{args.sample_dir}/*.png')): fname = image_file.split('/')[-1] if '_' in fname: prompt_id = int(fname.split('_')[0]) else: prompt_id = int(fname.split('.')[0]) info = prompt_map[prompt_id] data.append({'image': image_file, 'prompt': info['prompt'], 'text': info['text']}) data_chunks = split_list(data, world_size)
evaluator = ImageEvaluator(device) print(f'=============Evaluate {len(data_chunks[rank])} images in rank {rank}=============') results = evaluator.evaluate(data_chunks[rank]) output_path = os.path.join(args.output_dir, f'results_chunk{rank}.jsonl') with open(output_path, 'w', encoding='utf-8') as f: for r in results: f.write(json.dumps(r, ensure_ascii=False) + '\n')
if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--sample_dir", type=str, required=True) parser.add_argument("--output_dir", type=str, required=True) parser.add_argument("--mode", type=str, choices=['en', 'zh'], default='en') parser.add_argument("--prompt_file", type=str, default=None) parser.add_argument("--global_seed", type=str, default=42) args = parser.parse_args() main(args).gitattributesAdded+4
.gitignoreAdded+11
CODE_LICENSEAdded+201
LICENSE.mdAdded+11
README.mdAdded+138
README_zh.mdAdded+103
evaluation/README.mdAdded+47
evaluation/bench.pyAdded+291
evaluation/local_inference.pyAdded+39
evaluation/metrics.pyAdded+95
evaluation/requirements.txtAdded+7
evaluation/vendor/X-Omni-LICENSEAdded+201
evaluation/vendor/textbench/evaluate_text_reward.pyAdded+141
text_prompts.jsonlAdded
text_prompts_zh.jsonlAdded