Download microscopy_coreml.py from Reza2kn/Bina-0.4-Microscopy-CoreML: direct link, hf CLI and curl.
- Browser
- Download file 5.52 kB
-
https://huggingface.co/Reza2kn/Bina-0.4-Microscopy-CoreML/resolve/main/microscopy_coreml.py
- Command line
-
hf download hf://Reza2kn/Bina-0.4-Microscopy-CoreML/microscopy_coreml.py
-
curl -L -o microscopy_coreml.py https://huggingface.co/Reza2kn/Bina-0.4-Microscopy-CoreML/resolve/main/microscopy_coreml.py
5.52 kB
| #!/usr/bin/env python3 | |
| """Bina 0.4 Microscopy on Core ML (macOS): the reference pipeline for iPhone, iPad and Mac apps. | |
| Same steps and outputs as microscopy.py; the three networks run through Core ML: | |
| det_main.mlpackage, det_print.mlpackage : x (1,3,H,W) page in [-1,1], H and W multiples of 32 (<= 1024) -> prob (1,1,H/2,W/2) | |
| (det_*.fp16.mlpackage: the same in FP16) | |
| reader.fp16.mlpackage, reader.fp32.mlpackage, reader.int8.mlpackage | |
| : x (1,1,64,W) ink map (ink = 1), W a multiple of 8, widths (1,) int32 true width | |
| -> logprobs (1,W/4,1625) | |
| Default (fastest on Apple silicon): FP16 detectors on the GPU, FP16 reader on the CPU. --fp32 uses the FP32 files. | |
| The two detector branches run in parallel threads. | |
| usage: python microscopy_coreml.py page.jpg [more.png doc.pdf ...] [--out results] [--single] [--fp32] | |
| """ | |
| import argparse, json, sys, time | |
| from pathlib import Path | |
| import cv2 | |
| import numpy as np | |
| import coremltools as ct | |
| ROOT = Path(__file__).resolve().parent | |
| sys.path.insert(0, str(ROOT)) | |
| import microscopy as M # noqa: E402 (shared crop, ordering and clean-up code) | |
| from bina_rtl import flip # noqa: E402 | |
| UNITS = {"ALL": ct.ComputeUnit.ALL, "CPU_AND_NE": ct.ComputeUnit.CPU_AND_NE, "CPU_AND_GPU": ct.ComputeUnit.CPU_AND_GPU, "CPU_ONLY": ct.ComputeUnit.CPU_ONLY} | |
| class MicroscopyCoreML(M.Microscopy): | |
| def __init__(s, single=False, det_units="CPU_AND_GPU", reader_units="CPU_ONLY", reader="reader.fp16.mlpackage", det_suffix=".fp16", parallel=True): | |
| s.alpha = json.loads((ROOT / "vocab.json").read_text())["chars"] | |
| du, ru = UNITS[det_units], UNITS[reader_units] | |
| s.parallel = parallel | |
| s.dets = [dict(s.MAIN, file=f"det_main{det_suffix}.mlpackage")] | |
| if not single: | |
| s.dets.append(dict(s.PRINT, file=f"det_print{det_suffix}.mlpackage")) | |
| for d in s.dets: | |
| d["ml"] = ct.models.MLModel(str(ROOT / d["file"]), compute_units=du) | |
| # one reader per branch, so the branches can run at the same time | |
| d["rsess"] = ct.models.MLModel(str(ROOT / reader), compute_units=ru) | |
| def lines(s, rgb, det, long_side=1024, wf=.6): | |
| oh, ow = rgb.shape[:2] | |
| sc = min(1., long_side / max(oh, ow)) | |
| h = max(32, round(oh * sc / 32) * 32); w = max(32, round(ow * sc / 32) * 32) | |
| x = cv2.resize(rgb, (w, h), interpolation=cv2.INTER_AREA).transpose(2, 0, 1)[None].astype(np.float32) / 127.5 - 1 | |
| p = det["ml"].predict({"x": x})["prob"][0, 0] | |
| m = (p > det["thr"]).astype(np.uint8) | |
| n, lab, st, _ = cv2.connectedComponentsWithStats(m, 8) | |
| fx = ow / p.shape[1]; fy = oh / p.shape[0]; boxes = [] | |
| for i in range(1, n): | |
| if st[i, cv2.CC_STAT_AREA] < 4: | |
| continue | |
| ys, xs = np.nonzero(lab == i) | |
| (cx, cy), (rw, rh), ang = cv2.minAreaRect(np.stack([xs, ys], 1).astype(np.float32)) | |
| vertical = abs((ang + 90) % 180 - 90) >= 45 | |
| kh = rw if vertical else rh; kw = rh if vertical else rw | |
| lh = kh * det["hf"]; W = kw + wf * lh | |
| b = [max(0, (cx - W / 2) * fx), max(0, (cy - lh / 2) * fy), min(ow, (cx + W / 2) * fx), min(oh, (cy + lh / 2) * fy)] | |
| if b[2] - b[0] >= 2 and b[3] - b[1] >= 2: | |
| boxes.append(b) | |
| return boxes | |
| def read(s, gray, boxes, batch=1, rsess=None): | |
| model = rsess or s.dets[0]["rsess"] | |
| res = [] | |
| for b in boxes: | |
| c = M.crop_line64(gray, b); W = c.shape[1] | |
| P = (W + 7) // 8 * 8 | |
| x = np.zeros((1, 1, 64, P), np.float32); x[0, 0, :, :W] = c | |
| lp = model.predict({"x": x, "widths": np.array([W], np.int32)})["logprobs"][0, :(W + 3) // 4] | |
| z = lp.argmax(-1); keep = (z != 0) & np.r_[True, z[1:] != z[:-1]] | |
| text = flip("".join(s.alpha[t - 1] for t in z[keep]), base_rtl=True) | |
| res.append((text, float(np.exp(lp.max(-1))[keep].mean()) if keep.any() else 0.)) | |
| return res | |
| def main(): | |
| ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| ap.add_argument("inputs", nargs="+") | |
| ap.add_argument("--out", default="microscopy-out") | |
| ap.add_argument("--single", action="store_true") | |
| ap.add_argument("--fp32", action="store_true", help="FP32 detectors and reader (bit-exact with ONNX, about 20%% slower)") | |
| ap.add_argument("--reader", default=None, help="reader file, e.g. reader.int8.mlpackage") | |
| ap.add_argument("--det-units", default="CPU_AND_GPU", choices=list(UNITS)) | |
| ap.add_argument("--reader-units", default="CPU_ONLY", choices=list(UNITS)) | |
| ap.add_argument("--dpi", type=int, default=200) | |
| a = ap.parse_args() | |
| ocr = MicroscopyCoreML(single=a.single, det_units=a.det_units, reader_units=a.reader_units, | |
| reader=a.reader or ("reader.fp32.mlpackage" if a.fp32 else "reader.fp16.mlpackage"), det_suffix="" if a.fp32 else ".fp16") | |
| out = Path(a.out); out.mkdir(parents=True, exist_ok=True) | |
| for path in a.inputs: | |
| for name, im in M.pages(path, a.dpi): | |
| t = time.time(); r = ocr(im) | |
| (out / f"{name}.txt").write_text(r["text"] + "\n", encoding="utf-8") | |
| (out / f"{name}.json").write_text(json.dumps(r, ensure_ascii=False, indent=1), encoding="utf-8") | |
| print(f"{name}: {len(r['lines'])} lines, {time.time() - t:.2f}s -> {out / name}.txt") | |
| if __name__ == "__main__": | |
| main() | |