doctr-synth-generator 0.3.1__tar.gz → 0.4.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/PKG-INFO +12 -7
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/README.md +10 -6
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/doctr_synth_generator.egg-info/PKG-INFO +12 -7
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/doctr_synth_generator.egg-info/SOURCES.txt +1 -0
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/doctr_synth_generator.egg-info/requires.txt +1 -0
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/__init__.py +6 -1
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/components/corpus_downloader.py +67 -14
- doctr_synth_generator-0.4.0/generator/components/latex_generator.py +145 -0
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/components/vocab_coverage.py +65 -1
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/components/vocabs.py +2 -0
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/dataset_generator.py +63 -48
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/doctr_dataset.py +128 -9
- doctr_synth_generator-0.4.0/generator/version.py +1 -0
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/pyproject.toml +2 -0
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/scripts/generate_grid.py +1 -1
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/setup.py +1 -1
- doctr_synth_generator-0.3.1/generator/version.py +0 -1
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/LICENSE +0 -0
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/doctr_synth_generator.egg-info/dependency_links.txt +0 -0
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/doctr_synth_generator.egg-info/entry_points.txt +0 -0
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/doctr_synth_generator.egg-info/top_level.txt +0 -0
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/doctr_synth_generator.egg-info/zip-safe +0 -0
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/__main__.py +0 -0
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/api.py +0 -0
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/augmentations/__init__.py +0 -0
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/augmentations/augmentation_pipeline.py +0 -0
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/augmentations/random_blur.py +0 -0
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/augmentations/random_gaussian_noise.py +0 -0
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/augmentations/random_jpeg_compression.py +0 -0
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/augmentations/random_perspective.py +0 -0
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/augmentations/random_pixel_dropout.py +0 -0
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/augmentations/random_rotate.py +0 -0
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/components/__init__.py +0 -0
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/components/background_downloader.py +0 -0
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/components/background_manager.py +0 -0
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/components/config.py +0 -0
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/components/dataset_balancer.py +0 -0
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/components/dataset_splitter.py +0 -0
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/components/font_downloader.py +0 -0
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/components/font_selector.py +0 -0
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/components/generator.py +0 -0
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/components/page_generator.py +0 -0
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/components/text_renderer.py +0 -0
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/components/text_styling.py +0 -0
- {doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: doctr-synth-generator
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.0
|
|
4
4
|
Summary: A synthetic data generator for training OCR models
|
|
5
5
|
Author-email: Felix Dittrich <felixdittrich92@gmail.com>
|
|
6
6
|
Maintainer: Felix Dittrich
|
|
@@ -228,6 +228,7 @@ License-File: LICENSE
|
|
|
228
228
|
Requires-Dist: fonttools<5.0.0,>=4.50.0
|
|
229
229
|
Requires-Dist: numpy<3.0.0,>=2.0.0
|
|
230
230
|
Requires-Dist: Pillow>=11.0.0
|
|
231
|
+
Requires-Dist: matplotlib<4.0.0,>=3.7.0
|
|
231
232
|
Provides-Extra: testing
|
|
232
233
|
Requires-Dist: pytest>=5.3.2; extra == "testing"
|
|
233
234
|
Requires-Dist: coverage[toml]>=4.5.4; extra == "testing"
|
|
@@ -250,7 +251,7 @@ Dynamic: license-file
|
|
|
250
251
|

|
|
251
252
|
[](https://codecov.io/gh/felixdittrich92/docTR-Synth-Generator)
|
|
252
253
|
[](https://www.codefactor.io/repository/github/felixdittrich92/doctr-synth-generator)
|
|
253
|
-
[](https://pypi.org/project/docTR-Synth-Generator/)
|
|
254
255
|
|
|
255
256
|
# docTR-Synth-Generator
|
|
256
257
|
A tool to generate synthetic OCR datasets - made for docTR
|
|
@@ -361,11 +362,15 @@ cached (later runs are offline). Providing your own `font_dir` / `wordlist_path`
|
|
|
361
362
|
open-source [Noto](https://fonts.google.com/noto) font is downloaded, verified
|
|
362
363
|
and cached, so words are never silently skipped (the usual cause of biased,
|
|
363
364
|
latin-only datasets). Disable with `auto_download_fonts=False`.
|
|
364
|
-
- **Words** - with no `wordlist_path`, real frequency-ranked words
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
365
|
+
- **Words** - with no `wordlist_path`, real frequency-ranked words are downloaded
|
|
366
|
+
and cleaned (script filter, length bounds, punctuation removal). They come from
|
|
367
|
+
[FrequencyWords](https://github.com/hermitdave/FrequencyWords) first, falling
|
|
368
|
+
back to [most-common-words-multilingual](https://github.com/frekwencja/most-common-words-multilingual)
|
|
369
|
+
for the many languages it lacks (Odia, Khmer, Burmese and most Indic/SE-Asian
|
|
370
|
+
scripts), so far fewer languages need synthesised words. Any character still
|
|
371
|
+
missing from the corpus is then synthesised. Two realism helpers are on by
|
|
372
|
+
default: `casing_variant_prob` (0.3) adds Title/UPPERCASE variants, and
|
|
373
|
+
`numeric_token_ratio` (0.05) mixes in numbers, dates and prices.
|
|
369
374
|
- **Backgrounds** - with no `bg_image_dir`, a curated background set is downloaded
|
|
370
375
|
instead of blank pages. Disable with `auto_download_backgrounds=False`, or pass
|
|
371
376
|
a `background_manifest_url` for your own collection.
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|

|
|
3
3
|
[](https://codecov.io/gh/felixdittrich92/docTR-Synth-Generator)
|
|
4
4
|
[](https://www.codefactor.io/repository/github/felixdittrich92/doctr-synth-generator)
|
|
5
|
-
[](https://pypi.org/project/docTR-Synth-Generator/)
|
|
6
6
|
|
|
7
7
|
# docTR-Synth-Generator
|
|
8
8
|
A tool to generate synthetic OCR datasets - made for docTR
|
|
@@ -113,11 +113,15 @@ cached (later runs are offline). Providing your own `font_dir` / `wordlist_path`
|
|
|
113
113
|
open-source [Noto](https://fonts.google.com/noto) font is downloaded, verified
|
|
114
114
|
and cached, so words are never silently skipped (the usual cause of biased,
|
|
115
115
|
latin-only datasets). Disable with `auto_download_fonts=False`.
|
|
116
|
-
- **Words** - with no `wordlist_path`, real frequency-ranked words
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
116
|
+
- **Words** - with no `wordlist_path`, real frequency-ranked words are downloaded
|
|
117
|
+
and cleaned (script filter, length bounds, punctuation removal). They come from
|
|
118
|
+
[FrequencyWords](https://github.com/hermitdave/FrequencyWords) first, falling
|
|
119
|
+
back to [most-common-words-multilingual](https://github.com/frekwencja/most-common-words-multilingual)
|
|
120
|
+
for the many languages it lacks (Odia, Khmer, Burmese and most Indic/SE-Asian
|
|
121
|
+
scripts), so far fewer languages need synthesised words. Any character still
|
|
122
|
+
missing from the corpus is then synthesised. Two realism helpers are on by
|
|
123
|
+
default: `casing_variant_prob` (0.3) adds Title/UPPERCASE variants, and
|
|
124
|
+
`numeric_token_ratio` (0.05) mixes in numbers, dates and prices.
|
|
121
125
|
- **Backgrounds** - with no `bg_image_dir`, a curated background set is downloaded
|
|
122
126
|
instead of blank pages. Disable with `auto_download_backgrounds=False`, or pass
|
|
123
127
|
a `background_manifest_url` for your own collection.
|
{doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/doctr_synth_generator.egg-info/PKG-INFO
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: doctr-synth-generator
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.0
|
|
4
4
|
Summary: A synthetic data generator for training OCR models
|
|
5
5
|
Author-email: Felix Dittrich <felixdittrich92@gmail.com>
|
|
6
6
|
Maintainer: Felix Dittrich
|
|
@@ -228,6 +228,7 @@ License-File: LICENSE
|
|
|
228
228
|
Requires-Dist: fonttools<5.0.0,>=4.50.0
|
|
229
229
|
Requires-Dist: numpy<3.0.0,>=2.0.0
|
|
230
230
|
Requires-Dist: Pillow>=11.0.0
|
|
231
|
+
Requires-Dist: matplotlib<4.0.0,>=3.7.0
|
|
231
232
|
Provides-Extra: testing
|
|
232
233
|
Requires-Dist: pytest>=5.3.2; extra == "testing"
|
|
233
234
|
Requires-Dist: coverage[toml]>=4.5.4; extra == "testing"
|
|
@@ -250,7 +251,7 @@ Dynamic: license-file
|
|
|
250
251
|

|
|
251
252
|
[](https://codecov.io/gh/felixdittrich92/docTR-Synth-Generator)
|
|
252
253
|
[](https://www.codefactor.io/repository/github/felixdittrich92/doctr-synth-generator)
|
|
253
|
-
[](https://pypi.org/project/docTR-Synth-Generator/)
|
|
254
255
|
|
|
255
256
|
# docTR-Synth-Generator
|
|
256
257
|
A tool to generate synthetic OCR datasets - made for docTR
|
|
@@ -361,11 +362,15 @@ cached (later runs are offline). Providing your own `font_dir` / `wordlist_path`
|
|
|
361
362
|
open-source [Noto](https://fonts.google.com/noto) font is downloaded, verified
|
|
362
363
|
and cached, so words are never silently skipped (the usual cause of biased,
|
|
363
364
|
latin-only datasets). Disable with `auto_download_fonts=False`.
|
|
364
|
-
- **Words** - with no `wordlist_path`, real frequency-ranked words
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
365
|
+
- **Words** - with no `wordlist_path`, real frequency-ranked words are downloaded
|
|
366
|
+
and cleaned (script filter, length bounds, punctuation removal). They come from
|
|
367
|
+
[FrequencyWords](https://github.com/hermitdave/FrequencyWords) first, falling
|
|
368
|
+
back to [most-common-words-multilingual](https://github.com/frekwencja/most-common-words-multilingual)
|
|
369
|
+
for the many languages it lacks (Odia, Khmer, Burmese and most Indic/SE-Asian
|
|
370
|
+
scripts), so far fewer languages need synthesised words. Any character still
|
|
371
|
+
missing from the corpus is then synthesised. Two realism helpers are on by
|
|
372
|
+
default: `casing_variant_prob` (0.3) adds Title/UPPERCASE variants, and
|
|
373
|
+
`numeric_token_ratio` (0.05) mixes in numbers, dates and prices.
|
|
369
374
|
- **Backgrounds** - with no `bg_image_dir`, a curated background set is downloaded
|
|
370
375
|
instead of blank pages. Disable with `auto_download_backgrounds=False`, or pass
|
|
371
376
|
a `background_manifest_url` for your own collection.
|
|
@@ -33,6 +33,7 @@ generator/components/dataset_splitter.py
|
|
|
33
33
|
generator/components/font_downloader.py
|
|
34
34
|
generator/components/font_selector.py
|
|
35
35
|
generator/components/generator.py
|
|
36
|
+
generator/components/latex_generator.py
|
|
36
37
|
generator/components/page_generator.py
|
|
37
38
|
generator/components/text_renderer.py
|
|
38
39
|
generator/components/text_styling.py
|
|
@@ -4,5 +4,10 @@ from .components.config import (
|
|
|
4
4
|
CoverageConfig, RecognitionConfig, RealismConfig, DetectionConfig,
|
|
5
5
|
)
|
|
6
6
|
from .api import generate_dataset
|
|
7
|
-
from .doctr_dataset import
|
|
7
|
+
from .doctr_dataset import (
|
|
8
|
+
build_recognition_datasets,
|
|
9
|
+
build_detection_datasets,
|
|
10
|
+
build_latex_recognition_datasets,
|
|
11
|
+
synth_worker_init_fn,
|
|
12
|
+
)
|
|
8
13
|
from .version import __version__
|
|
@@ -15,6 +15,13 @@ __all__ = ["CorpusDownloader"]
|
|
|
15
15
|
|
|
16
16
|
_FW_BASE = "https://raw.githubusercontent.com/hermitdave/FrequencyWords/master/content/2018"
|
|
17
17
|
|
|
18
|
+
# Secondary source: ~5k most-frequent words for 109 languages, one word per line.
|
|
19
|
+
# Fills the languages hermitdave lacks (Odia, Khmer, Burmese, most Indic/SE-Asian
|
|
20
|
+
# scripts, ...) so far fewer vocabs fall back to pure synthesis.
|
|
21
|
+
_FW2_BASE = "https://raw.githubusercontent.com/frekwencja/most-common-words-multilingual/main/data/wordfrequency.info"
|
|
22
|
+
# A few codes differ from ISO 639-1 in the secondary source.
|
|
23
|
+
_FW2_ALIASES = {"zh": "zh-CN"}
|
|
24
|
+
|
|
18
25
|
# Some languages live under a different code or only ship a ``_full`` list.
|
|
19
26
|
_LANG_ALIASES: dict[str, list[str]] = {
|
|
20
27
|
"zh": ["zh_cn", "zh_tw"],
|
|
@@ -67,6 +74,25 @@ _LANG_SCRIPTS: dict[str, set[str]] = {
|
|
|
67
74
|
"ja": {"japanese", "cjk"},
|
|
68
75
|
"ko": {"korean"},
|
|
69
76
|
"zh": {"cjk"},
|
|
77
|
+
# Languages served mainly by the secondary source - listed so the script
|
|
78
|
+
# filter drops foreign (usually Latin) strays from those frequency lists.
|
|
79
|
+
"bn": {"bengali"},
|
|
80
|
+
"as": {"bengali"},
|
|
81
|
+
"or": {"oriya"},
|
|
82
|
+
"my": {"myanmar"},
|
|
83
|
+
"km": {"khmer"},
|
|
84
|
+
"lo": {"lao"},
|
|
85
|
+
"si": {"sinhala"},
|
|
86
|
+
"ta": {"tamil"},
|
|
87
|
+
"te": {"telugu"},
|
|
88
|
+
"kn": {"kannada"},
|
|
89
|
+
"ml": {"malayalam"},
|
|
90
|
+
"pa": {"gurmukhi"},
|
|
91
|
+
"gu": {"gujarati"},
|
|
92
|
+
"ne": {"devanagari"},
|
|
93
|
+
"ka": {"georgian"},
|
|
94
|
+
"hy": {"armenian"},
|
|
95
|
+
"am": {"ethiopic"},
|
|
70
96
|
}
|
|
71
97
|
|
|
72
98
|
_DOWNLOAD_LOCK = threading.Lock()
|
|
@@ -89,6 +115,7 @@ class CorpusDownloader:
|
|
|
89
115
|
self,
|
|
90
116
|
cache_dir: str,
|
|
91
117
|
source_base_url: str = _FW_BASE,
|
|
118
|
+
secondary_base_url: str = _FW2_BASE,
|
|
92
119
|
timeout: int = 30,
|
|
93
120
|
min_word_length: int = 1,
|
|
94
121
|
max_word_length: int = 24,
|
|
@@ -96,6 +123,7 @@ class CorpusDownloader:
|
|
|
96
123
|
):
|
|
97
124
|
self.cache_dir = cache_dir
|
|
98
125
|
self.source_base_url = source_base_url.rstrip("/")
|
|
126
|
+
self.secondary_base_url = secondary_base_url.rstrip("/") if secondary_base_url else None
|
|
99
127
|
self.timeout = timeout
|
|
100
128
|
self.min_word_length = min_word_length
|
|
101
129
|
self.max_word_length = max_word_length
|
|
@@ -114,31 +142,56 @@ class CorpusDownloader:
|
|
|
114
142
|
paths.append(f"{code}/{code}_full.txt")
|
|
115
143
|
return paths
|
|
116
144
|
|
|
145
|
+
def _fetch_url(self, url: str) -> bytes | None:
|
|
146
|
+
"""GET a URL, returning its bytes (or None on any failure/empty)."""
|
|
147
|
+
try:
|
|
148
|
+
req = urllib.request.Request(url, headers={"User-Agent": "docTR-Synth-Generator"})
|
|
149
|
+
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
|
150
|
+
data = resp.read()
|
|
151
|
+
return data or None
|
|
152
|
+
except Exception:
|
|
153
|
+
return None
|
|
154
|
+
|
|
117
155
|
def _download_raw(self, language: str) -> str | None:
|
|
118
|
-
"""Download the raw frequency list text for a language (cached on disk).
|
|
156
|
+
"""Download the raw frequency list text for a language (cached on disk).
|
|
157
|
+
|
|
158
|
+
Tries the primary mirror (hermitdave) first, then the secondary mirror
|
|
159
|
+
(frekwencja) for the many languages hermitdave does not cover.
|
|
160
|
+
"""
|
|
119
161
|
local_path = os.path.join(self.cache_dir, f"{language}_freq.txt")
|
|
120
162
|
if os.path.exists(local_path) and os.path.getsize(local_path) > 0:
|
|
121
163
|
with open(local_path, "r", encoding="utf-8", errors="replace") as fh:
|
|
122
164
|
return fh.read()
|
|
123
165
|
|
|
166
|
+
# Primary: hermitdave (``word count`` per line).
|
|
124
167
|
for rel in self._candidate_paths(language):
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
|
129
|
-
data = resp.read()
|
|
130
|
-
if not data:
|
|
131
|
-
continue
|
|
132
|
-
fd, tmp = tempfile.mkstemp(dir=self.cache_dir, suffix=".part")
|
|
133
|
-
with os.fdopen(fd, "wb") as fh:
|
|
134
|
-
fh.write(data)
|
|
135
|
-
os.replace(tmp, local_path)
|
|
168
|
+
data = self._fetch_url(f"{self.source_base_url}/{rel}")
|
|
169
|
+
if data:
|
|
170
|
+
self._cache_to_disk(local_path, data)
|
|
136
171
|
return data.decode("utf-8", "replace")
|
|
137
|
-
|
|
138
|
-
|
|
172
|
+
|
|
173
|
+
# Secondary: frekwencja (one word per line, with a leading code line).
|
|
174
|
+
if self.secondary_base_url:
|
|
175
|
+
code = _FW2_ALIASES.get(language, language)
|
|
176
|
+
data = self._fetch_url(f"{self.secondary_base_url}/{code}.txt")
|
|
177
|
+
if data:
|
|
178
|
+
text = data.decode("utf-8", "replace")
|
|
179
|
+
lines = text.splitlines()
|
|
180
|
+
if lines and lines[0].strip() in {code, language}: # drop the header line
|
|
181
|
+
text = "\n".join(lines[1:])
|
|
182
|
+
self._cache_to_disk(local_path, text.encode("utf-8"))
|
|
183
|
+
return text
|
|
184
|
+
|
|
139
185
|
print(f"CorpusDownloader: no frequency list found for language '{language}'")
|
|
140
186
|
return None
|
|
141
187
|
|
|
188
|
+
def _cache_to_disk(self, local_path: str, data: bytes) -> None:
|
|
189
|
+
"""Atomically write downloaded bytes to the on-disk cache."""
|
|
190
|
+
fd, tmp = tempfile.mkstemp(dir=self.cache_dir, suffix=".part")
|
|
191
|
+
with os.fdopen(fd, "wb") as fh:
|
|
192
|
+
fh.write(data)
|
|
193
|
+
os.replace(tmp, local_path)
|
|
194
|
+
|
|
142
195
|
def _clean(self, raw: str, language: str) -> list[str]:
|
|
143
196
|
"""Parse and filter the raw ``word count`` lines into a clean word list."""
|
|
144
197
|
expected = _LANG_SCRIPTS.get(language) if self.filter_by_script else None
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
# Copyright (C) 2021-2026, Felix Dittrich.
|
|
2
|
+
|
|
3
|
+
# This program is licensed under the Apache License 2.0.
|
|
4
|
+
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import io
|
|
9
|
+
import random
|
|
10
|
+
|
|
11
|
+
__all__ = ["generate_latex_formulas", "render_latex_image", "is_valid_latex"]
|
|
12
|
+
|
|
13
|
+
# Building blocks, all within the mathtext-supported subset of LaTeX.
|
|
14
|
+
_GREEK = [
|
|
15
|
+
r"\alpha",
|
|
16
|
+
r"\beta",
|
|
17
|
+
r"\gamma",
|
|
18
|
+
r"\delta",
|
|
19
|
+
r"\theta",
|
|
20
|
+
r"\lambda",
|
|
21
|
+
r"\mu",
|
|
22
|
+
r"\pi",
|
|
23
|
+
r"\rho",
|
|
24
|
+
r"\sigma",
|
|
25
|
+
r"\phi",
|
|
26
|
+
r"\omega",
|
|
27
|
+
r"\psi",
|
|
28
|
+
r"\tau",
|
|
29
|
+
]
|
|
30
|
+
_VARS = list("abcdefghijklmnpqrstuvxyz") + list("ABCDEFGHJKLMNPQRSTUVWXYZ")
|
|
31
|
+
_FUNCS = [r"\sin", r"\cos", r"\tan", r"\log", r"\ln", r"\exp"]
|
|
32
|
+
_REL = ["=", r"\leq", r"\geq", r"\neq", r"\approx", "<", ">", r"\equiv"]
|
|
33
|
+
_BINOP = ["+", "-", r"\times", r"\cdot", r"\div", r"\pm"]
|
|
34
|
+
_CONST = [r"\infty", r"\pi", r"0", r"1", r"2", r"n", r"k", r"x"]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _num(rng: random.Random) -> str:
|
|
38
|
+
return str(rng.randint(0, 99))
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _atom(rng: random.Random) -> str:
|
|
42
|
+
"""A leaf: a variable, Greek letter, or number."""
|
|
43
|
+
return rng.choice(_VARS + _GREEK + [_num(rng), _num(rng)])
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _term(rng: random.Random, depth: int) -> str:
|
|
47
|
+
"""A sub-expression, recursively, capped by ``depth``."""
|
|
48
|
+
if depth <= 0:
|
|
49
|
+
return _atom(rng)
|
|
50
|
+
kind = rng.choice(["atom", "atom", "pow", "sub", "frac", "sqrt", "func", "paren", "sum", "int"])
|
|
51
|
+
if kind == "atom":
|
|
52
|
+
return _atom(rng)
|
|
53
|
+
if kind == "pow":
|
|
54
|
+
return f"{_atom(rng)}^{{{_term(rng, depth - 1)}}}"
|
|
55
|
+
if kind == "sub":
|
|
56
|
+
return f"{_atom(rng)}_{{{_term(rng, depth - 1)}}}"
|
|
57
|
+
if kind == "frac":
|
|
58
|
+
return f"\\frac{{{_term(rng, depth - 1)}}}{{{_term(rng, depth - 1)}}}"
|
|
59
|
+
if kind == "sqrt":
|
|
60
|
+
return f"\\sqrt{{{_term(rng, depth - 1)}}}"
|
|
61
|
+
if kind == "func":
|
|
62
|
+
return f"{rng.choice(_FUNCS)}({_term(rng, depth - 1)})"
|
|
63
|
+
if kind == "paren":
|
|
64
|
+
return f"({_expr(rng, depth - 1)})"
|
|
65
|
+
if kind == "sum":
|
|
66
|
+
return f"\\sum_{{i=1}}^{{{rng.choice(['n', 'k', 'N'])}}} {_term(rng, depth - 1)}"
|
|
67
|
+
if kind == "int":
|
|
68
|
+
upper = rng.choice(["1", "n", r"\infty"])
|
|
69
|
+
return f"\\int_{{0}}^{{{upper}}} {_term(rng, depth - 1)}\\,dx"
|
|
70
|
+
return _atom(rng)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _expr(rng: random.Random, depth: int) -> str:
|
|
74
|
+
"""A chain of terms joined by binary operators."""
|
|
75
|
+
parts = [_term(rng, depth)]
|
|
76
|
+
for _ in range(rng.randint(0, 2)):
|
|
77
|
+
parts.append(rng.choice(_BINOP))
|
|
78
|
+
parts.append(_term(rng, depth))
|
|
79
|
+
return " ".join(parts)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _formula(rng: random.Random, max_depth: int) -> str:
|
|
83
|
+
"""A full formula: usually a relation ``lhs <rel> rhs``."""
|
|
84
|
+
lhs = _expr(rng, max_depth)
|
|
85
|
+
if rng.random() < 0.7:
|
|
86
|
+
return f"{lhs} {rng.choice(_REL)} {_expr(rng, max_depth)}"
|
|
87
|
+
return lhs
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
# A single reusable parser; mathtext raises on anything it cannot render.
|
|
91
|
+
_PARSER = None
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def is_valid_latex(formula: str) -> bool:
|
|
95
|
+
"""True if mathtext can parse (and therefore render) ``$formula$``."""
|
|
96
|
+
global _PARSER
|
|
97
|
+
if _PARSER is None:
|
|
98
|
+
import matplotlib
|
|
99
|
+
|
|
100
|
+
matplotlib.use("Agg")
|
|
101
|
+
from matplotlib.mathtext import MathTextParser
|
|
102
|
+
|
|
103
|
+
_PARSER = MathTextParser("agg")
|
|
104
|
+
try:
|
|
105
|
+
_PARSER.parse(f"${formula}$")
|
|
106
|
+
return True
|
|
107
|
+
except Exception:
|
|
108
|
+
return False
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def generate_latex_formulas(
|
|
112
|
+
n: int, *, seed: int | None = None, max_depth: int = 3, min_len: int = 3, max_len: int = 60
|
|
113
|
+
) -> list[str]:
|
|
114
|
+
"""Return ``n`` distinct, valid LaTeX math source strings (no surrounding ``$``)."""
|
|
115
|
+
rng = random.Random(seed)
|
|
116
|
+
out: list[str] = []
|
|
117
|
+
seen: set[str] = set()
|
|
118
|
+
attempts = 0
|
|
119
|
+
while len(out) < n and attempts < n * 40:
|
|
120
|
+
attempts += 1
|
|
121
|
+
f = _formula(rng, max_depth)
|
|
122
|
+
if not (min_len <= len(f) <= max_len) or f in seen:
|
|
123
|
+
continue
|
|
124
|
+
if is_valid_latex(f):
|
|
125
|
+
seen.add(f)
|
|
126
|
+
out.append(f)
|
|
127
|
+
return out
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def render_latex_image(formula: str, *, fontsize: int = 24, dpi: int = 200, color=(0, 0, 0)):
|
|
131
|
+
"""Render ``formula`` to a tightly-cropped RGBA ``PIL.Image`` (transparent bg)."""
|
|
132
|
+
import matplotlib
|
|
133
|
+
|
|
134
|
+
matplotlib.use("Agg")
|
|
135
|
+
from matplotlib import pyplot as plt
|
|
136
|
+
from PIL import Image
|
|
137
|
+
|
|
138
|
+
fig = plt.figure()
|
|
139
|
+
rgb = tuple(c / 255 for c in color)
|
|
140
|
+
fig.text(0.0, 0.0, f"${formula}$", fontsize=fontsize, color=rgb)
|
|
141
|
+
buf = io.BytesIO()
|
|
142
|
+
fig.savefig(buf, format="png", dpi=dpi, bbox_inches="tight", pad_inches=0.05, transparent=True)
|
|
143
|
+
plt.close(fig)
|
|
144
|
+
buf.seek(0)
|
|
145
|
+
return Image.open(buf).convert("RGBA")
|
{doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/components/vocab_coverage.py
RENAMED
|
@@ -57,6 +57,7 @@ LANGUAGE_TO_VOCAB: dict[str, str] = {
|
|
|
57
57
|
"lv": "latvian",
|
|
58
58
|
"mk": "macedonian",
|
|
59
59
|
"ml": "malayalam",
|
|
60
|
+
"ms": "malay",
|
|
60
61
|
"mr": "marathi",
|
|
61
62
|
"mt": "maltese",
|
|
62
63
|
"my": "burmese",
|
|
@@ -186,6 +187,47 @@ def _is_virama(char: str) -> bool:
|
|
|
186
187
|
return unicodedata.combining(char) == 9
|
|
187
188
|
|
|
188
189
|
|
|
190
|
+
# Thai/Lao vowels that are stored before their consonant in logical order and
|
|
191
|
+
# render to its left (Unicode "Logical_Order_Exception"). On their own they make
|
|
192
|
+
# an incomplete syllable, so a synthesised token must keep a consonant after them.
|
|
193
|
+
_PREBASE_VOWELS = set("\u0e40\u0e41\u0e42\u0e43\u0e44\u0ec0\u0ec1\u0ec2\u0ec3\u0ec4")
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _is_prebase_vowel(char: str) -> bool:
|
|
197
|
+
"""True for Thai/Lao left-reordering vowels that must precede a consonant."""
|
|
198
|
+
return char in _PREBASE_VOWELS
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
# Representative base consonant per script, keyed by the script name returned by
|
|
202
|
+
# ``_script_of``. Used only as a fallback when a target charset contains combining
|
|
203
|
+
# marks of a script but none of that script's base letters (e.g. the
|
|
204
|
+
# ``*_matras`` / ``*_virama`` building-block vocabs): a matra or virama cannot
|
|
205
|
+
# render alone, so we scaffold it on a valid same-script consonant.
|
|
206
|
+
_CARRIER: dict[str, list[str]] = {
|
|
207
|
+
"ARABIC": ["\u0628"], # beh
|
|
208
|
+
"HEBREW": ["\u05d1"], # bet
|
|
209
|
+
"DEVANAGARI": ["\u0915"], # ka
|
|
210
|
+
"BENGALI": ["\u0995"], # ka
|
|
211
|
+
"GUJARATI": ["\u0a95"], # ka
|
|
212
|
+
"GURMUKHI": ["\u0a15"], # ka
|
|
213
|
+
"ORIYA": ["\u0b15"], # ka
|
|
214
|
+
"TAMIL": ["\u0b95"], # ka
|
|
215
|
+
"TELUGU": ["\u0c15"], # ka
|
|
216
|
+
"KANNADA": ["\u0c95"], # ka
|
|
217
|
+
"MALAYALAM": ["\u0d15"], # ka
|
|
218
|
+
"SINHALA": ["\u0d9a"], # alpapraana kayanna
|
|
219
|
+
"THAI": ["\u0e01"], # ko kai
|
|
220
|
+
"LAO": ["\u0e81"], # ko
|
|
221
|
+
"MYANMAR": ["\u1000"], # ka
|
|
222
|
+
"KHMER": ["\u1780"], # ka
|
|
223
|
+
"TIBETAN": ["\u0f40"], # ka
|
|
224
|
+
"JAVANESE": ["\ua98f"], # ka
|
|
225
|
+
"SUNDANESE": ["\u1b8a"], # ka
|
|
226
|
+
"CYRILLIC": ["\u0430"], # a
|
|
227
|
+
"GREEK": ["\u03b1"], # alpha
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
|
|
189
231
|
def _make_token(
|
|
190
232
|
char: str,
|
|
191
233
|
script_words: dict[str, list[str]],
|
|
@@ -207,7 +249,13 @@ def _make_token(
|
|
|
207
249
|
digits = "".join(rng.choice("0123456789") for _ in range(rng.randint(0, 3)))
|
|
208
250
|
return char + digits
|
|
209
251
|
|
|
210
|
-
base_letters =
|
|
252
|
+
base_letters = [
|
|
253
|
+
c
|
|
254
|
+
for c in (script_base_letters.get(script, []) or _CARRIER.get(script, []))
|
|
255
|
+
if c not in _PREBASE_VOWELS # never use a left-reordering vowel as filler
|
|
256
|
+
]
|
|
257
|
+
if not base_letters:
|
|
258
|
+
base_letters = _CARRIER.get(script, [])
|
|
211
259
|
bases = script_words.get(script, [])
|
|
212
260
|
|
|
213
261
|
if _is_mark(char):
|
|
@@ -252,6 +300,22 @@ def _make_token(
|
|
|
252
300
|
return "" # no base letter available for this script -> cannot place validly
|
|
253
301
|
|
|
254
302
|
# Non-mark character (letter or standalone modifier).
|
|
303
|
+
if _is_prebase_vowel(char):
|
|
304
|
+
# A Thai/Lao left-reordering vowel needs a consonant after it. Prefer
|
|
305
|
+
# inserting it directly before a letter of a real word; else scaffold
|
|
306
|
+
# vowel + consonant(s).
|
|
307
|
+
for _ in range(6):
|
|
308
|
+
if not bases:
|
|
309
|
+
break
|
|
310
|
+
word = rng.choice(bases)
|
|
311
|
+
positions = [i for i, c in enumerate(word) if unicodedata.category(c).startswith("L")]
|
|
312
|
+
if positions:
|
|
313
|
+
i = rng.choice(positions)
|
|
314
|
+
return (word[:i] + char + word[i:])[:16]
|
|
315
|
+
if base_letters:
|
|
316
|
+
tail = "".join(rng.choice(base_letters) for _ in range(rng.randint(1, 2)))
|
|
317
|
+
return (char + tail)[:16]
|
|
318
|
+
return ""
|
|
255
319
|
if bases and rng.random() < 0.6:
|
|
256
320
|
word = rng.choice(bases)
|
|
257
321
|
pos = rng.randint(0, len(word))
|
|
@@ -9,6 +9,8 @@ import string
|
|
|
9
9
|
__all__ = ["VOCABS"]
|
|
10
10
|
|
|
11
11
|
_BASE_VOCABS = {
|
|
12
|
+
# LaTeX
|
|
13
|
+
"latex": "".join(sorted(set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\\{}^_=+-<>()[]/.,| "))),
|
|
12
14
|
# Latin
|
|
13
15
|
"digits": string.digits,
|
|
14
16
|
"ascii_letters": string.ascii_letters,
|
|
@@ -100,65 +100,80 @@ class SyntheticDatasetGenerator:
|
|
|
100
100
|
train, val = self._inject_coverage(train, val, target)
|
|
101
101
|
return filter_in_vocab(train, charset), filter_in_vocab(val, charset)
|
|
102
102
|
|
|
103
|
-
languages = cfg.core.languages or [
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
max_word_length=cfg.corpus.max_word_length,
|
|
111
|
-
filter_by_script=cfg.corpus.filter_by_script,
|
|
112
|
-
)
|
|
103
|
+
languages = list(cfg.core.languages or [])
|
|
104
|
+
target = self._coverage_target(languages)
|
|
105
|
+
# With neither explicit languages nor a vocab to synthesise from, fall
|
|
106
|
+
# back to English so a bare zero-config run still works.
|
|
107
|
+
if not languages and not target:
|
|
108
|
+
languages = ["en"]
|
|
109
|
+
target = self._coverage_target(languages)
|
|
113
110
|
|
|
114
|
-
# Per-language pools (casing variants folded in per language so they are
|
|
115
|
-
# balanced alongside their own language rather than globally).
|
|
116
111
|
language_pools: dict[str, list[str]] = {}
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
112
|
+
if languages:
|
|
113
|
+
cache_dir = cfg.resources.corpus_cache_dir or ".corpus_cache"
|
|
114
|
+
print(f"No wordlist given - downloading real words for languages: {languages}")
|
|
115
|
+
downloader = CorpusDownloader(
|
|
116
|
+
cache_dir=cache_dir,
|
|
117
|
+
timeout=cfg.resources.font_download_timeout,
|
|
118
|
+
min_word_length=cfg.corpus.min_word_length,
|
|
119
|
+
max_word_length=cfg.corpus.max_word_length,
|
|
120
|
+
filter_by_script=cfg.corpus.filter_by_script,
|
|
121
|
+
)
|
|
122
|
+
# Per-language pools (casing variants folded in per language so they
|
|
123
|
+
# are balanced alongside their own language rather than globally).
|
|
124
|
+
for lang in languages:
|
|
125
|
+
pool = downloader.fetch(lang)[: cfg.corpus.words_per_language]
|
|
126
126
|
if not pool:
|
|
127
|
-
print(f"
|
|
127
|
+
print(f" note: no frequency list for '{lang}' - its characters will be synthesised.")
|
|
128
128
|
continue
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
129
|
+
if cfg.corpus.casing_variant_prob > 0:
|
|
130
|
+
pool = apply_casing_variants(pool, prob=cfg.corpus.casing_variant_prob, seed=cfg.corpus.seed)
|
|
131
|
+
if charset:
|
|
132
|
+
pool = filter_in_vocab(pool, charset)
|
|
133
|
+
if not pool:
|
|
134
|
+
print(f" note: no '{lang}' words fall within the vocab - its characters will be synthesised.")
|
|
135
|
+
continue
|
|
136
|
+
language_pools[lang] = pool
|
|
137
|
+
|
|
138
|
+
if language_pools:
|
|
139
|
+
numeric_tokens = None
|
|
140
|
+
if cfg.corpus.numeric_token_ratio > 0:
|
|
141
|
+
n_pool = max(256, int(cfg.core.num_images * cfg.corpus.numeric_token_ratio) * 2)
|
|
142
|
+
numeric_tokens = generate_numeric_tokens(n_pool, seed=cfg.corpus.seed)
|
|
143
|
+
if charset:
|
|
144
|
+
numeric_tokens = filter_in_vocab(numeric_tokens, charset) or None
|
|
145
|
+
|
|
146
|
+
balancer = DatasetBalancer(seed=cfg.corpus.seed)
|
|
147
|
+
result = balancer.allocate_and_split(
|
|
148
|
+
language_pools=language_pools,
|
|
149
|
+
num_images=cfg.core.num_images,
|
|
150
|
+
val_percent=cfg.core.val_percent,
|
|
151
|
+
strategy=cfg.balance.language_balance,
|
|
152
|
+
weights=cfg.balance.language_weights,
|
|
153
|
+
numeric_tokens=numeric_tokens,
|
|
154
|
+
numeric_ratio=cfg.corpus.numeric_token_ratio,
|
|
155
|
+
min_char_coverage=cfg.balance.min_char_coverage,
|
|
156
|
+
report=cfg.balance.print_balance_report,
|
|
157
|
+
)
|
|
158
|
+
train, val = result.train, result.val
|
|
159
|
+
elif target:
|
|
160
|
+
# No usable corpus (no frequency list for these languages, or nothing
|
|
161
|
+
# within the target vocab). Rather than fail, build the whole pool
|
|
162
|
+
# from synthesised coverage tokens so vocabs like Odia/Khmer - and
|
|
163
|
+
# combined vocabs - still train.
|
|
164
|
+
print(" no in-vocab corpus words available - synthesising the pool from the target vocab.")
|
|
165
|
+
train, val = [], []
|
|
166
|
+
else:
|
|
132
167
|
raise ValueError(
|
|
133
|
-
f"Could not
|
|
134
|
-
"
|
|
168
|
+
f"Could not build a word pool for languages {languages} and there is "
|
|
169
|
+
"no target vocab to synthesise from. Provide a wordlist_path, languages "
|
|
170
|
+
"that have a frequency list, or a vocab."
|
|
135
171
|
)
|
|
136
172
|
|
|
137
|
-
numeric_tokens = None
|
|
138
|
-
if cfg.corpus.numeric_token_ratio > 0:
|
|
139
|
-
n_pool = max(256, int(cfg.core.num_images * cfg.corpus.numeric_token_ratio) * 2)
|
|
140
|
-
numeric_tokens = generate_numeric_tokens(n_pool, seed=cfg.corpus.seed)
|
|
141
|
-
if charset:
|
|
142
|
-
numeric_tokens = filter_in_vocab(numeric_tokens, charset) or None
|
|
143
|
-
|
|
144
|
-
balancer = DatasetBalancer(seed=cfg.corpus.seed)
|
|
145
|
-
result = balancer.allocate_and_split(
|
|
146
|
-
language_pools=language_pools,
|
|
147
|
-
num_images=cfg.core.num_images,
|
|
148
|
-
val_percent=cfg.core.val_percent,
|
|
149
|
-
strategy=cfg.balance.language_balance,
|
|
150
|
-
weights=cfg.balance.language_weights,
|
|
151
|
-
numeric_tokens=numeric_tokens,
|
|
152
|
-
numeric_ratio=cfg.corpus.numeric_token_ratio,
|
|
153
|
-
min_char_coverage=cfg.balance.min_char_coverage,
|
|
154
|
-
report=cfg.balance.print_balance_report,
|
|
155
|
-
)
|
|
156
|
-
train, val = result.train, result.val
|
|
157
173
|
# Hard per-split coverage guarantee: append synthesised tokens so train
|
|
158
174
|
# and val each contain every renderable vocab character. Done after the
|
|
159
175
|
# split (not via the balancer's stratified top-up) so a rare character
|
|
160
176
|
# can never end up in only one split.
|
|
161
|
-
target = self._coverage_target(languages)
|
|
162
177
|
if target:
|
|
163
178
|
train, val = self._inject_coverage(train, val, target)
|
|
164
179
|
return filter_in_vocab(train, charset), filter_in_vocab(val, charset)
|
|
@@ -16,8 +16,10 @@ from PIL import Image
|
|
|
16
16
|
|
|
17
17
|
from .components.config import GenerationConfig
|
|
18
18
|
from .components.generator import TextImageGenerator
|
|
19
|
+
from .components.latex_generator import generate_latex_formulas, render_latex_image
|
|
19
20
|
from .components.page_generator import PageGenerator
|
|
20
|
-
from .components.vocab_coverage import VOCAB_TO_LANGUAGE, resolve_vocab_charset
|
|
21
|
+
from .components.vocab_coverage import LANGUAGE_TO_VOCAB, VOCAB_TO_LANGUAGE, resolve_vocab_charset
|
|
22
|
+
from .components.vocabs import VOCABS
|
|
21
23
|
from .dataset_generator import SyntheticDatasetGenerator
|
|
22
24
|
|
|
23
25
|
try: # docTR's single-class name ("words"); fall back to the same literal if absent.
|
|
@@ -264,6 +266,46 @@ class SyntheticRecognitionDataset(_BaseSynthDataset):
|
|
|
264
266
|
return render_recognition_sample(self._generator, self.pool, max_attempts=self.max_attempts)
|
|
265
267
|
|
|
266
268
|
|
|
269
|
+
class SyntheticLatexDataset(_BaseSynthDataset):
|
|
270
|
+
"""On-the-fly LaTeX formula recognition dataset.
|
|
271
|
+
|
|
272
|
+
Each sample is a rendered math formula (Matplotlib mathtext - no system TeX)
|
|
273
|
+
whose label is the LaTeX *source* string. Train against ``VOCABS["latex"]``.
|
|
274
|
+
|
|
275
|
+
Args:
|
|
276
|
+
formulas: validated LaTeX source strings to sample from.
|
|
277
|
+
num_samples: virtual epoch length (``len(dataset)``).
|
|
278
|
+
fontsize_range: random font size per sample.
|
|
279
|
+
img_transforms / sample_transforms: docTR transforms, as elsewhere.
|
|
280
|
+
seed: ``None`` -> fresh every access (train); int -> reproducible (val).
|
|
281
|
+
"""
|
|
282
|
+
|
|
283
|
+
def __init__(
|
|
284
|
+
self,
|
|
285
|
+
formulas: list[str],
|
|
286
|
+
num_samples: int,
|
|
287
|
+
*,
|
|
288
|
+
fontsize_range: tuple[int, int] = (16, 30),
|
|
289
|
+
img_transforms: Callable | None = None,
|
|
290
|
+
sample_transforms: Callable | None = None,
|
|
291
|
+
seed: int | None = None,
|
|
292
|
+
) -> None:
|
|
293
|
+
super().__init__(num_samples, img_transforms=img_transforms, sample_transforms=sample_transforms, seed=seed)
|
|
294
|
+
if not formulas:
|
|
295
|
+
raise ValueError("latex formula pool is empty")
|
|
296
|
+
self.formulas = list(formulas)
|
|
297
|
+
self.fontsize_range = fontsize_range
|
|
298
|
+
self.charset = set(VOCABS["latex"])
|
|
299
|
+
|
|
300
|
+
def _render(self, index: int) -> tuple[Image.Image, str]:
|
|
301
|
+
formula = random.choice(self.formulas)
|
|
302
|
+
fontsize = random.randint(*self.fontsize_range)
|
|
303
|
+
rgba = render_latex_image(formula, fontsize=fontsize)
|
|
304
|
+
background = Image.new("RGB", rgba.size, (255, 255, 255))
|
|
305
|
+
background.paste(rgba, (0, 0), rgba.getchannel("A"))
|
|
306
|
+
return background, formula
|
|
307
|
+
|
|
308
|
+
|
|
267
309
|
class SyntheticDetectionDataset(_BaseSynthDataset):
|
|
268
310
|
"""On-the-fly detection dataset (full synthetic pages) for docTR.
|
|
269
311
|
|
|
@@ -328,6 +370,27 @@ def _to_corpus_languages(languages: list[str]) -> list[str]:
|
|
|
328
370
|
return [VOCAB_TO_LANGUAGE.get(lang, lang) for lang in languages]
|
|
329
371
|
|
|
330
372
|
|
|
373
|
+
def _corpus_languages_for_vocab(vocab: str | list[str]) -> list[str]:
|
|
374
|
+
"""Every corpus language whose characters fit entirely within ``vocab``.
|
|
375
|
+
|
|
376
|
+
This combines as many real word lists as possible: a broad vocab like
|
|
377
|
+
``"multilingual"`` pulls in every language fully encodable in it, while a
|
|
378
|
+
script-specific vocab like ``"khmer"`` or ``"odia"`` yields only its own
|
|
379
|
+
language(s) - or none, in which case the pool is synthesised downstream.
|
|
380
|
+
"""
|
|
381
|
+
charset = resolve_vocab_charset(vocab)
|
|
382
|
+
if not charset:
|
|
383
|
+
return []
|
|
384
|
+
ordered: list[str] = []
|
|
385
|
+
seen: set[str] = set()
|
|
386
|
+
for iso, vkey in LANGUAGE_TO_VOCAB.items():
|
|
387
|
+
sub = VOCABS.get(vkey)
|
|
388
|
+
if sub and set(sub) <= charset and iso not in seen:
|
|
389
|
+
seen.add(iso)
|
|
390
|
+
ordered.append(iso)
|
|
391
|
+
return ordered
|
|
392
|
+
|
|
393
|
+
|
|
331
394
|
def _split_sizes(config: GenerationConfig, train_samples: int | None, val_samples: int | None) -> tuple[int, int]:
|
|
332
395
|
"""Per-epoch ``(train, val)`` sizes derived from ``num_images`` and ``val_percent``.
|
|
333
396
|
|
|
@@ -349,7 +412,10 @@ def build_recognition_datasets(
|
|
|
349
412
|
train_samples: int | None = None,
|
|
350
413
|
val_samples: int | None = None,
|
|
351
414
|
val_seed: int = 1234,
|
|
352
|
-
) ->
|
|
415
|
+
) -> (
|
|
416
|
+
tuple[SyntheticRecognitionDataset, SyntheticRecognitionDataset]
|
|
417
|
+
| tuple[SyntheticLatexDataset, SyntheticLatexDataset]
|
|
418
|
+
):
|
|
353
419
|
"""Build ``(train, val)`` on-the-fly recognition datasets from a config.
|
|
354
420
|
|
|
355
421
|
Sizes come straight from the config: ``num_images`` total, split into
|
|
@@ -365,17 +431,27 @@ def build_recognition_datasets(
|
|
|
365
431
|
the matching ``--vocab`` never hits an un-encodable label.
|
|
366
432
|
|
|
367
433
|
Corpus languages come from ``languages`` (ISO codes or VOCABS keys) when
|
|
368
|
-
given
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
434
|
+
given. Otherwise they are derived from ``vocab``: every word list whose
|
|
435
|
+
characters fit within the vocab is combined (so ``"multilingual"`` blends
|
|
436
|
+
many real languages), and any character with no corpus word - or a vocab
|
|
437
|
+
with no matching corpus at all, like ``"khmer"`` or ``"odia"`` - is covered
|
|
438
|
+
by synthesised tokens instead of failing.
|
|
372
439
|
"""
|
|
440
|
+
# LaTeX is rendered math, not font-drawn words - route to its own builder.
|
|
441
|
+
if vocab is not None and (vocab == "latex" or vocab == ["latex"]):
|
|
442
|
+
return build_latex_recognition_datasets(
|
|
443
|
+
config,
|
|
444
|
+
img_transforms=img_transforms,
|
|
445
|
+
sample_transforms=sample_transforms,
|
|
446
|
+
train_samples=train_samples,
|
|
447
|
+
val_samples=val_samples,
|
|
448
|
+
val_seed=val_seed,
|
|
449
|
+
)
|
|
373
450
|
if languages is not None:
|
|
374
451
|
langs = _to_corpus_languages(languages)
|
|
375
452
|
elif vocab is not None:
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
langs = derived or list(config.core.languages or ["en"])
|
|
453
|
+
# Combine every word list that fits the vocab; empty -> synthesise the pool.
|
|
454
|
+
langs = _corpus_languages_for_vocab(vocab)
|
|
379
455
|
else:
|
|
380
456
|
langs = list(config.core.languages or ["en"])
|
|
381
457
|
|
|
@@ -407,6 +483,49 @@ def build_recognition_datasets(
|
|
|
407
483
|
return train_set, val_set
|
|
408
484
|
|
|
409
485
|
|
|
486
|
+
def build_latex_recognition_datasets(
|
|
487
|
+
config: GenerationConfig,
|
|
488
|
+
*,
|
|
489
|
+
img_transforms: Callable | None = None,
|
|
490
|
+
sample_transforms: Callable | None = None,
|
|
491
|
+
train_samples: int | None = None,
|
|
492
|
+
val_samples: int | None = None,
|
|
493
|
+
val_seed: int = 1234,
|
|
494
|
+
max_depth: int = 3,
|
|
495
|
+
pool_size: int = 3000,
|
|
496
|
+
) -> tuple[SyntheticLatexDataset, SyntheticLatexDataset]:
|
|
497
|
+
"""Build ``(train, val)`` LaTeX-formula recognition datasets.
|
|
498
|
+
|
|
499
|
+
Labels are valid LaTeX source strings; images are the rendered math. Sizes
|
|
500
|
+
come from the config (``num_images`` split by ``val_percent``), exactly like
|
|
501
|
+
:func:`build_recognition_datasets`. Train against ``VOCABS["latex"]``.
|
|
502
|
+
A disjoint pool of ``pool_size`` formulas is generated once and split so the
|
|
503
|
+
train and val formulas never overlap.
|
|
504
|
+
"""
|
|
505
|
+
train_n, val_n = _split_sizes(config, train_samples, val_samples)
|
|
506
|
+
formulas = generate_latex_formulas(pool_size, seed=config.corpus.seed, max_depth=max_depth)
|
|
507
|
+
if not formulas:
|
|
508
|
+
raise ValueError("could not generate any valid LaTeX formulas")
|
|
509
|
+
cut = max(1, int(len(formulas) * (1 - config.core.val_percent)))
|
|
510
|
+
train_pool = formulas[:cut]
|
|
511
|
+
val_pool = formulas[cut:] or formulas[:1]
|
|
512
|
+
train_set = SyntheticLatexDataset(
|
|
513
|
+
train_pool,
|
|
514
|
+
train_n,
|
|
515
|
+
img_transforms=img_transforms,
|
|
516
|
+
sample_transforms=sample_transforms,
|
|
517
|
+
seed=None,
|
|
518
|
+
)
|
|
519
|
+
val_set = SyntheticLatexDataset(
|
|
520
|
+
val_pool,
|
|
521
|
+
val_n,
|
|
522
|
+
img_transforms=img_transforms,
|
|
523
|
+
sample_transforms=sample_transforms,
|
|
524
|
+
seed=val_seed,
|
|
525
|
+
)
|
|
526
|
+
return train_set, val_set
|
|
527
|
+
|
|
528
|
+
|
|
410
529
|
def build_detection_datasets(
|
|
411
530
|
config: GenerationConfig,
|
|
412
531
|
*,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = '0.4.0'
|
|
@@ -32,6 +32,7 @@ dependencies = [
|
|
|
32
32
|
"fonttools>=4.50.0,<5.0.0",
|
|
33
33
|
"numpy>=2.0.0,<3.0.0",
|
|
34
34
|
"Pillow>=11.0.0",
|
|
35
|
+
"matplotlib>=3.7.0,<4.0.0",
|
|
35
36
|
]
|
|
36
37
|
|
|
37
38
|
[project.optional-dependencies]
|
|
@@ -91,6 +92,7 @@ module = [
|
|
|
91
92
|
"fontTools.*",
|
|
92
93
|
"numpy.*",
|
|
93
94
|
"PIL.*",
|
|
95
|
+
"matplotlib.*",
|
|
94
96
|
]
|
|
95
97
|
ignore_missing_imports = true
|
|
96
98
|
|
|
@@ -178,7 +178,7 @@ def build_grid(out_path: str, seed: int = 0):
|
|
|
178
178
|
|
|
179
179
|
if __name__ == "__main__":
|
|
180
180
|
ap = argparse.ArgumentParser(description="Render an example grid (detection pages + recognition crops).")
|
|
181
|
-
ap.add_argument("-o", "--out", default="docs/
|
|
181
|
+
ap.add_argument("-o", "--out", default="docs/examples_grid_x.png", help="output PNG path")
|
|
182
182
|
ap.add_argument("--seed", type=int, default=0)
|
|
183
183
|
args = ap.parse_args()
|
|
184
184
|
os.makedirs(os.path.dirname(args.out) or ".", exist_ok=True)
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
__version__ = '0.3.1'
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/doctr_synth_generator.egg-info/zip-safe
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
{doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/augmentations/__init__.py
RENAMED
|
File without changes
|
|
File without changes
|
{doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/augmentations/random_blur.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/augmentations/random_rotate.py
RENAMED
|
File without changes
|
{doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/components/__init__.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/components/dataset_balancer.py
RENAMED
|
File without changes
|
{doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/components/dataset_splitter.py
RENAMED
|
File without changes
|
{doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/components/font_downloader.py
RENAMED
|
File without changes
|
{doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/components/font_selector.py
RENAMED
|
File without changes
|
{doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/components/generator.py
RENAMED
|
File without changes
|
{doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/components/page_generator.py
RENAMED
|
File without changes
|
{doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/components/text_renderer.py
RENAMED
|
File without changes
|
{doctr_synth_generator-0.3.1 → doctr_synth_generator-0.4.0}/generator/components/text_styling.py
RENAMED
|
File without changes
|
|
File without changes
|