levossadtchi commited on
Commit
2091236
·
verified ·
1 Parent(s): e6e7051

Add the tracer and the photo route to your own style

Browse files
.gitattributes CHANGED
@@ -38,3 +38,5 @@ examples/demo_authors_hand/page_01.png filter=lfs diff=lfs merge=lfs -text
38
  examples/demo_authors_hand/page_05.png filter=lfs diff=lfs merge=lfs -text
39
  examples/demo_released_weights/page_05.png filter=lfs diff=lfs merge=lfs -text
40
  examples/demo_released_weights/pages.pdf filter=lfs diff=lfs merge=lfs -text
 
 
 
38
  examples/demo_authors_hand/page_05.png filter=lfs diff=lfs merge=lfs -text
39
  examples/demo_released_weights/page_05.png filter=lfs diff=lfs merge=lfs -text
40
  examples/demo_released_weights/pages.pdf filter=lfs diff=lfs merge=lfs -text
41
+ examples/from_scan.png filter=lfs diff=lfs merge=lfs -text
42
+ trace/example_open_lines.png filter=lfs diff=lfs merge=lfs -text
LICENSE-WEIGHTS CHANGED
@@ -1,5 +1,7 @@
1
- The model weights in ckpt_dl/, ckpt_glyph_dn_u2s/ and ckpt_semb3_all/ are licensed under the
2
  Creative Commons Attribution-NonCommercial 4.0 International license (CC BY-NC 4.0):
3
  https://creativecommons.org/licenses/by-nc/4.0/legalcode
4
 
5
- The code in scripts/ and tools/ is licensed under Apache-2.0, see LICENSE.
 
 
 
1
+ The model weights in ckpt_dl/, ckpt_glyph_dn_u2s/, ckpt_semb3_all/ and trace/weights/ are licensed under the
2
  Creative Commons Attribution-NonCommercial 4.0 International license (CC BY-NC 4.0):
3
  https://creativecommons.org/licenses/by-nc/4.0/legalcode
4
 
5
+ Conditions from the tracer's training data, and an open question about ShareAlike, are in trace/TRAINING_DATA.md.
6
+
7
+ The code in scripts/, tools/ and trace/ is licensed under Apache-2.0, see LICENSE.
NOTICE CHANGED
@@ -4,3 +4,6 @@ Copyright 2026 Lev Ossadtchi
4
  MathJax (mathjax-full, installed by npm into tools/mathjax) is Copyright The MathJax Consortium, Apache-2.0.
5
  examples/ref_hwr200.npy is one line of the HWR200 dataset (AntiplagiatCompany/HWR200, Apache-2.0), scan traced to pen strokes.
6
  The style encoder was also trained on traced HWR200 lines.
 
 
 
 
4
  MathJax (mathjax-full, installed by npm into tools/mathjax) is Copyright The MathJax Consortium, Apache-2.0.
5
  examples/ref_hwr200.npy is one line of the HWR200 dataset (AntiplagiatCompany/HWR200, Apache-2.0), scan traced to pen strokes.
6
  The style encoder was also trained on traced HWR200 lines.
7
+ The tracer (trace/) was trained on data credited in trace/TRAINING_DATA.md, including BRUSH, MathWriting, Korean Handwriting Strokes, OUHD-L, Make Me a Hanzi and Google Fonts.
8
+ examples/from_scan.png shows one line of HWR200.
9
+ trace/example_open_lines.png includes a render of Korean Handwriting Strokes by Jonathan Baudanza (hangul.ink), handwriting by Jo YW, CC BY-SA 4.0, and so is under CC BY-SA 4.0; it also shows OUHD-L (CC BY 4.0) and Digital Peter (MIT).
README.md CHANGED
@@ -40,11 +40,38 @@ Tested only on Python 3.14, torch 2.13, Apple M5 Max (MPS), where 11 pages took
40
 
41
  ## Writing in your own hand
42
 
43
- Export one line of your handwriting as pen strokes: 30-50 characters of ordinary prose, as a JSON list of strokes, each a list of `[x, y]` points with y pointing down, in writing order.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
  ```bash
46
  python scripts/make_ref.py my_line.json my_line.npy
47
- REF=/absolute/path/to/my_line.npy python scripts/write_pages.py notes.txt out
48
  ```
49
 
50
  The default reference is one traced line of the open HWR200 dataset.
@@ -81,6 +108,7 @@ The style vector comes from a line-level writer encoder. Fraction bars, radicals
81
  | `ckpt_semb3_all/best.pt` | writer style encoder | 7 MB |
82
  | `ckpt_glyph_dn_u2s/fp16/step050000.pt` | glyph model | 14 MB |
83
  | `ckpt_dl/glyph_cls2.pt` | glyph classifier | 1 MB |
 
84
 
85
  `scripts/` also holds training code. It is research code as it was used, not a clean library, and its comments are partly in Russian. The training data is not included.
86
 
