Datasets:

Modalities:
Text
Image
Formats:
json
Languages:
English
ArXiv:
License:
yunfanyang1 commited on
Commit
91eca9b
·
verified ·
1 Parent(s): 829da68

Update TableTex annotations, source metadata, rendering script, and dataset card

Browse files
Files changed (6) hide show
  1. .gitattributes +0 -59
  2. README.md +208 -78
  3. cspo_train.jsonl +0 -0
  4. generate_images.py +425 -0
  5. sft_train.json +2 -2
  6. test.jsonl +0 -0
.gitattributes CHANGED
@@ -1,61 +1,2 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.avro filter=lfs diff=lfs merge=lfs -text
4
- *.bin filter=lfs diff=lfs merge=lfs -text
5
- *.bz2 filter=lfs diff=lfs merge=lfs -text
6
- *.ckpt filter=lfs diff=lfs merge=lfs -text
7
- *.ftz filter=lfs diff=lfs merge=lfs -text
8
- *.gz filter=lfs diff=lfs merge=lfs -text
9
- *.h5 filter=lfs diff=lfs merge=lfs -text
10
- *.joblib filter=lfs diff=lfs merge=lfs -text
11
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
12
- *.lz4 filter=lfs diff=lfs merge=lfs -text
13
- *.mds filter=lfs diff=lfs merge=lfs -text
14
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
15
- *.model filter=lfs diff=lfs merge=lfs -text
16
- *.msgpack filter=lfs diff=lfs merge=lfs -text
17
- *.npy filter=lfs diff=lfs merge=lfs -text
18
- *.npz filter=lfs diff=lfs merge=lfs -text
19
- *.onnx filter=lfs diff=lfs merge=lfs -text
20
- *.ot filter=lfs diff=lfs merge=lfs -text
21
- *.parquet filter=lfs diff=lfs merge=lfs -text
22
- *.pb filter=lfs diff=lfs merge=lfs -text
23
- *.pickle filter=lfs diff=lfs merge=lfs -text
24
- *.pkl filter=lfs diff=lfs merge=lfs -text
25
- *.pt filter=lfs diff=lfs merge=lfs -text
26
- *.pth filter=lfs diff=lfs merge=lfs -text
27
- *.rar filter=lfs diff=lfs merge=lfs -text
28
- *.safetensors filter=lfs diff=lfs merge=lfs -text
29
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
30
- *.tar.* filter=lfs diff=lfs merge=lfs -text
31
- *.tar filter=lfs diff=lfs merge=lfs -text
32
- *.tflite filter=lfs diff=lfs merge=lfs -text
33
- *.tgz filter=lfs diff=lfs merge=lfs -text
34
- *.wasm filter=lfs diff=lfs merge=lfs -text
35
- *.xz filter=lfs diff=lfs merge=lfs -text
36
- *.zip filter=lfs diff=lfs merge=lfs -text
37
- *.zst filter=lfs diff=lfs merge=lfs -text
38
- *tfevents* filter=lfs diff=lfs merge=lfs -text
39
- # Audio files - uncompressed
40
- *.pcm filter=lfs diff=lfs merge=lfs -text
41
- *.sam filter=lfs diff=lfs merge=lfs -text
42
- *.raw filter=lfs diff=lfs merge=lfs -text
43
- # Audio files - compressed
44
- *.aac filter=lfs diff=lfs merge=lfs -text
45
- *.flac filter=lfs diff=lfs merge=lfs -text
46
- *.mp3 filter=lfs diff=lfs merge=lfs -text
47
- *.ogg filter=lfs diff=lfs merge=lfs -text
48
- *.wav filter=lfs diff=lfs merge=lfs -text
49
- # Image files - uncompressed
50
- *.bmp filter=lfs diff=lfs merge=lfs -text
51
- *.gif filter=lfs diff=lfs merge=lfs -text
52
  *.png filter=lfs diff=lfs merge=lfs -text
53
- *.tiff filter=lfs diff=lfs merge=lfs -text
54
- # Image files - compressed
55
- *.jpg filter=lfs diff=lfs merge=lfs -text
56
- *.jpeg filter=lfs diff=lfs merge=lfs -text
57
- *.webp filter=lfs diff=lfs merge=lfs -text
58
- # Video files - compressed
59
- *.mp4 filter=lfs diff=lfs merge=lfs -text
60
- *.webm filter=lfs diff=lfs merge=lfs -text
61
  sft_train.json filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  *.png filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
2
  sft_train.json filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -5,6 +5,8 @@ language:
5
  license: other
6
  tags:
7
  - image
 
 
8
  task_categories:
9
  - image-to-text
10
  size_categories:
@@ -28,75 +30,86 @@ configs:
28
 
29
  ## Dataset Summary
30
 
31
- TableTex is a dataset for **table image-to-LaTeX generation**. It contains 19,000 pairs of table images and renderable LaTeX table code collected from scientific articles on arXiv.
 
 
 
 
 
32
 
