Download src/linedet/data.py from treoa/turkic-ocr-code: direct link, hf CLI and curl.
- Browser
- Download file 14.1 kB
-
https://huggingface.co/treoa/turkic-ocr-code/resolve/main/src/linedet/data.py
- Command line
-
hf download hf://treoa/turkic-ocr-code/src/linedet/data.py
-
curl -L -o data.py https://huggingface.co/treoa/turkic-ocr-code/resolve/main/src/linedet/data.py
14.1 kB
| """Data side of the line recognizers: mix_v1 sampling by shares, image loading as kraken does it, collation. | |
| Image path (same for all arms, taken from kraken 7.2 lib/dataset/utils.py ImageInputTransforms and | |
| lib/functional_im_transforms.py): RGB, resize to height H keeping the aspect ratio (Lanczos), 16 px white padding on the | |
| left and right, scale to [0,1], invert (ink bright, background 0), kraken's DefaultAugmenter (training only, p=0.5). | |
| Arms with one channel average the three channels after augmentation. | |
| """ | |
| import os | |
| import sys | |
| import traceback | |
| import numpy as np | |
| import torch | |
| import torch.nn.functional as F | |
| from PIL import Image | |
| from torch.utils.data import Dataset | |
| from .common import read_manifest, to_train_text | |
| PAD = 16 | |
| class ArmSpec: | |
| """Input geometry of one arm.""" | |
| def __init__(self, name, height, channels, subsampling, max_width, fixed_width=None): | |
| self.name = name | |
| self.height = height | |
| self.channels = channels | |
| self.subsampling = subsampling # network width subsampling (frames = width // subsampling) | |
| self.max_width = max_width # training samples wider than this are skipped (kraken drops them too) | |
| self.fixed_width = fixed_width # A4: every image is padded or squashed to this width | |
| self.stretch = False # A4 diagnostic variant v2 (clarification H8): every crop is stretched to fill the fixed width | |
| SPECS = { | |
| # height 96 is the "height" stored in kraken_meta of both Zenodo weight files (base_*_info.json), although the | |
| # README text says 128 px. The backbone pools whatever height remains, so the height is a free choice. | |
| "A1": ArmSpec("A1", 96, 3, 8, 2560), | |
| "A2": ArmSpec("A2", 96, 3, 8, 2560), | |
| "A1s": ArmSpec("A1s", 96, 3, 8, 2560), | |
| "A3": ArmSpec("A3", 64, 1, 4, 2560), | |
| "A4": ArmSpec("A4", 64, 1, 4, 1024, fixed_width=1024), | |
| } | |
| # ----------------------------------------------------------------------------------------------- mix definition | |
| _COMP_KEYS = ("components", "sources", "mix", "parts", "entries", "streams", "groups", "shares") | |
| _MEMBER_KEYS = ("members", "items", "sources", "manifests", "components", "children") | |
| _MAN_KEYS = ("manifest", "path", "file", "tsv") | |
| _SHARE_KEYS = ("share", "weight", "fraction", "probability", "p", "proportion") | |
| def _leaf_list(node, parent_share, name_prefix, out): | |
| """Flatten a (possibly nested) mix description into leaf components (manifest, share, filter).""" | |
| if isinstance(node, str): | |
| out.append({"name": name_prefix or node, "manifest": node, "share": parent_share, "filter": None}) | |
| return | |
| man = next((node[k] for k in _MAN_KEYS if k in node), None) | |
| share = next((node[k] for k in _SHARE_KEYS if k in node), None) | |
| share = parent_share if share is None else (parent_share * float(share) if parent_share != 1.0 or name_prefix else float(share)) | |
| name = node.get("name", name_prefix or (os.path.basename(man) if isinstance(man, str) else "component")) | |
| flt = node.get("filter") or node.get("where") | |
| members = next((node[k] for k in _MEMBER_KEYS if k in node and isinstance(node[k], list)), None) | |
| if members is not None: | |
| have = [isinstance(m, dict) and any(k in m for k in _SHARE_KEYS) for m in members] | |
| if not any(have): | |
| for m in members: | |
| _leaf_list(m, share / len(members), name, out) | |
| else: | |
| tot = sum(float(next(m[k] for k in _SHARE_KEYS if k in m)) for m, h in zip(members, have) if h) | |
| for m, h in zip(members, have): | |
| sh = float(next(m[k] for k in _SHARE_KEYS if k in m)) / tot * share if h else 0.0 | |
| _leaf_list(dict(m, **{k: 1.0 for k in _SHARE_KEYS if k in m}), sh, name, out) | |
| return | |
| if isinstance(man, list): | |
| for m in man: | |
| _leaf_list(m, share / len(man), name, out) | |
| return | |
| if man is None: | |
| raise ValueError("component without a manifest: %s" % node) | |
| out.append({"name": name, "manifest": man, "share": share, "filter": flt}) | |
| def load_mix(path): | |
| """Parse mix_v1.yaml. Accepted: a list, or a mapping with a list/mapping under one of %s; each entry has a manifest path | |
| (keys %s) and a share (keys %s), optional filter (mapping column -> value or list), and optionally nested members with | |
| their own shares (a member's share is a share of its group). Shares are normalised to sum 1.""" % (_COMP_KEYS, _MAN_KEYS, _SHARE_KEYS) | |
| import yaml | |
| d = yaml.safe_load(open(path, encoding="utf-8")) | |
| comps = None | |
| if isinstance(d, list): | |
| comps = d | |
| else: | |
| for k in _COMP_KEYS: | |
| if k in d: | |
| comps = d[k] | |
| break | |
| if comps is None: | |
| raise ValueError("cannot find the component list in %s; keys: %s" % (path, list(d.keys()))) | |
| if isinstance(comps, dict): | |
| comps = [dict(v, name=k) if isinstance(v, dict) else {"name": k, "share": v} for k, v in comps.items()] | |
| out = [] | |
| for c in comps: | |
| _leaf_list(c, 1.0, "", out) | |
| tot = sum(c["share"] for c in out) | |
| if tot <= 0: | |
| raise ValueError("shares sum to zero in %s" % path) | |
| for c in out: | |
| c["share"] = c["share"] / tot | |
| return out | |
| def load_components(mix_comps, use_split="train"): | |
| """Read the manifests of a mix. Returns list of components with items = list of (image, text_nfd, kind).""" | |
| comps = [] | |
| for c in mix_comps: | |
| rows = read_manifest(c["manifest"]) | |
| items = [] | |
| flt = c.get("filter") or {} | |
| for r in rows: | |
| if r.get("unit") == "page": | |
| continue | |
| if use_split and r.get("split") and r["split"] != use_split: | |
| continue | |
| ok = True | |
| for col, vals in flt.items(): | |
| vals = vals if isinstance(vals, (list, tuple)) else [vals] | |
| if r.get(col) not in vals: | |
| ok = False | |
| break | |
| if not ok: | |
| continue | |
| t = to_train_text(r["text"]) | |
| if not t and r.get("kind") != "clutter": | |
| continue | |
| items.append((r["image"], t, r.get("kind", ""))) | |
| if not items: | |
| raise ValueError("component %s has no usable rows" % c["name"]) | |
| comps.append({"name": c["name"], "share": c["share"], "items": items}) | |
| return comps | |
| # ----------------------------------------------------------------------------------------------- deterministic stream | |
| class MixStream: | |
| """Deterministic endless stream of batches. Sample s belongs to pool s // pool_size. Pool p draws its component | |
| counts from a multinomial over the shares; inside a component the items are read in seeded epoch permutations | |
| (no repeats inside an epoch). Pools are sorted by label length, cut into batches, batches shuffled. | |
| Everything is a function of (seed, pool index), so resuming at a sample count reproduces the same batches.""" | |
| def __init__(self, comps, batch_size, seed, pool_size=2048): | |
| self.comps = comps | |
| self.bs = batch_size | |
| self.seed = seed | |
| self.pool_size = max(pool_size // batch_size, 1) * batch_size | |
| self.shares = np.array([c["share"] for c in comps], dtype=np.float64) | |
| self.shares = self.shares / self.shares.sum() | |
| self.offsets = np.cumsum([0] + [len(c["items"]) for c in comps]) | |
| self.lens = np.concatenate([[len(it[1]) for it in c["items"]] for c in comps]).astype(np.int32) | |
| self._perm_cache = {} | |
| def _counts(self, p): | |
| rng = np.random.default_rng([self.seed, 7, p]) | |
| return rng.multinomial(self.pool_size, self.shares) | |
| def _perm(self, i, e): | |
| key = (i, e) | |
| if key not in self._perm_cache: | |
| if len(self._perm_cache) > 4 * len(self.comps): | |
| self._perm_cache.clear() | |
| n = len(self.comps[i]["items"]) | |
| self._perm_cache[key] = np.random.default_rng([self.seed, 1000 + i, e]).permutation(n) | |
| return self._perm_cache[key] | |
| def cursors_at(self, p): | |
| cur = np.zeros(len(self.comps), dtype=np.int64) | |
| for q in range(p): | |
| cur += self._counts(q) | |
| return cur | |
| def batches(self, start_sample=0): | |
| p = start_sample // self.pool_size | |
| skip_batches = (start_sample % self.pool_size) // self.bs | |
| cur = self.cursors_at(p) | |
| while True: | |
| counts = self._counts(p) | |
| gids = [] | |
| for i, n in enumerate(counts): | |
| n_i = len(self.comps[i]["items"]) | |
| for c in range(cur[i], cur[i] + n): | |
| gids.append(int(self.offsets[i] + self._perm(i, c // n_i)[c % n_i])) | |
| cur += counts | |
| rng = np.random.default_rng([self.seed, 11, p]) | |
| gids = np.array(gids) | |
| noise = rng.random(len(gids)) | |
| order = np.lexsort((noise, self.lens[gids] + rng.integers(0, 3, len(gids)))) | |
| gids = gids[order] | |
| nb = len(gids) // self.bs | |
| bl = [gids[k * self.bs:(k + 1) * self.bs].tolist() for k in range(nb)] | |
| perm = rng.permutation(nb) | |
| for j, k in enumerate(perm): | |
| if j < skip_batches: | |
| continue | |
| yield bl[k] | |
| skip_batches = 0 | |
| p += 1 | |
| class FlatItems: | |
| """Flat view over the components for the dataset (global id -> (image, text)).""" | |
| def __init__(self, comps): | |
| self.items = [it for c in comps for it in c["items"]] | |
| self.comp_of = np.concatenate([[i] * len(c["items"]) for i, c in enumerate(comps)]) | |
| def __len__(self): | |
| return len(self.items) | |
| # ----------------------------------------------------------------------------------------------- images | |
| def load_tensor(path, spec, aug=None): | |
| """Load, height-normalise, pad, invert, augment. Returns float tensor (C, H, W).""" | |
| return pil_tensor(Image.open(path), spec, aug) | |
| def pil_tensor(im, spec, aug=None): | |
| """Same as load_tensor for an image that is already in memory.""" | |
| im = im.convert("RGB") | |
| w, h = im.size | |
| nw = max(int(w * spec.height / h), 1) | |
| im = im.resize((nw, spec.height), Image.LANCZOS) | |
| if spec.fixed_width is not None and spec.stretch: | |
| im = im.resize((spec.fixed_width, spec.height), Image.LANCZOS) | |
| arr = np.asarray(im, dtype=np.uint8) | |
| t = torch.from_numpy(arr).permute(2, 0, 1).float().div_(255.0) | |
| t = t.max() - t | |
| elif spec.fixed_width is None: | |
| arr = np.asarray(im, dtype=np.uint8) | |
| arr = np.pad(arr, ((0, 0), (PAD, PAD), (0, 0)), constant_values=255) | |
| t = torch.from_numpy(arr).permute(2, 0, 1).float().div_(255.0) | |
| t = t.max() - t | |
| else: | |
| # fixed-width arms: pad on the right (or squash if too wide), then invert | |
| if nw > spec.fixed_width: | |
| im = im.resize((spec.fixed_width, spec.height), Image.LANCZOS) | |
| arr = np.asarray(im, dtype=np.uint8) | |
| if arr.shape[1] < spec.fixed_width: | |
| arr = np.pad(arr, ((0, 0), (0, spec.fixed_width - arr.shape[1]), (0, 0)), constant_values=255) | |
| t = torch.from_numpy(arr).permute(2, 0, 1).float().div_(255.0) | |
| t = t.max() - t | |
| if aug is not None: | |
| t = aug(image=t) | |
| if spec.channels == 1: | |
| t = t.mean(0, keepdim=True) | |
| return t | |
| def frames_needed(target): | |
| """CTC needs at least len(target) + number of equal neighbours frames.""" | |
| t = target.tolist() if torch.is_tensor(target) else list(target) | |
| return len(t) + sum(1 for a, b in zip(t, t[1:]) if a == b) | |
| class LineDS(Dataset): | |
| def __init__(self, flat, spec, codec, train, seed=0): | |
| self.flat = flat | |
| self.spec = spec | |
| self.codec = codec | |
| self.train = train | |
| self.seed = seed | |
| self.aug = None | |
| def _aug(self): | |
| if self.aug is None and self.train: | |
| from kraken.lib.dataset.augment import DefaultAugmenter | |
| self.aug = DefaultAugmenter() | |
| return self.aug | |
| def __len__(self): | |
| return len(self.flat) | |
| def get_one(self, gid): | |
| path, text, kind = self.flat.items[gid] | |
| t = load_tensor(path, self.spec, self._aug() if self.train else None) | |
| target = self.codec.encode(text) if self.train else torch.zeros(0, dtype=torch.int32) | |
| w = t.shape[-1] | |
| if self.train: | |
| if self.spec.fixed_width is None and w > self.spec.max_width: | |
| raise ValueError("too wide") | |
| frames = (self.spec.fixed_width // self.spec.subsampling) if self.spec.fixed_width else w // self.spec.subsampling | |
| if frames_needed(target) > frames: | |
| raise ValueError("too many characters for the width") | |
| return {"image": t, "target": target, "text": text, "gid": gid} | |
| def __getitem__(self, gid): | |
| if not self.train: | |
| return self.get_one(gid) | |
| rs = np.random.default_rng() | |
| for attempt in range(20): | |
| try: | |
| return self.get_one(gid) | |
| except Exception: | |
| if attempt == 0: | |
| sys.stderr.write("[data] sample failed %s: %s\n" % (self.flat.items[gid][0], traceback.format_exc(limit=1).strip().splitlines()[-1])) | |
| gid = int(rs.integers(0, len(self.flat))) | |
| raise RuntimeError("20 consecutive failures") | |
| def collate(batch): | |
| seqs = [b["image"] for b in batch] | |
| seq_lens = torch.LongTensor([s.shape[2] for s in seqs]) | |
| wmax = int(seq_lens.max()) | |
| images = torch.stack([F.pad(s, (0, wmax - s.shape[2])) for s in seqs]) | |
| targets = torch.cat([b["target"] for b in batch]).long() if any(len(b["target"]) for b in batch) else torch.zeros(0, dtype=torch.long) | |
| return {"image": images, "seq_lens": seq_lens, "target": targets, | |
| "target_lens": torch.LongTensor([len(b["target"]) for b in batch]), | |
| "text": [b["text"] for b in batch], "gid": [b["gid"] for b in batch]} | |
| def eval_order(items, key=lambda it: len(it[1])): | |
| """Indices sorted by label length so batches have similar widths.""" | |
| return sorted(range(len(items)), key=lambda i: key(items[i])) | |