File size: 8,175 Bytes
24aaa76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
"""ONEMODEL pilot (design records/R5/ONEMODEL/design.json, id ONEMODEL-pilot-1): pure-Python helpers shared by the page build,
training, evaluation and scoring. No torch, no transformers: the scorer imports this file from .venv_kraken.

- spot_size: the one resize rule for page images (largest size with both sides multiples of 28 and area <= the pixel cap,
  up or down), used by the build (cap 1,605,632), the training jitter (u x cap) and evaluation (cap).
- target building and parsing of the spotting format: per line, text then 8 location tokens <|LOC_n|> for the quad
  TL, TR, BR, BL of the line's axis-aligned box, n = round(1000 x / W), clamped 0..1000; lines joined by one newline.
- R_SCHOOL (design target_order.school_pages): gutter split of a two-page spread and a stable partition of a line order.
- det_order: det_eval's reading order of detected boxes, (centre_y // 15, centre_x).
"""
import math
import re
import unicodedata

DESIGN_ID = "ONEMODEL-pilot-1"
SPOT_PROMPT = "Spotting:"
CROP_INSTRUCTION = "Transcribe the text in this image exactly."
FACTOR = 28                           # patch 14 x merge 2 (facts P17)
SPOT_MAX_PIXELS = 2048 * 28 * 28      # 1,605,632 (facts P6, P8, P11)
SPOT_MIN_PIXELS = 112896              # processor shortest_edge of the leader folder (facts P15)
TARGET_CAP = 4096                     # page target tokens incl. </s> (design sequence_length_cap)
MAX_NEW_CEILING = 6144
LOC_RE = re.compile(r"<\|LOC_(\d{1,4})\|>")
SPECIAL_RE = re.compile(r"<\|[A-Za-z_]+\|>|</s>|<s>")     # as records/R5/PAGECHK/b1_page_check.py lines_from
_WS = re.compile(r"\s+")


def norm_line(s):
    """NFC, every run of whitespace (newlines included) to one space, outer spaces stripped."""
    return _WS.sub(" ", unicodedata.normalize("NFC", s or "")).strip()


def spot_size(w, h, max_pixels=SPOT_MAX_PIXELS, factor=FACTOR):
    """(W, H) of the resized page: both sides multiples of `factor`, area <= max_pixels, scaled up or down so that the
    area is as large as the flooring allows. For an image already of that form and under the cap the processor's
    smart_resize leaves it unchanged (round(h/28)*28 == h, area <= max_pixels)."""
    beta = math.sqrt((w * h) / float(max_pixels))
    hb = max(factor, int(math.floor(h / beta / factor)) * factor)
    wb = max(factor, int(math.floor(w / beta / factor)) * factor)
    while hb * wb > max_pixels:          # guard against float rounding at an exact boundary
        if hb >= wb:
            hb -= factor
        else:
            wb -= factor
    return wb, hb


def fit_size(w, h, max_pixels=SPOT_MAX_PIXELS, factor=FACTOR):
    """size used for an image that is already a page image of the build (sides multiples of 28): unchanged if it is under
    the cap, else spot_size (down). Training jitter u < 1 and evaluation (u = 1) both go through this."""
    if w % factor == 0 and h % factor == 0 and w * h <= max_pixels:
        return w, h
    return spot_size(w, h, max_pixels, factor)


def loc(v, size):
    n = int(math.floor(1000.0 * float(v) / float(size) + 0.5))
    return min(1000, max(0, n))


def quad_of_box(box, W, H):
    """axis-aligned box (x0, y0, x1, y1) in a W x H frame -> 8 ints TL, TR, BR, BL in 0..1000"""
    x0, y0, x1, y1 = box
    a, b, c, d = loc(x0, W), loc(y0, H), loc(x1, W), loc(y1, H)
    return [a, b, c, b, c, d, a, d]


def loc_tokens(q):
    return "".join("<|LOC_%d|>" % n for n in q)


def build_target(texts, boxes, W, H, order):
    """texts, boxes: reference lines (det_eval page file order); order: target order (list of indices).
    Returns (target string, kept indices in target order, quads of the kept lines, counts)."""
    parts, kept, quads = [], [], []
    cnt = {"empty_text_lines_left_out": 0, "lines_with_special_like_text": 0}
    for i in order:
        t = norm_line(texts[i])
        if not t:
            cnt["empty_text_lines_left_out"] += 1
            continue
        if "<|" in t or "</s>" in t:
            cnt["lines_with_special_like_text"] += 1
        q = quad_of_box(boxes[i], W, H)
        parts.append(t + loc_tokens(q))
        kept.append(i)
        quads.append(q)
    return "\n".join(parts), kept, quads, cnt