33
- To support complete table generation, each LaTeX sample includes the necessary package declarations for compilation, the table caption, and the table body that preserves the structure, content, and visual formatting of the original table. The source articles span six arXiv subject categories: Computer Science, Mathematics, Economics, Electrical Engineering and Systems Science, Quantitative Finance, and Statistics, covering publications from 2012 to 2025.
 
 
 
 
 
 
 
 
 
34
 
35
  TableTex is introduced in:
36
 
37
  - **CSPO: Alleviating Reward Ambiguity for Structured Table-to-LaTeX Generation**
38
- - Paper: https://arxiv.org/pdf/2604.10918
39
  - Code: https://github.com/microsoft/CSPO
40
 
41
- For more details, please see the full data card in the GitHub repository: https://github.com/microsoft/CSPO/blob/main/TableTex_Data_Card.md
 
 
42
 
43
  ## Dataset Structure
44
 
45
- TableTex consists of paired table images and renderable LaTeX table code for table image-to-LaTeX generation. The annotations are provided in three files corresponding to the training and evaluation stages used in the CSPO paper:
46
-
47
- - `sft_train.json`: 10,000 samples for supervised fine-tuning
48
- - `cspo_train.jsonl`: 5,000 samples for reinforcement learning with CSPO
49
- - `test.jsonl`: 4,000 samples for evaluation
 
50
 
51
- The corresponding table images are provided as compressed subject-specific archives. After extraction, the images are organized under six `{subject}/image` directories:
52
 
53
  ```text
54
  tabletex/
55
- ├── README.md
56
- ├── sft_train.json # SFT annotations
57
- ├── cspo_train.jsonl # CSPO/RL annotations
58
- ├── test.jsonl # evaluation annotations
59
- ├── cs/
60
- │ └── image/
61
- ├── econ/
62
- │ └── image/
63
- ├── eess/
64
- │ └── image/
65
- ├── math/
66
- │ └── image/
67
- ├── q-fin/
68
- │ └── image/
69
- └── stat/
70
- └── image/
71
  ```
72
 
73
- ### Extracting Image Archives
74
-
75
- The table images are distributed as compressed `.tar.gz` archives to reduce upload and download overhead.
76
-
77
- To extract the image folders, run:
78
 
79
- ```bash
80
- tar -xzf cs.tar.gz
81
- tar -xzf econ.tar.gz
82
- tar -xzf eess.tar.gz
83
- tar -xzf math.tar.gz
84
- tar -xzf q-fin.tar.gz
85
- tar -xzf stat.tar.gz
 
 
 
 
 
 
 
 
86
  ```
87
 
88
- After extraction, the dataset directory structure will match the layout illustrated above.
89
 
90
- Image paths referenced in the annotation files are relative to the dataset root. For example:
91
-
92
- - `eess/image/2010.13713v2_tex_table3.png`
93
- - `stat/image/2501.02454v2_tex_table8.png`
94
 
95
  ## Data Instances
96
 
97
- ### `sft` configuration
98
 
99
- Each example is stored in a chat-style multimodal format for supervised fine-tuning.
100
 
101
  ```json
102
  {
@@ -107,76 +120,193 @@ Each example is stored in a chat-style multimodal format for supervised fine-tun
107
  },
108
  {
109
  "role": "assistant",
110
- "content": "[LaTeX code here]"
111
  }
112
  ],
113
  "images": [
114
  "eess/image/2010.13713v2_tex_table3.png"
115
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
  }
117
  ```
118
 
119
- ### `cspo` and `evaluation` configurations
 
 
 
 
 
 
120
 
121
- Each example contains a table image path, the subject category of the source article, and the corresponding LaTeX table code.
122
 
123
  ```json
124
  {
125
  "image_path": "stat/image/2501.02454v2_tex_table8.png",
126
  "subject": "stat",
127
- "tex_code": "\\documentclass{article}\n..."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
  }
129
  ```
130
 
131
- ## Data Fields
 
 
 
 
 
 
 
 
 
132
 
133
- ### `sft`
 
 
 
 
 
 
134
 
135
- - `messages`: conversation-style multimodal input and output used for supervised fine-tuning
136
- - `images`: relative path to the input table image
137
 
138
- ### `cspo` and `evaluation`
139
 
140
- - `image_path`: relative path to the input table image
141
- - `subject`: arXiv subject category of the source article
142
- - `tex_code`: renderable LaTeX code corresponding to the table image
143
 
144
- The subject categories are:
 
 
 
145
 
146
- - `cs`
147
- - `econ`
148
- - `eess`
149
- - `math`
150
- - `q-fin`
151
- - `stat`
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
 
153
  ## Dataset Creation
154
 
155
- TableTex was constructed from scientific articles collected from arXiv. Renderable table code was extracted directly from LaTeX source files, and each extracted LaTeX snippet was rendered into a table image, producing paired table image–LaTeX code samples.
 
 
 
156
 
157
- The collected articles span six arXiv subject categories and cover publications from 2012 to 2025. The source materials were restricted to papers released under the following license families:
 
158
 
159
  - CC BY
160
  - CC BY-SA
161
  - CC0
162
  - CC BY-NC
163
 
