doctr-synth-generator 0.3.0__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.
Files changed (45) hide show
  1. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/PKG-INFO +38 -32
  2. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/README.md +36 -31
  3. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/doctr_synth_generator.egg-info/PKG-INFO +38 -32
  4. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/doctr_synth_generator.egg-info/SOURCES.txt +1 -0
  5. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/doctr_synth_generator.egg-info/requires.txt +1 -0
  6. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/generator/__init__.py +6 -1
  7. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/generator/components/corpus_downloader.py +67 -14
  8. doctr_synth_generator-0.4.0/generator/components/latex_generator.py +145 -0
  9. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/generator/components/vocab_coverage.py +65 -1
  10. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/generator/components/vocabs.py +2 -0
  11. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/generator/dataset_generator.py +74 -48
  12. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/generator/doctr_dataset.py +193 -45
  13. doctr_synth_generator-0.4.0/generator/version.py +1 -0
  14. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/pyproject.toml +2 -0
  15. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/scripts/generate_grid.py +7 -2
  16. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/setup.py +1 -1
  17. doctr_synth_generator-0.3.0/generator/version.py +0 -1
  18. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/LICENSE +0 -0
  19. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/doctr_synth_generator.egg-info/dependency_links.txt +0 -0
  20. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/doctr_synth_generator.egg-info/entry_points.txt +0 -0
  21. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/doctr_synth_generator.egg-info/top_level.txt +0 -0
  22. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/doctr_synth_generator.egg-info/zip-safe +0 -0
  23. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/generator/__main__.py +0 -0
  24. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/generator/api.py +0 -0
  25. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/generator/augmentations/__init__.py +0 -0
  26. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/generator/augmentations/augmentation_pipeline.py +0 -0
  27. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/generator/augmentations/random_blur.py +0 -0
  28. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/generator/augmentations/random_gaussian_noise.py +0 -0
  29. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/generator/augmentations/random_jpeg_compression.py +0 -0
  30. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/generator/augmentations/random_perspective.py +0 -0
  31. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/generator/augmentations/random_pixel_dropout.py +0 -0
  32. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/generator/augmentations/random_rotate.py +0 -0
  33. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/generator/components/__init__.py +0 -0
  34. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/generator/components/background_downloader.py +0 -0
  35. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/generator/components/background_manager.py +0 -0
  36. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/generator/components/config.py +0 -0
  37. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/generator/components/dataset_balancer.py +0 -0
  38. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/generator/components/dataset_splitter.py +0 -0
  39. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/generator/components/font_downloader.py +0 -0
  40. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/generator/components/font_selector.py +0 -0
  41. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/generator/components/generator.py +0 -0
  42. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/generator/components/page_generator.py +0 -0
  43. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/generator/components/text_renderer.py +0 -0
  44. {doctr_synth_generator-0.3.0 → doctr_synth_generator-0.4.0}/generator/components/text_styling.py +0 -0
  45. {doctr_synth_generator-0.3.0 → 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.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
  ![Build Status](https://github.com/felixdittrich92/docTR-Synth-Generator/workflows/builds/badge.svg)
251
252
  [![codecov](https://codecov.io/gh/felixdittrich92/docTR-Synth-Generator/graph/badge.svg?token=31MDR20JGI)](https://codecov.io/gh/felixdittrich92/docTR-Synth-Generator)
252
253
  [![CodeFactor](https://www.codefactor.io/repository/github/felixdittrich92/doctr-synth-generator/badge)](https://www.codefactor.io/repository/github/felixdittrich92/doctr-synth-generator)
253
- [![Pypi](https://img.shields.io/badge/pypi-v0.3.0a0-blue.svg)](https://pypi.org/project/docTR-Synth-Generator/)
254
+ [![Pypi](https://img.shields.io/badge/pypi-v0.4.0a0-blue.svg)](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 come from
365
- [FrequencyWords](https://github.com/hermitdave/FrequencyWords) (~85 languages)
366
- and are cleaned (script filter, length bounds, punctuation removal). Two realism
367
- helpers are on by default: `casing_variant_prob` (0.3) adds Title/UPPERCASE
368
- variants, and `numeric_token_ratio` (0.05) mixes in numbers, dates and prices.
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.
@@ -579,19 +584,16 @@ treat them the same: recognition yields the label string; detection yields
579
584
  from generator.components import GenerationConfig
580
585
  from generator.doctr_dataset import build_detection_datasets, synth_worker_init_fn
581
586
 
582
- cfg = GenerationConfig.flat(
583
- task="detection",
584
- languages=["en", "de"],
585
- num_images=50_000, # POOL size (word variety + vocab coverage)
586
- auto_download_backgrounds=True,
587
- )
587
+ # num_images is the total dataset size; val_percent carves out the val set.
588
+ cfg = GenerationConfig.flat(task="detection", num_images=50_000, val_percent=0.2)
588
589
  train_set, val_set = build_detection_datasets(
589
590
  cfg,
590
- train_samples=args.epochs and 20_000, # virtual epoch length (len(dataset))
591
- val_samples=2_000,
591
+ languages=["german", "english", "french", "italian", "spanish", "malay"], # VOCABS keys or ISO codes
592
592
  use_polygons=args.rotation, # straight boxes unless --rotation
593
- sample_transforms=batch_transforms, # the script's existing transforms
593
+ sample_transforms=sample_transforms, # the script's image+target transforms
594
+ img_transforms=img_transforms, # the script's image-only transforms
594
595
  )
596
+ # len(train_set) == 40_000, len(val_set) == 10_000
595
597
  ```
596
598
 
597
599
  **Recognition** - in `references/recognition/train.py`, replace the
@@ -601,26 +603,29 @@ train_set, val_set = build_detection_datasets(
601
603
  from generator.components import GenerationConfig
602
604
  from generator.doctr_dataset import build_recognition_datasets, synth_worker_init_fn
603
605
 
604
- cfg = GenerationConfig.flat(task="recognition", num_images=100_000)
606
+ cfg = GenerationConfig.flat(task="recognition", num_images=10_000, val_percent=0.2)
605
607
  train_set, val_set = build_recognition_datasets(
606
608
  cfg,
607
- train_samples=50_000,
608
- val_samples=5_000,
609
- vocab=args.vocab, # e.g. ["german", "urdu", "odia"] - the model's vocab
609
+ vocab=args.vocab, # e.g. ["multilingual"] - a VOCABS key / list = the model's vocab
610
610
  img_transforms=img_transforms, # the script's existing resize/aug
611
611
  )
612
+ # len(train_set) == 8_000, len(val_set) == 2_000
612
613
  ```
613
614
 
614
615
  Pass `vocab` the **same vocab you train the model on** - a `VOCABS` key, a
615
616
  literal charset, or a list of keys whose union is the model's vocab (e.g.
616
- `["german", "urdu", "odia"]`). Every generated label is then guaranteed to
617
- contain only characters in that vocab, so docTR's label encoder never hits an
618
- out-of-vocab character (which would otherwise crash training on the first batch).
619
- Corpus words outside the vocab are dropped, character coverage is guaranteed
620
- *within* the vocab, and the corpus languages are derived from the vocab keys
621
- automatically (`german` -> `de`); a key with no corpus (e.g. `odia`) still has
622
- its characters covered via synthesis. Set `config.languages` explicitly to pull
623
- different corpora. The same restriction applies to the offline generator via
617
+ `["multilingual"]` or `["german", "urdu", "odia"]`). Every generated label is
618
+ then guaranteed to contain only characters in that vocab, so docTR's label
619
+ encoder never hits an out-of-vocab character (which would otherwise crash
620
+ training on the first batch). Corpus words outside the vocab are dropped,
621
+ character coverage is guaranteed *within* the vocab (missing characters are
622
+ synthesised so the set stays balanced), and the corpus languages are derived
623
+ from the vocab keys automatically (`german` -> `de`). For detection, pass
624
+ `languages=[...]` (VOCABS keys like `"german"`, `"malay"`, or ISO codes); for
625
+ recognition you can pass `languages=[...]` too. A combined vocab like
626
+ `"multilingual"` maps to no single language, so pass `languages=[...]` if you
627
+ want real multilingual words rather than mostly-synthesised coverage. The same
628
+ restriction applies to the offline generator via
624
629
  `GenerationConfig.flat(target_vocab=[...])`.
625
630
 
626
631
  The `DataLoader` lines stay as they are - just keep
@@ -642,10 +647,11 @@ train_loader = DataLoader(
642
647
 
643
648
  Notes:
644
649
 
645
- - **Pool size vs epoch length.** `config.num_images` sizes the word *pool*
646
- (variety and per-split vocab coverage); `train_samples` / `val_samples` set
647
- the virtual epoch length (`len(dataset)`). Samples are generated fresh, so the
648
- epoch length is just how many iterations you want per epoch.
650
+ - **Dataset size & split.** `num_images` is the total dataset size; `val_percent`
651
+ carves out the validation set, so `len(train_set)` / `len(val_set)` follow
652
+ directly (50k @ 0.2 -> 40k / 10k). Samples are generated fresh on every access,
653
+ so this is effectively the iterations per epoch. Pass `train_samples` /
654
+ `val_samples` only if you want to override the derived sizes.
649
655
  - **Seeding.** The train set draws a fresh random sample on every access (new
650
656
  data every epoch - the whole point of on-the-fly); the val set is a
651
657
  reproducible fixed virtual set (seeded per index) so metrics stay comparable.
@@ -2,7 +2,7 @@
2
2
  ![Build Status](https://github.com/felixdittrich92/docTR-Synth-Generator/workflows/builds/badge.svg)
3
3
  [![codecov](https://codecov.io/gh/felixdittrich92/docTR-Synth-Generator/graph/badge.svg?token=31MDR20JGI)](https://codecov.io/gh/felixdittrich92/docTR-Synth-Generator)
4
4
  [![CodeFactor](https://www.codefactor.io/repository/github/felixdittrich92/doctr-synth-generator/badge)](https://www.codefactor.io/repository/github/felixdittrich92/doctr-synth-generator)
5
- [![Pypi](https://img.shields.io/badge/pypi-v0.3.0a0-blue.svg)](https://pypi.org/project/docTR-Synth-Generator/)
5
+ [![Pypi](https://img.shields.io/badge/pypi-v0.4.0a0-blue.svg)](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 come from
117
- [FrequencyWords](https://github.com/hermitdave/FrequencyWords) (~85 languages)
118
- and are cleaned (script filter, length bounds, punctuation removal). Two realism
119
- helpers are on by default: `casing_variant_prob` (0.3) adds Title/UPPERCASE
120
- variants, and `numeric_token_ratio` (0.05) mixes in numbers, dates and prices.
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.
@@ -331,19 +335,16 @@ treat them the same: recognition yields the label string; detection yields
331
335
  from generator.components import GenerationConfig
332
336
  from generator.doctr_dataset import build_detection_datasets, synth_worker_init_fn
333
337
 
334
- cfg = GenerationConfig.flat(
335
- task="detection",
336
- languages=["en", "de"],
337
- num_images=50_000, # POOL size (word variety + vocab coverage)
338
- auto_download_backgrounds=True,
339
- )
338
+ # num_images is the total dataset size; val_percent carves out the val set.
339
+ cfg = GenerationConfig.flat(task="detection", num_images=50_000, val_percent=0.2)
340
340
  train_set, val_set = build_detection_datasets(
341
341
  cfg,
342
- train_samples=args.epochs and 20_000, # virtual epoch length (len(dataset))
343
- val_samples=2_000,
342
+ languages=["german", "english", "french", "italian", "spanish", "malay"], # VOCABS keys or ISO codes
344
343
  use_polygons=args.rotation, # straight boxes unless --rotation
345
- sample_transforms=batch_transforms, # the script's existing transforms
344
+ sample_transforms=sample_transforms, # the script's image+target transforms
345
+ img_transforms=img_transforms, # the script's image-only transforms
346
346
  )
347
+ # len(train_set) == 40_000, len(val_set) == 10_000
347
348
  ```
348
349
 
349
350
  **Recognition** - in `references/recognition/train.py`, replace the
@@ -353,26 +354,29 @@ train_set, val_set = build_detection_datasets(
353
354
  from generator.components import GenerationConfig
354
355
  from generator.doctr_dataset import build_recognition_datasets, synth_worker_init_fn
355
356
 
356
- cfg = GenerationConfig.flat(task="recognition", num_images=100_000)
357
+ cfg = GenerationConfig.flat(task="recognition", num_images=10_000, val_percent=0.2)
357
358
  train_set, val_set = build_recognition_datasets(
358
359
  cfg,
359
- train_samples=50_000,
360
- val_samples=5_000,
361
- vocab=args.vocab, # e.g. ["german", "urdu", "odia"] - the model's vocab
360
+ vocab=args.vocab, # e.g. ["multilingual"] - a VOCABS key / list = the model's vocab
362
361
  img_transforms=img_transforms, # the script's existing resize/aug
363
362
  )
363
+ # len(train_set) == 8_000, len(val_set) == 2_000
364
364
  ```
365
365
 
366
366
  Pass `vocab` the **same vocab you train the model on** - a `VOCABS` key, a
367
367
  literal charset, or a list of keys whose union is the model's vocab (e.g.
368
- `["german", "urdu", "odia"]`). Every generated label is then guaranteed to
369
- contain only characters in that vocab, so docTR's label encoder never hits an
370
- out-of-vocab character (which would otherwise crash training on the first batch).
371
- Corpus words outside the vocab are dropped, character coverage is guaranteed
372
- *within* the vocab, and the corpus languages are derived from the vocab keys
373
- automatically (`german` -> `de`); a key with no corpus (e.g. `odia`) still has
374
- its characters covered via synthesis. Set `config.languages` explicitly to pull
375
- different corpora. The same restriction applies to the offline generator via
368
+ `["multilingual"]` or `["german", "urdu", "odia"]`). Every generated label is
369
+ then guaranteed to contain only characters in that vocab, so docTR's label
370
+ encoder never hits an out-of-vocab character (which would otherwise crash
371
+ training on the first batch). Corpus words outside the vocab are dropped,
372
+ character coverage is guaranteed *within* the vocab (missing characters are
373
+ synthesised so the set stays balanced), and the corpus languages are derived
374
+ from the vocab keys automatically (`german` -> `de`). For detection, pass
375
+ `languages=[...]` (VOCABS keys like `"german"`, `"malay"`, or ISO codes); for
376
+ recognition you can pass `languages=[...]` too. A combined vocab like
377
+ `"multilingual"` maps to no single language, so pass `languages=[...]` if you
378
+ want real multilingual words rather than mostly-synthesised coverage. The same
379
+ restriction applies to the offline generator via
376
380
  `GenerationConfig.flat(target_vocab=[...])`.
377
381
 
378
382
  The `DataLoader` lines stay as they are - just keep
@@ -394,10 +398,11 @@ train_loader = DataLoader(
394
398
 
395
399
  Notes:
396
400
 
397
- - **Pool size vs epoch length.** `config.num_images` sizes the word *pool*
398
- (variety and per-split vocab coverage); `train_samples` / `val_samples` set
399
- the virtual epoch length (`len(dataset)`). Samples are generated fresh, so the
400
- epoch length is just how many iterations you want per epoch.
401
+ - **Dataset size & split.** `num_images` is the total dataset size; `val_percent`
402
+ carves out the validation set, so `len(train_set)` / `len(val_set)` follow
403
+ directly (50k @ 0.2 -> 40k / 10k). Samples are generated fresh on every access,
404
+ so this is effectively the iterations per epoch. Pass `train_samples` /
405
+ `val_samples` only if you want to override the derived sizes.
401
406
  - **Seeding.** The train set draws a fresh random sample on every access (new
402
407
  data every epoch - the whole point of on-the-fly); the val set is a
403
408
  reproducible fixed virtual set (seeded per index) so metrics stay comparable.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: doctr-synth-generator
3
- Version: 0.3.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
  ![Build Status](https://github.com/felixdittrich92/docTR-Synth-Generator/workflows/builds/badge.svg)
251
252
  [![codecov](https://codecov.io/gh/felixdittrich92/docTR-Synth-Generator/graph/badge.svg?token=31MDR20JGI)](https://codecov.io/gh/felixdittrich92/docTR-Synth-Generator)
252
253
  [![CodeFactor](https://www.codefactor.io/repository/github/felixdittrich92/doctr-synth-generator/badge)](https://www.codefactor.io/repository/github/felixdittrich92/doctr-synth-generator)
253
- [![Pypi](https://img.shields.io/badge/pypi-v0.3.0a0-blue.svg)](https://pypi.org/project/docTR-Synth-Generator/)
254
+ [![Pypi](https://img.shields.io/badge/pypi-v0.4.0a0-blue.svg)](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 come from
365
- [FrequencyWords](https://github.com/hermitdave/FrequencyWords) (~85 languages)
366
- and are cleaned (script filter, length bounds, punctuation removal). Two realism
367
- helpers are on by default: `casing_variant_prob` (0.3) adds Title/UPPERCASE
368
- variants, and `numeric_token_ratio` (0.05) mixes in numbers, dates and prices.
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.
@@ -579,19 +584,16 @@ treat them the same: recognition yields the label string; detection yields
579
584
  from generator.components import GenerationConfig
580
585
  from generator.doctr_dataset import build_detection_datasets, synth_worker_init_fn
581
586
 
582
- cfg = GenerationConfig.flat(
583
- task="detection",
584
- languages=["en", "de"],
585
- num_images=50_000, # POOL size (word variety + vocab coverage)
586
- auto_download_backgrounds=True,
587
- )
587
+ # num_images is the total dataset size; val_percent carves out the val set.
588
+ cfg = GenerationConfig.flat(task="detection", num_images=50_000, val_percent=0.2)
588
589
  train_set, val_set = build_detection_datasets(
589
590
  cfg,
590
- train_samples=args.epochs and 20_000, # virtual epoch length (len(dataset))
591
- val_samples=2_000,
591
+ languages=["german", "english", "french", "italian", "spanish", "malay"], # VOCABS keys or ISO codes
592
592
  use_polygons=args.rotation, # straight boxes unless --rotation
593
- sample_transforms=batch_transforms, # the script's existing transforms
593
+ sample_transforms=sample_transforms, # the script's image+target transforms
594
+ img_transforms=img_transforms, # the script's image-only transforms
594
595
  )
596
+ # len(train_set) == 40_000, len(val_set) == 10_000
595
597
  ```
596
598
 
597
599
  **Recognition** - in `references/recognition/train.py`, replace the
@@ -601,26 +603,29 @@ train_set, val_set = build_detection_datasets(
601
603
  from generator.components import GenerationConfig
602
604
  from generator.doctr_dataset import build_recognition_datasets, synth_worker_init_fn
603
605
 
604
- cfg = GenerationConfig.flat(task="recognition", num_images=100_000)
606
+ cfg = GenerationConfig.flat(task="recognition", num_images=10_000, val_percent=0.2)
605
607
  train_set, val_set = build_recognition_datasets(
606
608
  cfg,
607
- train_samples=50_000,
608
- val_samples=5_000,
609
- vocab=args.vocab, # e.g. ["german", "urdu", "odia"] - the model's vocab
609
+ vocab=args.vocab, # e.g. ["multilingual"] - a VOCABS key / list = the model's vocab
610
610
  img_transforms=img_transforms, # the script's existing resize/aug
611
611
  )
612
+ # len(train_set) == 8_000, len(val_set) == 2_000
612
613
  ```
613
614
 
614
615
  Pass `vocab` the **same vocab you train the model on** - a `VOCABS` key, a
615
616
  literal charset, or a list of keys whose union is the model's vocab (e.g.
616
- `["german", "urdu", "odia"]`). Every generated label is then guaranteed to
617
- contain only characters in that vocab, so docTR's label encoder never hits an
618
- out-of-vocab character (which would otherwise crash training on the first batch).
619
- Corpus words outside the vocab are dropped, character coverage is guaranteed
620
- *within* the vocab, and the corpus languages are derived from the vocab keys
621
- automatically (`german` -> `de`); a key with no corpus (e.g. `odia`) still has
622
- its characters covered via synthesis. Set `config.languages` explicitly to pull
623
- different corpora. The same restriction applies to the offline generator via
617
+ `["multilingual"]` or `["german", "urdu", "odia"]`). Every generated label is
618
+ then guaranteed to contain only characters in that vocab, so docTR's label
619
+ encoder never hits an out-of-vocab character (which would otherwise crash
620
+ training on the first batch). Corpus words outside the vocab are dropped,
621
+ character coverage is guaranteed *within* the vocab (missing characters are
622
+ synthesised so the set stays balanced), and the corpus languages are derived
623
+ from the vocab keys automatically (`german` -> `de`). For detection, pass
624
+ `languages=[...]` (VOCABS keys like `"german"`, `"malay"`, or ISO codes); for
625
+ recognition you can pass `languages=[...]` too. A combined vocab like
626
+ `"multilingual"` maps to no single language, so pass `languages=[...]` if you
627
+ want real multilingual words rather than mostly-synthesised coverage. The same
628
+ restriction applies to the offline generator via
624
629
  `GenerationConfig.flat(target_vocab=[...])`.
625
630
 
626
631
  The `DataLoader` lines stay as they are - just keep
@@ -642,10 +647,11 @@ train_loader = DataLoader(
642
647
 
643
648
  Notes:
644
649
 
645
- - **Pool size vs epoch length.** `config.num_images` sizes the word *pool*
646
- (variety and per-split vocab coverage); `train_samples` / `val_samples` set
647
- the virtual epoch length (`len(dataset)`). Samples are generated fresh, so the
648
- epoch length is just how many iterations you want per epoch.
650
+ - **Dataset size & split.** `num_images` is the total dataset size; `val_percent`
651
+ carves out the validation set, so `len(train_set)` / `len(val_set)` follow
652
+ directly (50k @ 0.2 -> 40k / 10k). Samples are generated fresh on every access,
653
+ so this is effectively the iterations per epoch. Pass `train_samples` /
654
+ `val_samples` only if you want to override the derived sizes.
649
655
  - **Seeding.** The train set draws a fresh random sample on every access (new
650
656
  data every epoch - the whole point of on-the-fly); the val set is a
651
657
  reproducible fixed virtual set (seeded per index) so metrics stay comparable.
@@ -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
@@ -1,6 +1,7 @@
1
1
  fonttools<5.0.0,>=4.50.0
2
2
  numpy<3.0.0,>=2.0.0
3
3
  Pillow>=11.0.0
4
+ matplotlib<4.0.0,>=3.7.0
4
5
 
5
6
  [dev]
6
7
  fonttools<5.0.0,>=4.50.0
@@ -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 build_recognition_datasets, synth_worker_init_fn, build_detection_datasets
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
- url = f"{self.source_base_url}/{rel}"
126
- try:
127
- req = urllib.request.Request(url, headers={"User-Agent": "docTR-Synth-Generator"})
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
- except Exception:
138
- continue
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