def parse_output(raw):
    """Spotting output (special tokens kept) -> list of instances {text, locs, box (x0, y0, x1, y1 in 0..1000) or None,
    malformed}. Blank output lines are skipped. box = bounds of the LAST 8 location tokens of the line; a line with fewer
    than 8 has no box; malformed = the number of location tokens is not exactly 8."""
    out = []
    for ln in (raw or "").split("\n"):
        locs = [int(m) for m in LOC_RE.findall(ln)]
        text = norm_line(SPECIAL_RE.sub("", LOC_RE.sub("", ln)))
        if not text and not locs:
            continue
        box = None
        if len(locs) >= 8:
            q = locs[-8:]
            xs, ys = q[0::2], q[1::2]
            box = (min(xs), min(ys), max(xs), max(ys))
        out.append({"text": text, "locs": locs, "box": box, "malformed": len(locs) != 8})
    return out


def page_lines(instances):
    """page text lines = non-empty instance texts in output order"""
    return [x["text"] for x in instances if x["text"]]


def boxes_to_frame(instances, W, H):
    """boxes of the instances that have one, mapped from 0..1000 to a W x H frame"""
    return [[b[0] / 1000.0 * W, b[1] / 1000.0 * H, b[2] / 1000.0 * W, b[3] / 1000.0 * H]
            for b in (x["box"] for x in instances) if b is not None]


# ------------------------------------------------------------------------------------------------ reading order
def gutter_x(boxes, W, lo=0.35, hi=0.65, tol=0.03, max_cross=0.10, min_side=0.15):
    """R_SCHOOL step 1-2. boxes: axis-aligned line boxes in a frame of width W. Returns (gutter x or None, info)."""
    n = len(boxes)
    if n < 4:
        return None, {"n": n}
    d = tol * W
    best, xs = None, []
    for x in range(int(lo * W), int(hi * W) + 1):
        c = 0
        for b in boxes:
            if b[0] < x - d and b[2] > x + d:
                c += 1
        if best is None or c < best:
            best, xs = c, [x]
        elif c == best:
            xs.append(x)
    runs, cur = [], [xs[0]]
    for x in xs[1:]:
        if x == cur[-1] + 1:
            cur.append(x)
        else:
            runs.append(cur)
            cur = [x]
    runs.append(cur)
    run = max(runs, key=len)                    # first longest run on ties
    xg = (run[0] + run[-1]) / 2.0
    left = sum(1 for b in boxes if (b[0] + b[2]) / 2.0 < xg)
    ok = best <= max_cross * n and min(left, n - left) >= min_side * n
    return (xg if ok else None), {"n": n, "min_cross": best, "left": left, "xg": xg, "two_columns": ok}


def partition_by_gutter(order, boxes, xg):
    """R_SCHOOL step 3: stable partition of `order` into the lines left of the gutter, then the lines right of it."""
    if xg is None:
        return list(order)
    left = [i for i in order if (boxes[i][0] + boxes[i][2]) / 2.0 < xg]
    right = [i for i in order if (boxes[i][0] + boxes[i][2]) / 2.0 >= xg]
    return left + right


def school_order(boxes, W):
    """reference / target order of a School page: stored order (indices 0..n-1, det_prep's baseline-y sort), partitioned
    by the gutter. Returns (order, gutter info)."""
    xg, info = gutter_x(boxes, W)
    return partition_by_gutter(list(range(len(boxes))), boxes, xg), info


def det_order(boxes):
    """det_eval / detb1_page_check reading order of detected boxes: (centre_y // 15, centre_x) in the 1280 px page"""
    return sorted(range(len(boxes)), key=lambda i: (int(((boxes[i][1] + boxes[i][3]) / 2) // 15), (boxes[i][0] + boxes[i][2]) / 2))


def det_order_columns(boxes, W):
    """baseline order of the decision: det_order, stably partitioned by the R_SCHOOL gutter of the detected boxes"""
    xg, info = gutter_x(boxes, W)
    return partition_by_gutter(det_order(boxes), boxes, xg), info


def guard_not_test(path):
    import os
    b = os.path.basename(str(path)).lower()
    for w in ("test", "kohtd_rand", "rukopys", "turkishocr", "more_real_print"):
        if w in b:
            raise SystemExit("REFUSED: %s looks like a locked set (%s)" % (path, w))