164
- ## Split Information
165
-
166
- | Configuration | Split | Number of Samples |
167
- | --- | --- | ---: |
168
- | `sft` | train | 10,000 |
169
- | `cspo` | train | 5,000 |
170
- | `evaluation` | test | 4,000 |
171
- | **Total** | | **19,000** |
172
 
173
  ## Intended Use
174
 
175
  TableTex is intended for research on table image-to-LaTeX generation, including supervised fine-tuning, reinforcement-learning-based post-training, and evaluation of models that reconstruct tables from images as LaTeX code.
176
 
177
- ## License
 
 
 
 
 
178
 
179
- TableTex contains samples derived from arXiv articles released under CC BY, CC BY-SA, CC0, and CC BY-NC licenses. Users are responsible for complying with the original license terms of the source materials when using or redistributing the dataset.
 
 
 
 
180
 
181
  ## Citation
182
 
@@ -189,4 +319,4 @@ If you use TableTex in your work, please cite:
189
  journal={arXiv preprint arXiv:2604.10918},
190
  year={2026}
191
  }
192
- ```
 
5
  license: other
6
  tags:
7
  - image
8
+ - latex
9
+ - table
10
  task_categories:
11
  - image-to-text
12
  size_categories:
 
30
 
31
  ## Dataset Summary
32
 
33
+ TableTex is a dataset for **table image-to-LaTeX generation**, comprising
34
+ 19,000 renderable LaTeX table annotations extracted from scientific articles
35
+ on arXiv. Each annotation corresponds to a table image that can be generated
36
+ locally using the provided `generate_images.py` script. The rendered images
37
+ are not included in the repository, which keeps the distributed dataset
38
+ compact while providing a reproducible image-generation pipeline.
39
 
40
+ To support complete and compilable table generation, each annotation is
41
+ provided as a standalone LaTeX document containing the required package
42
+ declarations, table caption, and table body. The annotations preserve the
43
+ structure, content, and visual formatting of the source tables.
44
+
45
+ The source articles cover publications from 2012 to 2025 across six arXiv
46
+ subject categories: Computer Science (`cs`), Mathematics (`math`), Economics
47
+ (`econ`), Electrical Engineering and Systems Science (`eess`), Quantitative
48
+ Finance (`q-fin`), and Statistics (`stat`). Each sample also includes
49
+ source-level attribution, license, and modification metadata.
50
 
51
  TableTex is introduced in:
52
 
53
  - **CSPO: Alleviating Reward Ambiguity for Structured Table-to-LaTeX Generation**
54
+ - Paper: https://arxiv.org/abs/2604.10918
55
  - Code: https://github.com/microsoft/CSPO
56
 
57
+ For additional details, see the
58
+ [TableTex data card](https://github.com/microsoft/CSPO/blob/main/TableTex_Data_Card.md)
59
+ in the CSPO repository.
60
 
61
  ## Dataset Structure
62
 
63
+ | Configuration | File | Split | Samples | Purpose |
64
+ | --- | --- | --- | ---: | --- |
65
+ | `sft` | `sft_train.json` | train | 10,000 | Supervised fine-tuning |
66
+ | `cspo` | `cspo_train.jsonl` | train | 5,000 | Reinforcement-learning post-training |
67
+ | `evaluation` | `test.jsonl` | test | 4,000 | Evaluation |
68
+ | **Total** | | | **19,000** | |
69
 
70
+ The distributed files are:
71
 
72
  ```text
73
  tabletex/
74
+ |-- README.md
75
+ |-- generate_images.py
76
+ |-- sft_train.json
77
+ |-- cspo_train.jsonl
78
+ `-- test.jsonl
 
 
 
 
 
 
 
 
 
 
 
79
  ```
80
 
81
+ After image generation, PNG files are stored in subject-specific directories,
82
+ and the standalone LaTeX files used for compilation are retained under `tex/`:
 
 
 
83
 
84
+ ```text
85
+ tabletex/
86
+ |-- tex/
87
+ | |-- cs/image/
88
+ | |-- econ/image/
89
+ | |-- eess/image/
90
+ | |-- math/image/
91
+ | |-- q-fin/image/
92
+ | `-- stat/image/
93
+ |-- cs/image/
94
+ |-- econ/image/
95
+ |-- eess/image/
96
+ |-- math/image/
97
+ |-- q-fin/image/
98
+ `-- stat/image/
99
  ```
100
 
101
+ All image paths in the annotations are relative to the dataset root. Examples:
102
 
103
+ ```text
104
+ eess/image/2010.13713v2_tex_table3.png
105
+ stat/image/2501.02454v2_tex_table8.png
106
+ ```
107
 
108
  ## Data Instances
109
 
110
+ ### SFT configuration
111
 
112
+ `sft_train.json` stores samples in a multimodal conversation format:
113
 
