Phospheneser commited on
Commit
efa0e35
·
0 Parent(s):

Release LongLongTextBench

Browse files
.gitattributes ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ *.jsonl text eol=lf
2
+ *.json text eol=lf
3
+ *.md text eol=lf
4
+ *.py text eol=lf
.gitignore ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ .cache/
5
+ .pytest_cache/
6
+ images/
7
+ score/
8
+ jobs.jsonl
9
+ *.sqlite3*
10
+ .env
11
+ *.log
CODE_LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
LICENSE.md ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # License scope
2
+
3
+ ## Literary texts
4
+
5
+ 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.
6
+
7
+ The dataset draws from 40 Project Gutenberg records, 20 chinese-poetry records, and 20 Chinese Wikisource records.
8
+
9
+ ## Evaluation software
10
+
11
+ 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).
README.md ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - en
4
+ - zh
5
+ task_categories:
6
+ - text-to-image
7
+ size_categories:
8
+ - n<1K
9
+ license: other
10
+ license_name: mixed-source-literary-texts
11
+ license_link: LICENSE.md
12
+ pretty_name: LongLongTextBench (LLTB)
13
+ tags:
14
+ - benchmark
15
+ - text-rendering
16
+ - long-text
17
+ - ocr
18
+ configs:
19
+ - config_name: default
20
+ default: true
21
+ data_files:
22
+ - split: test
23
+ path:
24
+ - text_prompts.jsonl
25
+ - text_prompts_zh.jsonl
26
+ - config_name: en
27
+ data_files:
28
+ - split: test
29
+ path: text_prompts.jsonl
30
+ - config_name: zh
31
+ data_files:
32
+ - split: test
33
+ path: text_prompts_zh.jsonl
34
+ ---
35
+
36
+ # LongLongTextBench (LLTB)
37
+
38
+ **English** | [简体中文](README_zh.md)
39
+
40
+ 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.
41
+
42
+ 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.
43
+
44
+ ## Dataset
45
+
46
+ | Language | Length group | Prompts | Target text length | Unit |
47
+ |---|---|---:|---:|---|
48
+ | English | short | 40 | 69–93 | words |
49
+ | English | medium | 40 | 191–246 | words |
50
+ | English | long | 40 | 470–570 | words |
51
+ | Chinese | short | 40 | 330–393 | characters |
52
+ | Chinese | medium | 40 | 923–1,078 | characters |
53
+ | Chinese | long | 40 | 1,284–1,601 | characters |
54
+
55
+ 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.
56
+
57
+ ## Load
58
+
59
+ ```bash
60
+ pip install datasets
61
+ ```
62
+
63
+ ```python
64
+ from datasets import load_dataset
65
+
66
+ ds = load_dataset("OpenMOSS-Team/LongLongTextBench", "default", split="test")
67
+ prompt = ds[0]["prompt"]
68
+ ground_truth = ds[0]["gt_text"]
69
+ ```
70
+
71
+ The `default`, `en`, and `zh` configurations contain 240, 120, and 120 rows in their `test` splits.
72
+
73
+ | Field | Meaning |
74
+ |---|---|
75
+ | `prompt_id`, `sample_id` | Numeric and descriptive task identifiers |
76
+ | `language` | `en` or `zh` |
77
+ | `style` | `classical` or `modern` |
78
+ | `length` | `short`, `medium`, or `long` |
79
+ | `prompt` | Full generation input, including instructions and line breaks |
80
+ | `gt_text` | Target title, author, and passage for scoring |
81
+ | `text` | A one-element list containing `gt_text` |
82
+ | `text_length`, `text_length_unit` | Normalized target length and unit (`word` or `character`) |
83
+ | `title`, `author` | Title and author attribution |
84
+
85
+ ## Generate
86
+
87
+ With Python 3.10+ and Pillow, run from the repository root:
88
+
89
+ ```bash
90
+ python evaluation/bench.py export --output jobs.jsonl --n-samples 4 --seed 42
91
+ python evaluation/local_inference.py --adapter my_adapter:generate \
92
+ --jobs jobs.jsonl --images images
93
+ ```
94
+
95
+ 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.
96
+
97
+ ## Evaluate
98
+
99
+ 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:
100
+
101
+ ```bash
102
+ python -m pip install -r evaluation/requirements.txt
103
+ python evaluation/bench.py check --images images --n-samples 4
104
+ python evaluation/bench.py score \
105
+ --images images --output score \
106
+ --ocr-model /path/to/Qwen2.5-VL-7B-Instruct \
107
+ --workers 1 --n-samples 4
108
+ ```
109
+
110
+ 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.
111
+
112
+ ```text
113
+ matched = sum_u min(count_target(u), count_ocr(u))
114
+ group coverage = sum_image(matched) / sum_image(target_units)
115
+ Mean-6 = mean(EN-short, EN-medium, EN-long, ZH-short, ZH-medium, ZH-long)
116
+ ```
117
+
118
+ 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.
119
+
120
+ ## Citation
121
+
122
+ If you use LLTB, please cite the [MOSS-Image technical report](https://arxiv.org/abs/2610.23374):
123
+
124
+ ```bibtex
125
+ @misc{ai2026mossimagetechnicalreport,
126
+ title={MOSS-Image Technical Report},
127
+ author={MOSI. AI},
128
+ year={2026},
129
+ eprint={2610.23374},
130
+ archivePrefix={arXiv},
131
+ primaryClass={cs.CV},
132
+ url={https://arxiv.org/abs/2610.23374},
133
+ }
134
+ ```
135
+
136
+ ## License
137
+
138
+ 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).
README_zh.md ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LongLongTextBench (LLTB)
2
+
3
+ [English](README.md) | **简体中文**
4
+
5
+ LLTB 是 [MOSS-Image](https://github.com/OpenMOSS/MOSS-Image) 项目用于评估生成图像中中英文长文本渲染能力的基准,包含 **240 条提示词**,英文和中文各 120 条。每条提示词要求生成包含标题、作者和文学节选的页面。
6
+
7
+ 我们遵循 [X-Omni 的 LongText-Bench](https://huggingface.co/datasets/X-Omni/LongText-Bench) 评测设置:每条提示词生成四张图像,通过 OCR 计算文本覆盖率。
8
+
9
+ ## 数据集
10
+
11
+ | 语言 | 长度组 | 提示词数量 | 目标文本长度 | 单位 |
12
+ |---|---|---:|---:|---|
13
+ | 英文 | short | 40 | 69–93 | 单词 |
14
+ | 英文 | medium | 40 | 191–246 | 单词 |
15
+ | 英文 | long | 40 | 470–570 | 单词 |
16
+ | 中文 | short | 40 | 330–393 | 字符 |
17
+ | 中文 | medium | 40 | 923–1,078 | 字符 |
18
+ | 中文 | long | 40 | 1,284–1,601 | 字符 |
19
+
20
+ 上表长度按计分归一化后的标题、作者和正文统计。每个语言与长度组合包含 20 条 `classical` 和 20 条 `modern` 节选。240 条提示词来自 80 段节选,每段对应三个长度版本。
21
+
22
+ ## 加载数据
23
+
24
+ ```bash
25
+ pip install datasets
26
+ ```
27
+
28
+ ```python
29
+ from datasets import load_dataset
30
+
31
+ ds = load_dataset("OpenMOSS-Team/LongLongTextBench", "default", split="test")
32
+ prompt = ds[0]["prompt"]
33
+ ground_truth = ds[0]["gt_text"]
34
+ ```
35
+
36
+ `default`、`en` 和 `zh` 配置的 `test` 划分分别包含 240、120 和 120 条数据。
37
+
38
+ | 字段 | 含义 |
39
+ |---|---|
40
+ | `prompt_id`, `sample_id` | 数值与描述性任务标识 |
41
+ | `language` | `en` 或 `zh` |
42
+ | `style` | `classical` 或 `modern` |
43
+ | `length` | `short`、`medium` 或 `long` |
44
+ | `prompt` | 完整生成输入,包含指令与换行 |
45
+ | `gt_text` | 用于计分的目标标题、作者和正文 |
46
+ | `text` | 包含 `gt_text` 的单元素列表 |
47
+ | `text_length`, `text_length_unit` | 归一化后的目标长度及单位(`word` 或 `character`) |
48
+ | `title`, `author` | 标题和作者署名 |
49
+
50
+ ## 生成图像
51
+
52
+ 使用 Python 3.10+ 和 Pillow,在仓库根目录运行:
53
+
54
+ ```bash
55
+ python evaluation/bench.py export --output jobs.jsonl --n-samples 4 --seed 42
56
+ python evaluation/local_inference.py --adapter my_adapter:generate \
57
+ --jobs jobs.jsonl --images images
58
+ ```
59
+
60
+ 导出结果包含 960 个任务,每个任务提供完整提示词、图像尺寸、种子和输出文件名。在 `my_adapter.py` 中提供 `generate(*, prompt, seed, width, height)`,返回一张 PIL 图像。生成画布为 1024×1024,图像保存为 `images/<prompt_id>/samples/<sample_index>.png`,两个编号均补零至五位。
61
+
62
+ ## 评测
63
+
64
+ 使用兼容 CUDA 的 PyTorch/torchvision 环境,以及本地 [Qwen2.5-VL-7B-Instruct](https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct) 模型:
65
+
66
+ ```bash
67
+ python -m pip install -r evaluation/requirements.txt
68
+ python evaluation/bench.py check --images images --n-samples 4
69
+ python evaluation/bench.py score \
70
+ --images images --output score \
71
+ --ocr-model /path/to/Qwen2.5-VL-7B-Instruct \
72
+ --workers 1 --n-samples 4
73
+ ```
74
+
75
+ OCR 使用经 LANCZOS 缩放至 1024×1024 的 RGB 图像,输出上限为 4,096 tokens。覆盖率将归一化后的目标文本与 OCR 文本按多重集匹配:英文按单词计数,中文按字符计数,重复单位最多计入其在目标文本中出现的次数。
76
+
77
+ ```text
78
+ matched = sum_u min(count_target(u), count_ocr(u))
79
+ group coverage = sum_image(matched) / sum_image(target_units)
80
+ Mean-6 = mean(EN-short, EN-medium, EN-long, ZH-short, ZH-medium, ZH-long)
81
+ ```
82
+
83
+ 主要结果为 `score/summary.json` 中的 `macro_overall_mean6`,即六个语言与长度组分数的平均值。分数范围为 0 到 1。逐图像 OCR 和分数保存在 `score/en/results.jsonl` 与 `score/zh/results.jsonl`。其他选项见[评测用法](evaluation/README.md)。
84
+
85
+ ## 引用
86
+
87
+ 使用 LLTB 时,请引用 [MOSS-Image 技术报告](https://arxiv.org/abs/2610.23374):
88
+
89
+ ```bibtex
90
+ @misc{ai2026mossimagetechnicalreport,
91
+ title={MOSS-Image Technical Report},
92
+ author={MOSI. AI},
93
+ year={2026},
94
+ eprint={2610.23374},
95
+ archivePrefix={arXiv},
96
+ primaryClass={cs.CV},
97
+ url={https://arxiv.org/abs/2610.23374},
98
+ }
99
+ ```
100
+
101
+ ## 许可证
102
+
103
+ 评测工具采用 [Apache-2.0](CODE_LICENSE),并保留所附 [X-Omni 许可证](evaluation/vendor/X-Omni-LICENSE)。文本署名及许可范围见 [LICENSE.md](LICENSE.md)。
evaluation/README.md ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Evaluation
2
+
3
+ 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.
4
+
5
+ ## Generate images
6
+
7
+ ```bash
8
+ python evaluation/bench.py export --output jobs.jsonl --n-samples 4 --seed 42
9
+ python evaluation/local_inference.py --adapter my_adapter:generate \
10
+ --jobs jobs.jsonl --images images
11
+ python evaluation/bench.py check --images images --n-samples 4
12
+ ```
13
+
14
+ 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.
15
+
16
+ The adapter supports `--num-shards N --shard-index I`. For another dataset directory containing the two prompt files, pass `--data-dir` to `bench.py`.
17
+
18
+ ## OCR and coverage
19
+
20
+ Install a CUDA-compatible PyTorch/torchvision pair and the evaluation dependencies:
21
+
22
+ ```bash
23
+ python -m pip install -r evaluation/requirements.txt
24
+ python evaluation/bench.py score --images images --n-samples 4 \
25
+ --output scores --ocr-model /path/to/Qwen2.5-VL-7B-Instruct --workers 1
26
+ ```
27
+
28
+ `--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.
29
+
30
+ 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.
31
+
32
+ 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`.
33
+
34
+ For one image per prompt, use `--n-samples 1` for export, image checks, and scoring.
35
+
36
+ ## Reuse OCR results
37
+
38
+ ```bash
39
+ python evaluation/bench.py summarize --results scores \
40
+ --output rescored --n-samples 4
41
+ ```
42
+
43
+ This recomputes coverage from saved OCR text and dataset targets. Use the same sample count and language selection as the original run.
44
+
45
+ ## Attribution
46
+
47
+ 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).
evaluation/bench.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Export generation jobs and evaluate LongLongTextBench text coverage."""
3
+ import argparse
4
+ from datetime import datetime, timezone
5
+ import hashlib
6
+ import json
7
+ import os
8
+ from pathlib import Path
9
+ import shutil
10
+ import subprocess
11
+ import sys
12
+
13
+ from metrics import LANGUAGES, strip_instruction, summarize as aggregate
14
+
15
+ ROOT = Path(__file__).resolve().parent
16
+ DATA_DIR = ROOT.parent
17
+
18
+
19
+ def data_paths(data_dir=None):
20
+ directory = Path(data_dir or DATA_DIR)
21
+ return [directory / name for name in ("text_prompts.jsonl", "text_prompts_zh.jsonl")]
22
+
23
+
24
+ def data_hashes(data_dir=None):
25
+ return {path.name: hashlib.sha256(path.read_bytes()).hexdigest() for path in data_paths(data_dir)}
26
+
27
+
28
+ def read_jsonl(path):
29
+ with Path(path).open(encoding="utf-8") as handle:
30
+ return [json.loads(line) for line in handle if line.strip()]
31
+
32
+
33
+ def write_json(path, value):
34
+ path = Path(path)
35
+ path.parent.mkdir(parents=True, exist_ok=True)
36
+ path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
37
+
38
+
39
+ def write_jsonl(path, rows):
40
+ path = Path(path)
41
+ path.parent.mkdir(parents=True, exist_ok=True)
42
+ path.write_text("".join(json.dumps(row, ensure_ascii=False) + "\n" for row in rows), encoding="utf-8")
43
+
44
+
45
+ def select_metadata(language="both", limit=0, data_dir=None):
46
+ rows = [{**row, "language": row["language"].upper(),
47
+ "render_text": row["prompt"], "target_text": row["gt_text"]}
48
+ for path in data_paths(data_dir) for row in read_jsonl(path)]
49
+ selected = []
50
+ for lang in LANGUAGES if language == "both" else (language.upper(),):
51
+ group = [row for row in rows if row["language"] == lang]
52
+ selected.extend(group[:limit] if limit else group)
53
+ return selected
54
+
55
+
56
+ def export(args):
57
+ jobs = []
58
+ for item in select_metadata(args.language, args.limit, args.data_dir):
59
+ for sample in range(args.n_samples):
60
+ pid = int(item["prompt_id"])
61
+ jobs.append({"prompt_id": pid, "sample_id": item["sample_id"],
62
+ "sample_index": sample, "language": item["language"],
63
+ "style": item["style"], "length": item["length"],
64
+ "prompt": item["render_text"], "width": 1024, "height": 1024,
65
+ "seed": args.seed + pid * args.n_samples + sample,
66
+ "output_relpath": f"{pid:05d}/samples/{sample:05d}.png"})
67
+ write_jsonl(args.output, jobs)
68
+ print(json.dumps({"jobs": len(jobs), "output": str(Path(args.output).resolve())}))
69
+
70
+
71
+ def inspect_images(metadata, image_root, *, n_samples, image_manifest=None, data_dir=None):
72
+ from PIL import Image
73
+ image_root = Path(image_root).resolve()
74
+ mapping = {}
75
+ if image_manifest:
76
+ valid_ids = {int(row["prompt_id"]) for row in select_metadata(data_dir=data_dir)}
77
+ for row in read_jsonl(image_manifest):
78
+ key = int(row["prompt_id"]), int(row["sample_index"])
79
+ if key in mapping:
80
+ raise ValueError(f"duplicate image mapping: {key}")
81
+ if key[0] not in valid_ids or not 0 <= key[1] < n_samples:
82
+ raise ValueError(f"Invalid image mapping: {key}")
83
+ path = Path(row["image_path"])
84
+ mapping[key] = path if path.is_absolute() else image_root / path
85
+ report = {"expected_images": len(metadata) * n_samples, "found_images": 0,
86
+ "missing": [], "invalid": [], "non_1024_images": 0, "sizes": {}}
87
+ images = []
88
+ for item in metadata:
89
+ pid = int(item["prompt_id"])
90
+ for sample in range(n_samples):
91
+ path = (mapping.get((pid, sample)) if image_manifest else
92
+ image_root / f"{pid:05d}/samples/{sample:05d}.png")
93
+ if path is None or not path.is_file():
94
+ report["missing"].append({"prompt_id": pid, "sample_index": sample})
95
+ continue
96
+ try:
97
+ with Image.open(path) as image:
98
+ image.load()
99
+ size = image.size
100
+ report["non_1024_images"] += size != (1024, 1024)
101
+ name = f"{size[0]}x{size[1]}"
102
+ report["sizes"][name] = report["sizes"].get(name, 0) + 1
103
+ images.append((item, sample, path))
104
+ except (OSError, ValueError) as exc:
105
+ report["invalid"].append({"path": str(path), "error": str(exc)})
106
+ report["found_images"] = len(images)
107
+ return images, report
108
+
109
+
110
+ def checked_images(args):
111
+ metadata = select_metadata(args.language, args.limit, args.data_dir)
112
+ images, report = inspect_images(metadata, args.images, n_samples=args.n_samples,
113
+ image_manifest=args.image_manifest, data_dir=args.data_dir)
114
+ if report["invalid"] or (report["missing"] and not args.allow_missing):
115
+ raise ValueError("Image preflight failed: " + json.dumps(report, ensure_ascii=False))
116
+ if not images:
117
+ raise ValueError("No valid images found")
118
+ return metadata, images, report
119
+
120
+
121
+ def check(args):
122
+ _, report = inspect_images(select_metadata(args.language, args.limit, args.data_dir), args.images,
123
+ n_samples=args.n_samples, image_manifest=args.image_manifest, data_dir=args.data_dir)
124
+ if args.output:
125
+ write_json(args.output, report)
126
+ print(json.dumps(report, ensure_ascii=False, indent=2))
127
+ if report["invalid"] or (report["missing"] and not args.allow_missing) or not report["found_images"]:
128
+ raise ValueError("Image preflight failed; see the report above")
129
+
130
+
131
+ def save_scores(output, results, metadata, args):
132
+ summary, rows = aggregate(results, metadata, n_samples=args.n_samples,
133
+ allow_missing=args.allow_missing)
134
+ for language in LANGUAGES:
135
+ if not any(item["language"] == language for item in metadata):
136
+ continue
137
+ directory = output / language.lower()
138
+ directory.mkdir(parents=True, exist_ok=True)
139
+ write_jsonl(directory / "results.jsonl", [row for row in rows if row["language"] == language])
140
+ coverage = summary[language.lower()]["coverage"]
141
+ (directory / "scores.txt").write_text(
142
+ f"Text Score: {coverage:.4f}\n" if coverage is not None else "Text Score: unavailable\n")
143
+ write_json(output / "summary.json", summary)
144
+ print(json.dumps(summary, ensure_ascii=False, indent=2))
145
+ return summary
146
+
147
+
148
+ def fresh_output(path):
149
+ output = Path(path).resolve()
150
+ if output.exists() and (not output.is_dir() or any(output.iterdir())):
151
+ raise ValueError(f"Output must be a new or empty directory: {output}")
152
+ output.mkdir(parents=True, exist_ok=True)
153
+ return output
154
+
155
+
156
+ def score(args):
157
+ from PIL import Image
158
+ model = Path(args.ocr_model).resolve()
159
+ if not (model / "config.json").is_file():
160
+ raise ValueError(f"--ocr-model must point to a local HF checkpoint with config.json: {model}")
161
+ metadata, images, report = checked_images(args)
162
+ output = fresh_output(args.output)
163
+ env = os.environ.copy()
164
+ env.update({"LONGTEXT_QWEN_MODEL_PATH": str(model),
165
+ "LONGTEXT_MAX_NEW_TOKENS": "4096", "HF_HUB_OFFLINE": "1",
166
+ "TRANSFORMERS_OFFLINE": "1", "TOKENIZERS_PARALLELISM": "false"})
167
+ write_json(output / "run_config.json", {
168
+ "created_utc": datetime.now(timezone.utc).isoformat(),
169
+ "data_sha256": data_hashes(args.data_dir),
170
+ "ocr_model": str(model), "ocr_max_new_tokens": 4096, "requested_workers": args.workers,
171
+ "n_samples": args.n_samples, "language": args.language, "limit_per_language": args.limit,
172
+ "allow_missing": args.allow_missing, "image_root": str(Path(args.images).resolve()),
173
+ "image_manifest": str(Path(args.image_manifest).resolve()) if args.image_manifest else None,
174
+ "image_preflight": report, "ocr_input_size": [1024, 1024], "resize": "LANCZOS"})
175
+ results = []
176
+ image_records = []
177
+ for language in LANGUAGES:
178
+ selected = [image for image in images if image[0]["language"] == language]
179
+ if not selected:
180
+ continue
181
+ directory = output / language.lower()
182
+ samples = directory / "samples"
183
+ samples.mkdir(parents=True)
184
+ for item, sample, source in selected:
185
+ target = samples / f"{int(item['prompt_id'])}_{sample + 1}.png"
186
+ with Image.open(source) as image:
187
+ size = image.size
188
+ if size == (1024, 1024) and source.suffix.lower() == ".png":
189
+ shutil.copyfile(source, target)
190
+ else:
191
+ image.convert("RGB").resize((1024, 1024), Image.Resampling.LANCZOS).save(target)
192
+ image_records.append({"prompt_id": int(item["prompt_id"]), "sample_index": sample,
193
+ "source": str(source.resolve()), "source_size": list(size),
194
+ "ocr_image": str(target.relative_to(output))})
195
+ prompt_file = directory / "prompt_file.jsonl"
196
+ write_jsonl(prompt_file, [{"prompt_id": int(item["prompt_id"]), "prompt": "A paper writes:",
197
+ "target_text": strip_instruction(item["target_text"]),
198
+ "text": strip_instruction(item["target_text"]).splitlines()}
199
+ for item in metadata if item["language"] == language])
200
+ workers = min(args.workers, len(selected))
201
+ command = [sys.executable, "-m", "torch.distributed.run", "--standalone",
202
+ f"--nproc_per_node={workers}", str(ROOT / "vendor/textbench/evaluate_text_reward.py"),
203
+ "--sample_dir", str(samples), "--output_dir", str(directory),
204
+ "--mode", language.lower(), "--prompt_file", str(prompt_file)]
205
+ print(f"OCR {language}: {len(selected)} images, {workers} workers", flush=True)
206
+ subprocess.run(command, cwd=str(ROOT), env=env, check=True)
207
+ language_results = []
208
+ for rank in range(workers):
209
+ language_results.extend(read_jsonl(directory / f"results_chunk{rank}.jsonl"))
210
+ expected_keys = {(int(item["prompt_id"]), sample) for item, sample, _ in selected}
211
+ from metrics import result_key
212
+ actual_keys = [result_key(row) for row in language_results]
213
+ if set(actual_keys) != expected_keys or len(actual_keys) != len(expected_keys):
214
+ raise ValueError(f"OCR results do not cover the staged {language} images exactly")
215
+ results.extend(language_results)
216
+ write_jsonl(output / "image_manifest.jsonl", image_records)
217
+ save_scores(output, results, metadata, args)
218
+
219
+
220
+ def summarize(args):
221
+ result_dir = Path(args.results).resolve()
222
+ metadata = select_metadata(args.language, args.limit, args.data_dir)
223
+ rows = []
224
+ for language in LANGUAGES if args.language == "both" else (args.language.upper(),):
225
+ file = result_dir / language.lower() / "results.jsonl"
226
+ if file.is_file():
227
+ rows.extend(read_jsonl(file))
228
+ if not rows:
229
+ raise ValueError("No en/results.jsonl or zh/results.jsonl found")
230
+ output = fresh_output(args.output)
231
+ save_scores(output, rows, metadata, args)
232
+ write_json(output / "run_config.json", {"mode": "reuse_ocr", "source": str(result_dir),
233
+ "data_sha256": data_hashes(args.data_dir),
234
+ "n_samples": args.n_samples, "language": args.language,
235
+ "limit_per_language": args.limit, "allow_missing": args.allow_missing})
236
+
237
+
238
+ def positive(value):
239
+ number = int(value)
240
+ if number < 1:
241
+ raise argparse.ArgumentTypeError("must be >= 1")
242
+ return number
243
+
244
+
245
+ def nonnegative(value):
246
+ number = int(value)
247
+ if number < 0:
248
+ raise argparse.ArgumentTypeError("must be >= 0")
249
+ return number
250
+
251
+
252
+ def parser():
253
+ cli = argparse.ArgumentParser(description=__doc__)
254
+ cli.add_argument("--data-dir", type=Path, default=DATA_DIR,
255
+ help="directory containing text_prompts.jsonl and text_prompts_zh.jsonl (default: repository root)")
256
+ commands = cli.add_subparsers(dest="command", required=True)
257
+ for name, handler in (("export", export), ("check", check), ("score", score), ("summarize", summarize)):
258
+ cmd = commands.add_parser(name)
259
+ cmd.add_argument("--data-dir", type=Path, default=argparse.SUPPRESS)
260
+ cmd.set_defaults(handler=handler)
261
+ cmd.add_argument("--language", choices=("both", "en", "zh"), default="both")
262
+ cmd.add_argument("--limit", type=nonnegative, default=0, help="first N prompts per language; 0 = all")
263
+ cmd.add_argument("--n-samples", type=positive, default=4)
264
+ cmd.add_argument("--output", required=name != "check")
265
+ if name == "export":
266
+ cmd.add_argument("--seed", type=int, default=42)
267
+ else:
268
+ cmd.add_argument("--allow-missing", action="store_true")
269
+ if name in ("check", "score"):
270
+ cmd.add_argument("--images", required=True)
271
+ cmd.add_argument("--image-manifest", help="JSONL: prompt_id, sample_index (0-based), image_path")
272
+ if name == "score":
273
+ cmd.add_argument("--ocr-model", required=True, help="local Qwen2.5-VL-7B-Instruct HF directory")
274
+ cmd.add_argument("--workers", type=positive, default=1)
275
+ if name == "summarize":
276
+ cmd.add_argument("--results", required=True, help="directory containing en/zh/results.jsonl")
277
+ return cli
278
+
279
+
280
+ def main():
281
+ args = parser().parse_args()
282
+ try:
283
+ args.handler(args)
284
+ except (ValueError, OSError, ImportError, subprocess.CalledProcessError) as exc:
285
+ print(f"ERROR: {exc}", file=sys.stderr)
286
+ return 1
287
+ return 0
288
+
289
+
290
+ if __name__ == "__main__":
291
+ raise SystemExit(main())
evaluation/local_inference.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Adapt an existing inference function returning PIL.Image to the exported jobs."""
3
+ import argparse
4
+ import importlib
5
+ import json
6
+ from pathlib import Path
7
+ import sys
8
+
9
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
10
+
11
+
12
+ def main():
13
+ parser = argparse.ArgumentParser(description=__doc__)
14
+ parser.add_argument("--adapter", required=True, help="importable module:function returning PIL.Image")
15
+ parser.add_argument("--jobs", required=True)
16
+ parser.add_argument("--images", required=True)
17
+ parser.add_argument("--num-shards", type=int, default=1)
18
+ parser.add_argument("--shard-index", type=int, default=0)
19
+ args = parser.parse_args()
20
+ if args.num_shards < 1 or not 0 <= args.shard_index < args.num_shards:
21
+ parser.error("require 0 <= shard-index < num-shards")
22
+ module, name = args.adapter.split(":", 1)
23
+ generate = getattr(importlib.import_module(module), name)
24
+ root = Path(args.images).resolve()
25
+ jobs = [json.loads(line) for line in Path(args.jobs).read_text(encoding="utf-8").splitlines() if line.strip()]
26
+ for index, job in enumerate(jobs):
27
+ if index % args.num_shards != args.shard_index:
28
+ continue
29
+ target = (root / job["output_relpath"]).resolve()
30
+ if not target.is_relative_to(root):
31
+ raise ValueError(f"Output path escapes image root: {target}")
32
+ target.parent.mkdir(parents=True, exist_ok=True)
33
+ image = generate(prompt=job["prompt"], seed=job["seed"], width=job["width"], height=job["height"])
34
+ image.save(target, format="PNG")
35
+ print(f"[{index + 1}/{len(jobs)}] {target}", flush=True)
36
+
37
+
38
+ if __name__ == "__main__":
39
+ main()
evaluation/metrics.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Text normalization and coverage aggregation following X-Omni."""
2
+ from collections import Counter
3
+ from pathlib import Path
4
+ import re
5
+
6
+ LANGUAGES = ("EN", "ZH")
7
+ LENGTHS = ("short", "medium", "long")
8
+ ALLOWED = r"\u4e00-\u9fa5a-zA-Z0-9àâäéèêëîïôöùûüçÀÂÄÉÈÊËÎÏÔÖÙÛÜÇ"
9
+
10
+
11
+ def strip_instruction(text):
12
+ lines = str(text).splitlines()
13
+ if lines and lines[0].strip() == "A paper writes:":
14
+ return "\n".join(lines[1:]).lstrip("\n")
15
+ return str(text)
16
+
17
+
18
+ def normalize(text, language):
19
+ if language == "EN":
20
+ cleaned = re.sub(f"[^{ALLOWED}\\s]", "", str(text))
21
+ return re.sub(r"\s+", " ", cleaned).strip().lower()
22
+ if language == "ZH":
23
+ return "".join(re.findall(f"[{ALLOWED}]", str(text))).strip()
24
+ raise ValueError(f"Unknown language: {language}")
25
+
26
+
27
+ def measure(target, recognized, language):
28
+ gt = normalize(target, language)
29
+ ocr = normalize(recognized, language)
30
+ gt_units = gt.split() if language == "EN" else gt
31
+ ocr_units = ocr.split() if language == "EN" else ocr
32
+ if not gt_units:
33
+ raise ValueError("Ground truth contains no scoring units")
34
+ matched = sum((Counter(gt_units) & Counter(ocr_units)).values())
35
+ return {"ocr_gt": gt, "ocr_results": ocr, "match_word_count": matched,
36
+ "gt_word_count": len(gt_units), "text_accuray": matched / len(gt_units)}
37
+
38
+
39
+ def result_key(row):
40
+ if "prompt_id" in row and "sample_index" in row:
41
+ return int(row["prompt_id"]), int(row["sample_index"])
42
+ match = re.fullmatch(r"(\d+)_(\d+)", Path(row["image"]).stem)
43
+ if not match:
44
+ raise ValueError(f"Cannot identify OCR image: {row['image']}")
45
+ return int(match[1]), int(match[2]) - 1
46
+
47
+
48
+ def summarize(results, metadata, *, n_samples=4, allow_missing=False):
49
+ by_id = {int(item["prompt_id"]): item for item in metadata}
50
+ expected = {(pid, sample) for pid in by_id for sample in range(n_samples)}
51
+ rows, seen = [], set()
52
+ for original in results:
53
+ key = result_key(original)
54
+ if key in seen:
55
+ raise ValueError(f"duplicate OCR result: {key}")
56
+ if key not in expected:
57
+ raise ValueError(f"Unexpected OCR result: {key}")
58
+ seen.add(key)
59
+ item = by_id[key[0]]
60
+ rows.append({**original, "prompt_id": key[0], "sample_index": key[1],
61
+ "sample_id": item.get("sample_id"), "language": item["language"],
62
+ "length": item["length"], "style": item.get("style"),
63
+ **measure(strip_instruction(item["target_text"]),
64
+ original["ocr_results"], item["language"])})
65
+ missing = sorted(expected - seen)
66
+ if missing and not allow_missing:
67
+ raise ValueError(f"missing OCR results: {len(missing)}; first: {missing[:5]}")
68
+
69
+ def stats(selected, prompts):
70
+ matched = sum(row["match_word_count"] for row in selected)
71
+ gt = sum(row["gt_word_count"] for row in selected)
72
+ return {"coverage": matched / gt if gt else None, "images": len(selected),
73
+ "expected_images": prompts * n_samples, "matched_units": matched,
74
+ "gt_units": gt}
75
+
76
+ summary = {"protocol": "longlongtext-official-v1", "n_samples": n_samples,
77
+ "prompts": len(metadata), "images": len(rows),
78
+ "expected_images": len(expected), "complete": not missing,
79
+ "missing": [{"prompt_id": pid, "sample_index": sample} for pid, sample in missing]}
80
+ coverages = []
81
+ for language in LANGUAGES:
82
+ selected = [row for row in rows if row["language"] == language]
83
+ prompts = [item for item in metadata if item["language"] == language]
84
+ groups = {length: stats([row for row in selected if row["length"] == length],
85
+ sum(item["length"] == length for item in prompts))
86
+ for length in LENGTHS}
87
+ values = [groups[length]["coverage"] for length in LENGTHS]
88
+ summary[language.lower()] = {**stats(selected, len(prompts)), "by_length": groups,
89
+ "mean3": sum(values) / 3 if all(v is not None for v in values) else None}
90
+ coverages.extend(values)
91
+ summary["macro_overall_mean6"] = (sum(coverages) / 6
92
+ if all(v is not None for v in coverages) else None)
93
+ summary["total_coverage"] = stats(rows, len(metadata))["coverage"]
94
+ summary["benchmark_scope"] = "full" if len(metadata) == 240 else "subset"
95
+ return summary, rows
evaluation/requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Pinned OCR dependencies.
2
+ # Install a CUDA-compatible torch + torchvision pair FIRST; see README.md.
3
+ transformers==4.56.2
4
+ accelerate==1.4.0
5
+ qwen-vl-utils==0.0.14
6
+ Pillow==11.2.1
7
+ tqdm==4.67.1
evaluation/vendor/X-Omni-LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
evaluation/vendor/textbench/evaluate_text_reward.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import glob
3
+ import json
4
+ import argparse
5
+ import warnings
6
+ warnings.filterwarnings("ignore")
7
+
8
+ import torch
9
+ import torch.distributed as dist
10
+
11
+ from tqdm import tqdm
12
+ from datetime import timedelta
13
+
14
+ from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor
15
+ from qwen_vl_utils import process_vision_info
16
+
17
+
18
+ def clean_and_remove_hallucinations(text):
19
+ # keywords_list can be added to process ocr results to a cleaner version
20
+ keywords_list = ["addCriterion", "No text recognized."]
21
+ for keyword in keywords_list:
22
+ s = text.replace(keyword, "").replace(f"\n{keyword}", "").replace(f"{keyword}\n", "")
23
+
24
+ return s
25
+
26
+
27
+ class ImageEvaluator:
28
+ def __init__(self, device):
29
+ self.device = device
30
+
31
+ model_id = os.environ.get("LONGTEXT_QWEN_MODEL_PATH", "Qwen/Qwen2.5-VL-7B-Instruct")
32
+ self.qwen_model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
33
+ model_id,
34
+ torch_dtype=torch.bfloat16,
35
+ device_map=device,
36
+ )
37
+ self.qwen_processor = AutoProcessor.from_pretrained(model_id)
38
+ self.qwen_prompt = (
39
+ "Recognize the text in the image, only reply with the text content, "
40
+ "but avoid repeating previously mentioned content. "
41
+ "If no text is recognized, please reply with 'No text recognized'."
42
+ )
43
+
44
+ def qwen_ocr(self, image):
45
+ message = [{"role": "user",
46
+ "content": [{"type": "image", "image": image},
47
+ {"type": "text", "text": self.qwen_prompt}],}]
48
+ texts = self.qwen_processor.apply_chat_template(message, tokenize=False, add_generation_prompt=True)
49
+ image_inputs, _ = process_vision_info(message)
50
+ inputs = self.qwen_processor(
51
+ text=texts,
52
+ images=image_inputs,
53
+ padding=True,
54
+ return_tensors="pt",
55
+ ).to(self.device)
56
+ max_new_tokens = int(os.environ.get("LONGTEXT_MAX_NEW_TOKENS", "1024"))
57
+ generated_ids = self.qwen_model.generate(**inputs, max_new_tokens=max_new_tokens)
58
+ generated_ids_trimmed = [out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
59
+ outputs = self.qwen_processor.batch_decode(
60
+ generated_ids_trimmed,
61
+ skip_special_tokens=True,
62
+ clean_up_tokenization_spaces=False,
63
+ )
64
+ qwen_results = clean_and_remove_hallucinations(outputs[0])
65
+ return qwen_results
66
+
67
+ def evaluate(self, data_chunk):
68
+ assert len(data_chunk) >= 1, f'At least one document is required.'
69
+ eval_results = []
70
+ with torch.no_grad():
71
+ for data in tqdm(data_chunk):
72
+ ocr_results = self.qwen_ocr(data['image'])
73
+ final_result = {'image': data['image'],
74
+ 'prompt': data['prompt'],
75
+ 'ocr_gt': data['text'],
76
+ 'ocr_results': ocr_results}
77
+ eval_results.append(final_result)
78
+
79
+ return eval_results
80
+
81
+
82
+ def split_list(x, n):
83
+ k, m = divmod(len(x), n)
84
+ return [x[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] for i in range(n)]
85
+
86
+
87
+ def main(args):
88
+ # Setup PyTorch:
89
+ torch.set_grad_enabled(False)
90
+ dist.init_process_group("nccl", timeout=timedelta(hours=1))
91
+ rank = dist.get_rank()
92
+ device = rank % torch.cuda.device_count()
93
+ world_size = dist.get_world_size()
94
+ seed = args.global_seed * world_size + rank
95
+ torch.manual_seed(seed)
96
+
97
+ os.makedirs(args.output_dir, exist_ok=True)
98
+
99
+ prompt_file = args.prompt_file or ('text_prompts.jsonl' if args.mode == 'en' else 'text_prompts_zh.jsonl')
100
+ prompts = [json.loads(line) for line in open(prompt_file)]
101
+ prompt_map = {}
102
+ for prompt in prompts:
103
+ # LLTB metadata uses target_text instead of the upstream
104
+ # LongText-Bench text list.
105
+ if "text" not in prompt and "target_text" in prompt:
106
+ prompt = dict(prompt)
107
+ prompt["text"] = str(prompt["target_text"]).splitlines()
108
+ prompt_map[prompt["prompt_id"]] = prompt
109
+
110
+ data = []
111
+ for image_file in sorted(glob.glob(f'{args.sample_dir}/*.png')):
112
+ fname = image_file.split('/')[-1]
113
+ if '_' in fname:
114
+ prompt_id = int(fname.split('_')[0])
115
+ else:
116
+ prompt_id = int(fname.split('.')[0])
117
+ info = prompt_map[prompt_id]
118
+ data.append({'image': image_file,
119
+ 'prompt': info['prompt'],
120
+ 'text': info['text']})
121
+ data_chunks = split_list(data, world_size)
122
+
123
+ evaluator = ImageEvaluator(device)
124
+ print(f'=============Evaluate {len(data_chunks[rank])} images in rank {rank}=============')
125
+ results = evaluator.evaluate(data_chunks[rank])
126
+ output_path = os.path.join(args.output_dir, f'results_chunk{rank}.jsonl')
127
+ with open(output_path, 'w', encoding='utf-8') as f:
128
+ for r in results:
129
+ f.write(json.dumps(r, ensure_ascii=False) + '\n')
130
+
131
+
132
+ if __name__ == '__main__':
133
+ parser = argparse.ArgumentParser()
134
+ parser.add_argument("--sample_dir", type=str, required=True)
135
+ parser.add_argument("--output_dir", type=str, required=True)
136
+ parser.add_argument("--mode", type=str, choices=['en', 'zh'], default='en')
137
+ parser.add_argument("--prompt_file", type=str, default=None)
138
+ parser.add_argument("--global_seed", type=str, default=42)
139
+
140
+ args = parser.parse_args()
141
+ main(args)
text_prompts.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
text_prompts_zh.jsonl ADDED
The diff for this file is too large to render. See raw diff