@@ -115,6 +143,7 @@ Style similarity by the writer encoder (cosine to the writer's real line, one re
115
 
116
  - **Generator models:** tablet handwriting of 13 writers who agreed to this use, about 63 000 lines and 86 000 glyphs. Writer names are removed from the weights. The notes themselves are not published.
117
  - **Style encoder:** the same kind of tablet data, plus traced lines of [HWR200](https://huggingface.co/datasets/AntiplagiatCompany/HWR200) (Apache-2.0).
 
118
 
119
  ## Responsible use
120
 
@@ -122,4 +151,4 @@ This is for notes, experiments and research. Do not use it to forge signatures,
122
 
123
  ## License
124
 
125
- Code: Apache-2.0 (`LICENSE`). Weights: CC BY-NC 4.0 (`LICENSE-WEIGHTS`). See `NOTICE` for third-party components.
 
40
 
41
  ## Writing in your own hand
42
 
43
+ You need one line of your handwriting: 30-50 characters of ordinary prose. There are two ways to get it into the models.
44
+
45
+ ### From a photo or scan
46
+
47
+ Crop the photo to **one line** and run it through the [tracer](trace/README.md), which recovers the pen strokes from the image.
48
+
49
+ ```bash
50
+ pip install -r trace/requirements.txt
51
+ python trace/scrawler_trace.py my_line.png --out my_line.json
52
+ python scripts/make_ref.py my_line.json my_line.npy
53
+ REF=$PWD/my_line.npy python scripts/write_pages.py notes.txt out
54
+ ```
55
+
56
+ For a good result:
57
+
58
+ - Crop tightly to one line. Parts of the lines above and below can get into the trace.
59
+ - Use dark pen on light paper. Colour photos, dark backgrounds and low contrast work poorly.
60
+ - Look at the trace before using it: add `--svg my_line.svg` to the tracer command to see the strokes.
61
+
62
+ ![A scan, its trace and new text in that style](examples/from_scan.png)
63
+
64
+ *Top: a real scan on squared paper (HWR200, open data). Middle: the trace. Bottom: new text and formulas in that style. One example, not a measurement.*
65
+
66
+ The tracer weights take 62 MB and have their own licence caveat, see [its training data](trace/TRAINING_DATA.md).
67
+
68
+ ### From tablet strokes
69
+
70
+ If you have the pen strokes already, skip the tracer. Export them as a JSON list of strokes, each a list of `[x, y]` points with y pointing down, in writing order.
71
 
72
  ```bash
73
  python scripts/make_ref.py my_line.json my_line.npy
74
+ REF=$PWD/my_line.npy python scripts/write_pages.py notes.txt out
75
  ```
76
 
77
  The default reference is one traced line of the open HWR200 dataset.
 
108
  | `ckpt_semb3_all/best.pt` | writer style encoder | 7 MB |
109
  | `ckpt_glyph_dn_u2s/fp16/step050000.pt` | glyph model | 14 MB |
110
  | `ckpt_dl/glyph_cls2.pt` | glyph classifier | 1 MB |
111
+ | `trace/weights/` | tracer and ink restorer, optional: only for the photo route | 62 MB |
112
 
113
  `scripts/` also holds training code. It is research code as it was used, not a clean library, and its comments are partly in Russian. The training data is not included.
114
 
 
143
 
144
  - **Generator models:** tablet handwriting of 13 writers who agreed to this use, about 63 000 lines and 86 000 glyphs. Writer names are removed from the weights. The notes themselves are not published.
145
  - **Style encoder:** the same kind of tablet data, plus traced lines of [HWR200](https://huggingface.co/datasets/AntiplagiatCompany/HWR200) (Apache-2.0).
146
+ - **Tracer:** a mix of tablet notes and open sets, some with non-commercial or ShareAlike terms. See [trace/TRAINING_DATA.md](trace/TRAINING_DATA.md), including the open question about ShareAlike.
147
 
148
  ## Responsible use
149
 
 
151
 
152
  ## License
153
 
154
+ Code: Apache-2.0 (`LICENSE`). Weights: CC BY-NC 4.0 (`LICENSE-WEIGHTS`). See `NOTICE` for third-party components. The tracer weights carry further conditions from their training data: [trace/TRAINING_DATA.md](trace/TRAINING_DATA.md).
examples/from_scan.png ADDED

Git LFS Details

  • SHA256: c504365480ef1190ad39f243d1cadee496cb2b4ccbfdcb4a04c1e3cdbf701ed4
  • Pointer size: 131 Bytes
  • Size of remote file: 172 kB
scripts/make_ref.py CHANGED
@@ -1,7 +1,8 @@
1
  # -*- coding: utf-8 -*-
2
  """Your own reference line for write_pages.py: pen strokes of ONE handwritten line -> the [n,3] array the models take as the style
3
  (dx, dy, pen_up; line height = 1, points every 0.05 of it along the pen path, as in training).
4
- input : JSON, a list of strokes, each a list of points [x, y] in any units, y pointing down, in writing order
 
5
  python scripts/make_ref.py my_line.json my_line.npy
6
  then REF=/path/to/my_line.npy python scripts/write_pages.py notes.txt out
7
  Write a line of ordinary prose of 30-50 characters: the style is taken from this one line only."""
@@ -22,4 +23,11 @@ def to_ref(strokes):
22
  a = np.concatenate(out); d = a.copy(); d[1:, :2] = a[1:, :2] - a[:-1, :2]; d[0, :2] = 0
23
  return d.astype(np.float32)
24
  if __name__ == '__main__':
25
- q = to_ref(json.load(open(sys.argv[1]))); np.save(sys.argv[2], q); print(f'{sys.argv[2]}: {len(q)} points, {int(q[:, 2].sum())} strokes')
 
 
 
 
 
 
 
 
1
  # -*- coding: utf-8 -*-
2
  """Your own reference line for write_pages.py: pen strokes of ONE handwritten line -> the [n,3] array the models take as the style
3
  (dx, dy, pen_up; line height = 1, points every 0.05 of it along the pen path, as in training).
4
+ input : JSON, a list of strokes, each a list of points [x, y] in any units, y pointing down, in writing order;
5
+ or the JSON written by trace/scrawler_trace.py (a photo of your line)
6
  python scripts/make_ref.py my_line.json my_line.npy
7
  then REF=/path/to/my_line.npy python scripts/write_pages.py notes.txt out
8
  Write a line of ordinary prose of 30-50 characters: the style is taken from this one line only."""
 
23
  a = np.concatenate(out); d = a.copy(); d[1:, :2] = a[1:, :2] - a[:-1, :2]; d[0, :2] = 0
24
  return d.astype(np.float32)
25
  if __name__ == '__main__':
26
+ J = json.load(open(sys.argv[1]))
27
+ if isinstance(J, dict): # the output of trace/scrawler_trace.py: points [x, y, pen_up, pressure]
28
+ J_, cur = [], []
29
+ for x, y, pen, _ in J['points']:
30
+ cur.append([x, y])
31
+ if pen: J_.append(cur); cur = []
32
+ J = J_ + ([cur] if cur else [])
33
+ q = to_ref(J); np.save(sys.argv[2], q); print(f'{sys.argv[2]}: {len(q)} points, {int(q[:, 2].sum())} strokes')
trace/BENCH_part_A.md ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Tracer benchmark, part A: true pen, lines unseen in training
2
+
3
+ F1 at R = 2 px on a 64 px frame (recall in brackets). Precision is in the JSON reports kept locally. 2026-11-06.
4
+
5
+ | source, lines | look | previous recipe | released | with --erase_neighbours |
6
+ |---|---|---|---|---|
7
+ | all, 2677 | clean | 0.954 (0.935) | **0.960 (0.945)** | 0.941 (0.918) |
8
+ | all, 2677 | scan | 0.938 (0.915) | **0.945 (0.938)** | 0.931 (0.909) |
9
+ | all, 2677 | photo | 0.935 (0.912) | **0.943 (0.938)** | 0.933 (0.914) |
10
+ | English (BRUSH), 600 | clean | 0.981 (0.979) | **0.984 (0.984)** | 0.983 (0.982) |
11
+ | English (BRUSH), 600 | scan | 0.974 (0.968) | **0.974 (0.978)** | 0.976 (0.974) |
12
+ | English (BRUSH), 600 | photo | 0.971 (0.967) | **0.972 (0.977)** | 0.975 (0.975) |
13
+ | Russian tablet prose, 830 | clean | 0.952 (0.922) | **0.955 (0.926)** | 0.943 (0.908) |
14
+ | Russian tablet prose, 830 | scan | 0.936 (0.903) | **0.941 (0.921)** | 0.934 (0.904) |
15
+ | Russian tablet prose, 830 | photo | 0.934 (0.900) | **0.941 (0.920)** | 0.935 (0.905) |
16
+ | Russian tablet math, 300 | clean | 0.961 (0.941) | **0.962 (0.945)** | 0.922 (0.886) |
17
+ | Russian tablet math, 300 | scan | 0.938 (0.912) | **0.947 (0.941)** | 0.920 (0.890) |
18
+ | Russian tablet math, 300 | photo | 0.941 (0.921) | **0.942 (0.943)** | 0.926 (0.904) |
19
+ | MathWriting, 500 | clean | 0.939 (0.915) | **0.945 (0.926)** | 0.891 (0.848) |
20
+ | MathWriting, 500 | scan | 0.910 (0.878) | **0.921 (0.911)** | 0.869 (0.825) |
21
+ | MathWriting, 500 | photo | 0.907 (0.873) | **0.922 (0.918)** | 0.879 (0.842) |
22
+ | Korean, 297 | clean | 0.937 (0.915) | **0.956 (0.947)** | 0.956 (0.947) |
23
+ | Korean, 297 | scan | 0.924 (0.897) | **0.939 (0.934)** | 0.940 (0.931) |
24
+ | Korean, 297 | photo | 0.920 (0.893) | **0.935 (0.933)** | 0.938 (0.932) |
25
+ | Urdu (OUHD-L), 150 | clean | 0.925 (0.928) | **0.942 (0.959)** | 0.941 (0.959) |
26
+ | Urdu (OUHD-L), 150 | scan | 0.927 (0.930) | **0.936 (0.955)** | 0.941 (0.954) |
27
+ | Urdu (OUHD-L), 150 | photo | 0.914 (0.909) | **0.929 (0.949)** | 0.934 (0.944) |
trace/README.md ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Scrawler tracer
2
+
3
+ Image of one handwritten line -> pen trajectory: points, pen lifts, pressure.
4
+
5
+ ![Traced lines on open data: true pen and trace, then traces only](example_open_lines.png)
6
+
7
+ *Colour runs along the pen path. The bottom four lines are the hand of Peter I, where garbage is visible too. This image includes a render of Korean Handwriting Strokes and so is under CC BY-SA 4.0.*
8
+
9
+ **Licence caveat: read [TRAINING_DATA.md](TRAINING_DATA.md) before using the weights.**
10
+
11
+ ## Files
12
+
13
+ | file | what | size |
14
+ |---|---|---|
15
+ | `scrawler_trace.py` | the whole inference, one file, no training imports | 36 KB |
16
+ | `weights/trace8_fp16.pt` | tracer: CNN + 2-layer transformer encoder, autoregressive 6-layer decoder, 23.4M parameters | 46.8 MB |
17
+ | `weights/inkfix1.pt` | ink restorer: U-Net, 7.5M parameters | 15.0 MB |
18
+ | `requirements.txt` | torch, numpy, pillow, opencv-python | |
19
+ | `TRAINING_DATA.md` | training data, its terms and the open ShareAlike question | |
20
+ | `example_open_lines.png` | example on open data only | |
21
+
22
+ Both weight files load with `torch.load(..., weights_only=True)`. They hold only the keys `e` (weights), `step`, `cfg`.
23
+
24
+ ## Run
25
+
26
+ ```bash
27
+ cd trace
28
+ pip install -r requirements.txt
29
+ python scrawler_trace.py line.png --out trace.json --svg trace.svg --seed 0
30
+ ```
31
+
32
+ ```python
33
+ from scrawler_trace import Tracer
34
+ r = Tracer('weights').trace_image(gray_uint8_array, seed=0)
35
+ # r['px'] (n, 2) crop pixels; r['pen'] (n,) 1 = pen lifts after this point; r['pres'] (n,) pressure 0..1
36
+ ```
37
+
38
+ Input is a crop of ONE line, any size. Page segmentation is not included. The tracer samples, so a different seed gives a slightly different trace. On a Mac the benchmark ran at about 3 lines/s in the batched research script; this single-line runner is slower, its speed was not measured separately.
39
+
40
+ ## Recipe
41
+
42
+ Restored frame, rule removal, islands (with the long-thin rule off), tracer per island, guard, second pass over untraced own ink, stroke merge. Removing neighbour-line ink is optional and off by default (`--erase_neighbours`).
43
+
44
+ ## Quality
45
+
46
+ Benchmark: 2677 lines of true pen the tracer never saw in training (English 600, Korean 297, MathWriting 500, Russian tablet prose 830 and math 300, Urdu 150), each rendered in three looks. F1 at R = 2 px on a 64 px frame.
47
+
48
+ | recipe | clean | scan | photo | strokes / true (median) | direction | order (Kendall) |
49
+ |---|---|---|---|---|---|---|
50
+ | **released (second pass, no erase)** | **0.960** | **0.945** | **0.943** | 1.00 / 1.00 / 1.00 | 0.856 / 0.844 / 0.848 | 0.823 / 0.820 / 0.818 |
51
+ | previous recipe | 0.954 | 0.938 | 0.935 | 0.96 / 0.95 / 0.95 | 0.860 / 0.850 / 0.854 | 0.837 / 0.838 / 0.839 |
52
+ | with `--erase_neighbours` | 0.941 | 0.931 | 0.933 | 0.95 / 0.95 / 1.00 | 0.857 / 0.847 / 0.852 | 0.835 / 0.828 / 0.827 |
53
+
54
+ The order column is pulled down by Urdu, written right to left: its strokes are traced in reverse (order about -0.85, direction about 0.55); the second pass costs 0.01-0.02 of order overall (Korean 0.986 -> 0.913 on clean). Do not rely on stroke order where it matters.
55
+
56
+ Against Google InkSight (older comparison, 27.10, previous recipe, InkSight's own protocol): geometry on HierText 0.655 vs 0.645 (Small-i); readable lines, exact match, are worse: HierText 47/100 vs 69, IAM 19/34 vs 23, IMGUR5K 36/93 vs 45. This model is narrow: it is at its best on handwriting close to its training mix and loses on colour photos, dark backgrounds and low contrast.
57
+
58
+ Per source: `BENCH_part_A.md`.
59
+
60
+ ## From a photo of your line to your style
61
+
62
+ ```bash
63
+ python trace/scrawler_trace.py my_line.png --out my_line.json
64
+ python scripts/make_ref.py my_line.json my_line.npy
65
+ REF=$PWD/my_line.npy python scripts/write_pages.py notes.txt out
66
+ ```
67
+
68
+ ## Limits
69
+
70
+ - One line at a time.
71
+ - Stroke order of the second-pass strokes is not the writing order.
72
+ - Colour photos and dark or low-contrast backgrounds: weak, see InkSight above.
73
+ - Picks up parts of the neighbouring lines on tight crops (about 30% of lines in our HWR200 sample). `--erase_neighbours` removes that but also deletes own ink of formulas and of crops holding two lines.
74
+ - Crops cut out as a polygon on pure white: fill the white with the paper grey first, otherwise it traces the polygon edge.
75
+ - Latin and Cyrillic pen handwriting are the best covered; other scripts come mostly from fonts and small sets.
76
+ - Non-commercial, see [TRAINING_DATA.md](TRAINING_DATA.md).
trace/TRAINING_DATA.md ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Training data of the tracer and its terms
2
+
3
+ Checked 2026-11-06 against the licence files in our local copies and the sources' pages. This is an engineer's reading, not legal advice.
4
+
5
+ Licence of this release: code Apache-2.0, weights CC BY-NC 4.0, chosen with the open question below in view.
6
+
7
+ ## trace8 (`weights/trace8_fp16.pt`): data/trace_mix_v1, 220 000 lines
8
+
9
+ | source | share | stated terms | with CC BY-NC 4.0 on the weights |
10
+ |---|---|---|---|
11
+ | our tablet notebooks (data/ink_lines_v6, 13 writers, about 45k lines) | 28% | private, not published; the writers agreed to this use | fine: the data is not published |
12
+ | Google Fonts handwriting: 237 fonts passed our filter, 225 OFL, 12 Apache-2.0 | 22% | OFL / Apache-2.0 | fine |
13
+ | pseudo-script (scripts/pseudo_script.py, our generator) | 16% | ours | fine |
14
+ | BRUSH (Brown), 170 writers | 13% | "may only be used for non-commercial research purposes"; requests a citation of the paper. Says nothing about derived models. Other uses: contact the authors (Prof. James Tompkin) | compatible on NC, but its "research" is narrower than CC BY-NC. Cite it and state the restriction on the card |
15
+ | Make Me a Hanzi medians (graphics.txt) | 8% | Arphic Public License (font licence; requires derivatives of the Font to stay under it) | no conflict seen: weights are not a font. Credit it |
16
+ | MathWriting (Google) | 6% | **CC BY-NC-SA 4.0** | **ShareAlike: conflict if the weights count as based on the data** |
17
+ | korean-handwriting-strokes (hangul.ink, handwriting by Jo YW) | 4% | **CC BY-SA 4.0**. "Use for education, art, research, and products is welcome"; attribution string is given | **ShareAlike: same conflict, and NC is an added restriction** |
18
+ | OUHD-L (Urdu) | 3% | CC BY 4.0 (Zenodo 10.5281/zenodo.20642162), consent covered per its card | fine, with attribution |
19
+
20
+ The text shown in the font and Hanzi lines came from the transcriptions of IAM, RIMES-2011, NorHand-v3, KHATT, CASIA-HWDB2, Korean Handwriting Strokes, OUHD-L and our own labels (scripts/ext_texts.py). Only the words were used, no images. The terms of those transcription sets were **not checked**.
21
+
22
+ ## inkfix1 (`weights/inkfix1.pt`): data/ink_lines_v7
23
+
24
+ Synthetic pairs rendered from our own tablet lines only (65k lines, 14 writers, 3 of them held out). No open dataset and no HWR200 crops (those went into inkfix1r, which is not released).
25
+
26
+ ## The ShareAlike question
27
+
28
+ Creative Commons' AI-training guide says that if models based on SA content are shared publicly, they would need the same licence as the original works. The same guide does not say a trained model is adapted material, so whether SA applies at all is unsettled.
29
+
30
+ If it does apply, there are two consequences:
31
+ - CC BY-NC 4.0 on the weights does not satisfy MathWriting (BY-NC-SA) or the Korean set (BY-SA).
32
+ - No single licence satisfies both, because BY-SA adaptations cannot go under BY-NC-SA. Changing the weights to BY-NC-SA would fix MathWriting only.
33
+
34
+ We publish the weights under CC BY-NC 4.0 and state this openly: the question is not resolved, and we have not asked the rights holders. If you hold rights in one of these sets and object, please open a discussion on this repository.
35
+
36
+ ## Attribution
37
+
38
+ - BRUSH: Atsunobu Kotani, Stefanie Tellex, James Tompkin, "Generating Handwriting via Decoupled Style Descriptors", ECCV 2020; non-commercial research use only.
39
+ - MathWriting: Google LLC, CC BY-NC-SA 4.0.
40
+ - *Korean Handwriting Strokes by Jonathan Baudanza (hangul.ink), handwriting by Jo YW, CC BY-SA 4.0; transcripts partly from Korean Wikipedia (CC BY-SA 4.0).*
41
+ - OUHD-L: Zenodo 10.5281/zenodo.20642162, CC BY 4.0.
42
+ - Make Me a Hanzi (Shaunak Kishore), graphics derived from Arphic PL fonts under the Arphic Public License.
43
+ - Google Fonts handwriting families, OFL / Apache-2.0.
44
+
45
+ Because of BRUSH, treat the tracer weights as non-commercial research use, which is narrower than CC BY-NC.
46
+
47
+ ## Example image
48
+
49
+ `example_open_lines.png` uses only:
50
+ - Korean Handwriting Strokes (CC BY-SA 4.0) and OUHD-L (CC BY 4.0), rendered from the benchmark's held-out lines;
51
+ - Digital Peter (hand of Peter I; the Hugging Face card says MIT; the competition repository is MIT and does not state dataset terms separately). This set is not in the training mix.
52
+
53
+ The image itself is under CC BY-SA 4.0 because of the Korean render.
trace/example_open_lines.png ADDED

Git LFS Details

  • SHA256: 23831b6a674752877bd4da8d70911aacfc7002babdf9eccaf4ba47d0e11a527b
  • Pointer size: 131 Bytes
  • Size of remote file: 526 kB
trace/requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ torch>=2.2
2
+ numpy
3
+ pillow
4
+ opencv-python
trace/scrawler_trace.py ADDED
@@ -0,0 +1,532 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Scrawler tracer: image of ONE handwritten line -> pen trajectory (points, pen lifts, pressure).
3
+
4
+ Pipeline: crop -> 64 px high frame -> ink restorer (U-Net) -> rule removal -> [optional neighbour-line ink removal] -> islands ->
5
+ autoregressive tracer per island (sampling, seeded) -> guard -> second pass over untraced own ink -> stroke merge.
6
+ Known limits: strokes of the second pass are appended at the end of the trace, so the stroke ORDER of that part is not the writing order.
7
+ erase_neighbours=True cuts pick-ups from the lines above/below on tight prose crops, but it also deletes own ink of multi-level layouts
8
+ (fractions, roots, formulas) and costs recall on the benchmark, so it is off by default.
9
+
10
+ Usage: python scrawler_trace.py line.png --out trace.json [--svg trace.svg] [--seed 0] [--erase_neighbours]
11
+ API: tr = Tracer('weights'); r = tr.trace_image(gray_uint8_array) # r['px'] (n,2) in input-crop pixels, r['pen'] (n,) 1 = pen lifts after the point, r['pres'] (n,)
12
+ Needs: torch, numpy, pillow, opencv-python. Device: cuda > mps > cpu."""
13
+ import os, math, json, argparse, numpy as np, torch, torch.nn as nn, torch.nn.functional as F, cv2
14
+ from PIL import Image
15
+
16
+ MAXPTS = 1200; SAMPLE_BIAS = 2.0; PENW = 5.0; PEN_TH = PENW / (1.0 + PENW)
17
+ DERULE = 0.5; SPLIT_LONG = 6; GUARD_W = 1.5; GUARD_K = 6; BRIDGE = 1.5; MERGE = 1.5; MERGE_COS = 0.5; IBS = 48; TRACE_ML_K = 3.0; RES_R = 1.5; RES_MIN = 40
18
+ CORE_FRAC = 0.35; CORE_MIN = 0.15; FLAT_H = 0.3; NB_FAR = 1.2
19
+
20
+ # ---------------------------------------------------------------- model (tracer)
21
+ def strokes_of(pen):
22
+ """pen [N] (1 = pen lifts AFTER this point) -> list of (a,b) inclusive index ranges."""
23
+ N=len(pen); ends=list(np.where(pen>0.5)[0])
24
+ if not ends or ends[-1]!=N-1: ends.append(N-1)
25
+ out=[]; a=0
26
+ for e in ends:
27
+ if e>=a: out.append((a,int(e)))
28
+ a=int(e)+1
29
+ return out
30
+ def norm_img(g):
31
+ """uint8 gray [H,W] (dark ink on light paper) -> float32, paper ~0, ink ~1. Same at train time and on real scans."""
32
+ x=1.0-np.asarray(g,np.float32)/255.0; med=float(np.median(x)); hi=float(np.percentile(x,99.5)); x=(x-med)/max(hi-med,0.15)
33
+ return np.clip(x,-1.0,1.5).astype(np.float32)
34
+ def fourier(p,nf):
35
+ """p [...,2] in image-height units -> [..., 4*nf]; wavelengths 32 .. 0.05 (x spans up to MAXW/IMH = 16)."""
36
+ wl=torch.logspace(math.log10(32.0),math.log10(0.05),nf).to(p.device); a=p[...,:,None].float()*(2*math.pi/wl)
37
+ return torch.cat([a.sin(),a.cos()],-1).flatten(-2)
38
+ def step_pe(t,d):
39
+ """sinusoidal encoding of step indices t [...] -> [..., d]."""
40
+ i=torch.arange(d//2,device=t.device).float(); a=t[...,None].float()/(10000**(2*i/d))
41
+ return torch.cat([a.sin(),a.cos()],-1)
42
+ class Block(nn.Module):
43
+ def __init__(s,ci,co,st):
44
+ super().__init__(); s.c1=nn.Conv2d(ci,co,3,st,1,bias=False); s.n1=nn.GroupNorm(8,co); s.c2=nn.Conv2d(co,co,3,1,1,bias=False); s.n2=nn.GroupNorm(8,co)
45
+ s.sc=nn.Sequential(nn.Conv2d(ci,co,1,st,bias=False),nn.GroupNorm(8,co)) if (st!=1 or ci!=co) else nn.Identity()
46
+ def forward(s,x): return F.relu(s.sc(x)+s.n2(s.c2(F.relu(s.n1(s.c1(x))))))
47
+ class CNN(nn.Module):
48
+ """GroupNorm (no running stats -> EMA of parameters is a complete EMA model). Returns stride-4 and stride-8 maps."""
49
+ def __init__(s,ch):
50
+ super().__init__()
51
+ s.stem=nn.Sequential(nn.Conv2d(1,32,3,1,1,bias=False),nn.GroupNorm(8,32),nn.ReLU(),nn.Conv2d(32,ch,3,2,1,bias=False),nn.GroupNorm(8,ch),nn.ReLU())
52
+ s.l1=nn.Sequential(Block(ch,ch,1),Block(ch,ch,1)); s.l2=nn.Sequential(Block(ch,2*ch,2),Block(2*ch,2*ch,1))
53
+ s.l3=nn.Sequential(Block(2*ch,4*ch,2),Block(4*ch,4*ch,1),Block(4*ch,4*ch,1),Block(4*ch,4*ch,1))
54
+ def forward(s,x): f4=s.l2(s.l1(s.stem(x))); return f4,s.l3(f4)
55
+ class DecLayer(nn.Module):
56
+ def __init__(s,d,h,drop):
57
+ super().__init__(); s.h=h; s.n1=nn.LayerNorm(d); s.qkv=nn.Linear(d,3*d); s.o1=nn.Linear(d,d); s.n2=nn.LayerNorm(d); s.q2=nn.Linear(d,d); s.kv2=nn.Linear(d,2*d); s.o2=nn.Linear(d,d)
58
+ s.n3=nn.LayerNorm(d); s.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)); s.dr=nn.Dropout(drop)
59
+ def mem(s,m):
60
+ Bn,K,d=m.shape; k,v=s.kv2(m).view(Bn,K,2,s.h,d//s.h).permute(2,0,3,1,4); return k,v
61
+ def forward(s,x,mkv,mmask,cache=None):
62
+ Bn,T,d=x.shape; q,k,v=s.qkv(s.n1(x)).view(Bn,T,3,s.h,d//s.h).permute(2,0,3,1,4)
63
+ if cache is not None:
64
+ if 'k' in cache: k=torch.cat([cache['k'],k],2); v=torch.cat([cache['v'],v],2)
65
+ cache['k']=k; cache['v']=v; a=F.scaled_dot_product_attention(q,k,v)
66
+ else: a=F.scaled_dot_product_attention(q,k,v,is_causal=True)
67
+ x=x+s.dr(s.o1(a.transpose(1,2).reshape(Bn,T,d)))
68
+ q2=s.q2(s.n2(x)).view(Bn,T,s.h,d//s.h).transpose(1,2); a2=F.scaled_dot_product_attention(q2,mkv[0],mkv[1],attn_mask=mmask)
69
+ x=x+s.dr(s.o2(a2.transpose(1,2).reshape(Bn,T,d)))
70
+ return x+s.dr(s.ff(s.n3(x)))
71
+ class Model(nn.Module):
72
+ def __init__(s,cfg):
73
+ super().__init__(); s.cfg=dict(cfg); d=cfg['DM']; ch=cfg['CH']; s.nf=cfg['NF']; s.imh=cfg['IMH']; s.M=cfg['M']; s.pres=cfg['PRES']
74
+ s.cnn=CNN(ch); s.proj=nn.Conv2d(4*ch,d,1); s.kpos=nn.Linear(4*s.nf,d)
75
+ s.enc=nn.TransformerEncoder(nn.TransformerEncoderLayer(d,cfg['NH'],4*d,cfg['DROP'],batch_first=True,norm_first=True),cfg['NE'],enable_nested_tensor=False); s.enorm=nn.LayerNorm(d)
76
+ s.gproj=nn.Conv2d(2*ch,cfg['GC'],1); gs=cfg['GSP']; s.register_buffer('goff',torch.tensor([[dx,dy] for dy in (-gs,0,gs) for dx in (-gs,0,gs)],dtype=torch.float32),persistent=False)
77
+ s.inp=nn.Linear(3,d); s.qpos=nn.Linear(4*s.nf,d); s.glin=nn.Linear(9*cfg['GC'],d); s.start=nn.Parameter(torch.randn(d)*0.02)
78
+ s.dec=nn.ModuleList([DecLayer(d,cfg['NH'],cfg['DROP']) for _ in range(cfg['NL'])]); s.dnorm=nn.LayerNorm(d)
79
+ s.head=nn.Linear(d,6*s.M+2+(1 if s.pres else 0)); s.shead=nn.Linear(d,6*s.M)
80
+ def encode(s,img,wc):
81
+ f4,f8=s.cnn(img); m=s.proj(f8); Bn,d,h8,w8=m.shape
82
+ ys,xs=torch.meshgrid(torch.arange(h8,device=img.device),torch.arange(w8,device=img.device),indexing='ij')
83
+ pos=torch.stack([(xs.flatten()+0.5)*8/s.imh,(ys.flatten()+0.5)*8/s.imh],-1)
84
+ m=m.flatten(2).transpose(1,2)+s.kpos(fourier(pos,s.nf))[None]
85
+ valid=(xs.flatten()[None,:]<wc[:,None])
86
+ m=s.enorm(s.enc(m,src_key_padding_mask=~valid))
87
+ return m,valid[:,None,None,:],s.gproj(f4)
88
+ def glimpse(s,g4,Pa):
89
+ Bn,C,h4,w4=g4.shape; px=Pa*s.imh; g=px[:,:,None,:]+s.goff[None,None]
90
+ grid=torch.stack([g[...,0]/(w4*4)*2-1,g[...,1]/(h4*4)*2-1],-1)
91
+ out=F.grid_sample(g4.float(),grid.float(),align_corners=False)
92
+ return out.permute(0,2,3,1).reshape(Bn,Pa.size(1),9*C)
93
+ def embed(s,Xin,Pa,g4,t0=0):
94
+ Bn,T,_=Xin.shape; t=torch.arange(t0,t0+T,device=Xin.device)
95
+ e=s.inp(Xin)+s.qpos(fourier(Pa,s.nf))+s.glin(s.glimpse(g4,Pa).to(Xin.dtype))
96
+ e=torch.where((t==0)[None,:,None],s.start[None,None].to(e.dtype),e)
97
+ return e+step_pe(t,e.size(-1))[None].to(e.dtype)
98
+ def forward(s,img,wc,Xin,Pa):
99
+ m,mm,g4=s.encode(img,wc); h=s.embed(Xin,Pa,g4)
100
+ for L in s.dec: h=L(h,L.mem(m),mm)
101
+ h=s.dnorm(h); return s.head(h),s.shead(h[:,0])
102
+ def mdn_draw(o,M,bias,greedy=False):
103
+ """o [B,6M] -> (dx,dy) [B,2] with the generators' low-temperature bias (pi sharpened by 1+bias, sigma / e^bias)."""
104
+ Bn=o.size(0); ar=torch.arange(Bn,device=o.device)
105
+ pi=F.softmax(o[:,:M]*(1+bias),-1); mu=o[:,M:3*M].view(Bn,M,2); ls=o[:,3*M:5*M].view(Bn,M,2).clamp(-7,5)-bias; rho=torch.tanh(o[:,5*M:6*M])
106
+ k=pi.argmax(-1) if greedy else torch.multinomial(pi,1)[:,0]; m=mu[ar,k]
107
+ if greedy: return m
108
+ sd=ls[ar,k].exp(); r=rho[ar,k]; e1=torch.randn(Bn,device=o.device); e2=torch.randn(Bn,device=o.device)
109
+ return torch.stack([m[:,0]+sd[:,0]*e1,m[:,1]+sd[:,1]*(r*e1+torch.sqrt(1-r**2)*e2)],-1)
110
+ @torch.no_grad()
111
+ def trace(model,img,wc,bias=SAMPLE_BIAS,maxlen=MAXPTS,greedy=False,pen_th=PEN_TH):
112
+ """img [B,1,H,W] normalised (norm_img), wc [B] valid stride-8 columns -> list of dict(absu (n,2) image units, pen (n,), pres (n,)|None)."""
113
+ was=model.training; model.eval(); dv=img.device; Bn=img.size(0); M_=model.M; SC=model.cfg['SCALE']
114
+ m,mm,g4=model.encode(img,wc); mkv=[L.mem(m) for L in model.dec]; caches=[{} for _ in model.dec]
115
+ def run(xin,pa,t):
116
+ h=model.embed(xin,pa,g4,t)
117
+ for L,kv,c in zip(model.dec,mkv,caches): h=L(h,kv,mm,c)
118
+ h=model.dnorm(h); return model.head(h)[:,-1],h[:,-1]
119
+ o,h0=run(torch.zeros(Bn,1,3,device=dv),torch.zeros(Bn,1,2,device=dv),0)
120
+ p=mdn_draw(model.shead(h0[:,None])[:,0],M_,bias,greedy)
121
+ pts=[p]; pens=[(torch.sigmoid(o[:,6*M_])>pen_th).float()]; prs=[torch.sigmoid(o[:,6*M_+2])] if model.pres else None
122
+ done=torch.sigmoid(o[:,6*M_+1])>pen_th; stop=torch.where(done,torch.ones(Bn,dtype=torch.long,device=dv),torch.zeros(Bn,dtype=torch.long,device=dv))
123
+ prev=torch.zeros(Bn,2,device=dv)
124
+ for t in range(1,maxlen):
125
+ if bool(done.all()): break
126
+ xin=torch.cat([prev*SC,pens[-1][:,None]],-1)[:,None]
127
+ o,_=run(xin,pts[-1][:,None],t)
128
+ dl=mdn_draw(o,M_,bias,greedy)/SC; p=pts[-1]+dl; prev=dl
129
+ pens.append((torch.sigmoid(o[:,6*M_])>pen_th).float()); pts.append(p)
130
+ if prs is not None: prs.append(torch.sigmoid(o[:,6*M_+2]))
131
+ eos=(torch.sigmoid(o[:,6*M_+1])>pen_th)&~done; stop[eos]=t+1; done=done|eos
132
+ stop[stop==0]=len(pts)
133
+ P=torch.stack(pts,1).float().cpu().numpy(); Pn=torch.stack(pens,1).cpu().numpy(); Pr=torch.stack(prs,1).float().cpu().numpy() if prs is not None else None
134
+ if was: model.train()
135
+ out=[]
136
+ for b in range(Bn):
137
+ n=int(stop[b]); pn=Pn[b,:n].copy(); pn[-1]=1; out.append(dict(absu=P[b,:n],pen=pn,pres=(Pr[b,:n] if Pr is not None else None)))
138
+ return out
139
+
140
+ # ---------------------------------------------------------------- ink restorer
141
+ class Blk(nn.Module):
142
+ def __init__(s,c,g=8):
143
+ super().__init__(); s.n1=nn.GroupNorm(g,c); s.c1=nn.Conv2d(c,c,3,padding=1); s.n2=nn.GroupNorm(g,c); s.c2=nn.Conv2d(c,c,3,padding=1)
144
+ def forward(s,x): h=s.c1(F.silu(s.n1(x))); h=s.c2(F.silu(s.n2(h))); return x+h
145
+ class UNet(nn.Module):
146
+ def __init__(s,ch=32,nblk=2):
147
+ super().__init__(); C=[ch,2*ch,4*ch,8*ch]; s.cfg=dict(ch=ch,nblk=nblk)
148
+ s.stem=nn.Conv2d(1,C[0],3,padding=1)
149
+ s.enc=nn.ModuleList([nn.Sequential(*[Blk(c) for _ in range(nblk)]) for c in C])
150
+ s.down=nn.ModuleList([nn.Conv2d(C[i],C[i+1],3,stride=2,padding=1) for i in range(3)])
151
+ s.mid=nn.Sequential(Blk(C[3]),nn.Conv2d(C[3],C[3],3,padding=2,dilation=2),nn.SiLU(),Blk(C[3]))
152
+ s.up=nn.ModuleList([nn.ConvTranspose2d(C[i+1],C[i],2,stride=2) for i in range(3)])
153
+ s.fuse=nn.ModuleList([nn.Conv2d(2*C[i],C[i],1) for i in range(3)])
154
+ s.dec=nn.ModuleList([nn.Sequential(*[Blk(c) for _ in range(nblk)]) for c in C[:3]])
155
+ s.head=nn.Sequential(nn.GroupNorm(8,C[0]),nn.SiLU(),nn.Conv2d(C[0],1,3,padding=1))
156
+ def forward(s,x):
157
+ h=s.stem(x); skips=[]
158
+ for i in range(3): h=s.enc[i](h); skips.append(h); h=s.down[i](h)
159
+ h=s.enc[3](h); h=s.mid(h)
160
+ for i in (2,1,0): h=s.up[i](h); h=s.fuse[i](torch.cat([h,skips[i]],1)); h=s.dec[i](h)
161
+ return s.head(h)
162
+
163
+ # ---------------------------------------------------------------- image helpers
164
+ def dilate(mask,r):
165
+ from PIL import Image, ImageFilter
166
+ if r<1: return mask
167
+ return np.asarray(Image.fromarray(mask.astype(np.uint8)*255,'L').filter(ImageFilter.MaxFilter(2*int(r)+1)))>127
168
+ def skeletonize(mask):
169
+ """Zhang-Suen thinning, numpy."""
170
+ m=np.pad(mask.astype(np.uint8),1)
171
+ while True:
172
+ changed=False
173
+ for it in (0,1):
174
+ P2=m[:-2,1:-1];P3=m[:-2,2:];P4=m[1:-1,2:];P5=m[2:,2:];P6=m[2:,1:-1];P7=m[2:,:-2];P8=m[1:-1,:-2];P9=m[:-2,:-2]
175
+ nb=[P2,P3,P4,P5,P6,P7,P8,P9]; Bc=sum(x.astype(np.int32) for x in nb); seq=nb+[P2]
176
+ A=sum(((seq[k]==0)&(seq[k+1]==1)).astype(np.int32) for k in range(8))
177
+ cond=((P2*P4*P6)==0)&((P4*P6*P8)==0) if it==0 else ((P2*P4*P8)==0)&((P2*P6*P8)==0)
178
+ rm=(m[1:-1,1:-1]==1)&(Bc>=2)&(Bc<=6)&(A==1)&cond
179
+ if rm.any(): m[1:-1,1:-1][rm]=0; changed=True
180
+ if not changed: break
181
+ return m[1:-1,1:-1].astype(bool)
182
+ def skel_len(sk):
183
+ p=np.pad(sk.astype(np.uint8),1); c=p[1:-1,1:-1]; R=p[1:-1,2:]; L=p[1:-1,:-2]; Dn=p[2:,1:-1]; DR=p[2:,2:]; DL=p[2:,:-2]
184
+ return float((c&R).sum()+(c&Dn).sum()+math.sqrt(2)*((c&DR&(1-R)&(1-Dn)).sum()+(c&DL&(1-L)&(1-Dn)).sum()))
185
+ def to_input(crop,imh,maxw):
186
+ from PIL import Image
187
+ h,w=crop.shape; W=max(8,int(round(w*imh/h))); im=Image.fromarray(crop,'L')
188
+ if W<=maxw: return np.asarray(im.resize((W,imh),Image.BILINEAR))
189
+ H2=max(8,int(round(h*maxw/w))); small=np.asarray(im.resize((maxw,H2),Image.BILINEAR)); g=np.full((imh,maxw),int(np.median(crop)),np.uint8); y=(imh-H2)//2; g[y:y+H2]=small; return g
190
+ def _runlen(B,axis):
191
+ """length of the run of ink each pixel belongs to, along axis 0 (vertical runs) or 1 (horizontal runs)."""
192
+ A=(B if axis==0 else B.T).astype(np.int32); H=A.shape[0]; up=np.zeros(A.shape,np.int32); dn=np.zeros(A.shape,np.int32)
193
+ for y in range(H): up[y]=(up[y-1]+1)*A[y] if y else A[y]
194
+ for y in range(H-1,-1,-1): dn[y]=(dn[y+1]+1)*A[y] if y<H-1 else A[y]
195
+ r=(up+dn-1)*A; return r if axis==0 else r.T
196
+ def _shear(Tm,off):
197
+ """S[i,j] = Tm[i+off[j], j] (0 outside)."""
198
+ n=Tm.shape[0]; S=np.zeros_like(Tm)
199
+ for o in np.unique(off):
200
+ m=np.where(off==o)[0]; src=np.arange(n)+o; ok=(src>=0)&(src<n); S[np.ix_(np.where(ok)[0],m)]=Tm[np.ix_(src[ok],m)]
201
+ return S
202
+ def rule_mask_full(G,N,hsharp=0.2,gapmin=0.5,vsharp=0.3,vcov=0.8,maxth=3,d=3):
203
+ """ruled / grid lines over the WHOLE line frame, found on the GREY image: a faint rule mostly vanishes in the
204
+ binarised mask, but the tracer sees the grey crop and follows it (the binarised rule was
205
+ 3% of the line, the traced one ran along all of it). N = norm_img(frame) (paper 0, ink 1), G = binarised ink {0,1}.
206
+ Horizontal: for slopes in +-0.04 shear N so that a line of that slope is a row; row profile = MEDIAN over columns (text covers
207
+ < half of the columns of any row, a rule all of them); candidate = sharp peak prof[y] - max(prof[y-d], prof[y+d]) >= hsharp;
208
+ accepted only if it is dark (>0.2) in >= gapmin of the WORD-GAP columns (no ink away from the band): a dense cursive baseline
209
+ makes a peak too, but is paper in the gaps. Band = rows around the peak with sharpness >= 0.4 peak (<= 2 px each side).
210
+ Vertical (grid, margin, page edge): the same on columns, slopes +-0.08, peak >= vsharp AND dark (>0.2) over >= vcov of the height.
211
+ Mask = band pixels EXCEPT letter ink crossing the line (binarised pixels whose run across the line is > maxth+1 px).
212
+ -> (mask bool [H,W] = pixels to repaint as paper, info dict(h=[(row,slope,sharp,gapfrac)], v=[...]))."""
213
+ G=(np.asarray(G)>0).astype(np.uint8); N=np.asarray(N,np.float32); H,W=G.shape; out=np.zeros((H,W),bool); info=dict(h=[],v=[])
214
+ def peaks(M,slopes,thr):
215
+ n,length=M.shape; best=None; pos=np.arange(length)
216
+ for sl in slopes:
217
+ off=np.round(sl*(pos-0.5*length)).astype(int); prof=np.median(_shear(M,off),axis=1)
218
+ pp=np.pad(prof,d,mode='edge'); sh=prof-np.maximum(pp[:-2*d],pp[2*d:])
219
+ if best is None or sh.max()>best[0]: best=(float(sh.max()),float(sl),sh,off)
220
+ if best is None or best[0]<thr: return [],None,None
221
+ _,sl,sh,off=best; rows=[]
222
+ for y in np.argsort(sh)[::-1]:
223
+ if sh[y]<thr: break
224
+ if all(abs(int(y)-r)>2 for r,_,_,_,_ in rows):
225
+ a=int(y); b=int(y)
226
+ while a-1>=0 and a>y-2 and sh[a-1]>=0.4*sh[y]: a-=1
227
+ while b+1<n and b<y+2 and sh[b+1]>=0.4*sh[y]: b+=1
228
+ rows.append((int(y),a,b,sl,float(sh[y])))
229
+ return rows,off,sh
230
+ hr,off,_=peaks(N,np.linspace(-0.04,0.04,17),hsharp)
231
+ if hr:
232
+ Gs=_shear(G,off); Ns=_shear(N,off); letter=(_runlen(G,0)>maxth+1)&(G>0)
233
+ cols=np.where(G.any(0))[0]; x0,x1=(int(cols[0]),int(cols[-1])) if len(cols) else (0,W-1)
234
+ for y0,a,b,sl,shp in hr:
235
+ outside=Gs.copy(); outside[max(0,a-2):min(H,b+3)]=0; empty=np.where(~outside.any(0))[0]; empty=empty[(empty>=x0)&(empty<=x1)]
236
+ if len(empty)<8:
237
+ gapfrac=float('nan')
238
+ if shp<2*hsharp: continue
239
+ else:
240
+ gapfrac=float((Ns[a:b+1,empty].max(0)>0.2).mean())
241
+ if gapfrac<gapmin: continue
242
+ for x in range(W):
243
+ ys=np.arange(a,b+1)+off[x]; ys=ys[(ys>=0)&(ys<H)]; out[ys,x]|=~letter[ys,x]
244
+ info['h'].append((y0,round(sl,3),round(shp,2),round(gapfrac,2)))
245
+ vr,offv,_=peaks(np.ascontiguousarray(N.T),np.linspace(-0.08,0.08,17),vsharp)
246
+ if vr:
247
+ NT=np.ascontiguousarray(N.T); letter=(_runlen(G,1)>maxth+1)&(G>0)
248
+ for x0,a,b,sl,shp in vr:
249
+ dark=np.zeros(H,bool); xs_all=[]
250
+ for y in range(H):
251
+ xs=np.arange(a,b+1)+offv[y]; xs=xs[(xs>=0)&(xs<W)]; xs_all.append(xs); dark[y]=(NT[xs,y]>0.2).any() if len(xs) else False
252
+ if dark.mean()<vcov: continue
253
+ for y,xs in enumerate(xs_all): out[y,xs]|=~letter[y,xs]
254
+ info['v'].append((x0,round(sl,3),round(shp,2)))
255
+ return out,info
256
+ def clean_rules(L):
257
+ """repaint the detected rule / grid pixels of the grey frame L with the local paper level (median of the frame)."""
258
+ N=norm_img(L); m,info=rule_mask_full(N>0.5,N)
259
+ if not m.any(): return L,info
260
+ L2=L.copy(); L2[m]=int(np.median(L)); return L2,info
261
+ def split_long_units(units,ink,nx):
262
+ """islands wider than nx x-heights (long solid words: the decoder ends early or loses its way on them) are cut into
263
+ pieces <= nx x-heights at the THINNEST column (fewest ink pixels) in the last 40% of each piece; each piece is traced on its own
264
+ (the neighbour piece is painted out like any other island) and --merge_cross glues the strokes back across the cut.
265
+ x-height = FWHM of the row profile of the kept ink."""
266
+ if nx<=0 or not units: return units
267
+ r=np.convolve(ink.sum(1).astype(np.float64),np.ones(3)/3,'same')
268
+ if r.max()<=0: return units
269
+ k=int(r.argmax()); lo=hi=k
270
+ while lo>0 and r[lo-1]>=0.5*r[k]: lo-=1
271
+ while hi<len(r)-1 and r[hi+1]>=0.5*r[k]: hi+=1
272
+ xh=float(np.clip(hi-lo+1,4,0.6*ink.shape[0])); Lmax=nx*xh; out=[]
273
+ for u in units:
274
+ if u['x1']-u['x0']<=Lmax: out.append(u); continue
275
+ m=u['mask']; col=m.sum(0); cuts=[u['x0']]; s=u['x0']
276
+ while u['x1']-s>Lmax:
277
+ a=int(s+0.6*Lmax); b=int(min(u['x1']-0.3*Lmax,s+Lmax))
278
+ if b<=a: break
279
+ seg=col[a:b+1]; c=a+int(np.flatnonzero(seg==seg.min())[-1]); cuts.append(c); s=c
280
+ cuts.append(u['x1'])
281
+ for c0,c1 in zip(cuts[:-1],cuts[1:]):
282
+ pm=np.zeros_like(m); pm[:,c0:c1]=m[:,c0:c1]
283
+ if not pm.any(): continue
284
+ ys,xs=np.nonzero(pm); out.append(dict(x0=int(xs.min()),x1=int(xs.max())+1,y0=int(ys.min()),y1=int(ys.max())+1,mask=pm,split=True))
285
+ out.sort(key=lambda v:(v['x0'],v['x1']))
286
+ return out
287
+ def find_islands(L,bridge=0.0):
288
+ """L uint8 line frame, height imh. Binarise as the metric does (norm_img > 0.5), drop non-ink (thick blobs, rules, page
289
+ edges, specks; logic of hwr_pages.clean_components), merge x-overlapping components (parts of one letter) and glue small
290
+ pieces (dots, ticks) to a neighbour closer than 0.15 line height. -> (units: list of dict(x0,x1,y0,y1,mask) left->right,
291
+ ink mask kept, dropped mask, line height hb)."""
292
+ import cv2
293
+ G=(norm_img(L)>0.5).astype(np.uint8); H,W=G.shape; hb=H/1.3
294
+ r=int(max(3,round(0.2*hb))); thick=cv2.morphologyEx(G,cv2.MORPH_OPEN,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(2*r+1,2*r+1)))
295
+ drop=np.zeros_like(G)
296
+ if thick.any():
297
+ nb,lb,sb,_=cv2.connectedComponentsWithStats(thick,8)
298
+ for i in range(1,nb):
299
+ if sb[i,cv2.CC_STAT_AREA]>=(0.3*hb)**2: drop[lb==i]=1
300
+ if drop.any(): drop=cv2.dilate(drop,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)))&G
301
+ if DERULE>0:
302
+ Lh=max(8,int(round(DERULE*hb))); Lv=max(8,int(round(1.1*hb)))
303
+ rl=cv2.morphologyEx(G,cv2.MORPH_OPEN,cv2.getStructuringElement(cv2.MORPH_RECT,(Lh,1)))|cv2.morphologyEx(G,cv2.MORPH_OPEN,cv2.getStructuringElement(cv2.MORPH_RECT,(1,Lv)))
304
+ drop|=rl
305
+ ink=G&(1-drop); n,lab,st,_=cv2.connectedComponentsWithStats(ink,8)
306
+ a=st[:,cv2.CC_STAT_AREA].astype(np.float64); x=st[:,0]; y=st[:,1]; w=st[:,2]; h=st[:,3]
307
+ speck=a<4
308
+ linear=((w>0.4*W)&(h<0.25*hb))|((h>=0.85*H)&(w<0.12*H)&(y<=1)&(y+h>=H-1))
309
+ bad=speck|linear; bad[0]=True
310
+ for i in np.where(bad[1:])[0]+1:
311
+ if not speck[i]: drop[lab==i]=1
312
+ keep=[i for i in range(1,n) if not bad[i]]
313
+ par={i:i for i in keep}
314
+ if bridge>0 and len(keep)>1:
315
+ r=max(1,int(math.ceil(bridge/2))); km=np.isin(lab,keep).astype(np.uint8)
316
+ _,ld=cv2.connectedComponents(cv2.dilate(km,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(2*r+1,2*r+1))),connectivity=8); first={}
317
+ for i in keep:
318
+ yy,xx=np.nonzero(lab==i); gid=int(ld[yy[0],xx[0]])
319
+ if gid in first: par[i]=first[gid]
320
+ else: first[gid]=i
321
+ def f(i):
322
+ while par[i]!=i: par[i]=par[par[i]]; i=par[i]
323
+ return i
324
+ def box(gr):
325
+ return min(x[i] for i in gr),max(x[i]+w[i] for i in gr),min(y[i] for i in gr),max(y[i]+h[i] for i in gr),sum(a[i] for i in gr)
326
+ for _ in range(4):
327
+ groups={}
328
+ for i in keep: groups.setdefault(f(i),[]).append(i)
329
+ B={g:box(v) for g,v in groups.items()}; gs=sorted(B,key=lambda g:B[g][0]); changed=False
330
+ for ii,g1 in enumerate(gs):
331
+ for g2 in gs[ii+1:]:
332
+ a1,b1=B[g1][:2]; a2,b2=B[g2][:2]
333
+ if a2>=b1: break
334
+ ov=min(b1,b2)-max(a1,a2)
335
+ if ov>=0.3*min(b1-a1,b2-a2) and f(g1)!=f(g2): par[f(g2)]=f(g1); changed=True
336
+ groups={}
337
+ for i in keep: groups.setdefault(f(i),[]).append(i)
338
+ B={g:box(v) for g,v in groups.items()}
339
+ for g,(x0,x1,y0,y1,ar) in B.items():
340
+ if max(x1-x0,y1-y0)>=0.25*hb: continue
341
+ best=None
342
+ for g2,(u0,u1,v0,v1,_) in B.items():
343
+ if f(g2)==f(g): continue
344
+ dx=max(0,u0-x1,x0-u1); dy=max(0,v0-y1,y0-v1); d=math.hypot(dx,dy)
345
+ if d<0.15*hb and (best is None or d<best[0]): best=(d,g2)
346
+ if best is not None: par[f(g)]=f(best[1]); changed=True
347
+ if not changed: break
348
+ groups={}
349
+ for i in keep: groups.setdefault(f(i),[]).append(i)
350
+ units=[]
351
+ for g,v in groups.items():
352
+ x0,x1,y0,y1,_=box(v); m=np.isin(lab,v); units.append(dict(x0=int(x0),x1=int(x1),y0=int(y0),y1=int(y1),mask=m))
353
+ units.sort(key=lambda u:(u['x0'],u['x1']))
354
+ return units,ink.astype(bool),drop.astype(bool),hb
355
+ def guard(px,pen,dist,thr,k):
356
+ """pen-down runs of >= k points farther than thr px from the island ink: pen up before the run, run dropped.
357
+ -> (kept index array, new pen)."""
358
+ H,W=dist.shape; xi=np.clip(np.round(px[:,0]).astype(int),0,W-1); yi=np.clip(np.round(px[:,1]).astype(int),0,H-1)
359
+ inside=(px[:,0]>=0)&(px[:,0]<W)&(px[:,1]>=0)&(px[:,1]<H); off=~inside|(dist[yi,xi]>thr)
360
+ keep=np.ones(len(px),bool); newpen=pen.copy()
361
+ if k<=0: return np.arange(len(px)),newpen
362
+ for a,b in strokes_of(pen):
363
+ if b-a+1<k: continue
364
+ t=a
365
+ while t<=b:
366
+ if off[t]:
367
+ u=t
368
+ while u+1<=b and off[u+1]: u+=1
369
+ if u-t+1>=k:
370
+ keep[t:u+1]=False
371
+ if t>a: newpen[t-1]=1
372
+ if u==b and t>a: newpen[t-1]=1
373
+ t=u+1
374
+ else: t+=1
375
+ idx=np.where(keep)[0]; p2=newpen[idx]
376
+ if len(p2): p2[-1]=1
377
+ return idx,p2
378
+ def merge_strokes(px,pen,uid,w,k=1.5,cmin=0.5,cross=False):
379
+ """a stroke torn by a break in the ink -> one stroke. Consecutive strokes A,B of the SAME island are glued (pen stays down over
380
+ the jump) when |B0 - A_end| < k*w and the directions agree: cos(tangent at A's end, tangent at B's start) > cmin and, unless the
381
+ jump is shorter than 0.5 w, cos(A's end tangent, jump) > cmin. Tangents over ~1.5 w of path. -> (new pen, number of glued joints)."""
382
+ pen=pen.copy(); ab=strokes_of(pen); n=0
383
+ def tang(q,end):
384
+ if len(q)<2: return None
385
+ seg=np.hypot(*np.diff(q,axis=0).T); c=np.concatenate([[0],np.cumsum(seg)]); L=c[-1]
386
+ if L<1e-6: return None
387
+ if end: j=int(np.searchsorted(c,max(0.0,L-1.5*w))); v=q[-1]-q[min(j,len(q)-2)]
388
+ else: j=int(np.searchsorted(c,min(L,1.5*w))); v=q[min(max(j,1),len(q)-1)]-q[0]
389
+ nv=float(np.hypot(*v)); return v/nv if nv>1e-6 else None
390
+ for (a1,b1),(a2,b2) in zip(ab[:-1],ab[1:]):
391
+ if uid[b1]!=uid[a2] and not cross: continue
392
+ jump=px[a2]-px[b1]; d=float(np.hypot(*jump))
393
+ if d>=k*w: continue
394
+ t1=tang(px[a1:b1+1],True); t2=tang(px[a2:b2+1],False)
395
+ if t1 is None or t2 is None or float(t1@t2)<=cmin: continue
396
+ if d>=0.5*w and float(t1@(jump/d))<=cmin: continue
397
+ pen[b1]=0; n+=1
398
+ pen[-1]=1
399
+ return pen,n
400
+
401
+ # ---------------------------------------------------------------- own line / neighbour ink
402
+ def _core(G):
403
+ H = G.shape[0]; prof = G.sum(1).astype(float)
404
+ a0, b0 = H // 4, 3 * H // 4; m = a0 + int(np.argmax(prof[a0:b0])); thr = CORE_FRAC * max(prof[m], 1.0); a = b = m
405
+ while a > 0 and prof[a - 1] >= thr: a -= 1
406
+ while b < H - 1 and prof[b + 1] >= thr: b += 1
407
+ return a, b
408
+ def own_mask(x, derule=False):
409
+ """derule rule-remnant pixels (rule_px) are taken out BEFORE the core band and the components — an underline is the densest
410
+ row (it pulled the band onto itself) and it fuses the words it crosses with the neighbour lines' ink."""
411
+ import cv2
412
+ G = norm_img(x) > 0.5; H, W = G.shape; a, b = _core(G)
413
+ if derule: G = G & ~rule_px(G, (a, b)); a, b = _core(G)
414
+ n, lab, st, _ = cv2.connectedComponentsWithStats(G.astype(np.uint8), connectivity=8)
415
+ inb = np.bincount(lab[a:b + 1].ravel(), minlength=n); tot = st[:, cv2.CC_STAT_AREA]
416
+ keep = (inb >= CORE_MIN * tot) & (st[:, cv2.CC_STAT_HEIGHT] >= max(3, FLAT_H * (b - a + 1))); keep[0] = False
417
+ return keep[lab], (a, b), lab, keep
418
+ def rule_px(G, core):
419
+ """01.11: pixels of thin near-horizontal runs (rule remnants, often fused with the letters they cross): opening with thin line kernels
420
+ of length max(24, 2.2 x core height) at -4..4 deg, minus parts thicker than 0.35 x core height (bold bars), dilated 1 px vertically."""
421
+ import cv2
422
+ hc = core[1] - core[0] + 1; L = max(24, int(2.2 * hc)); g = G.astype(np.uint8); oh = np.zeros_like(g)
423
+ for ang in (-4, -2, 0, 2, 4):
424
+ dy = int(round(np.tan(np.radians(ang)) * L / 2)); k = np.zeros((2 * abs(dy) + 1, L), np.uint8); cv2.line(k, (0, abs(dy) - dy), (L - 1, abs(dy) + dy), 1, 1)
425
+ oh |= cv2.morphologyEx(g, cv2.MORPH_OPEN, k)
426
+ thick = cv2.morphologyEx(oh, cv2.MORPH_OPEN, np.ones((max(3, int(0.35 * hc)), 1), np.uint8))
427
+ return cv2.dilate((oh & (1 - thick)), np.ones((3, 1), np.uint8)) > 0
428
+ def neighbour_mask(G, own, core, lab, rule=None):
429
+ """Ink of the NEIGHBOUR lines = not-own components (rule pixels aside) that touch the
430
+ top/bottom frame edge (a line cut by the crop) or whose centre lies more than NB_FAR core heights beyond the core band; small marks
431
+ near the band (commas, dots, accents, dashes) stay as they are (neither own nor neighbour)."""
432
+ import cv2
433
+ H, W = G.shape; a, b = core; hc = b - a + 1; oth = G & ~own & (~rule if rule is not None else True)
434
+ n, lb, st, cen = cv2.connectedComponentsWithStats(oth.astype(np.uint8), connectivity=8); nb = np.zeros(n, bool)
435
+ for c in range(1, n):
436
+ y0 = st[c, cv2.CC_STAT_TOP]; y1 = y0 + st[c, cv2.CC_STAT_HEIGHT] - 1; cy = cen[c, 1]
437
+ nb[c] = y0 <= 0 or y1 >= H - 1 or cy < a - NB_FAR * hc or cy > b + NB_FAR * hc
438
+ return nb[lb]
439
+
440
+ # ---------------------------------------------------------------- the line tracer
441
+ @torch.no_grad()
442
+ def restore(model, L, bs=16):
443
+ """uint8 line frame (height 64) -> restored uint8 frame (paper 255, ink 0 = 255*(1-p))."""
444
+ dev = next(model.parameters()).device; Wm = int(math.ceil(L.shape[1] / 8) * 8); x = np.zeros((1, 1, L.shape[0], Wm), np.float32); x[0, 0, :, :L.shape[1]] = norm_img(L)
445
+ p = torch.sigmoid(model(torch.from_numpy(x).to(dev)).float()).cpu().numpy()
446
+ return np.clip(np.round(255 * (1 - p[0, 0, :, :L.shape[1]])), 0, 255).astype(np.uint8)
447
+ def _erase_neighbours(L, paper):
448
+ G_ = norm_img(L) > 0.5; o_, c_, lb_, _k = own_mask(L, derule=True); r_ = rule_px(G_, c_) & G_; o_ = o_ & ~r_; nb_ = neighbour_mask(G_, o_, c_, lb_, r_)
449
+ nb_ = cv2.dilate(nb_.astype(np.uint8), np.ones((3, 3), np.uint8)) > 0; nb_ &= ~cv2.dilate(o_.astype(np.uint8), np.ones((3, 3), np.uint8)).astype(bool); L = L.copy(); L[nb_] = paper
450
+ return L
451
+ def trace_frame(model, L, residual_pass=False, erase_neighbours=False):
452
+ """L restored line frame (height 64, any width) -> dict(px (n,2) frame px, pen, pres, uid, w)."""
453
+ dv = next(model.parameters()).device; L, _ = clean_rules(L); imh = model.cfg['IMH']; H, W = L.shape; paper = int(np.median(L))
454
+ if erase_neighbours and not residual_pass: L = _erase_neighbours(L, paper)
455
+ G0 = norm_img(L) > 0.5; wb = float(np.clip(G0.sum() / max(skel_len(skeletonize(G0)), 1.0), 1.0, 8.0)); units, ink, drop, hb = find_islands(L, BRIDGE * wb)
456
+ units = split_long_units(units, ink, SPLIT_LONG)
457
+ sk = skeletonize(ink); w = float(np.clip(ink.sum() / max(skel_len(sk), 1.0), 1.0, 8.0))
458
+ if not units: return dict(px=np.zeros((1, 2), np.float32), pen=np.ones(1), pres=np.full(1, 0.5, np.float32), uid=np.zeros(1, int), w=w)
459
+ allm = np.zeros((H, W), np.uint8)
460
+ for u in units: allm |= u['mask'].astype(np.uint8)
461
+ k3 = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)); dropd = cv2.dilate(drop.astype(np.uint8), k3).astype(bool)
462
+ m = int(round(0.25 * imh)); wins = []
463
+ for u in units:
464
+ a = max(0, u['x0'] - m); b = min(W, u['x1'] + m)
465
+ if b - a < imh // 2: c = (a + b) // 2; a = max(0, c - imh // 4); b = min(W, a + imh // 2); a = max(0, b - imh // 2)
466
+ own = u['mask'].astype(np.uint8); other = cv2.dilate((allm & (1 - own)), k3).astype(bool) | dropd
467
+ other &= ~cv2.dilate(own, np.ones((3, 3), np.uint8)).astype(bool)
468
+ crop = L.copy(); crop[other] = paper; wins.append((a, b, crop[:, a:b]))
469
+ order = np.argsort([b - a for a, b, _ in wins]); res = [None] * len(wins)
470
+ for s in range(0, len(order), IBS):
471
+ ids = order[s:s + IBS]; Wm = int(math.ceil(max(wins[i][1] - wins[i][0] for i in ids) / 8) * 8)
472
+ img = np.zeros((len(ids), 1, imh, Wm), np.float32); wc = np.zeros(len(ids), np.int64)
473
+ for q, i in enumerate(ids): x_ = wins[i][2]; img[q, 0, :, :x_.shape[1]] = norm_img(x_); wc[q] = math.ceil(x_.shape[1] / 8)
474
+ ml = int(min(MAXPTS, TRACE_ML_K * Wm + 100))
475
+ trs = trace(model, torch.from_numpy(img).to(dv), torch.from_numpy(wc).to(dv), bias=SAMPLE_BIAS, maxlen=ml)
476
+ for i, tr in zip(ids, trs): res[i] = tr
477
+ P = []; Pn = []; Pr = []; U = []
478
+ for u, (a, b, _), tr in zip(units, wins, res):
479
+ px = tr['absu'] * imh + np.array([a, 0], np.float32); pen = tr['pen'].copy(); pen[-1] = 1
480
+ dist = cv2.distanceTransform((1 - u['mask'].astype(np.uint8)), cv2.DIST_L2, 3)
481
+ idx, p2 = guard(px, pen, dist, GUARD_W * w, GUARD_K)
482
+ if len(idx): # strokes with every point off this island's ink are dropped
483
+ q = px[idx]; xi_ = np.clip(np.round(q[:, 0]).astype(int), 0, W - 1); yi_ = np.clip(np.round(q[:, 1]).astype(int), 0, H - 1); far = dist[yi_, xi_] > GUARD_W * w
484
+ kk = np.ones(len(idx), bool)
485
+ for a_, b_ in strokes_of(p2):
486
+ if far[a_:b_ + 1].all(): kk[a_:b_ + 1] = False
487
+ idx = idx[kk]; p2 = p2[kk]
488
+ if len(p2): p2[-1] = 1
489
+ if not len(idx): continue
490
+ P.append(px[idx]); Pn.append(p2); Pr.append(tr['pres'][idx] if tr['pres'] is not None else np.full(len(idx), 0.5, np.float32)); U.append(np.full(len(idx), len(U)))
491
+ if not P: P = [np.zeros((1, 2), np.float32)]; Pn = [np.ones(1)]; Pr = [np.full(1, 0.5, np.float32)]; U = [np.zeros(1, int)]
492
+ Pc, Pnc, Prc, Uc = np.concatenate(P), np.concatenate(Pn), np.concatenate(Pr), np.concatenate(U)
493
+ if len(Pc) > 2 and not residual_pass: # second pass: own ink of the kept units left untraced
494
+ cov = np.zeros((H, W), np.uint8)
495
+ for a_, b_ in strokes_of(Pnc):
496
+ q = np.round(Pc[a_:b_ + 1]).astype(np.int32)
497
+ if len(q) > 1: cv2.polylines(cov, [q.reshape(-1, 1, 2)], False, 1, thickness=max(1, int(round(2 * RES_R * w))))
498
+ else: cv2.circle(cov, tuple(int(v) for v in q[0]), max(1, int(round(RES_R * w))), 1, -1)
499
+ res_m = (allm > 0) & (cov == 0); res_m &= own_mask(L)[0]
500
+ n_, lab_, st_, _ = cv2.connectedComponentsWithStats(res_m.astype(np.uint8), 8)
501
+ big = [i for i in range(1, n_) if st_[i, cv2.CC_STAT_AREA] >= RES_MIN]
502
+ if big:
503
+ Lr = np.full_like(L, paper); keep_m = np.isin(lab_, big); Lr[keep_m] = L[keep_m]
504
+ r2 = trace_frame(model, Lr, residual_pass=True)
505
+ if len(r2['px']) > 1:
506
+ Pc = np.concatenate([Pc, r2['px']]); Pnc = np.concatenate([Pnc, r2['pen']]); Prc = np.concatenate([Prc, r2['pres']]); Uc = np.concatenate([Uc, r2['uid'] + Uc.max() + 1])
507
+ return dict(px=Pc, pen=Pnc, pres=Prc, uid=Uc, w=w)
508
+ class Tracer:
509
+ def __init__(s, weights='weights', device=None):
510
+ s.dev = torch.device(device or ('cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'))
511
+ st = torch.load(os.path.join(weights, 'trace8_fp16.pt'), map_location='cpu', weights_only=True); s.model = Model(st['cfg']); s.model.load_state_dict({k: v.float() for k, v in st['e'].items()}); s.model.to(s.dev).eval()
512
+ st = torch.load(os.path.join(weights, 'inkfix1.pt'), map_location='cpu', weights_only=True); s.fix = UNet(**st['cfg']); s.fix.load_state_dict({k: v.float() for k, v in st['e'].items()}); s.fix.to(s.dev).eval()
513
+ def trace_frame64(s, frame, seed=0, erase_neighbours=False):
514
+ """uint8 frame of height 64 -> trace in frame px, stroke merge included."""
515
+ torch.manual_seed(seed); L = restore(s.fix, frame); r = trace_frame(s.model, L, erase_neighbours=erase_neighbours)
516
+ pen, _ = merge_strokes(r['px'], r['pen'], r['uid'], r['w'], MERGE, MERGE_COS, True); return dict(px=np.asarray(r['px'], np.float32), pen=np.asarray(pen, np.float32), pres=np.asarray(r['pres'], np.float32))
517
+ def trace_image(s, gray, seed=0, erase_neighbours=False):
518
+ """uint8 grey crop of one line, any size -> trace in the crop's pixels."""
519
+ f = to_input(gray, s.model.cfg['IMH'], 10 ** 9); r = s.trace_frame64(f, seed, erase_neighbours); r['px'] = r['px'] * (gray.shape[0] / s.model.cfg['IMH']); return r
520
+ def to_svg(px, pen, w, h):
521
+ d = []; a = 0
522
+ for k in range(len(px)):
523
+ if pen[k] > 0.5 or k == len(px) - 1:
524
+ d.append('M' + ' L'.join(f'{x:.1f} {y:.1f}' for x, y in px[a:k + 1])); a = k + 1
525
+ return f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {w} {h}"><path d="{" ".join(d)}" fill="none" stroke="black" stroke-width="{max(1.0, h / 40):.1f}" stroke-linecap="round" stroke-linejoin="round"/></svg>'
526
+ if __name__ == '__main__':
527
+ ap = argparse.ArgumentParser(); ap.add_argument('image'); ap.add_argument('--weights', default=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'weights')); ap.add_argument('--out', default='trace.json')
528
+ ap.add_argument('--svg'); ap.add_argument('--seed', type=int, default=0); ap.add_argument('--device'); ap.add_argument('--erase_neighbours', action='store_true'); A = ap.parse_args()
529
+ g = np.asarray(Image.open(A.image).convert('L')); r = Tracer(A.weights, A.device).trace_image(g, A.seed, A.erase_neighbours)
530
+ json.dump(dict(height=g.shape[0], width=g.shape[1], points=[[round(float(x), 2), round(float(y), 2), int(p > 0.5), round(float(q), 3)] for (x, y), p, q in zip(r['px'], r['pen'], r['pres'])]), open(A.out, 'w'))
531
+ if A.svg: open(A.svg, 'w').write(to_svg(r['px'], r['pen'], g.shape[1], g.shape[0]))
532
+ print(A.out, len(r['px']), 'points', int((r['pen'] > 0.5).sum()), 'strokes')
trace/weights/inkfix1.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4bb807634496fa881b21275db32ed54243aa6955d694cee1235a3b1a1e02a510
3
+ size 14989195
trace/weights/trace8_fp16.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:562c414fa86005d228273a8cdaf6bb173dbdc39f8c6927b0c0c89c327e692615
3
+ size 46822425