114
  ```json
115
  {
 
120
  },
121
  {
122
  "role": "assistant",
123
+ "content": "```latex\n\\documentclass{article}\n...\n```"
124
  }
125
  ],
126
  "images": [
127
  "eess/image/2010.13713v2_tex_table3.png"
128
+ ],
129
+ "source": {
130
+ "title": "Self-supervised Human Activity Recognition by Learning to Predict Cross-Dimensional Motion",
131
+ "authors": [
132
+ "Setareh Rahimi Taghanaki",
133
+ "Michael Rainbow",
134
+ "Ali Etemad"
135
+ ],
136
+ "url": "https://arxiv.org/abs/2010.13713v2",
137
+ "attribution": "\"Self-supervised Human Activity Recognition by Learning to Predict Cross-Dimensional Motion\" by Setareh Rahimi Taghanaki, Michael Rainbow, and Ali Etemad, arXiv:2010.13713v2, licensed under CC BY-SA 4.0. The table was extracted, wrapped as standalone LaTeX, rendered, and cropped by TableTex.",
138
+ "license": {
139
+ "name": "CC BY-SA 4.0",
140
+ "url": "https://creativecommons.org/licenses/by-sa/4.0/"
141
+ },
142
+ "modifications": [
143
+ "Extracted the table LaTeX from the article source.",
144
+ "Wrapped it as a standalone LaTeX document.",
145
+ "Rendered and cropped it into a PNG image."
146
+ ]
147
+ }
148
  }
149
  ```
150
 
151
+ Fields:
152
+
153
+ - `messages`: multimodal prompt and target LaTeX response.
154
+ - `images`: list containing the relative output path of the table image.
155
+ - `source`: source and rights metadata for the sample.
156
+
157
+ ### CSPO and evaluation configurations
158
 
159
+ `cspo_train.jsonl` and `test.jsonl` store one JSON object per line:
160
 
161
  ```json
162
  {
163
  "image_path": "stat/image/2501.02454v2_tex_table8.png",
164
  "subject": "stat",
165
+ "tex_code": "\\documentclass{article}\n...",
166
+ "source": {
167
+ "title": "Finite-Sample Valid Randomization Tests for Monotone Spillover Effects",
168
+ "authors": [
169
+ "Shunzhuang Huang",
170
+ "Xinran Li",
171
+ "Panos Toulis"
172
+ ],
173
+ "url": "https://arxiv.org/abs/2501.02454v2",
174
+ "attribution": "\"Finite-Sample Valid Randomization Tests for Monotone Spillover Effects\" by Shunzhuang Huang, Xinran Li, and Panos Toulis, arXiv:2501.02454v2, licensed under CC BY-SA 4.0. The table was extracted, wrapped as standalone LaTeX, rendered, and cropped by TableTex.",
175
+ "license": {
176
+ "name": "CC BY-SA 4.0",
177
+ "url": "https://creativecommons.org/licenses/by-sa/4.0/"
178
+ },
179
+ "modifications": [
180
+ "Extracted the table LaTeX from the article source.",
181
+ "Wrapped it as a standalone LaTeX document.",
182
+ "Rendered and cropped it into a PNG image."
183
+ ]
184
+ }
185
  }
186
  ```
187
 
188
+ Fields:
189
+
190
+ - `image_path`: relative output path of the table image.
191
+ - `subject`: arXiv subject category.
192
+ - `tex_code`: standalone LaTeX code corresponding to the image.
193
+ - `source`: source and rights metadata for the sample.
194
+
195
+ ### Source metadata
196
+
197
+ Every sample includes:
198
 
199
+ - `source.title`: complete title of the source article.
200
+ - `source.authors`: authors of the source article.
201
+ - `source.url`: version-specific arXiv abstract URL.
202
+ - `source.attribution`: attribution statement for the sample.
203
+ - `source.license.name`: exact source-license name.
204
+ - `source.license.url`: URL of the source license.
205
+ - `source.modifications`: transformations performed by TableTex.
206
 
207
+ ## Generating the Images
 
208
 
209
+ ### 1. Install Dependencies
210
 
211
+ TableTex image generation requires:
 
 
212
 
213
+ - Python 3.10 or later
214
+ - `tqdm`
215
+ - TeX Live providing `pdflatex` and `pdfcrop`
216
+ - Poppler providing `pdftoppm`
217
 
218
+ Install the Python dependency with:
219
+
220
+ ```bash
221
+ pip install tqdm
222
+ ```
223
+
224
+ Install TeX Live using the official resources:
225
+
226
+ - **TeX Live:** [Official Website](https://tug.org/texlive/)
227
+ - **Installation Guide:** [TeX Live Documentation](https://tug.org/texlive/doc.html)
228
+
229
+ We recommend installing the full TeX Live distribution to ensure that all
230
+ LaTeX packages used by the dataset are available.
231
+
232
+ On Ubuntu/Debian systems, also install the following system dependencies:
233
+
234
+ ```bash
235
+ sudo apt-get update
236
+ sudo apt-get install -y ghostscript poppler-utils
237
+ ```
238
+
239
+ ### 2. Run the Script
240
+
241
+ Run the following commands from the dataset root:
242
+
243
+ ```bash
244
+ python generate_images.py sft_train.json
245
+ python generate_images.py cspo_train.jsonl
246
+ python generate_images.py test.jsonl
247
+ ```
248
+
249
+ The default behavior is to process every record. To process only the first 20
250
+ records:
251
+
252
+ ```bash
253
+ python generate_images.py test.jsonl --limit 20
254
+ ```
255
+
256
+ To use a different output root:
257
+
258
+ ```bash
259
+ python generate_images.py test.jsonl --output-root ./rendered
260
+ ```
261
+
262
+ ### 3. Output Files
263
+
264
+ By default, generated PNG images are written directly to:
265
+
266
+ ```text
267
+ <dataset-root>/<subject>/image/<filename>.png
268
+ ```
269
+
270
+ The standalone LaTeX files used for compilation are written to:
271
+
272
+ ```text
273
+ <dataset-root>/tex/<subject>/image/<filename>.tex
274
+ ```
275
 
276
  ## Dataset Creation
277
 
278
+ TableTex was constructed from LaTeX sources of scientific articles on arXiv.
279
+ For each sample, the table LaTeX was extracted from an article, wrapped as a
280
+ standalone document, and associated with version-specific source and licensing
281
+ metadata. Images can be generated using the included rendering script.
282
 
283
+ The source articles cover publications from 2012 to 2025 and were selected from
284
+ the following Creative Commons license families:
285
 
286
  - CC BY
287
  - CC BY-SA
288
  - CC0
289
  - CC BY-NC
290
 
291
+ The exact license applicable to each sample is recorded in its `source.license`
292
+ object.
 
 
 
 
 
 
293
 
294
  ## Intended Use
295
 
296
  TableTex is intended for research on table image-to-LaTeX generation, including supervised fine-tuning, reinforcement-learning-based post-training, and evaluation of models that reconstruct tables from images as LaTeX code.
297
 
298
+ ## Copyright, Attribution, and Licensing
299
+
300
+ TableTex contains samples derived from arXiv articles released under CC BY,
301
+ CC BY-SA, CC0, or CC BY-NC licenses. Copyright remains with the respective
302
+ authors and/or other rightsholders. The applicable license, attribution, and
303
+ modification information for each sample is recorded in its `source` metadata.
304
 
305
+ Users are responsible for complying with the applicable source license when
306
+ using, adapting, or redistributing the LaTeX annotations or generated images,
307
+ including any attribution, share-alike, and non-commercial requirements where
308
+ applicable. Rendering an image locally does not alter the copyright or license
309
+ terms of the source material.
310
 
311
  ## Citation
312
 
 
319
  journal={arXiv preprint arXiv:2604.10918},
320
  year={2026}
321
  }
322
+ ```
cspo_train.jsonl CHANGED
The diff for this file is too large to render. See raw diff
 
generate_images.py ADDED
@@ -0,0 +1,425 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Recompile LaTeX annotations from a dataset file into table images.
2
+
3
+ Usage examples:
4
+
5
+ python generate_images.py test_with.jsonl
6
+ python generate_images.py cspo_train.jsonl --limit 0
7
+ python generate_images.py sft_train.json --limit 0
8
+
9
+ The generated files follow the annotation paths directly under ``tabletex``:
10
+
11
+ <subject>/image/<arxiv_id>_tex_table<n>.png
12
+
13
+ The corresponding LaTeX sources are kept under:
14
+
15
+ tex/<subject>/image/<arxiv_id>_tex_table<n>.tex
16
+
17
+ The LaTeX/PDF/PNG conversion pipeline is implemented directly in this file.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import json
24
+ import os
25
+ import re
26
+ import subprocess
27
+ from pathlib import Path, PurePosixPath
28
+
29
+ from tqdm import tqdm
30
+
31
+
32
+ PROJECT_ROOT = Path(__file__).resolve().parent
33
+ DEFAULT_OUTPUT = PROJECT_ROOT
34
+
35
+
36
+ def parse_args() -> argparse.Namespace:
37
+ parser = argparse.ArgumentParser(
38
+ description="Write dataset LaTeX to .tex files and compile them to PNG."
39
+ )
40
+ parser.add_argument(
41
+ "input_file",
42
+ type=Path,
43
+ help=(
44
+ "Input dataset filename or path. Relative filenames are resolved "
45
+ f"under {PROJECT_ROOT}."
46
+ ),
47
+ )
48
+ parser.add_argument(
49
+ "--output-root",
50
+ type=Path,
51
+ default=DEFAULT_OUTPUT,
52
+ help=f"Root for generated files (default: {DEFAULT_OUTPUT})",
53
+ )
54
+ parser.add_argument(
55
+ "--limit",
56
+ type=int,
57
+ default=0,
58
+ help="Only process the first N records; use 0 for all records (default: 0).",
59
+ )
60
+ return parser.parse_args()
61
+
62
+
63
+ def print_process_error(tool_name: str, error: BaseException) -> None:
64
+ """Print subprocess diagnostics without aborting the remaining files."""
65
+ print(f"{tool_name} details:")
66
+ if isinstance(error, subprocess.CalledProcessError):
67
+ details = (error.stdout or "") + (error.stderr or "")
68
+ if details.strip():
69
+ print(details.rstrip())
70
+ return
71
+ print(str(error))
72
+
73
+
74
+ def remove_intermediate_files(*paths: Path) -> None:
75
+ """Remove compilation intermediates when present."""
76
+ for path in paths:
77
+ if path.is_file():
78
+ path.unlink()
79
+
80
+
81
+ def generate_image(input_base_dir: str, output_base_dir: str) -> None:
82
+ """Compile all .tex files one directory below input_base_dir into PNGs."""
83
+ input_root = Path(input_base_dir)
84
+ output_root = Path(output_base_dir)
85
+ output_root.mkdir(parents=True, exist_ok=True)
86
+
87
+ tex_files: list[tuple[Path, Path, Path]] = []
88
+ for folder_path in sorted(input_root.iterdir()):
89
+ if not folder_path.is_dir():
90
+ continue
91
+ print(folder_path)
92
+ output_folder = output_root / folder_path.name
93
+ output_folder.mkdir(parents=True, exist_ok=True)
94
+ for tex_path in sorted(folder_path.glob("*.tex")):
95
+ tex_files.append((folder_path, tex_path, output_folder))
96
+
97
+ total = len(tex_files)
98
+ failures = 0
99
+ for folder_path, tex_path, output_folder in tqdm(
100
+ tex_files, desc="Processing .tex files"
101
+ ):
102
+ pdf_path = tex_path.with_suffix(".pdf")
103
+ cropped_pdf = pdf_path.with_name(
104
+ f"{pdf_path.stem}.pdfcrop-{os.getpid()}.pdf"
105
+ )
106
+ image_path = output_folder / tex_path.with_suffix(".png").name
107
+ aux_path = tex_path.with_suffix(".aux")
108
+ log_path = tex_path.with_suffix(".log")
109
+ out_path = tex_path.with_suffix(".out")
110
+
111
+ try:
112
+ subprocess.run(
113
+ ["pdflatex", "-interaction=nonstopmode", str(tex_path)],
114
+ cwd=folder_path,
115
+ check=True,
116
+ stdout=subprocess.DEVNULL,
117
+ stderr=subprocess.DEVNULL,
118
+ timeout=60,
119
+ )
120
+ except (OSError, subprocess.SubprocessError) as error:
121
+ failures += 1
122
+ print(f"ERROR 1 pdflatex failed: {tex_path}")
123
+ print_process_error("pdflatex", error)
124
+ remove_intermediate_files(
125
+ pdf_path, cropped_pdf, aux_path, log_path, out_path
126
+ )
127
+ continue
128
+
129
+ try:
130
+ # pdfcrop creates tmp-pdfcrop-*.tex in its current directory.
131
+ # Keep the project/output path ASCII-only on Windows.
132
+ subprocess.run(
133
+ [
134
+ "pdfcrop",
135
+ "--margins",
136
+ "5 5 5 5",
137
+ str(pdf_path).replace("\\", "/"),
138
+ str(cropped_pdf).replace("\\", "/"),
139
+ ],
140
+ cwd=folder_path,
141
+ check=True,
142
+ stdout=subprocess.PIPE,
143
+ stderr=subprocess.PIPE,
144
+ text=True,
145
+ errors="replace",
146
+ )
147
+ os.replace(cropped_pdf, pdf_path)
148
+ except (OSError, subprocess.SubprocessError) as error:
149
+ failures += 1
150
+ print(f"ERROR 2 pdfcrop failed: {tex_path}")
151
+ print_process_error("pdfcrop", error)
152
+ remove_intermediate_files(
153
+ pdf_path, cropped_pdf, aux_path, log_path, out_path
154
+ )
155
+ continue
156
+
157
+ try:
158
+ subprocess.run(
159
+ [
160
+ "pdftoppm",
161
+ "-png",
162
+ "-r",
163
+ "300",
164
+ str(pdf_path).replace("\\", "/"),
165
+ str(image_path),
166
+ ],
167
+ check=True,
168
+ stdout=subprocess.PIPE,
169
+ stderr=subprocess.PIPE,
170
+ text=True,
171
+ errors="replace",
172
+ )
173
+ normalize_pdftoppm_outputs(image_path)
174
+ except (OSError, subprocess.SubprocessError) as error:
175
+ failures += 1
176
+ print(f"ERROR 3 pdftoppm failed: {tex_path}")
177
+ print_process_error("pdftoppm", error)
178
+ finally:
179
+ remove_intermediate_files(
180
+ pdf_path, cropped_pdf, aux_path, log_path, out_path
181
+ )
182
+
183
+ print(f"Success: {total - failures}/{total} tables.")
184
+
185
+
186
+ def extract_sft_tex(record: dict[str, object], record_number: int) -> str:
187
+ """Extract the assistant's fenced LaTeX response from an SFT record."""
188
+ messages = record.get("messages")
189
+ if not isinstance(messages, list):
190
+ raise ValueError(f"Record {record_number}: missing messages list")
191
+
192
+ assistant_content: str | None = None
193
+ for message in messages:
194
+ if (
195
+ isinstance(message, dict)
196
+ and message.get("role") == "assistant"
197
+ and isinstance(message.get("content"), str)
198
+ ):
199
+ assistant_content = message["content"]
200
+ break
201
+
202
+ if assistant_content is None:
203
+ raise ValueError(
204
+ f"Record {record_number}: missing assistant message with string content"
205
+ )
206
+
207
+ fenced = re.fullmatch(
208
+ r"\s*```(?:latex|tex)?\s*\n?(.*?)\n?```\s*",
209
+ assistant_content,
210
+ flags=re.IGNORECASE | re.DOTALL,
211
+ )
212
+ return (fenced.group(1) if fenced else assistant_content).strip()
213
+
214
+
215
+ def preprocess_tex_code(tex_code: str) -> str:
216
+ """Add adjustbox support and constrain unwrapped tabular environments."""
217
+ package_pattern = re.compile(
218
+ r"\\usepackage(?:\s*\[[^\]]*\])?\s*\{[^}]*\badjustbox\b[^}]*\}"
219
+ )
220
+ if not package_pattern.search(tex_code):
221
+ package_line = "\\usepackage{adjustbox}\n"
222
+ documentclass = re.search(
223
+ r"\\documentclass(?:\s*\[[^\]]*\])?\s*\{[^}]+\}[^\r\n]*(?:\r?\n)?",
224
+ tex_code,
225
+ )
226
+ if documentclass:
227
+ insert_at = documentclass.end()
228
+ tex_code = tex_code[:insert_at] + package_line + tex_code[insert_at:]
229
+ else:
230
+ begin_document = tex_code.find(r"\begin{document}")
231
+ if begin_document >= 0:
232
+ tex_code = (
233
+ tex_code[:begin_document]
234
+ + package_line
235
+ + tex_code[begin_document:]
236
+ )
237
+ else:
238
+ tex_code = package_line + tex_code
239
+
240
+ # Existing samples may already wrap their table correctly. Avoid nesting a
241
+ # second adjustbox around those environments.
242
+ if r"\begin{adjustbox}" not in tex_code:
243
+ adjustbox_begin = (
244
+ "\\begin{adjustbox}{max width=\\textwidth, "
245
+ "max height=0.8\\textheight, keepaspectratio}\n"
246
+ )
247
+ adjustbox_end = "\\end{adjustbox}\n"
248
+ tex_code = tex_code.replace(
249
+ r"\begin{tabular}",
250
+ adjustbox_begin + r"\begin{tabular}",
251
+ )
252
+ tex_code = tex_code.replace(
253
+ r"\end{tabular}",
254
+ r"\end{tabular}" + "\n" + adjustbox_end,
255
+ )
256
+
257
+ return tex_code
258
+
259
+
260
+ def normalize_record(
261
+ record: object, record_number: int
262
+ ) -> dict[str, str]:
263
+ """Normalize JSONL and SFT schemas to image_path/tex_code."""
264
+ if not isinstance(record, dict):
265
+ raise ValueError(f"Record {record_number}: expected a JSON object")
266
+
267
+ image_path = record.get("image_path")
268
+ tex_code = record.get("tex_code")
269
+
270
+ if isinstance(image_path, str) and isinstance(tex_code, str):
271
+ return {
272
+ "image_path": image_path,
273
+ "tex_code": preprocess_tex_code(tex_code),
274
+ }
275
+
276
+ images = record.get("images")
277
+ if (
278
+ isinstance(images, list)
279
+ and len(images) == 1
280
+ and isinstance(images[0], str)
281
+ ):
282
+ return {
283
+ "image_path": images[0],
284
+ "tex_code": preprocess_tex_code(
285
+ extract_sft_tex(record, record_number)
286
+ ),
287
+ }
288
+
289
+ raise ValueError(
290
+ f"Record {record_number}: expected image_path/tex_code strings, "
291
+ "or one images entry plus an assistant message"
292
+ )
293
+
294
+
295
+ def read_records(input_path: Path, limit: int) -> list[dict[str, str]]:
296
+ """Read and normalize records from a JSONL file or JSON array."""
297
+ if limit < 0:
298
+ raise ValueError("--limit must be non-negative")
299
+ if not input_path.is_file():
300
+ raise FileNotFoundError(f"Input dataset not found: {input_path}")
301
+
302
+ records: list[dict[str, str]] = []
303
+ if input_path.suffix.lower() == ".json":
304
+ with input_path.open("r", encoding="utf-8") as input_file:
305
+ data = json.load(input_file)
306
+ if not isinstance(data, list):
307
+ raise ValueError(f"Expected a JSON array in: {input_path}")
308
+ selected = data[:limit] if limit else data
309
+ for record_number, record in enumerate(selected, start=1):
310
+ records.append(normalize_record(record, record_number))
311
+ else:
312
+ with input_path.open("r", encoding="utf-8") as input_file:
313
+ for line_number, line in enumerate(input_file, start=1):
314
+ if not line.strip():
315
+ continue
316
+ record = json.loads(line)
317
+ records.append(normalize_record(record, line_number))
318
+ if limit and len(records) >= limit:
319
+ break
320
+ return records
321
+
322
+
323
+ def validated_image_path(raw_path: str) -> PurePosixPath:
324
+ """Return a safe dataset-relative PNG path."""
325
+ image_path = PurePosixPath(raw_path.replace("\\", "/"))
326
+ if image_path.is_absolute() or ".." in image_path.parts:
327
+ raise ValueError(f"image_path must be relative and cannot contain '..': {raw_path}")
328
+ if len(image_path.parts) != 3 or image_path.parts[1] != "image":
329
+ raise ValueError(
330
+ "Expected image_path in '<subject>/image/<filename>.png' form, "
331
+ f"got: {raw_path}"
332
+ )
333
+ if image_path.suffix.lower() != ".png":
334
+ raise ValueError(f"Expected a .png image_path, got: {raw_path}")
335
+ return image_path
336
+
337
+
338
+ def write_tex_files(
339
+ records: list[dict[str, str]], output_root: Path
340
+ ) -> tuple[set[str], list[tuple[PurePosixPath, Path]]]:
341
+ """Write one .tex file per annotation and return subjects/output mappings."""
342
+ subjects: set[str] = set()
343
+ outputs: list[tuple[PurePosixPath, Path]] = []
344
+ tex_root = output_root / "tex"
345
+
346
+ for record in records:
347
+ image_path = validated_image_path(record["image_path"])
348
+ subject = image_path.parts[0]
349
+ tex_path = tex_root.joinpath(*image_path.with_suffix(".tex").parts)
350
+ final_png = output_root.joinpath(*image_path.parts)
351
+
352
+ tex_path.parent.mkdir(parents=True, exist_ok=True)
353
+ with tex_path.open("w", encoding="utf-8", newline="\n") as out_file:
354
+ out_file.write(record["tex_code"])
355
+ if not record["tex_code"].endswith("\n"):
356
+ out_file.write("\n")
357
+
358
+ subjects.add(subject)
359
+ outputs.append((image_path, final_png))
360
+
361
+ return subjects, outputs
362
+
363
+
364
+ def normalize_pdftoppm_outputs(final_png: Path) -> None:
365
+ """Normalize pdftoppm's '<name>.png-1.png' output to '<name>.png'."""
366
+ generated_first_page = final_png.with_name(final_png.name + "-1.png")
367
+ if generated_first_page.is_file():
368
+ final_png.parent.mkdir(parents=True, exist_ok=True)
369
+ os.replace(generated_first_page, final_png)
370
+
371
+ # Preserve unexpected additional pages with readable, deterministic names.
372
+ pattern = re.compile(re.escape(final_png.name) + r"-(\d+)\.png$")
373
+ for generated_page in final_png.parent.glob(final_png.name + "-*.png"):
374
+ match = pattern.fullmatch(generated_page.name)
375
+ if not match or match.group(1) == "1":
376
+ continue
377
+ page_output = final_png.with_name(
378
+ f"{final_png.stem}_page{match.group(1)}{final_png.suffix}"
379
+ )
380
+ os.replace(generated_page, page_output)
381
+
382
+
383
+ def compile_images_directly(
384
+ subjects: set[str],
385
+ output_root: Path,
386
+ ) -> None:
387
+ """Compile stored TEX files directly into their final image directories."""
388
+ tex_root = output_root / "tex"
389
+
390
+ for subject in sorted(subjects):
391
+ generate_image(
392
+ str(tex_root / subject),
393
+ str(output_root / subject),
394
+ )
395
+
396
+
397
+ def main() -> int:
398
+ args = parse_args()
399
+ input_path = args.input_file
400
+ if not input_path.is_absolute():
401
+ input_path = PROJECT_ROOT / input_path
402
+ input_path = input_path.resolve()
403
+ output_root = args.output_root.resolve()
404
+
405
+ records = read_records(input_path, args.limit)
406
+ if not records:
407
+ print("No records found; nothing to do.")
408
+ return 0
409
+
410
+ subjects, outputs = write_tex_files(records, output_root)
411
+ print(f"Wrote {len(records)} TEX files under: {output_root / 'tex'}")
412
+
413
+ compile_images_directly(subjects, output_root)
414
+
415
+ succeeded = [(path, png) for path, png in outputs if png.is_file()]
416
+ failed = [(path, png) for path, png in outputs if not png.is_file()]
417
+ print(f"Reproduced images: {len(succeeded)}/{len(outputs)}")
418
+ for image_path, png_path in failed:
419
+ print(f"FAILED: {image_path} -> {png_path}")
420
+
421
+ return 1 if failed else 0
422
+
423
+
424
+ if __name__ == "__main__":
425
+ raise SystemExit(main())
sft_train.json CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:00b7c90bfcf4fd24658e3913de21bc9455de5120a30046f867bc3325c3bc1597
3
- size 14808288
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ace4a459b5e717db3294ad0e40152ecfd55533d7474805d1964fb2facb93fece
3
+ size 24063731
test.jsonl CHANGED
The diff for this file is too large to render. See raw diff