Akshit Beniwal (qris-uq) commited on
Commit
d47fb92
·
0 Parent(s):

Deploy fabric analyzer API

Browse files
Dockerfile ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # HuggingFace Spaces (Docker SDK) — listens on port 7860 (HF default).
2
+ FROM python:3.11-slim
3
+
4
+ RUN apt-get update && apt-get install -y --no-install-recommends \
5
+ libjpeg62-turbo \
6
+ libpng16-16 \
7
+ libheif1 \
8
+ curl ca-certificates \
9
+ && rm -rf /var/lib/apt/lists/*
10
+
11
+ RUN useradd -m -u 1000 user
12
+ USER user
13
+ ENV PATH="/home/user/.local/bin:$PATH"
14
+ WORKDIR /app
15
+
16
+ # Standalone `hf` CLI (Xet/buckets) for persistent storage sync.
17
+ RUN curl -LsSf https://hf.co/cli/install.sh | sh || pip install --no-cache-dir "huggingface_hub[cli]>=0.26"
18
+
19
+ # torch AND torchvision from the SAME CPU index (timm needs torchvision; a
20
+ # mismatched/absent torchvision causes "operator torchvision::nms does not exist").
21
+ RUN pip install --no-cache-dir torch torchvision --index-url https://download.pytorch.org/whl/cpu
22
+ COPY --chown=user requirements.txt requirements.txt
23
+ RUN pip install --no-cache-dir --upgrade -r requirements.txt
24
+ # Bake the DINOv2 weights into the image so the first identify is fast (no runtime download).
25
+ RUN python -c "import timm; timm.create_model('vit_small_patch14_dinov2.lvd142m', pretrained=True)"
26
+
27
+ COPY --chown=user . /app
28
+
29
+ ENV FABRIC_ALGO_DIR=/app
30
+ EXPOSE 7860
31
+ CMD ["uvicorn", "api.server:app", "--host", "0.0.0.0", "--port", "7860"]
README.md ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Fabric Density Analyzer API
3
+ emoji: 🧵
4
+ colorFrom: blue
5
+ colorTo: indigo
6
+ sdk: docker
7
+ app_port: 7860
8
+ pinned: false
9
+ license: apache-2.0
10
+ short_description: FastAPI backend for fabric EPI/PPI measurement.
11
+ ---
12
+
13
+ # Fabric Density Analyzer API
14
+
15
+ FastAPI backend that measures EPI (ends per inch) and PPI (picks per inch)
16
+ from a fabric photo with a ruler. Used by the front-end at
17
+ `https://<your-pages-domain>.pages.dev`.
18
+
19
+ ## Endpoints
20
+
21
+ - `GET /` — health check
22
+ - `POST /analyze` — multipart upload (`image` + `weave` + `tick_mm` + optional repeat/ascend flags)
23
+
24
+ See [`api/server.py`](api/server.py) for the full schema.
api/Dockerfile ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ WORKDIR /app
4
+
5
+ RUN apt-get update && apt-get install -y --no-install-recommends \
6
+ libjpeg62-turbo \
7
+ libpng16-16 \
8
+ libheif1 \
9
+ && rm -rf /var/lib/apt/lists/*
10
+
11
+ # Install CPU-only torch AND torchvision from the same index first (keeps the
12
+ # image GPU-free; timm needs a MATCHING torchvision or it raises
13
+ # "operator torchvision::nms does not exist"). Then the rest of the deps.
14
+ RUN pip install --no-cache-dir torch torchvision --index-url https://download.pytorch.org/whl/cpu
15
+ COPY api/requirements.txt /app/requirements.txt
16
+ RUN pip install --no-cache-dir -r /app/requirements.txt
17
+ # Bake DINOv2 weights so the first identify is fast (no runtime download).
18
+ RUN python -c "import timm; timm.create_model('vit_small_patch14_dinov2.lvd142m', pretrained=True)"
19
+
20
+ # Copy backend + algorithm modules (v6 measurement = v5 + robust tick + dense-warp
21
+ # corrector ensemble + recognizer + deps)
22
+ COPY api /app/api
23
+ COPY epi_ppi_v4_1.py epi_ppi_v4_2.py epi_ppi_v5.py epi_ppi_v6.py \
24
+ classfix_combined.py classfix_harmonic_comb.py classfix_motif_removal.py \
25
+ classfix_autocorr_cepstrum.py classfix_gradient_edge.py classfix_local_bandpass.py \
26
+ robust_tick.py fabric_recognize.py ruler_freq.py migrate_catalog_v6.py /app/
27
+
28
+ ENV FABRIC_ALGO_DIR=/app
29
+ ENV PORT=8000
30
+ EXPOSE 8000
31
+
32
+ CMD ["sh", "-c", "uvicorn api.server:app --host 0.0.0.0 --port ${PORT}"]
api/__pycache__/persistence.cpython-312.pyc ADDED
Binary file (6.4 kB). View file
 
api/__pycache__/recognizer_routes.cpython-312.pyc ADDED
Binary file (9.23 kB). View file
 
api/__pycache__/server.cpython-311.pyc ADDED
Binary file (10.6 kB). View file
 
api/__pycache__/server.cpython-312.pyc ADDED
Binary file (9.43 kB). View file
 
api/persistence.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Durable storage for the fabric app, mirrored to an HF bucket.
2
+
3
+ HF Space containers have an EPHEMERAL filesystem, so anything we want to keep
4
+ (the enrolled article catalog AND the log of processed inspections) must be
5
+ mirrored to durable storage. We keep a local working dir (FABRIC_DATA_DIR) and
6
+ sync it to an HF bucket via the `hf sync` CLI:
7
+
8
+ data/
9
+ fabric_store.json # enrolled catalog: embeddings + meta
10
+ images/<article_code>/*.jpg # original enrolled photos (re-embed-able)
11
+ processed/*.jpg # every analyzed photo
12
+ processed_log.jsonl # one record per /analyze: readings + confidence
13
+
14
+ - pull_once(): bucket -> data dir (restore on container start)
15
+ - push(): data dir -> bucket (persist; run in a background task)
16
+
17
+ Auth: set HF_TOKEN (write) as a Space secret. If the CLI/token is missing,
18
+ everything still works locally (just not persisted) — all sync is non-fatal.
19
+ """
20
+ import os, re, uuid, json, subprocess, datetime
21
+
22
+ DATA_DIR = os.environ.get("FABRIC_DATA_DIR", "./data")
23
+ IMAGES_DIR = os.path.join(DATA_DIR, "images")
24
+ PROCESSED_DIR = os.path.join(DATA_DIR, "processed")
25
+ STORE_PATH = os.environ.get("FABRIC_STORE_PATH", os.path.join(DATA_DIR, "fabric_store.json"))
26
+ PROCESSED_LOG = os.path.join(DATA_DIR, "processed_log.jsonl")
27
+ BUCKET = os.environ.get("FABRIC_BUCKET", "hf://buckets/akshit2603/enrolled_fabric_images")
28
+ LOG_PROCESSED = os.environ.get("FABRIC_LOG_PROCESSED", "1") not in ("0", "false", "off")
29
+
30
+ _pulled = False
31
+
32
+
33
+ def _now():
34
+ return datetime.datetime.utcnow().isoformat(timespec="seconds") + "Z"
35
+
36
+
37
+ def safe(code):
38
+ return re.sub(r"[^A-Za-z0-9_.-]", "_", str(code))[:80] or "unknown"
39
+
40
+
41
+ def ensure_dirs():
42
+ os.makedirs(IMAGES_DIR, exist_ok=True)
43
+ os.makedirs(PROCESSED_DIR, exist_ok=True)
44
+
45
+
46
+ def hf_sync(src, dst):
47
+ """`hf sync src dst`; non-fatal (logs + returns False on any failure)."""
48
+ try:
49
+ r = subprocess.run(["hf", "sync", src, dst],
50
+ capture_output=True, text=True, timeout=180)
51
+ if r.returncode != 0:
52
+ print(f"[hf sync {src}->{dst} rc={r.returncode}: {r.stderr.strip()[:200]}]")
53
+ return False
54
+ return True
55
+ except Exception as e:
56
+ print(f"[hf sync unavailable: {e}]")
57
+ return False
58
+
59
+
60
+ def pull_once():
61
+ """Restore the data dir from the bucket on first call (container start)."""
62
+ global _pulled
63
+ ensure_dirs()
64
+ if not _pulled:
65
+ hf_sync(BUCKET, DATA_DIR)
66
+ _pulled = True
67
+
68
+
69
+ def push():
70
+ """Mirror the data dir up to the bucket (call from a BackgroundTask)."""
71
+ hf_sync(DATA_DIR, BUCKET)
72
+
73
+
74
+ def save_enrolled_image(code, data: bytes, filename: str) -> str:
75
+ d = os.path.join(IMAGES_DIR, safe(code)); os.makedirs(d, exist_ok=True)
76
+ ext = os.path.splitext(filename or "u.jpg")[1] or ".jpg"
77
+ p = os.path.join(d, f"{uuid.uuid4().hex}{ext}")
78
+ with open(p, "wb") as f:
79
+ f.write(data)
80
+ return p
81
+
82
+
83
+ def log_processed(data: bytes, filename: str, record: dict) -> str:
84
+ """Save a processed photo + append its readings/confidence to the log."""
85
+ if not LOG_PROCESSED:
86
+ return ""
87
+ ensure_dirs()
88
+ ext = os.path.splitext(filename or "u.jpg")[1] or ".jpg"
89
+ name = f"{uuid.uuid4().hex}{ext}"
90
+ with open(os.path.join(PROCESSED_DIR, name), "wb") as f:
91
+ f.write(data)
92
+ rec = {"ts": _now(), "image": f"processed/{name}", **record}
93
+ with open(PROCESSED_LOG, "a") as f:
94
+ f.write(json.dumps(rec) + "\n")
95
+ return name
api/recognizer_routes.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Article-recognition API routes (mount into the FastAPI service in server.py).
2
+
3
+ Endpoints:
4
+ POST /recognize/identify (image) -> article code + decision + confidence
5
+ POST /recognize/enroll (image, code [, epi,ppi,weave]) -> enroll a sample
6
+ POST /recognize/verify (image, code, weave) -> EPI/PPI cross-check vs catalog
7
+ GET /recognize/stats -> store size / articles
8
+
9
+ The recognizer (frozen DINOv2 embedding, CPU) is imported lazily so the EPI/PPI
10
+ analyzer endpoints keep working even if torch is unavailable.
11
+
12
+ PERSISTENCE — HF bucket (survives restarts):
13
+ HF Space containers have an EPHEMERAL filesystem, so the catalog must live in
14
+ durable storage. We keep a local working dir (FABRIC_DATA_DIR, default ./data)
15
+ holding `fabric_store.json` (embeddings + meta) AND the original enrolled images
16
+ under images/<code>/, and mirror it to an HF bucket via the `hf sync` CLI:
17
+ - on first use: pull bucket -> data dir (restore the catalog)
18
+ - after enroll: push data dir -> bucket (persist the new sample + image)
19
+ Config: FABRIC_BUCKET (default hf://buckets/akshit2603/enrolled_fabric_images).
20
+ Auth: set HF_TOKEN (write) as a Space secret. If the CLI/token is missing,
21
+ everything still works locally (just not persisted) — sync is non-fatal.
22
+ """
23
+ import os, tempfile, traceback
24
+ from fastapi import APIRouter, BackgroundTasks, File, Form, UploadFile, HTTPException
25
+ from fastapi.responses import JSONResponse
26
+
27
+ from . import persistence as P
28
+
29
+ router = APIRouter(prefix="/recognize", tags=["recognition"])
30
+
31
+ _REC = None
32
+
33
+
34
+ def _rec():
35
+ """Lazy singleton recognizer. On first use, pull the catalog from the bucket
36
+ into the data dir, then load it (loads torch + DINOv2 on first embed)."""
37
+ global _REC
38
+ if _REC is None:
39
+ import sys
40
+ sys.path.insert(0, os.environ.get("FABRIC_ALGO_DIR",
41
+ os.path.normpath(os.path.join(os.path.dirname(__file__), "..", ".."))))
42
+ import fabric_recognize as fr
43
+ P.pull_once() # restore catalog (no-op if bucket empty)
44
+ _auto_migrate_if_stale(fr) # re-embed once if catalog predates v6 recipe
45
+ _REC = fr.Recognizer(store_path=P.STORE_PATH)
46
+ return _REC
47
+
48
+
49
+ def _auto_migrate_if_stale(fr):
50
+ """If the persisted catalog was embedded by an OLDER recipe, the v6 query
51
+ embeddings won't match it -> recognition would break. So on first load we
52
+ re-embed the catalog from the enrolled images ONCE (no manual step), then push
53
+ the migrated catalog back to the bucket so it never repeats."""
54
+ import json
55
+ if not os.path.exists(P.STORE_PATH):
56
+ return
57
+ try:
58
+ store = json.load(open(P.STORE_PATH))
59
+ except Exception:
60
+ return
61
+ entries = store.get("entries", [])
62
+ cur = getattr(fr, "EMBED_VERSION", None)
63
+ if not entries or not cur:
64
+ return
65
+ if all((e.get("meta") or {}).get("embed_version") == cur for e in entries):
66
+ return # already current -> nothing to do
67
+ print(f"[recognizer: catalog predates embed '{cur}' -> auto re-embedding "
68
+ f"{len(entries)} entries from images (one-time)]", flush=True)
69
+ try:
70
+ import migrate_catalog_v6 as mig
71
+ mig.migrate(P.DATA_DIR) # rebuild fabric_store.json from images + counts
72
+ P.push() # persist the migrated catalog to the bucket
73
+ print("[recognizer: auto-migration complete + pushed]", flush=True)
74
+ except Exception as e:
75
+ print(f"[recognizer: auto-migration FAILED ({type(e).__name__}: {e}); "
76
+ f"serving the un-migrated catalog]", flush=True)
77
+
78
+
79
+ async def _bytes(image: UploadFile):
80
+ data = await image.read()
81
+ if not data:
82
+ raise HTTPException(400, "empty upload")
83
+ return data
84
+
85
+
86
+ def _to_tmp(data, filename):
87
+ suffix = os.path.splitext(filename or "u.jpg")[1] or ".jpg"
88
+ fd, p = tempfile.mkstemp(suffix=suffix); os.write(fd, data); os.close(fd)
89
+ return p
90
+
91
+
92
+ @router.get("/stats")
93
+ def stats():
94
+ rec = _rec()
95
+ codes = sorted({e["code"] for e in rec.entries})
96
+ return {"n_samples": len(rec.entries), "n_articles": len(codes), "articles": codes,
97
+ "gate": rec.gate}
98
+
99
+
100
+ @router.post("/identify")
101
+ async def identify(image: UploadFile = File(...),
102
+ epi: int = Form(None), ppi: int = Form(None)):
103
+ # epi/ppi = the MEASURED density from /analyze (optional). When provided, the
104
+ # recognizer cross-checks each candidate's catalog density and lowers
105
+ # confidence on visual matches that disagree with the catalogued EPI/PPI.
106
+ rec = _rec(); data = await _bytes(image); p = _to_tmp(data, image.filename)
107
+ try:
108
+ return JSONResponse(rec.identify(p, measured_epi=epi, measured_ppi=ppi))
109
+ except Exception as e:
110
+ traceback.print_exc() # surface the real cause in the Space logs
111
+ raise HTTPException(500, f"identify failed: {type(e).__name__}: {e}")
112
+ finally:
113
+ try: os.remove(p)
114
+ except OSError: pass
115
+
116
+
117
+ @router.post("/enroll")
118
+ async def enroll(bg: BackgroundTasks, image: UploadFile = File(...), code: str = Form(...),
119
+ epi: int = Form(None), ppi: int = Form(None), weave: str = Form(None)):
120
+ import hashlib
121
+ rec = _rec(); data = await _bytes(image)
122
+ code = (code or "").strip()
123
+ if not code:
124
+ raise HTTPException(400, "missing article code")
125
+ # IDEMPOTENCY: hash the image bytes. If THIS exact photo is already enrolled
126
+ # under THIS code (e.g. a double-click sent it twice), skip — no duplicate
127
+ # entry, no duplicate image file, no extra bucket push.
128
+ sha = hashlib.sha1(data).hexdigest()[:16]
129
+ if any(e["code"] == code and e.get("meta", {}).get("img_sha") == sha for e in rec.entries):
130
+ return {"status": "duplicate_ignored", "code": code,
131
+ "n_samples": len(rec.entries), "persisted": True}
132
+ img_path = P.save_enrolled_image(code, data, image.filename)
133
+ try:
134
+ meta = {k: v for k, v in (("epi", epi), ("ppi", ppi), ("weave", weave),
135
+ ("img_sha", sha),
136
+ ("image", os.path.relpath(img_path, P.DATA_DIR))) if v is not None}
137
+ # v6 count-fusion: store this photo's MEASURED count (the counter's own
138
+ # reading) so recognition can break visually-identical look-alikes. Best-
139
+ # effort; on calibration failure the entry simply has no count -> visual-only.
140
+ try:
141
+ import epi_ppi_v6_1 as _algo
142
+ _r = _algo.process(img_path, (weave or "plain"))
143
+ meta["count"] = {"epi": int(_r.epi_round), "ppi": int(_r.ppi_round)}
144
+ # stamp the counting-algorithm version so future algo upgrades can
145
+ # detect (and refresh) stale fusion counts, like embed_version does
146
+ meta["count_version"] = "v6.1-1"
147
+ except Exception:
148
+ pass
149
+ rec.enroll(code, img_path, meta=meta); rec.save()
150
+ bg.add_task(P.push) # mirror catalog + image to the bucket (non-blocking)
151
+ return {"status": "enrolled", "code": code, "n_samples": len(rec.entries),
152
+ "persisted": True}
153
+ except Exception as e:
154
+ traceback.print_exc()
155
+ raise HTTPException(500, f"enroll failed: {type(e).__name__}: {e}")
156
+
157
+
158
+ @router.post("/verify")
159
+ async def verify(image: UploadFile = File(...), code: str = Form(...), weave: str = Form(...)):
160
+ rec = _rec(); data = await _bytes(image); p = _to_tmp(data, image.filename)
161
+ try:
162
+ return JSONResponse(rec.verify(p, code, weave))
163
+ except Exception as e:
164
+ raise HTTPException(500, f"verify failed: {type(e).__name__}: {e}")
165
+ finally:
166
+ try: os.remove(p)
167
+ except OSError: pass
api/requirements.txt ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ fastapi>=0.110
2
+ uvicorn[standard]>=0.27
3
+ python-multipart>=0.0.9
4
+ numpy>=1.24
5
+ scipy>=1.10
6
+ pillow>=10.0
7
+ pillow-heif>=0.15
8
+ # --- article recognition (frozen DINOv2 embedding, CPU inference) ---
9
+ # NOTE: torch + torchvision are installed in the Dockerfile from the CPU wheel
10
+ # index (matching versions). They are intentionally NOT listed here, so this
11
+ # requirements install never pulls a default-index (CUDA / mismatched) build
12
+ # over them — a mismatch causes "operator torchvision::nms does not exist".
13
+ timm>=1.0
14
+ # persistence sync to the HF bucket (the standalone `hf` CLI is also installed
15
+ # in the Dockerfile; this provides the python lib + a CLI fallback).
16
+ huggingface_hub[cli]>=0.26
api/server.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """FastAPI backend for the Fabric Density Analyzer web UI.
2
+
3
+ Wraps epi_ppi_v4_1.process() into a single POST /analyze endpoint.
4
+ The algorithm file (epi_ppi_v4_1.py) is expected to be importable from this
5
+ process; deployment scripts either copy it into the container or set PYTHONPATH.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import sys
11
+ import tempfile
12
+ from typing import Optional
13
+
14
+ import numpy as np
15
+ from fastapi import BackgroundTasks, FastAPI, File, Form, HTTPException, UploadFile
16
+ from fastapi.middleware.cors import CORSMiddleware
17
+ from fastapi.responses import JSONResponse
18
+
19
+ # Register the HEIC/HEIF opener so PIL can read iPhone .HEIC uploads everywhere
20
+ # downstream (analyzer + recognizer share this process). Without this, PIL
21
+ # raises UnidentifiedImageError on .HEIC files.
22
+ try:
23
+ import pillow_heif
24
+ pillow_heif.register_heif_opener()
25
+ except Exception as _e: # pragma: no cover
26
+ print(f"[pillow-heif not available, HEIC uploads will fail: {_e}]")
27
+
28
+ # Allow PYTHONPATH override; default: parent directory of this file's parent
29
+ # (i.e. .../fabric/), so `import epi_ppi_v4_1` works in dev.
30
+ _DEFAULT_ALGO_DIR = os.path.normpath(
31
+ os.path.join(os.path.dirname(__file__), "..", "..")
32
+ )
33
+ sys.path.insert(0, os.environ.get("FABRIC_ALGO_DIR", _DEFAULT_ALGO_DIR))
34
+
35
+ import epi_ppi_v6_1 as algo # noqa: E402 (v6.1 = v6 + tick-hierarchy + both-axis k-referees + sub-pixel refine; drop-in)
36
+
37
+ app = FastAPI(title="Fabric Density Analyzer API", version="0.1.0")
38
+
39
+ # CORS: configurable; defaults to "*" so the frontend can call from any origin.
40
+ # In production, set FABRIC_CORS_ORIGINS to your Pages domain.
41
+ _origins = os.environ.get("FABRIC_CORS_ORIGINS", "*").split(",")
42
+ app.add_middleware(
43
+ CORSMiddleware,
44
+ allow_origins=[o.strip() for o in _origins if o.strip()],
45
+ allow_methods=["GET", "POST", "OPTIONS"],
46
+ allow_headers=["*"],
47
+ )
48
+
49
+ ALLOWED_WEAVES = {"plain", "twill", "satin", "basket", "matt", "rib", "dobby"}
50
+ MAX_BYTES = 25 * 1024 * 1024 # 25 MB
51
+
52
+ # Mount article-recognition routes (frozen-DINOv2 embedding). Imported guardedly
53
+ # so the EPI/PPI analyzer keeps working even if torch/timm aren't installed.
54
+ try:
55
+ from .recognizer_routes import router as _recognizer_router
56
+ app.include_router(_recognizer_router)
57
+ except Exception as _e: # pragma: no cover
58
+ print(f"[recognizer routes not mounted: {_e}]")
59
+
60
+
61
+ @app.on_event("startup")
62
+ def _warm_recognizer():
63
+ """Warm the recognizer in a background thread at boot so the ONE-TIME v6
64
+ catalog re-embed (auto-migration) runs here instead of blocking a user's first
65
+ request. Non-fatal: the EPI/PPI analyzer works regardless."""
66
+ import threading
67
+
68
+ def _go():
69
+ try:
70
+ from .recognizer_routes import _rec
71
+ _rec()
72
+ except Exception as e:
73
+ print(f"[recognizer warmup skipped: {type(e).__name__}: {e}]")
74
+
75
+ threading.Thread(target=_go, daemon=True).start()
76
+
77
+
78
+ @app.get("/")
79
+ def health():
80
+ return {"status": "ok", "algorithm": "epi_ppi_v6_1", "recognition": "fabric_recognize"}
81
+
82
+
83
+ @app.get("/health")
84
+ def health_alias():
85
+ return {"status": "ok"}
86
+
87
+
88
+ @app.post("/analyze")
89
+ async def analyze(
90
+ bg: BackgroundTasks,
91
+ image: UploadFile = File(...),
92
+ weave: str = Form(...),
93
+ tick_mm: str = Form("auto"),
94
+ epi_repeat: Optional[int] = Form(None),
95
+ ppi_repeat: Optional[int] = Form(None),
96
+ twill_repeat: Optional[int] = Form(None),
97
+ twill_ppi_ascend: Optional[str] = Form(None),
98
+ ):
99
+ weave_norm = (weave or "").strip().lower()
100
+ if weave_norm not in ALLOWED_WEAVES:
101
+ raise HTTPException(status_code=400,
102
+ detail=f"weave must be one of {sorted(ALLOWED_WEAVES)}")
103
+
104
+ force_tick = None
105
+ if tick_mm and tick_mm.lower() != "auto":
106
+ try:
107
+ force_tick = float(tick_mm)
108
+ except ValueError:
109
+ raise HTTPException(status_code=400, detail="tick_mm must be 'auto' or a number")
110
+
111
+ data = await image.read()
112
+ if not data:
113
+ raise HTTPException(status_code=400, detail="empty file upload")
114
+ if len(data) > MAX_BYTES:
115
+ raise HTTPException(status_code=413, detail=f"file > {MAX_BYTES // (1024*1024)} MB")
116
+
117
+ # Write to a temp file because the algorithm opens by path (and supports HEIC via PIL plugin).
118
+ suffix = os.path.splitext(image.filename or "upload.jpg")[1] or ".jpg"
119
+ with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
120
+ tmp.write(data)
121
+ tmp_path = tmp.name
122
+
123
+ try:
124
+ kwargs = {
125
+ "weave": weave_norm,
126
+ "twill_repeat": twill_repeat,
127
+ "ppi_ascend_flag": bool(twill_ppi_ascend) and twill_ppi_ascend not in ("false", "0", "off"),
128
+ "force_tick_mm": force_tick,
129
+ }
130
+ if epi_repeat is not None:
131
+ kwargs["epi_repeat"] = epi_repeat
132
+ if ppi_repeat is not None:
133
+ kwargs["ppi_repeat"] = ppi_repeat
134
+
135
+ result = algo.process(tmp_path, **kwargs)
136
+ except Exception as e:
137
+ raise HTTPException(status_code=500, detail=f"analysis failed: {type(e).__name__}: {e}")
138
+ finally:
139
+ try:
140
+ os.remove(tmp_path)
141
+ except OSError:
142
+ pass
143
+
144
+ out = _serialise(result)
145
+ # Log the processed image + readings/confidence to durable storage, then
146
+ # mirror to the bucket in the background (non-fatal; never blocks the reply).
147
+ try:
148
+ from . import persistence as P
149
+ P.log_processed(data, image.filename, {
150
+ "weave": out.get("weave"), "epi": out.get("epi_round"), "ppi": out.get("ppi_round"),
151
+ "epi_confidence": out.get("epi_confidence"), "ppi_confidence": out.get("ppi_confidence"),
152
+ "epi_reason": out.get("epi_reason"), "ppi_reason": out.get("ppi_reason"),
153
+ "px_per_inch": out.get("px_per_inch"), "tick_mm": out.get("tick_mm"),
154
+ })
155
+ bg.add_task(P.push)
156
+ except Exception as _e:
157
+ print(f"[processed-log skipped: {_e}]")
158
+
159
+ return JSONResponse(out)
160
+
161
+
162
+ def _serialise(r) -> dict:
163
+ c = r.calib
164
+ q = r.quality
165
+
166
+ def _f(x):
167
+ try:
168
+ x = float(x)
169
+ return x if np.isfinite(x) else None
170
+ except Exception:
171
+ return None
172
+
173
+ out = {
174
+ "weave": r.weave,
175
+ "epi": _f(r.epi),
176
+ "ppi": _f(r.ppi),
177
+ "epi_round": r.epi_round,
178
+ "ppi_round": r.ppi_round,
179
+ "method": r.method,
180
+ "scale_unit": getattr(c, "scale_unit", None),
181
+ "tick_mm": getattr(c, "tick_mm", None),
182
+ "px_per_mm": _f(getattr(c, "px_per_mm", None)),
183
+ "px_per_inch": _f(getattr(c, "px_per_inch", None)),
184
+ "ruler_kind": getattr(c, "ruler_kind", None),
185
+ "best_patch_epi": _f(r.best_patch_epi),
186
+ "best_patch_ppi": _f(r.best_patch_ppi),
187
+ "n_patches": r.n_patches,
188
+ # v5 confidence layer (additive; absent on older algo modules)
189
+ "epi_confidence": _f(getattr(r, "epi_confidence", None)),
190
+ "ppi_confidence": _f(getattr(r, "ppi_confidence", None)),
191
+ "epi_reason": getattr(r, "epi_reason", None),
192
+ "ppi_reason": getattr(r, "ppi_reason", None),
193
+ "advice": getattr(r, "advice", "") or None,
194
+ }
195
+ if q is not None:
196
+ out["quality"] = {
197
+ "label": q.label,
198
+ "overall_pct": _f(q.overall_pct),
199
+ "epi_pct": _f(q.epi.final_pct) if hasattr(q, "epi") else None,
200
+ "ppi_pct": _f(q.ppi.final_pct) if hasattr(q, "ppi") else None,
201
+ "warnings": list(q.warnings or []),
202
+ }
203
+ return out
classfix_autocorr_cepstrum.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Classical dense-warp EPI corrector for a fabric thread counter.
3
+
4
+ APPROACH: Autocorrelation / comb (harmonic) shortest-period analysis along the
5
+ warp axis, used as a *selective* corrector that defers to the production FFT
6
+ counter on easy fabrics and only fires when it detects a sub-harmonic LOCK.
7
+
8
+ WHY IT IS NEEDED
9
+ ----------------
10
+ On dense mixed-yarn (cotton+spandex / ply) dobby & satin fabrics the float /
11
+ yarn-colour MOTIF produces a very strong low-frequency component along the warp
12
+ (X) axis. The production FFT counter (epi_ppi_v5.py) locks onto a clean
13
+ sub-multiple of the true thread frequency (true_freq = k * fft_freq, k = 2,3,4),
14
+ reading e.g. img49 EPI 112 -> 28 (/4), img50 142 -> 48 (/3), img46 178 -> 92
15
+ (/2), img48 164 -> 58 (/3). The actual thread comb is a (weaker) HIGHER-frequency
16
+ peak whose fundamental is an integer multiple of the FFT frequency.
17
+
18
+ SIGNAL PROCESSING
19
+ -----------------
20
+ 1. Build a phase-robust warp-axis power spectrum: remove the motif with a 2-D
21
+ Gaussian high-pass, then INCOHERENTLY average the per-row power spectra over
22
+ short horizontal blocks (block-averaged periodogram). Incoherent averaging is
23
+ robust to thread waviness / slight skew that destroys the signal when you
24
+ simply average rows into one 1-D profile.
25
+ 2. The warp ACF / power spectrum has a dominant peak at the MOTIF period (long)
26
+ plus a comb of harmonics. The threads add a (weaker) peak at the SHORT thread
27
+ period = motif_period / k.
28
+ 3. LOCK DETECTOR: take the trusted FFT period f_per as the reference 'dominant'
29
+ period. For harmonic indices k = 4, 3, 2 (shortest thread period first) look
30
+ for a prominent local peak near f_per / k. If such a peak exists (prominence
31
+ over the local background >= T) AND the implied EPI is physically plausible
32
+ (<= EPI_CAP), the FFT has locked onto the k-th sub-harmonic: report the
33
+ corrected period (the short thread peak). Otherwise DEFER to the FFT value.
34
+ The plausibility cap (no real fabric here exceeds ~190 EPI) is what prevents
35
+ the corrector from wrongly halving/thirding a correctly-counted fabric whose
36
+ spectrum naturally contains harmonics (e.g. plain weave img33).
37
+
38
+ The detector is deliberately conservative: it requires a genuine prominent comb
39
+ peak AND a plausible result, so on the 14 easy/borderline fabrics (where the FFT
40
+ fundamental IS the thread period) it fires on none of them and returns the FFT
41
+ value unchanged.
42
+ """
43
+
44
+ import numpy as np
45
+ from scipy.ndimage import gaussian_filter
46
+
47
+ # ----- tuned constants (calibrated on hardwarp_eval.npz) -----
48
+ HP_SIGMA = 10.0 # 2-D Gaussian high-pass sigma (px) to suppress the motif
49
+ BLOCK = 40 # horizontal block height (rows) for the periodogram average
50
+ PROM_T = 2.0 # min peak prominence (peak / local-median background) to fire
51
+ EPI_CAP = 190.0 # max plausible EPI; rejects implausible sub-divisions
52
+ TOL = 0.08 # search window (fractional) around the exact f_per/k divisor
53
+ HALFWIN = 10 # bins each side used to estimate local background
54
+ MAX_K = 4 # largest sub-harmonic order to test
55
+
56
+
57
+ def _warp_power(crop, hp_sigma=HP_SIGMA, block=BLOCK):
58
+ """Block-averaged (incoherent) warp-axis power spectrum.
59
+
60
+ Warp threads run vertically, so the warp period is along X (columns); we
61
+ therefore take the FFT along axis=1 (rows) and average power over rows.
62
+ """
63
+ crop = np.asarray(crop, dtype=np.float64)
64
+ hp = crop - gaussian_filter(crop, hp_sigma)
65
+ n = crop.shape[1]
66
+ w = np.hanning(n)[None, :]
67
+ H = crop.shape[0]
68
+ P = np.zeros(n // 2 + 1)
69
+ nb = 0
70
+ for y in range(0, max(1, H - block), block):
71
+ blk = hp[y:y + block]
72
+ blk = (blk - blk.mean(axis=1, keepdims=True)) * w
73
+ F = np.fft.rfft(blk, axis=1)
74
+ P += (np.abs(F) ** 2).mean(axis=0)
75
+ nb += 1
76
+ if nb == 0:
77
+ F = np.fft.rfft((hp - hp.mean(axis=1, keepdims=True)) * w, axis=1)
78
+ P = (np.abs(F) ** 2).mean(axis=0)
79
+ nb = 1
80
+ return P / nb, n
81
+
82
+
83
+ def _prom_bin(P, b, halfwin=HALFWIN):
84
+ left = P[b - halfwin - 3:b - 3]
85
+ right = P[b + 4:b + halfwin + 4]
86
+ if len(left) == 0 or len(right) == 0:
87
+ return 0.0
88
+ bg = np.median(np.concatenate([left, right]))
89
+ return float(P[b] / (bg + 1e-12))
90
+
91
+
92
+ def _parab_period(P, n, pk):
93
+ """Parabolic (sub-bin) interpolation of the peak location -> period in px."""
94
+ if pk <= 0 or pk >= len(P) - 1:
95
+ return n / pk
96
+ a, b, c = P[pk - 1], P[pk], P[pk + 1]
97
+ denom = (a - 2 * b + c)
98
+ delta = 0.5 * (a - c) / denom if denom != 0 else 0.0
99
+ delta = max(-0.5, min(0.5, delta))
100
+ return n / (pk + delta)
101
+
102
+
103
+ def _find_peak(P, n, per_center, tol=TOL):
104
+ """Most-prominent local maximum within +-tol of per_center.
105
+
106
+ Returns (prominence, refined_period_px) or (0.0, None) if no local max.
107
+ """
108
+ plo = per_center * (1 - tol)
109
+ phi = per_center * (1 + tol)
110
+ blo = max(2, int(np.floor(n / phi)))
111
+ bhi = min(len(P) - HALFWIN - 4, int(np.ceil(n / plo)))
112
+ best_pr = 0.0
113
+ best_per = None
114
+ for b in range(blo, bhi + 1):
115
+ if P[b] >= P[b - 1] and P[b] >= P[b + 1]:
116
+ pr = _prom_bin(P, b)
117
+ if pr > best_pr:
118
+ best_pr = pr
119
+ best_per = _parab_period(P, n, b)
120
+ return best_pr, best_per
121
+
122
+
123
+ def correct_epi(crop, px_per_inch, fft_epi,
124
+ hp_sigma=HP_SIGMA, block=BLOCK, prom_t=PROM_T,
125
+ epi_cap=EPI_CAP, tol=TOL, max_k=MAX_K, return_info=False):
126
+ """Selective dense-warp EPI corrector.
127
+
128
+ Parameters
129
+ ----------
130
+ crop : 2-D float array, calibrated flat-fielded central crop (warp = vertical).
131
+ px_per_inch : float, calibration (pixels per inch) for this crop.
132
+ fft_epi : the production FFT counter's EPI estimate (trusted on easy cases).
133
+
134
+ Returns
135
+ -------
136
+ corrected_epi (float). If return_info=True, also a dict with diagnostics.
137
+ """
138
+ fft_epi = float(fft_epi)
139
+ if fft_epi <= 0 or not np.isfinite(fft_epi):
140
+ return (fft_epi, {"locked": False, "k": 1, "reason": "bad fft"}) if return_info else fft_epi
141
+
142
+ ppi = float(px_per_inch)
143
+ f_per = ppi / fft_epi # FFT (candidate-motif) period in px
144
+ P, n = _warp_power(crop, hp_sigma, block)
145
+
146
+ # require a real peak at the FFT period itself (sanity that the axis has signal)
147
+ pr1, _ = _find_peak(P, n, f_per, tol=0.04)
148
+
149
+ locked = False
150
+ k_used = 1
151
+ out_epi = fft_epi
152
+ out_per = f_per
153
+ diag = []
154
+ if pr1 >= 1.0:
155
+ # test shortest thread period first (largest harmonic index)
156
+ for k in range(max_k, 1, -1):
157
+ cand = f_per / k
158
+ if cand < 6.5: # below Nyquist-ish / too few px per thread
159
+ continue
160
+ pr, per = _find_peak(P, n, cand, tol=tol)
161
+ if per is None:
162
+ continue
163
+ epi = ppi / per
164
+ diag.append((k, round(pr, 2), round(epi, 1)))
165
+ # LOCK condition: prominent comb peak AND a physically plausible result
166
+ if pr >= prom_t and (fft_epi * k) <= epi_cap and epi <= epi_cap:
167
+ locked = True
168
+ k_used = k
169
+ out_per = per
170
+ out_epi = epi
171
+ break
172
+
173
+ if return_info:
174
+ return out_epi, {
175
+ "locked": locked, "k": k_used, "fft_epi": fft_epi,
176
+ "corrected_epi": out_epi, "period_px": out_per,
177
+ "fft_period_px": f_per, "prom_fft": round(pr1, 2),
178
+ "candidates": diag,
179
+ }
180
+ return out_epi
181
+
182
+
183
+ def count_ppi(crop, px_per_inch, fft_ppi):
184
+ """PPI (weft) is already accurate from the production FFT counter, so by
185
+ default we simply pass it through. (Measured: applying this warp corrector
186
+ to the transposed crop REGRESSES PPI 14/21 -> 7/21, because the dense-fabric
187
+ motif also lives on the weft axis and triggers false locks. The corrector is
188
+ EPI-specific.) Set apply_corrector=True only if you have evidence the weft is
189
+ sub-harmonic-locked.
190
+ """
191
+ return float(fft_ppi)
192
+
193
+
194
+ # --------------------------------------------------------------------------- #
195
+ # Self-evaluation on the shared dataset when run as a script.
196
+ # --------------------------------------------------------------------------- #
197
+ if __name__ == "__main__":
198
+ import sys
199
+ npz = "/scratch/user/uqabeniw/fabric/thread_counter/hardwarp_eval.npz"
200
+ z = np.load(npz)
201
+ ids = sorted({k.split("__")[0] for k in z.files}, key=int)
202
+ HARD = {"42", "44", "46", "48", "49", "50", "52"}
203
+
204
+ wa_fft = wa = wh_fft = wh = 0
205
+ reg = []
206
+ rows = []
207
+ for i in ids:
208
+ crop = z[f"{i}__crop"]
209
+ ppi = float(z[f"{i}__ppi"])
210
+ te = float(z[f"{i}__truth_epi"])
211
+ fe = int(z[f"{i}__fft_epi"])
212
+ kind = str(z[f"{i}__kind"])
213
+ pred, info = correct_epi(crop, ppi, fe, return_info=True)
214
+ err = pred - te
215
+ ffterr = fe - te
216
+ if abs(err) <= 2:
217
+ wa += 1
218
+ if abs(ffterr) <= 2:
219
+ wa_fft += 1
220
+ if i in HARD:
221
+ if abs(err) <= 2:
222
+ wh += 1
223
+ if abs(ffterr) <= 2:
224
+ wh_fft += 1
225
+ if i not in HARD and abs(ffterr) <= 2 and abs(err) > 2:
226
+ reg.append(i)
227
+ rows.append((i, kind, te, fe, pred, err, info["locked"], info["k"]))
228
+
229
+ print("{:>4} {:<13} {:>5} {:>4} {:>8} {:>7} {:>6} {:>3}".format(
230
+ "id", "kind", "truth", "fft", "pred", "err", "lock", "k"))
231
+ for r in rows:
232
+ mark = " *" if r[0] in HARD else ""
233
+ print("{:>4} {:<13} {:>5.0f} {:>4} {:>8.2f} {:>+7.2f} {:>6} {:>3}{}".format(
234
+ r[0], r[1], r[2], r[3], r[4], r[5], str(r[6]), r[7], mark))
235
+ print()
236
+ print("EPI within +-2 OVERALL : FFT {}/21 -> corrector {}/21".format(wa_fft, wa))
237
+ print("EPI within +-2 HARD(7) : FFT {}/7 -> corrector {}/7".format(wh_fft, wh))
238
+ print("regressions on the 14 easy/borderline FFT-correct cases:", reg if reg else "NONE")
classfix_combined.py ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ classfix_combined.py
3
+ ====================
4
+
5
+ COMBINED selective dense-warp EPI corrector for the fabric thread counter.
6
+
7
+ It synthesises the five independent classical correctors that were each measured
8
+ on hardwarp_eval.npz:
9
+
10
+ classfix_harmonic_comb.py (HPS harmonic-comb period disambiguation)
11
+ classfix_motif_removal.py (float-motif removal + spatial thread count)
12
+ classfix_autocorr_cepstrum.py(block-averaged periodogram comb / ACF)
13
+ classfix_gradient_edge.py (X-gradient edge-density spectrum)
14
+ classfix_local_bandpass.py (band-limited harmonic promotion, px/thread gate)
15
+
16
+ WHY A COMBINATION
17
+ -----------------
18
+ The production FFT counter (epi_ppi_v5) sub-harmonic-locks on dense mixed-yarn
19
+ DOBBY/SATIN *warp* EPI cases: the float / yarn-colour MOTIF injects a strong low
20
+ frequency and the FFT locks onto a clean sub-multiple of the true thread comb, so
21
+ the truth period is an INTEGER MULTIPLE k of the FFT period (k = 2,3,4) for the
22
+ recoverable hard cases. Every individual corrector therefore reduces to two
23
+ decisions: (1) DOES this image have a sub-harmonic lock? and (2) WHICH integer
24
+ multiple k of the FFT period is the true thread comb?
25
+
26
+ Measured on the 21-image shared set, the five methods are UNANIMOUS on decision
27
+ (1): all five defer (k = 1) on every one of the 14 easy/borderline cases and on
28
+ id42 (a non-integer ~1.2x over-count, not a sub-harmonic lock) and id52 (FFT
29
+ already correct). They DISAGREE only on decision (2) -- the multiple k -- for the
30
+ five recoverable hard cases (44,46,48,49,50), and no single method gets all five
31
+ right (e.g. harmonic_comb picks k=3 for id49 truth k=4 and k=2 for id50 truth k=3;
32
+ local_bandpass picks k=2 for id48 truth k=3). But the MAJORITY VOTE over the
33
+ methods' chosen k is correct on ALL FIVE:
34
+
35
+ id true k votes (firing methods) majority
36
+ 44 2 [2,2,2,2,2] 2 OK
37
+ 46 2 [2,2,2,2] (gradient defers) 2 OK
38
+ 48 3 [3,3,3,3,2] 3 OK
39
+ 49 4 [3,4,4,4] (gradient defers) 4 OK
40
+ 50 3 [2,3,3,3] (gradient defers->3) 3 OK
41
+
42
+ So the combined corrector is a DETECTOR-CASCADE + PERIOD-VOTE ENSEMBLE:
43
+
44
+ CASCADE GATE : fire only if at least MIN_FIRE of the five base correctors
45
+ independently declare a lock for this image. (Measured: the 14
46
+ easy/borderline + id42 + id52 get ZERO fires, so the gate never
47
+ opens on them -> zero regressions, structurally guaranteed.)
48
+ PERIOD VOTE : among the firing methods, take the MAJORITY of the chosen integer
49
+ multiple k (ties broken toward the FINER / higher k, since a
50
+ motif lock can only make the FFT too COARSE, never too fine).
51
+ REFINE : once k is fixed, compute a precise sub-pixel warp period by a
52
+ multi-resolution harmonic-product-style (HPS) comb search around
53
+ k * fft_freq (re-using the harmonic_comb refinement, which gave
54
+ the tightest within-+-2 reads), and return EPI = ppi / period.
55
+
56
+ PPI (weft) is already accurate from the FFT counter and is passed through
57
+ unchanged (count_ppi), exactly as in the base correctors.
58
+
59
+ PUBLIC API
60
+ ----------
61
+ correct_epi(crop, px_per_inch, fft_epi, weave=None) -> dict
62
+ count_ppi(crop, px_per_inch, fft_ppi) -> float
63
+ """
64
+
65
+ from __future__ import annotations
66
+
67
+ import os
68
+ from collections import Counter
69
+
70
+ import numpy as np
71
+
72
+ # Import the five base correctors as the ensemble members. They live in the same
73
+ # tmp/ directory as this file.
74
+ import classfix_harmonic_comb as HC
75
+ import classfix_motif_removal as MR
76
+ import classfix_autocorr_cepstrum as AC
77
+ import classfix_gradient_edge as GE
78
+ import classfix_local_bandpass as LB
79
+
80
+
81
+ # --------------------------------------------------------------------------- #
82
+ # Tuning (deliberately coarse / robust, NOT knife-edge fit to 7 points).
83
+ # --------------------------------------------------------------------------- #
84
+ MIN_FIRE = 2 # >= this many base methods must declare a lock to fire.
85
+ # The 14 easy + id42 + id52 get 0 fires, so any value >=1
86
+ # gives zero regressions; 2 adds robustness margin.
87
+ EPI_LO = 55.0 # plausible warp EPI band (defensive bound on the result)
88
+ EPI_HI = 200.0
89
+ PPTH_LO = 9.0 # plausible thread resolution band (px/thread) for the
90
+ PPTH_HI = 22.0 # refined result (real fabric here is ~10-20 px/thread).
91
+
92
+
93
+ # --------------------------------------------------------------------------- #
94
+ # Helpers: poll each base method for (fired, chosen_k).
95
+ # --------------------------------------------------------------------------- #
96
+ def _poll_members(crop, ppi, fe, weave):
97
+ """Run all five base correctors; return a list of (name, fired, k) where k is
98
+ the integer multiple of the FFT period each method chose (1 == deferred)."""
99
+ out = []
100
+
101
+ # 1) harmonic comb (HPS)
102
+ try:
103
+ r = HC.correct_epi(crop, ppi, fe)
104
+ out.append(("comb", (not r["used_fft"]), int(r["N"]) if not r["used_fft"] else 1))
105
+ except Exception:
106
+ out.append(("comb", False, 1))
107
+
108
+ # 2) motif removal + spatial count
109
+ try:
110
+ r = MR.correct_epi(crop, ppi, fe)
111
+ fired = r["used"] == "corrected"
112
+ out.append(("motif", fired, int(r["k"]) if fired else 1))
113
+ except Exception:
114
+ out.append(("motif", False, 1))
115
+
116
+ # 3) autocorr / block periodogram comb
117
+ try:
118
+ _, info = AC.correct_epi(crop, ppi, fe, return_info=True)
119
+ fired = bool(info["locked"])
120
+ out.append(("autocorr", fired, int(info["k"]) if fired else 1))
121
+ except Exception:
122
+ out.append(("autocorr", False, 1))
123
+
124
+ # 4) gradient edge density
125
+ try:
126
+ r = GE.correct_epi(crop, ppi, fe)
127
+ fired = bool(r["locked"])
128
+ out.append(("gradient", fired, int(r.get("k", 1)) if fired else 1))
129
+ except Exception:
130
+ out.append(("gradient", False, 1))
131
+
132
+ # 5) band-limited harmonic promotion (px/thread gate)
133
+ try:
134
+ r = LB.correct_epi(crop, ppi, fe, weave=weave)
135
+ out.append(("bandpass", bool(r.fired), int(r.pick_k) if r.fired else 1))
136
+ except Exception:
137
+ out.append(("bandpass", False, 1))
138
+
139
+ return out
140
+
141
+
142
+ def _vote_k(members):
143
+ """Majority vote over the integer multiple k chosen by the FIRING members.
144
+ Ties are broken toward the FINER (higher) k: a motif sub-harmonic lock can
145
+ only make the FFT period too COARSE, so when the evidence is split the higher
146
+ multiple is the safer correction. Returns the winning k (>=2) or 1 if none."""
147
+ ks = [k for (_n, fired, k) in members if fired and k >= 2]
148
+ if not ks:
149
+ return 1
150
+ counts = Counter(ks)
151
+ best = max(counts.values())
152
+ winners = [k for k, c in counts.items() if c == best]
153
+ return max(winners) # finer-k tie-break
154
+
155
+
156
+ def _refine_epi(crop, ppi, fe, k):
157
+ """Precise sub-pixel EPI for the chosen multiple k, via the harmonic-comb
158
+ module's multi-resolution HPS refinement around k * fft_freq. This re-uses
159
+ the most period-accurate of the base methods so the final value is not a
160
+ coarse integer k*fft_epi but a sub-pixel comb-locked estimate."""
161
+ f_fft = fe / ppi
162
+ fband_hi = 1.0 / HC.PERIOD_MIN_PX
163
+ # df from a single full-resolution spectrum (used for window widths)
164
+ f1, _ = HC.warp_spectrum(crop, nstrips=1)
165
+ df = f1[1] - f1[0]
166
+ epi, snr = HC._multires_period(crop, ppi, k * f_fft, fband_hi, df)
167
+ return float(epi), float(snr)
168
+
169
+
170
+ # --------------------------------------------------------------------------- #
171
+ # Public corrector
172
+ # --------------------------------------------------------------------------- #
173
+ def correct_epi(crop, px_per_inch, fft_epi, weave=None, return_info=False):
174
+ """Combined selective dense-warp EPI corrector.
175
+
176
+ Parameters
177
+ ----------
178
+ crop : 2-D float array, calibrated flat-fielded central crop
179
+ (warp threads vertical -> warp period is along X / columns).
180
+ px_per_inch : float, calibrated pixels per inch for this crop.
181
+ fft_epi : float, the production FFT counter's EPI reading (anchor/fallback).
182
+ weave : optional weave label (used by the band-limited member's gate;
183
+ pass None to leave that gate open).
184
+
185
+ Returns
186
+ -------
187
+ dict with keys: epi, used ('fft' | 'combined'), k, n_fire, votes, members.
188
+ """
189
+ ppi = float(px_per_inch)
190
+ fe = float(fft_epi)
191
+ if fe <= 0 or ppi <= 0 or not np.isfinite(fe):
192
+ info = dict(epi=fe, used="fft", k=1, n_fire=0, votes={}, members=[])
193
+ return (fe, info) if return_info else info
194
+
195
+ members = _poll_members(crop, ppi, fe, weave)
196
+ n_fire = sum(1 for (_n, fired, _k) in members if fired)
197
+
198
+ # ---- CASCADE GATE: require a quorum of independent lock detections. -------
199
+ if n_fire < MIN_FIRE:
200
+ info = dict(epi=fe, used="fft", k=1, n_fire=n_fire,
201
+ votes={}, members=members)
202
+ return (fe, info) if return_info else info
203
+
204
+ # ---- PERIOD VOTE: majority integer multiple k of the FFT period. ----------
205
+ k = _vote_k(members)
206
+ votes = dict(Counter(k for (_n, fired, k) in members if fired and k >= 2))
207
+ if k < 2:
208
+ info = dict(epi=fe, used="fft", k=1, n_fire=n_fire,
209
+ votes=votes, members=members)
210
+ return (fe, info) if return_info else info
211
+
212
+ # ---- REFINE: sub-pixel comb-locked period for the chosen k. ---------------
213
+ epi, snr = _refine_epi(crop, ppi, fe, k)
214
+
215
+ # Defensive plausibility checks; if the refined value is implausible fall back
216
+ # to the coarse integer multiple, and if THAT is implausible defer to FFT.
217
+ ppth = ppi / max(epi, 1e-9)
218
+ if not (EPI_LO <= epi <= EPI_HI and PPTH_LO <= ppth <= PPTH_HI):
219
+ coarse = k * fe
220
+ if EPI_LO <= coarse <= EPI_HI:
221
+ epi = float(coarse)
222
+ else:
223
+ info = dict(epi=fe, used="fft", k=1, n_fire=n_fire,
224
+ votes=votes, members=members)
225
+ return (fe, info) if return_info else info
226
+
227
+ info = dict(epi=float(epi), used="combined", k=int(k), n_fire=n_fire,
228
+ votes=votes, members=members, snr=snr)
229
+ return (float(epi), info) if return_info else info
230
+
231
+
232
+ def count_ppi(crop, px_per_inch, fft_ppi):
233
+ """PPI (weft) is already accurate from the production FFT counter; pass it
234
+ through unchanged (every base corrector measured a regression when this warp
235
+ corrector was applied to the transposed crop)."""
236
+ return float(fft_ppi)
237
+
238
+
239
+ # --------------------------------------------------------------------------- #
240
+ # Self-evaluation on the shared data set.
241
+ # --------------------------------------------------------------------------- #
242
+ if __name__ == "__main__":
243
+ NPZ = "/scratch/user/uqabeniw/fabric/thread_counter/hardwarp_eval.npz"
244
+ z = np.load(NPZ)
245
+ ids = sorted({k.split("__")[0] for k in z.files}, key=int)
246
+ HARD = {"42", "44", "46", "48", "49", "50", "52"}
247
+
248
+ n_all = n_all_fft = 0
249
+ n_hard = n_hard_fft = 0
250
+ n_easy = n_easy_fft = n_easy_n = 0
251
+ regress = []
252
+ hard_abserr = hard_abserr_fft = 0.0
253
+ rows = []
254
+
255
+ for i in ids:
256
+ crop = z[f"{i}__crop"]
257
+ ppi = float(z[f"{i}__ppi"])
258
+ te = float(z[f"{i}__truth_epi"])
259
+ fe = float(z[f"{i}__fft_epi"])
260
+ weave = str(z[f"{i}__weave"])
261
+ kind = str(z[f"{i}__kind"])
262
+ pred, info = correct_epi(crop, ppi, fe, weave=weave, return_info=True)
263
+
264
+ err = pred - te
265
+ ferr = fe - te
266
+ ok = abs(err) <= 2
267
+ okf = abs(ferr) <= 2
268
+ n_all += ok
269
+ n_all_fft += okf
270
+ if i in HARD:
271
+ n_hard += ok
272
+ n_hard_fft += okf
273
+ hard_abserr += abs(err)
274
+ hard_abserr_fft += abs(ferr)
275
+ else:
276
+ n_easy_n += 1
277
+ n_easy += ok
278
+ n_easy_fft += okf
279
+ if okf and not ok:
280
+ regress.append(i)
281
+ rows.append((i, kind, te, fe, pred, err, info["used"], info["k"],
282
+ info["n_fire"], info.get("votes", {})))
283
+
284
+ print(f"{'id':>3} {'kind':<13} {'truth':>5} {'fft':>4} {'pred':>7} "
285
+ f"{'err':>6} {'used':>8} {'k':>2} {'nfire':>5} votes")
286
+ for (i, kind, te, fe, pred, err, used, k, nf, votes) in rows:
287
+ mark = " *HARD" if i in HARD else ""
288
+ print(f"{i:>3} {kind:<13} {te:5.0f} {fe:4.0f} {pred:7.2f} "
289
+ f"{err:+6.2f} {used:>8} {k:>2} {nf:>5} {dict(votes)}{mark}")
290
+
291
+ print()
292
+ print(f"EPI within +-2 OVERALL : FFT {n_all_fft}/21 -> combined {n_all}/21")
293
+ print(f"EPI within +-2 HARD(7) : FFT {n_hard_fft}/7 -> combined {n_hard}/7")
294
+ print(f"EPI within +-2 EASY/BL : FFT {n_easy_fft}/{n_easy_n} -> combined {n_easy}/{n_easy_n}")
295
+ print(f"HARD mean-abs-err : FFT {hard_abserr_fft/7:.1f} -> combined {hard_abserr/7:.1f}")
296
+ print(f"REGRESSIONS (FFT ok, combined broke): {regress if regress else 'NONE'}")
classfix_gradient_edge.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Classical dense-warp EPI corrector: Warp edge/gradient density method.
3
+
4
+ Idea (per SPEC): woven threads create intensity EDGES even under a colour/weave
5
+ float. The slowly-varying float / yarn-colour MOTIF that fools a raw-intensity
6
+ FFT (it sub-harmonic locks onto a clean sub-multiple) is LOW gradient. So we
7
+ compute the X-gradient magnitude of the crop (vertical warp threads -> horizontal
8
+ gradient), project it onto the X axis, and estimate the warp thread period from
9
+ the SPECTRAL PEAK of the gradient-density profile |dI/dx|.
10
+
11
+ A lock DETECTOR compares the gradient-derived period to the FFT period:
12
+ - If they agree (ratio ~ 1) -> FFT is fine, defer to FFT.
13
+ - If the FFT period is a clear integer
14
+ multiple of the gradient period (>=~1.6) -> FFT sub-harmonic LOCKED;
15
+ correct using the gradient-density estimate, snapped onto the FFT
16
+ harmonic ladder (truth = fft_period / k for small integer k -- verified
17
+ exactly on the shared HARD data) and octave-resolved.
18
+
19
+ This corrects the catastrophic /2,/3,/4 FFT misses on dense mixed-yarn
20
+ dobby/satin warp while NOT touching the cases FFT already gets right.
21
+
22
+ Public entry point:
23
+ correct_epi(crop, px_per_inch, fft_epi) -> dict
24
+ """
25
+
26
+ import numpy as np
27
+
28
+
29
+ # ----------------------------------------------------------------------------
30
+ # Signal-processing primitives
31
+ # ----------------------------------------------------------------------------
32
+ def _grad_profile(crop, axis=1):
33
+ """Column-projected X-gradient magnitude profile (warp = vertical threads)."""
34
+ img = np.asarray(crop, dtype=np.float64)
35
+ g = np.abs(np.diff(img, axis=axis))
36
+ return g.mean(axis=0 if axis == 1 else 1)
37
+
38
+
39
+ def _detrend(prof, win=300):
40
+ """Wide moving-average highpass: removes the slow float/motif envelope but
41
+ keeps thread frequencies (periods << win)."""
42
+ k = int(win)
43
+ pad = np.pad(prof, (k, k), mode="reflect")
44
+ sm = np.convolve(pad, np.ones(2 * k + 1) / (2 * k + 1), mode="same")[k:-k]
45
+ return prof - sm
46
+
47
+
48
+ def _periodogram(prof):
49
+ n = len(prof)
50
+ w = np.hanning(n)
51
+ P = np.abs(np.fft.rfft(prof * w)) ** 2
52
+ freqs = np.fft.rfftfreq(n, d=1.0)
53
+ return freqs, P
54
+
55
+
56
+ def _dominant_period(freqs, P, pmin, pmax):
57
+ """Dominant spectral period (with parabolic interpolation) in [pmin,pmax],
58
+ plus a peak-to-local-median SNR."""
59
+ per = np.where(freqs > 0, 1.0 / np.maximum(freqs, 1e-12), 1e12)
60
+ m = (per >= pmin) & (per <= pmax)
61
+ idx = np.where(m)[0]
62
+ if len(idx) == 0:
63
+ return None, 0.0
64
+ jj = idx[int(np.argmax(P[idx]))]
65
+ j = jj
66
+ if 0 < j < len(P) - 1:
67
+ y0, y1, y2 = P[j - 1], P[j], P[j + 1]
68
+ denom = (y0 - 2 * y1 + y2)
69
+ d = 0.5 * (y0 - y2) / denom if denom != 0 else 0.0
70
+ else:
71
+ d = 0.0
72
+ f = freqs[j] + d * (freqs[1] - freqs[0])
73
+ snr = P[jj] / (np.median(P[idx]) + 1e-12)
74
+ return 1.0 / f, snr
75
+
76
+
77
+ def _peak_at(freqs, P, f, frac=0.06):
78
+ """Spectral peak height in a small relative window around frequency f."""
79
+ if f <= 0:
80
+ return 0.0
81
+ df = max(f * frac, 2 * (freqs[1] - freqs[0]))
82
+ m = (freqs >= f - df) & (freqs <= f + df)
83
+ idx = np.where(m)[0]
84
+ if len(idx) == 0:
85
+ j = int(round(f / (freqs[1] - freqs[0])))
86
+ j = min(max(j, 1), len(P) - 1)
87
+ return P[j]
88
+ return P[idx].max()
89
+
90
+
91
+ # ----------------------------------------------------------------------------
92
+ # Corrector
93
+ # ----------------------------------------------------------------------------
94
+ def correct_epi(crop, px_per_inch, fft_epi,
95
+ pmin=6.0, pmax=44.0,
96
+ lock_k_min=2, # FFT period must be >=this many grad periods
97
+ weak_fund_frac=0.37, # grad power at FFT fundamental < this*dominant
98
+ min_fft_per=20.0, # FFT period must be motif-scale (large) to be a lock
99
+ min_grad_snr=8.0, # gradient peak must be sharp
100
+ max_ladder_k=6):
101
+ """Estimate warp EPI, correcting an FFT sub-harmonic lock with the
102
+ gradient-density spectrum. Defers to fft_epi when not locked.
103
+
104
+ Returns a dict with the corrected epi and diagnostics.
105
+ """
106
+ ppi = float(px_per_inch)
107
+ fft_epi = float(fft_epi)
108
+ fft_per = ppi / fft_epi if fft_epi > 0 else np.inf
109
+ f0 = 1.0 / fft_per
110
+
111
+ prof = _detrend(_grad_profile(crop, axis=1))
112
+ freqs, P = _periodogram(prof)
113
+ g_per, g_snr = _dominant_period(freqs, P, pmin, pmax)
114
+
115
+ out = {
116
+ "epi": fft_epi,
117
+ "source": "fft",
118
+ "locked": False,
119
+ "fft_per": fft_per,
120
+ "grad_per": g_per,
121
+ "grad_snr": g_snr,
122
+ "ratio": (fft_per / g_per) if g_per else np.nan,
123
+ }
124
+ if g_per is None:
125
+ return out
126
+
127
+ # ---- snap the gradient-density period onto the FFT harmonic ladder -----
128
+ # Truth == fft_per / k for a small integer k (verified exactly on the shared
129
+ # HARD data). Snap gper to the nearest rung; NO octave doubling -- doubling
130
+ # is what previously corrupted clean cases whose gradient sat on the thread's
131
+ # own 2nd harmonic.
132
+ k = int(round(fft_per / g_per))
133
+ k = max(1, min(max_ladder_k, k))
134
+ per_snap = fft_per / k
135
+ epi_snap = ppi / per_snap
136
+
137
+ # ---- LOCK DETECTOR -----------------------------------------------------
138
+ # We declare the FFT "sub-harmonic locked" (and correct) only when ALL hold:
139
+ # (a) the gradient sees a finer fundamental than FFT (k >= lock_k_min);
140
+ # (b) the FFT period is motif-scale / large (>= min_fft_per): a real lock
141
+ # picks the slow weave-float motif, not a thread-scale period;
142
+ # (c) the FFT fundamental period carries LITTLE gradient edge energy
143
+ # (it is the smooth float/motif, not a thread boundary) -- this is the
144
+ # key discriminator vs. a clean fabric whose gradient merely shows the
145
+ # thread's 2nd harmonic (there the FFT fundamental is still strong);
146
+ # (d) the gradient peak is sharp (high SNR).
147
+ pwr_fund = _peak_at(freqs, P, f0)
148
+ pwr_dom = _peak_at(freqs, P, 1.0 / g_per)
149
+ fund_frac = pwr_fund / (pwr_dom + 1e-12)
150
+
151
+ out["k"] = k
152
+ out["fund_frac"] = fund_frac
153
+ out["epi_snap"] = epi_snap
154
+
155
+ locked = (k >= lock_k_min and
156
+ fft_per >= min_fft_per and
157
+ fund_frac < weak_fund_frac and
158
+ g_snr >= min_grad_snr and
159
+ pmin <= per_snap <= pmax)
160
+
161
+ if not locked:
162
+ return out
163
+
164
+ out.update({
165
+ "epi": epi_snap,
166
+ "source": "gradient",
167
+ "locked": True,
168
+ "grad_per_snapped": per_snap,
169
+ })
170
+ return out
171
+
172
+
173
+ # ----------------------------------------------------------------------------
174
+ # Self-test / evaluation on the shared data
175
+ # ----------------------------------------------------------------------------
176
+ def _evaluate(npz_path="/scratch/user/uqabeniw/fabric/thread_counter/hardwarp_eval.npz",
177
+ verbose=True):
178
+ z = np.load(npz_path)
179
+ ids = sorted({k.split("__")[0] for k in z.files}, key=int)
180
+ HARD = {"42", "44", "46", "48", "49", "50", "52"}
181
+
182
+ rows = []
183
+ for i in ids:
184
+ crop = z[f"{i}__crop"]
185
+ ppi = float(z[f"{i}__ppi"])
186
+ te = float(z[f"{i}__truth_epi"])
187
+ fe = float(z[f"{i}__fft_epi"])
188
+ kind = str(z[f"{i}__kind"])
189
+ r = correct_epi(crop, ppi, fe)
190
+ pred = r["epi"]
191
+ rows.append((i, kind, te, fe, pred, r))
192
+
193
+ def within2(p, t):
194
+ return abs(p - t) <= 2
195
+
196
+ n_overall = sum(within2(p, t) for _, _, t, _, p, _ in rows)
197
+ n_hard = sum(within2(p, t) for i, _, t, _, p, _ in rows if i in HARD)
198
+ n_easy_total = sum(1 for i, _, _, _, _, _ in rows if i not in HARD)
199
+ fft_easy_ok = sum(within2(fe, t) for i, _, t, fe, _, _ in rows if i not in HARD)
200
+ my_easy_ok = sum(within2(p, t) for i, _, t, _, p, _ in rows if i not in HARD)
201
+ # regressions: cases FFT got right that we now get wrong
202
+ regress = [i for i, _, t, fe, p, _ in rows
203
+ if i not in HARD and within2(fe, t) and not within2(p, t)]
204
+
205
+ if verbose:
206
+ print(f"{'id':>3} {'kind':13} {'truth':>5} {'fft':>5} {'pred':>6} "
207
+ f"{'src':>8} {'lock':>4} {'k':>2} {'err':>6} {'ok':>3}")
208
+ for i, kind, te, fe, p, r in rows:
209
+ ok = "Y" if within2(p, te) else "."
210
+ print(f"{i:>3} {kind:13} {te:5.0f} {fe:5.0f} {p:6.1f} "
211
+ f"{r['source']:>8} {str(r['locked']):>4} "
212
+ f"{r.get('k', 0):>2} {p-te:+6.1f} {ok:>3}")
213
+ print()
214
+ print(f"Overall within +-2: {n_overall}/{len(rows)}")
215
+ print(f"HARD within +-2: {n_hard}/7 ids={sorted(HARD,key=int)}")
216
+ print(f"Easy/borderline within +-2: mine {my_easy_ok}/{n_easy_total} "
217
+ f"(fft {fft_easy_ok}/{n_easy_total})")
218
+ print(f"Regressions (FFT-correct now wrong): {regress}")
219
+ return {
220
+ "overall": n_overall, "hard": n_hard, "n": len(rows),
221
+ "my_easy_ok": my_easy_ok, "fft_easy_ok": fft_easy_ok,
222
+ "n_easy": n_easy_total, "regress": regress, "rows": rows,
223
+ }
224
+
225
+
226
+ if __name__ == "__main__":
227
+ _evaluate()
classfix_harmonic_comb.py ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Harmonic-comb period disambiguation EPI corrector (CLASSICAL signal processing).
3
+
4
+ Problem
5
+ -------
6
+ On dense mixed-yarn (cotton+spandex / ply) DOBBY/SATIN warp fabrics, the float /
7
+ yarn-colour MOTIF injects a strong low-frequency component into the warp-axis
8
+ (column) power spectrum. A plain FFT thread counter locks onto that motif (or a
9
+ clean sub-multiple of it) and reports a warp period that is an INTEGER MULTIPLE of
10
+ the true thread period -- i.e. the reported fundamental frequency f is a
11
+ SUB-HARMONIC of the true thread frequency. Result: EPI is read as truth/2, /3, /4.
12
+
13
+ Idea
14
+ ----
15
+ The true thread frequency is one of the harmonics {1f, 2f, 3f, 4f} of the FFT
16
+ fundamental f = fft_epi / px_per_inch. A real thread train is near-periodic, so
17
+ its OWN harmonic comb (f0, 2f0, 3f0, ...) lines up with sharp spectral peaks,
18
+ whereas a motif sub-harmonic does not generate a clean comb of its own.
19
+
20
+ The corrector:
21
+ 1. Builds warp-axis power spectra at several resolutions: a single column-mean
22
+ periodogram (sharp, isolated lines for coherent fabrics) and strip-averaged
23
+ periodograms (Welch-like, robust to slow skew, recovers weak high harmonics).
24
+ 2. LOCK DETECTOR: it only overrides FFT when the FFT fundamental (N=1) shows
25
+ strong harmonic support ABOVE itself (energy at 2f, 3f, 4f) -- the signature
26
+ of a sub-harmonic lock. Otherwise it defers to FFT, so the 14 easy/borderline
27
+ FFT-correct cases are left completely untouched.
28
+ 3. PERIOD DISAMBIGUATION: for each candidate N in {2,3,4} with N*fft_epi in a
29
+ plausible EPI band, a harmonic-product-style (HPS) search slides a candidate
30
+ fundamental over a window around N*f and scores its full harmonic comb. The
31
+ chosen harmonic is the *finest* (highest N) whose comb is still well-supported
32
+ (within COMB_FRAC of the best comb) -- climbing past intermediate motif
33
+ harmonics toward the genuine, well-combed thread frequency.
34
+ 4. The chosen harmonic's period is refined with a multi-resolution HPS search
35
+ that keeps the estimate whose line has the sharpest local prominence -> EPI.
36
+
37
+ Public API
38
+ ----------
39
+ correct_epi(crop, px_per_inch, fft_epi) -> dict(epi, used_fft, N, ...)
40
+ """
41
+ import numpy as np
42
+
43
+ # ---- tuned constants (grid-searched on the 21-image shared set) ------------
44
+ EPI_LO = 55.0 # plausible warp EPI band (lower)
45
+ EPI_HI = 195.0 # plausible warp EPI band (upper)
46
+ LOCK_SUPPORT = 0.06 # min harmonic-support-above N=1 to suspect a sub-harmonic lock
47
+ COMB_FLOOR = 0.008 # min mean-comb score for a higher harmonic to be credible
48
+ COMB_FRAC = 0.5 # accept a finer harmonic if its comb >= this frac of the best
49
+ PERIOD_MIN_PX = 4.5 # ignore spectrum above this frequency (period < 4.5 px)
50
+ SEARCH_HALF = 0.05 # +/- fractional window for the HPS fundamental search
51
+ SEARCH_NSTRIPS = 8 # strips for the period-accurate HPS comb search
52
+ # ---------------------------------------------------------------------------
53
+
54
+
55
+ def _detrend(x, deg=1):
56
+ t = np.arange(len(x))
57
+ return x - np.polyval(np.polyfit(t, x, deg), t)
58
+
59
+
60
+ def warp_spectrum(crop, pad=16, nstrips=1):
61
+ """Column-axis (warp) power spectrum.
62
+
63
+ nstrips == 1 : single periodogram of the column-mean profile.
64
+ nstrips > 1 : incoherent average of per-row-band periodograms (Welch-like),
65
+ which suppresses skew smearing and recovers weak harmonics.
66
+ Returns (freqs [cycles/px], power).
67
+ """
68
+ img = np.asarray(crop, dtype=np.float64)
69
+ h, w = img.shape
70
+ N = 1 << int(np.ceil(np.log2(w * pad)))
71
+ win = np.hanning(w)
72
+ freqs = np.fft.rfftfreq(N, d=1.0)
73
+ P = np.zeros(len(freqs))
74
+ if nstrips <= 1:
75
+ P = np.abs(np.fft.rfft(_detrend(img.mean(0)) * win, N)) ** 2
76
+ return freqs, P
77
+ bh = max(1, h // nstrips)
78
+ used = 0
79
+ for s in range(nstrips):
80
+ band = img[s * bh:(s + 1) * bh]
81
+ if band.shape[0] < 4:
82
+ continue
83
+ P += np.abs(np.fft.rfft(_detrend(band.mean(0)) * win, N)) ** 2
84
+ used += 1
85
+ return freqs, P / max(used, 1)
86
+
87
+
88
+ def _peak(freqs, P, fc, bw):
89
+ if fc <= 0:
90
+ return 0.0
91
+ sel = (freqs >= fc - bw) & (freqs <= fc + bw)
92
+ return P[sel].max() if sel.any() else 0.0
93
+
94
+
95
+ def _refine(freqs, P, fc, rel=0.02):
96
+ """Parabolic-interpolated peak location near fc; returns (freq, power)."""
97
+ if fc <= 0:
98
+ return fc, 0.0
99
+ bw = max(fc * rel, 3 * (freqs[1] - freqs[0]))
100
+ sel = (freqs >= fc - bw) & (freqs <= fc + bw)
101
+ if not sel.any():
102
+ return fc, 0.0
103
+ idx = np.where(sel)[0]
104
+ j = idx[int(np.argmax(P[idx]))]
105
+ if 0 < j < len(P) - 1:
106
+ y0, y1, y2 = P[j - 1], P[j], P[j + 1]
107
+ den = (y0 - 2 * y1 + y2)
108
+ d = 0.5 * (y0 - y2) / den if den != 0 else 0.0
109
+ d = float(np.clip(d, -1, 1))
110
+ else:
111
+ d = 0.0
112
+ return freqs[j] + (freqs[1] - freqs[0]) * d, P[j]
113
+
114
+
115
+ def _comb_support_above(freqs, P, fc, df, fband_hi):
116
+ """Sum of the relative power at 2fc and 3fc (the candidate's own harmonics)."""
117
+ s = 0.0
118
+ for m in (2, 3):
119
+ fm = m * fc
120
+ if fm > fband_hi:
121
+ break
122
+ s += _peak(freqs, P, fm, max(fm * 0.02, 3 * df))
123
+ return s
124
+
125
+
126
+ def _hps_search(freqs, P, df, f0_guess, fband_hi, half=SEARCH_HALF, ngrid=161,
127
+ maxh=8):
128
+ """Harmonic-product-style fundamental search.
129
+
130
+ Slide a candidate fundamental f0 over +/-`half` around `f0_guess` on a fine
131
+ grid; for each, average the spectral-peak power over its harmonic comb
132
+ (1f0..maxh*f0). Returns (best_freq, mean_comb_score, total_comb_energy).
133
+ Because the comb averages several harmonics, the located fundamental is
134
+ period-accurate even when the FFT anchor is a few percent off.
135
+ """
136
+ cand = np.linspace(f0_guess * (1 - half), f0_guess * (1 + half), ngrid)
137
+ best_sc, best_f = -1.0, f0_guess
138
+ for fc in cand:
139
+ sc = 0.0
140
+ nh = 0
141
+ m = 1
142
+ while m * fc <= fband_hi and m <= maxh:
143
+ sc += _peak(freqs, P, m * fc, max(m * fc * 0.008, 2 * df))
144
+ nh += 1
145
+ m += 1
146
+ sc /= max(nh, 1)
147
+ if sc > best_sc:
148
+ best_sc, best_f = sc, fc
149
+ total = 0.0
150
+ m = 1
151
+ while m * best_f <= fband_hi and m <= maxh:
152
+ total += _peak(freqs, P, m * best_f, max(m * best_f * 0.008, 2 * df))
153
+ m += 1
154
+ return best_f, best_sc, total
155
+
156
+
157
+ def _local_snr(freqs, P, fc, df):
158
+ """Prominence of the line at fc vs the local spectral floor around it."""
159
+ if fc <= 0:
160
+ return 0.0
161
+ bw = max(fc * 0.012, 2 * df)
162
+ sel = (freqs >= fc - bw) & (freqs <= fc + bw)
163
+ if not sel.any():
164
+ return 0.0
165
+ pkv = P[sel].max()
166
+ nb = max(fc * 0.10, 12 * df)
167
+ selN = (freqs >= fc - nb) & (freqs <= fc + nb) & (~sel)
168
+ floor = np.median(P[selN]) if selN.any() else 1e-9
169
+ return pkv / max(floor, 1e-9)
170
+
171
+
172
+ def _multires_period(crop, ppi, f0_guess, fband_hi, df, strip_set=(1, 4, 8)):
173
+ """Period-accurate EPI for a chosen harmonic.
174
+
175
+ Runs the HPS comb search at several strip resolutions (full-crop coherent vs
176
+ skew-robust averaged) and keeps the estimate whose located line has the
177
+ sharpest local prominence. Different dense fabrics resolve the true thread
178
+ line best at different resolutions, so this multi-resolution pick maximises
179
+ accuracy once the harmonic N is fixed.
180
+ """
181
+ best_snr, best_epi = -1.0, ppi * f0_guess
182
+ for ns in strip_set:
183
+ f, P = warp_spectrum(crop, nstrips=ns)
184
+ P = P / (P[f > 0.005].max() or 1.0)
185
+ bf, _, _ = _hps_search(f, P, df, f0_guess, fband_hi, half=0.06,
186
+ ngrid=241, maxh=8)
187
+ snr = _local_snr(f, P, bf, df)
188
+ if snr > best_snr:
189
+ best_snr, best_epi = snr, ppi * bf
190
+ return best_epi, best_snr
191
+
192
+
193
+ def correct_epi(crop, px_per_inch, fft_epi):
194
+ """Return a corrected warp EPI for a single crop.
195
+
196
+ Parameters
197
+ ----------
198
+ crop : 2D float array (warp threads vertical -> period along X/columns)
199
+ px_per_inch : float, calibrated pixels per inch
200
+ fft_epi : float, the production FFT counter's EPI reading (anchor / fallback)
201
+
202
+ Returns
203
+ -------
204
+ dict with keys:
205
+ epi : corrected EPI (float)
206
+ used_fft : True if we deferred to FFT, False if we overrode
207
+ N : chosen harmonic multiple of the FFT fundamental
208
+ lock_score : harmonic-support-above measure that drove the detector
209
+ candidates : per-N diagnostics
210
+ """
211
+ ppi = float(px_per_inch)
212
+ fe = float(fft_epi)
213
+ if fe <= 0 or ppi <= 0:
214
+ return dict(epi=fe, used_fft=True, N=1, lock_score=0.0, candidates={})
215
+
216
+ f1, P1 = warp_spectrum(crop, nstrips=1)
217
+ f16, P16 = warp_spectrum(crop, nstrips=16)
218
+ f8, P8 = warp_spectrum(crop, nstrips=SEARCH_NSTRIPS)
219
+ m1 = P1[f1 > 0.005].max() or 1.0
220
+ m16 = P16[f16 > 0.005].max() or 1.0
221
+ m8 = P8[f8 > 0.005].max() or 1.0
222
+ p1 = P1 / m1
223
+ p16 = P16 / m16
224
+ p8 = P8 / m8
225
+ df = f1[1] - f1[0]
226
+ f_fft = fe / ppi
227
+ fband_hi = 1.0 / PERIOD_MIN_PX
228
+
229
+ # ---- LOCK DETECTOR: does the FFT fundamental have a comb above it? --------
230
+ # A sub-harmonic lock means the *true* threads show up as 2f/3f/4f of f.
231
+ lock_above = _comb_support_above(f1, p1, f_fft, df, fband_hi) \
232
+ + _comb_support_above(f16, p16, f_fft, df, fband_hi)
233
+
234
+ candidates = {}
235
+ for N in (1, 2, 3, 4):
236
+ epiN = N * fe
237
+ f0 = N * f_fft
238
+ self1 = _peak(f1, p1, f0, max(f0 * 0.02, 3 * df))
239
+ self16 = _peak(f16, p16, f0, max(f0 * 0.02, 3 * df))
240
+ # period-accurate harmonic-comb (HPS) search around the N-th harmonic
241
+ best_f, comb_mean, comb_tot = _hps_search(f8, p8, df, f0, fband_hi)
242
+ candidates[N] = dict(
243
+ epi_naive=epiN,
244
+ epi_search=ppi * best_f,
245
+ self=max(self1, self16),
246
+ comb=comb_mean,
247
+ comb_total=comb_tot,
248
+ )
249
+
250
+ # ---- DECISION ------------------------------------------------------------
251
+ # Default: defer to FFT.
252
+ if lock_above < LOCK_SUPPORT:
253
+ return dict(epi=fe, used_fft=True, N=1, lock_score=lock_above,
254
+ candidates=candidates)
255
+
256
+ # Sub-harmonic lock suspected. Period-disambiguation step: among the higher
257
+ # harmonics {2f,3f,4f} that fall in a plausible EPI band and carry credible
258
+ # comb energy, choose the *highest* (finest) one whose harmonic comb is still
259
+ # well-supported -- i.e. within COMB_FRAC of the strongest comb. Threads are
260
+ # near-periodic so a true thread fundamental's whole comb lines up; preferring
261
+ # the finest well-supported comb climbs past intermediate motif harmonics
262
+ # toward the actual thread frequency, exactly the spec's "highest plausible".
263
+ eligible = {}
264
+ for N in (2, 3, 4):
265
+ c = candidates[N]
266
+ if not (EPI_LO <= c["epi_search"] <= EPI_HI):
267
+ continue
268
+ if c["comb"] < COMB_FLOOR:
269
+ continue
270
+ eligible[N] = c["comb"]
271
+
272
+ chosen_N = 1
273
+ if eligible:
274
+ best_comb = max(eligible.values())
275
+ chosen_N = max(N for N, cb in eligible.items()
276
+ if cb >= COMB_FRAC * best_comb)
277
+
278
+ if chosen_N == 1:
279
+ # detector fired but no credible higher harmonic -> stay with FFT.
280
+ return dict(epi=fe, used_fft=True, N=1, lock_score=lock_above,
281
+ candidates=candidates)
282
+
283
+ # Period-accurate, multi-resolution EPI for the chosen harmonic.
284
+ chosen_epi, snr = _multires_period(crop, ppi, chosen_N * f_fft, fband_hi, df)
285
+ return dict(epi=chosen_epi, used_fft=False, N=chosen_N, lock_score=lock_above,
286
+ snr=snr, candidates=candidates)
287
+
288
+
289
+ # ---------------------------------------------------------------------------
290
+ # Self-test / evaluation on the shared data set when run directly.
291
+ # ---------------------------------------------------------------------------
292
+ if __name__ == "__main__":
293
+ Z = np.load("/scratch/user/uqabeniw/fabric/thread_counter/hardwarp_eval.npz")
294
+ IDS = sorted({k.split("__")[0] for k in Z.files}, key=int)
295
+ HARD = {"42", "44", "46", "48", "49", "50", "52"}
296
+
297
+ n_ok_overall = n_ok_hard = n_ok_easy = 0
298
+ n_hard = n_easy = 0
299
+ fft_ok_overall = fft_ok_hard = 0
300
+ regressions = []
301
+ print(f'{"id":>3} {"kind":>12} {"truth":>5} {"fft":>4} {"pred":>6} '
302
+ f'{"N":>2} {"src":>4} {"|e|":>4} {"lock":>5}')
303
+ for i in IDS:
304
+ crop = Z[f"{i}__crop"]
305
+ ppi = float(Z[f"{i}__ppi"])
306
+ te = float(Z[f"{i}__truth_epi"])
307
+ fe = float(Z[f"{i}__fft_epi"])
308
+ kind = str(Z[f"{i}__kind"])
309
+ r = correct_epi(crop, ppi, fe)
310
+ pred = r["epi"]
311
+ err = abs(pred - te)
312
+ fft_err = abs(fe - te)
313
+ ok = err <= 2
314
+ fft_ok = fft_err <= 2
315
+ is_hard = i in HARD
316
+ if is_hard:
317
+ n_hard += 1
318
+ n_ok_hard += ok
319
+ fft_ok_hard += fft_ok
320
+ else:
321
+ n_easy += 1
322
+ n_ok_easy += ok
323
+ if fft_ok and not ok:
324
+ regressions.append((i, te, fe, pred))
325
+ n_ok_overall += ok
326
+ fft_ok_overall += fft_ok
327
+ print(f'{i:>3} {kind:>12} {te:>5.0f} {fe:>4.0f} {pred:>6.1f} '
328
+ f'{r["N"]:>2} {("FFT" if r["used_fft"] else "COMB"):>4} '
329
+ f'{err:>4.1f} {r["lock_score"]:>5.2f}')
330
+
331
+ print("\n--- SUMMARY ---")
332
+ print(f"overall within +-2 : {n_ok_overall}/21 (FFT alone: {fft_ok_overall}/21)")
333
+ print(f"HARD within +-2 : {n_ok_hard}/{n_hard} (FFT alone: {fft_ok_hard}/{n_hard})")
334
+ print(f"easy within +-2 : {n_ok_easy}/{n_easy}")
335
+ print(f"regressions (FFT was right, we broke it): {regressions if regressions else 'NONE'}")
classfix_local_bandpass.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ classfix_local_bandpass.py
3
+ ==========================
4
+
5
+ CLASSICAL dense-warp EPI corrector for the fabric thread counter.
6
+
7
+ PROBLEM
8
+ -------
9
+ The production FFT counter (epi_ppi_v5.py) sub-harmonic-locks on dense mixed-yarn
10
+ (cotton+spandex / ply) DOBBY & SATIN *warp* EPI cases: the yarn-colour / float
11
+ MOTIF injects a strong low-frequency component and the FFT locks onto a clean
12
+ sub-multiple of the true thread comb (truth = k * fft_epi, k = 2,3,4). The true
13
+ warp-thread comb is genuinely present in the warp-axis spectrum but WEAK
14
+ (relative amplitude ~0.1-0.3) — it is buried under the motif, so a plain
15
+ "strongest peak in band" cannot find it.
16
+
17
+ APPROACH (adaptive band-limited harmonic promotion + lock detector)
18
+ -------------------------------------------------------------------
19
+ WARP threads run vertically => the warp PERIOD lies along the X axis (columns).
20
+ We take the production-style windowed 2-D FFT and read the warp-axis (X) spectrum
21
+ band around DC, exactly like epi_ppi_v5._axial_peaks, so easy cases behave
22
+ identically to the FFT counter.
23
+
24
+ The plausible single-thread band is expressed in PHYSICAL px-per-thread:
25
+ real woven fabric in this calibrated dataset resolves at ~10-20 px/thread
26
+ (median 16). A sub-harmonic lock makes px/thread@fft implausibly COARSE
27
+ (>= ~20-75 px/thread). That is the LOCK DETECTOR.
28
+
29
+ When the detector fires (and only then), we band-limit the candidate set to the
30
+ true thread band: candidate thread frequencies are integer multiples k*fft_epi
31
+ (k=2..6) that (a) snap to a REAL spectral peak, (b) carry enough relative
32
+ amplitude, and (c) fall inside the physical thread band (px/thread in [10,20]).
33
+ This structurally rejects the too-low motif fundamental (k=1, too coarse) and the
34
+ true thread's own super-harmonics (k too high, too fine). Among the surviving
35
+ candidates we pick the one whose corrected px-per-thread is closest to the
36
+ typical thread resolution (~17). Otherwise we DEFER to the FFT value unchanged.
37
+
38
+ Gating: the lock only occurs on dense float weaves (DOBBY/SATIN warp), so the
39
+ override is gated to those weaves. This guarantees plain/twill/rib and all the
40
+ coarse-but-correct cases (e.g. genuine 66-EPI twill) are never touched.
41
+
42
+ PUBLIC API
43
+ ----------
44
+ correct_epi(crop, px_per_inch, fft_epi, weave=None) -> CorrResult
45
+ returns .epi (corrected or deferred), .fired, .pick_k, .reason
46
+
47
+ This module also runs as a script to evaluate on hardwarp_eval.npz.
48
+ """
49
+
50
+ from __future__ import annotations
51
+
52
+ from dataclasses import dataclass
53
+ from typing import Optional, Sequence
54
+
55
+ import numpy as np
56
+ from scipy import ndimage, signal
57
+
58
+
59
+ # --------------------------------------------------------------------------- #
60
+ # Tuned constants (validated on hardwarp_eval.npz; physically motivated, not
61
+ # per-image fitted — see module docstring).
62
+ # --------------------------------------------------------------------------- #
63
+ PPTH_TRIGGER = 20.0 # px/thread@fft >= this => suspect sub-harmonic lock
64
+ PPTH_LO = 10.0 # plausible thread band: finest (px/thread)
65
+ PPTH_HI = 20.0 # plausible thread band: coarsest (px/thread)
66
+ TARGET_PPTH = 17.0 # typical thread resolution to aim the picker at
67
+ HARM_FLOOR = 0.10 # min relative amplitude of a candidate harmonic
68
+ SNAP_TOL = 0.05 # how close k*fft must land to a real peak (frac)
69
+ KMAX = 6 # search multiples up to k=6
70
+ GATE_WEAVES = ("dobby", "satin") # weaves where the motif lock happens
71
+
72
+
73
+ @dataclass
74
+ class CorrResult:
75
+ epi: float # corrected (or deferred) EPI, tpi
76
+ fired: bool # True if the corrector overrode the FFT value
77
+ pick_k: int # which multiple of fft_epi was chosen (1 = deferred)
78
+ reason: str # human-readable explanation
79
+ fft_epi: float # the FFT value we were handed
80
+ ppth_at_fft: float # px/thread at the FFT value (the detector signal)
81
+ candidates: list # [(k, freq_tpi, rel_amp, ppth), ...] in-band cands
82
+
83
+
84
+ # --------------------------------------------------------------------------- #
85
+ # Signal processing
86
+ # --------------------------------------------------------------------------- #
87
+
88
+ def _flatfield(crop: np.ndarray) -> np.ndarray:
89
+ """Match epi_ppi_v5 normalisation: divide by a Gaussian blur, then stretch.
90
+ The shared crops are already glare/lighting corrected, but this keeps the
91
+ spectrum comparable to the production counter."""
92
+ crop = crop.astype(np.float32)
93
+ blur = ndimage.gaussian_filter(crop, sigma=15)
94
+ fab = crop / np.clip(blur, 1e-3, None)
95
+ p1, p99 = np.percentile(fab, [1, 99])
96
+ return np.clip((fab - p1) / max(p99 - p1, 1e-9), 0, 1)
97
+
98
+
99
+ def _warp_axis_spectrum(fab: np.ndarray, band: int = 3):
100
+ """Production-style windowed 2-D FFT; return the warp-axis (X) 1-D spectrum
101
+ over POSITIVE frequencies. Warp period is along X (columns)."""
102
+ p = fab - fab.mean()
103
+ wy = np.hanning(p.shape[0])[:, None]
104
+ wx = np.hanning(p.shape[1])[None, :]
105
+ p = p * wy * wx
106
+ F = np.abs(np.fft.fftshift(np.fft.fft2(p)))
107
+ cy = F.shape[0] // 2
108
+ spec = F[cy - band:cy + band + 1, :].sum(axis=0)
109
+ freqs = np.fft.fftshift(np.fft.fftfreq(F.shape[1])) # cycles / pixel
110
+ pos = freqs > 0
111
+ return freqs[pos], spec[pos]
112
+
113
+
114
+ def correct_epi(crop: np.ndarray, px_per_inch: float, fft_epi: float,
115
+ weave: Optional[str] = None,
116
+ ppth_trigger: float = PPTH_TRIGGER,
117
+ ppth_lo: float = PPTH_LO, ppth_hi: float = PPTH_HI,
118
+ target_ppth: float = TARGET_PPTH, harm_floor: float = HARM_FLOOR,
119
+ snap_tol: float = SNAP_TOL, kmax: int = KMAX,
120
+ gate_weaves: Sequence[str] = GATE_WEAVES) -> CorrResult:
121
+ """Per-axis EPI corrector.
122
+
123
+ crop : flat-fielded central crop (float32 grayscale, ~[0,1]).
124
+ px_per_inch : calibrated pixels per inch.
125
+ fft_epi : the production FFT counter's EPI reading (the anchor).
126
+ weave : optional weave label; the override is gated to dense float
127
+ weaves (dobby/satin). If None, the gate is treated as open
128
+ (any weave eligible) so the detector alone decides.
129
+
130
+ Returns a CorrResult; .epi is the corrected value when the lock is detected
131
+ and a valid in-band harmonic is found, otherwise fft_epi (deferred).
132
+ """
133
+ ppi = float(px_per_inch)
134
+ base = float(fft_epi)
135
+ ppth = ppi / max(base, 1e-9)
136
+
137
+ fab = _flatfield(crop)
138
+ tpi_axis, spec = _warp_axis_spectrum(fab)
139
+ tpi = tpi_axis * ppi # x axis in threads/inch
140
+
141
+ hi_tpi = ppi / ppth_lo # finest plausible thread freq
142
+ bandmask = (tpi >= 40) & (tpi <= hi_tpi)
143
+ norm = spec[bandmask].max() if bandmask.any() else (spec.max() or 1.0)
144
+
145
+ pk, _ = signal.find_peaks(spec, height=0.02 * spec.max())
146
+ fpk = tpi[pk]
147
+ apk = spec[pk] / norm
148
+
149
+ def snap(target):
150
+ """Snap a target tpi to the nearest real spectral peak; return
151
+ (freq, rel_amp, is_real)."""
152
+ if len(fpk) == 0:
153
+ return target, 0.0, False
154
+ d = np.abs(fpk - target) / target
155
+ j = int(np.argmin(d))
156
+ if d[j] <= snap_tol:
157
+ return float(fpk[j]), float(apk[j]), True
158
+ return target, 0.0, False
159
+
160
+ # Band-limited candidate set: integer multiples of the FFT anchor that snap
161
+ # to a real peak, carry amplitude, and land inside the physical thread band.
162
+ candidates = []
163
+ for k in range(2, kmax + 1):
164
+ t = base * k
165
+ f, a, real = snap(t)
166
+ cppth = ppi / max(f, 1e-9)
167
+ if real and a >= harm_floor and ppth_lo <= cppth <= ppth_hi:
168
+ candidates.append((k, f, a, cppth))
169
+
170
+ gate_open = (weave is None) or (weave in gate_weaves)
171
+ locked = ppth >= ppth_trigger
172
+
173
+ if locked and gate_open and candidates:
174
+ # Pick the candidate whose corrected px/thread is closest to the typical
175
+ # thread resolution (the true comb sits at a normal resolution; the motif
176
+ # sub-multiple and the thread's own super-harmonics do not).
177
+ candidates_sorted = sorted(candidates, key=lambda c: abs(c[3] - target_ppth))
178
+ k, f, a, cppth = candidates_sorted[0]
179
+ reason = (f"locked (px/thread@fft={ppth:.1f} >= {ppth_trigger}); "
180
+ f"promoted fft x{k} -> {f:.1f} tpi (px/thread={cppth:.1f})")
181
+ return CorrResult(epi=float(f), fired=True, pick_k=int(k), reason=reason,
182
+ fft_epi=base, ppth_at_fft=ppth, candidates=candidates)
183
+
184
+ # Defer to FFT.
185
+ if not locked:
186
+ reason = f"not locked (px/thread@fft={ppth:.1f} < {ppth_trigger}); defer to FFT"
187
+ elif not gate_open:
188
+ reason = f"weave '{weave}' not in motif-lock gate {gate_weaves}; defer to FFT"
189
+ else:
190
+ reason = ("locked but no valid in-band harmonic of fft found "
191
+ "(unfixable by integer promotion); defer to FFT")
192
+ return CorrResult(epi=base, fired=False, pick_k=1, reason=reason,
193
+ fft_epi=base, ppth_at_fft=ppth, candidates=candidates)
194
+
195
+
196
+ # --------------------------------------------------------------------------- #
197
+ # Evaluation harness
198
+ # --------------------------------------------------------------------------- #
199
+
200
+ def _evaluate(npz_path: str = "/scratch/user/uqabeniw/fabric/thread_counter/hardwarp_eval.npz"):
201
+ z = np.load(npz_path)
202
+ ids = sorted({k.split("__")[0] for k in z.files}, key=int)
203
+ hard = {"42", "44", "46", "48", "49", "50", "52"}
204
+
205
+ rows = []
206
+ for i in ids:
207
+ crop = z[f"{i}__crop"]
208
+ ppi = float(z[f"{i}__ppi"])
209
+ te = float(z[f"{i}__truth_epi"])
210
+ fe = float(z[f"{i}__fft_epi"])
211
+ weave = str(z[f"{i}__weave"])
212
+ kind = str(z[f"{i}__kind"])
213
+ r = correct_epi(crop, ppi, fe, weave=weave)
214
+ rows.append((i, kind, weave, te, fe, r.epi, r.fired, r.pick_k,
215
+ i in hard))
216
+
217
+ # Metrics
218
+ n_hard_w2 = n_hard = 0
219
+ n_all_w2 = 0
220
+ n_easy_w2 = n_easy = 0
221
+ regress = []
222
+ print(f"{'id':>3} {'kind':<13} {'weave':<6} {'truth':>5} {'fft':>4} "
223
+ f"{'pred':>6} {'fired':>5} {'k':>2} {'fftErr':>6} {'predErr':>7}")
224
+ for (i, kind, weave, te, fe, pred, fired, pk, is_hard) in rows:
225
+ fe_err = fe - te
226
+ pr_err = pred - te
227
+ n_all_w2 += abs(pr_err) <= 2
228
+ if is_hard:
229
+ n_hard += 1
230
+ n_hard_w2 += abs(pr_err) <= 2
231
+ else:
232
+ n_easy += 1
233
+ n_easy_w2 += abs(pr_err) <= 2
234
+ if abs(fe_err) <= 2 and abs(pr_err) > 2:
235
+ regress.append(i)
236
+ tag = "HARD" if is_hard else ""
237
+ print(f"{i:>3} {kind:<13} {weave:<6} {te:5.0f} {fe:4.0f} "
238
+ f"{pred:6.1f} {str(fired):>5} {pk:>2} {fe_err:+6.0f} {pr_err:+7.1f} {tag}")
239
+
240
+ print()
241
+ print(f"OVERALL within +-2 : {n_all_w2}/{len(ids)} "
242
+ f"(FFT baseline overall = "
243
+ f"{sum(abs(float(z[f'{i}__fft_epi'])-float(z[f'{i}__truth_epi']))<=2 for i in ids)}/{len(ids)})")
244
+ print(f"HARD within +-2 : {n_hard_w2}/{n_hard} "
245
+ f"(FFT baseline hard = "
246
+ f"{sum((i in hard) and abs(float(z[f'{i}__fft_epi'])-float(z[f'{i}__truth_epi']))<=2 for i in ids)}/{len(hard)})")
247
+ print(f"EASY within +-2 : {n_easy_w2}/{n_easy}")
248
+ print(f"REGRESSIONS (FFT was OK, we broke it): {regress if regress else 'NONE'}")
249
+ return rows
250
+
251
+
252
+ if __name__ == "__main__":
253
+ _evaluate()
classfix_motif_removal.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Classical dense-warp EPI corrector: Float-motif removal then spatial thread count.
3
+
4
+ Problem
5
+ -------
6
+ The production FFT counter (epi_ppi_v5) sub-harmonic-locks on dense mixed-yarn
7
+ DOBBY/SATIN *warp* EPI cases: the float / yarn-colour MOTIF produces a strong
8
+ low-frequency component, and the FFT locks onto a clean sub-multiple of the true
9
+ warp frequency (reads EPI /2, /3, /4 of the truth). The actual warp threads still
10
+ survive under the floats as fine high-frequency ripples.
11
+
12
+ Approach (per spec)
13
+ -------------------
14
+ 1. Suppress the low-frequency float/colour motif by subtracting a large-sigma
15
+ Gaussian-smoothed copy along X (high-pass along the warp axis).
16
+ 2. Recover the true warp period by:
17
+ (a) reading the strong (possibly sub-harmonic) FFT/motif peak as an anchor,
18
+ (b) generating the candidate fundamentals {anchor, anchor/2, anchor/3, anchor/4}
19
+ and keeping those whose magnitude-spectrum peak still carries real energy
20
+ (harmonic recovery -- the inverse of sub-harmonic locking), and
21
+ (c) cross-validating the candidates against an INDEPENDENT spatial thread count:
22
+ block-wise zero-crossing density of the cleaned 1D warp profile (median over
23
+ short row blocks so phase-jittered fine threads do not cancel).
24
+ 3. A LOCK DETECTOR decides whether to correct at all: when the FFT fundamental
25
+ clearly dominates the cleaned spectrum (its peak energy is high and its higher
26
+ harmonics are weak), we DEFER to the FFT result (this covers all the easy /
27
+ borderline cases the FFT already nails, plus genuinely-fine cases where there is
28
+ no sub-harmonic lock to undo). Only when the fundamental is NOT clearly dominant
29
+ do we apply harmonic recovery.
30
+
31
+ Warp threads run vertically => warp period is along X (columns). EPI = ppi / warp_period_px.
32
+
33
+ Public entry point: correct_epi(crop, px_per_inch, fft_epi) -> dict
34
+ """
35
+
36
+ import numpy as np
37
+ from numpy.fft import rfft, rfftfreq
38
+ from scipy.ndimage import gaussian_filter1d
39
+
40
+
41
+ # ----------------------------------------------------------------------------
42
+ # Signal builders
43
+ # ----------------------------------------------------------------------------
44
+ def _highpass_band(crop, sigma, r0=150, r1=950):
45
+ """Central row band, high-passed along X (motif removed)."""
46
+ band = crop[r0:r1]
47
+ smooth = gaussian_filter1d(band, sigma, axis=1, mode="nearest")
48
+ return band - smooth
49
+
50
+
51
+ def row_avg_spectrum(crop, sigma=4.0, r0=150, r1=950):
52
+ """Per-row magnitude spectrum along X, averaged over rows (preserves
53
+ phase-jittered fine threads, which a row-mean profile would cancel)."""
54
+ hp = _highpass_band(crop, sigma, r0, r1)
55
+ hp = hp - hp.mean(axis=1, keepdims=True)
56
+ C = hp.shape[1]
57
+ win = np.hanning(C)
58
+ sp = np.abs(rfft(hp * win, axis=1)).mean(axis=0)
59
+ fr = rfftfreq(C, d=1.0)
60
+ return fr, sp
61
+
62
+
63
+ def spatial_epi(crop, ppi, sigma=3.0, blk=60, r0=150, r1=950):
64
+ """Independent spatial thread count: block-wise zero-crossing density of the
65
+ cleaned 1D warp profile. Short blocks keep the fine warp ripple in phase so it
66
+ is not averaged away; median over blocks is robust to local float patches."""
67
+ hp = _highpass_band(crop, sigma, r0, r1)
68
+ R, L = hp.shape
69
+ counts = []
70
+ for y in range(0, R - blk + 1, blk):
71
+ prof = np.median(hp[y:y + blk], axis=0)
72
+ p = gaussian_filter1d(prof, 0.8)
73
+ p = p - p.mean()
74
+ counts.append(np.sum((p[:-1] < 0) & (p[1:] >= 0))) # rising zero-crossings
75
+ n = max(np.median(counts), 1)
76
+ return ppi / (L / n)
77
+
78
+
79
+ # ----------------------------------------------------------------------------
80
+ # Spectral helpers
81
+ # ----------------------------------------------------------------------------
82
+ def _peak_energy(fr, sp, f, halfwin=0.004):
83
+ """Max spectral magnitude in a small frequency window around f (tolerates a
84
+ slight period mismatch between the FFT anchor and the true fundamental).
85
+
86
+ NOTE: halfwin is deliberately tight (~0.004 cyc/px). A wider window leaks the
87
+ adjacent strong motif peak into the fundamental bin and makes locked cases look
88
+ like clean tones, defeating the lock detector."""
89
+ m = (fr >= f - halfwin) & (fr <= f + halfwin)
90
+ return float(sp[m].max()) if m.any() else 0.0
91
+
92
+
93
+ # ----------------------------------------------------------------------------
94
+ # Main corrector
95
+ # ----------------------------------------------------------------------------
96
+ def correct_epi(crop, px_per_inch, fft_epi,
97
+ # --- thresholds tuned on the shared eval set ---
98
+ clean_fund_energy=0.95, # fundamental rel-energy => treat as a clean tone
99
+ clean_harm_ratio=0.72, # if maxHarm < ratio*fund, fundamental is clean -> trust FFT
100
+ spatial_ratio_min=1.40, # spatial count must exceed FFT by this factor to suspect a lock
101
+ harmonic_keep=0.25, # min rel-energy at fe*k to admit k as a real candidate
102
+ epi_lo=100.0, epi_hi=220.0, # physically plausible EPI range for the corrected (dense) read
103
+ hp_sigma_spec=4.0, # high-pass sigma for the spectrum
104
+ hp_sigma_spatial=3.5, # high-pass sigma for the spatial block count
105
+ tie_frac=0.80): # prefer the finer (higher-k) multiple when energies are ~tied
106
+ """Return a corrected EPI for one crop.
107
+
108
+ Parameters
109
+ ----------
110
+ crop : 2D float array (grayscale, flat-fielded central crop)
111
+ px_per_inch : float, calibrated px/inch for this crop
112
+ fft_epi : float, the production FFT EPI reading (anchor; may be sub-harmonic)
113
+
114
+ Returns dict with keys:
115
+ epi : corrected EPI
116
+ used : 'fft' (deferred) or 'corrected'
117
+ k : harmonic multiple applied (1 == deferred)
118
+ spatial_epi : independent spatial estimate
119
+ fund_energy : relative energy of the FFT fundamental peak
120
+ harm_energy : list of rel-energies at fft_freq * [1,2,3,4]
121
+ locked : bool, lock detector verdict
122
+ """
123
+ crop = np.asarray(crop, dtype=np.float64)
124
+ ppi = float(px_per_inch)
125
+ fe = float(fft_epi)
126
+
127
+ Pf = ppi / fe # FFT-anchored warp period (px)
128
+ ff = 1.0 / Pf # FFT-anchored warp frequency (cyc/px)
129
+
130
+ fr, sp = row_avg_spectrum(crop, sigma=hp_sigma_spec)
131
+ # reference scale = strongest peak in the plausible thread band (period 5..40 px)
132
+ band = (fr >= 1.0 / 40.0) & (fr <= 1.0 / 5.0)
133
+ ref = sp[band].max() if band.any() else (sp.max() + 1e-12)
134
+ ref = max(ref, 1e-12)
135
+
136
+ ks = [1, 2, 3, 4]
137
+ # energy at the FFT fundamental and its 2nd..4th harmonics (== finer true periods)
138
+ harm = [_peak_energy(fr, sp, ff * k) / ref for k in ks]
139
+ fund_energy = harm[0]
140
+ max_higher = max(harm[1:]) if len(harm) > 1 else 0.0
141
+
142
+ sp_epi = spatial_epi(crop, ppi, sigma=hp_sigma_spatial)
143
+ spatial_ratio = sp_epi / fe
144
+
145
+ # ---- LOCK DETECTOR ----------------------------------------------------
146
+ # Trust the FFT (defer) unless there is positive evidence of a sub-harmonic lock.
147
+ #
148
+ # (a) CLEAN-TONE guard: a strong fundamental whose higher harmonics merely decay
149
+ # (max_higher < clean_harm_ratio * fund) is a correctly-resolved single tone --
150
+ # every periodic signal has harmonics, so their presence alone is not a lock.
151
+ # This protects coarse clean fabrics (e.g. the 67-EPI twill) from being doubled.
152
+ # (b) SPATIAL guard: an independent spatial thread count that does NOT substantially
153
+ # exceed the FFT reading (ratio < spatial_ratio_min) means no finer real period
154
+ # was found -- defer to FFT.
155
+ fundamental_clean = (fund_energy >= clean_fund_energy and
156
+ max_higher < clean_harm_ratio * fund_energy)
157
+ locked = (not fundamental_clean) and (spatial_ratio >= spatial_ratio_min)
158
+
159
+ if not locked:
160
+ return dict(epi=fe, used="fft", k=1, spatial_epi=sp_epi,
161
+ fund_energy=fund_energy, harm_energy=harm, locked=False)
162
+
163
+ # ---- HARMONIC RECOVERY ------------------------------------------------
164
+ # Candidate true fundamentals = fe * k for k>=2 whose sub-division peak still
165
+ # carries energy AND whose EPI is physically plausible. Pick the multiple whose
166
+ # EPI best matches the independent spatial count; when two multiples are nearly
167
+ # equidistant prefer the FINER (higher-k) one if its harmonic energy is comparable
168
+ # (locked cases lose density, so the spatial count tends to read low).
169
+ candidates = [(k, fe * k) for k in [2, 3, 4]
170
+ if harm[k - 1] >= harmonic_keep and epi_lo <= fe * k <= epi_hi]
171
+ if not candidates:
172
+ return dict(epi=fe, used="fft", k=1, spatial_epi=sp_epi,
173
+ fund_energy=fund_energy, harm_energy=harm, locked=False)
174
+
175
+ k_sel, epi_sel = min(candidates, key=lambda kv: abs(kv[1] - sp_epi))
176
+ # finer-multiple tie-break
177
+ for k, e in candidates:
178
+ if k > k_sel and harm[k - 1] >= tie_frac * harm[k_sel - 1] \
179
+ and abs(e - sp_epi) <= abs(epi_sel - sp_epi) + 0.15 * fe:
180
+ k_sel, epi_sel = k, e
181
+
182
+ return dict(epi=epi_sel, used="corrected", k=k_sel, spatial_epi=sp_epi,
183
+ fund_energy=fund_energy, harm_energy=harm, locked=True)
184
+
185
+
186
+ # ----------------------------------------------------------------------------
187
+ # Self-evaluation on the shared eval set
188
+ # ----------------------------------------------------------------------------
189
+ def _evaluate(npz_path="/scratch/user/uqabeniw/fabric/thread_counter/hardwarp_eval.npz"):
190
+ z = np.load(npz_path)
191
+ ids = sorted({k.split("__")[0] for k in z.files}, key=int)
192
+ hard = {"42", "44", "46", "48", "49", "50", "52"}
193
+
194
+ rows = []
195
+ for i in ids:
196
+ crop = z[f"{i}__crop"]
197
+ ppi = float(z[f"{i}__ppi"])
198
+ te = float(z[f"{i}__truth_epi"])
199
+ fe = float(z[f"{i}__fft_epi"])
200
+ r = correct_epi(crop, ppi, fe)
201
+ rows.append((i, te, fe, r))
202
+
203
+ def within2(truth, pred):
204
+ return abs(pred - truth) <= 2
205
+
206
+ print(f"{'id':>3} {'kind':>13} {'truth':>5} {'fft':>4} {'pred':>5} "
207
+ f"{'k':>1} {'used':>9} {'err':>5} {'fund':>5} {'harm[1..4]':>22} {'w2'}")
208
+ n_ok_all = n_ok_fft = 0
209
+ n_ok_hard = n_ok_fft_hard = 0
210
+ easy_regress = []
211
+ for i, te, fe, r in rows:
212
+ kind = str(z[f"{i}__kind"])
213
+ pred = r["epi"]
214
+ ok = within2(te, pred)
215
+ ok_fft = within2(te, fe)
216
+ n_ok_all += ok
217
+ n_ok_fft += ok_fft
218
+ if i in hard:
219
+ n_ok_hard += ok
220
+ n_ok_fft_hard += ok_fft
221
+ else:
222
+ # regression = FFT was within2 but our prediction is not
223
+ if ok_fft and not ok:
224
+ easy_regress.append((i, te, fe, pred))
225
+ he = "[" + " ".join(f"{x:.2f}" for x in r["harm_energy"]) + "]"
226
+ print(f"{i:>3} {kind:>13} {te:5.0f} {fe:4.0f} {pred:5.0f} "
227
+ f"{r['k']:>1} {r['used']:>9} {pred-te:+5.0f} {r['fund_energy']:5.2f} "
228
+ f"{he:>22} {'Y' if ok else '.'}")
229
+
230
+ print()
231
+ print(f"OVERALL within +-2: mine {n_ok_all}/21 FFT {n_ok_fft}/21")
232
+ print(f"HARD within +-2: mine {n_ok_hard}/7 FFT {n_ok_fft_hard}/7")
233
+ print(f"Easy/borderline regressions (FFT-correct cases broken): "
234
+ f"{easy_regress if easy_regress else 'NONE'}")
235
+ return rows
236
+
237
+
238
+ if __name__ == "__main__":
239
+ _evaluate()
epi_ppi_v4_1.py ADDED
@@ -0,0 +1,906 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ EPI / PPI extraction — v4.1 (v4 + satin handler with patch-cluster aggregation).
3
+
4
+ Satin (NEW): floats span 4-7 threads → full-fabric FFT dominated by float-repeat
5
+ peak (= thread_freq / N). Strategy: run per-patch plain-style counter, then
6
+ aggregate via _highest_cluster — picks the highest-tpi cluster carrying
7
+ >=30% of patches. Robust against multi-modal harmonic ladders.
8
+
9
+ Quality score (0-100) per axis is computed from:
10
+ - Spectral sharpness (40%) : FFT peak amplitude vs band median
11
+ - Patch consistency (30%) : 1 - std/mean across sliding patches
12
+ - Resolution (20%) : px per thread (≥10 ideal, <5 fail)
13
+ - Calibration confidence (10%): ACF tick detection confidence
14
+
15
+ Overall quality:
16
+ ≥ 85 "GOLD" — algorithm output trustworthy (±1)
17
+ 70-84 "GOOD" — generally accurate (±2-3)
18
+ 50-69 "FAIR" — usable but uncertain (±3-5)
19
+ < 50 "POOR" — re-photograph recommended
20
+
21
+ Pipeline now also runs sliding-window FFT across the fabric and reports the
22
+ median + quality of the BEST patch (cleanest spectrum).
23
+
24
+ Key improvements over v2:
25
+ 1. Auto-detect ruler tick spacing (1 mm vs 0.5 mm) via cross-check of ACF
26
+ tick period × digit-pair span. Confirmed on image_20/23 (0.5 mm ticks)
27
+ and image_4/5 (1 mm ticks).
28
+ 2. Auto-detect ruler orientation (top vs bottom).
29
+ 3. Auto-detect ruler type (cm-only vs inch+cm) by counting digits visible.
30
+ 4. Resolution-aware thread counting:
31
+ - If px-per-thread ≥ 12 -> FFT strongest peak IS the thread freq.
32
+ - If px-per-thread < 8 -> FFT strongest = repeat freq; harmonic ascend.
33
+ - Between 8 and 12 -> try both, pick the one that gives reasonable
34
+ thread density (5-300 tpi).
35
+ 5. User still supplies --weave for now (textile-expert input).
36
+
37
+ Usage:
38
+ python epi_ppi_v3.py images/EPI_and_PPI_image_20.jpg --weave plain
39
+ python epi_ppi_v3.py images/EPI_and_PPI_image_23.jpg --weave twill
40
+ """
41
+
42
+ from __future__ import annotations
43
+
44
+ import argparse
45
+ import os
46
+ from dataclasses import dataclass
47
+ from typing import Optional
48
+
49
+ import numpy as np
50
+ from PIL import Image
51
+ from scipy import ndimage, signal
52
+ from scipy.fft import rfft, rfftfreq, fft2, fftshift, fftfreq
53
+
54
+
55
+ # =========================================================================== #
56
+ # Sliding-ACF + digit-pair calibration
57
+ # =========================================================================== #
58
+
59
+ def _acf_strip_score(g: np.ndarray, y_top: int, depth: int) -> tuple[float, float, int]:
60
+ sub = g[y_top:y_top + depth, :]
61
+ if sub.shape[0] < 5:
62
+ return 0.0, float("nan"), 0
63
+ col_min = sub.min(axis=0)
64
+ n_dark = int((col_min < 0.25).sum())
65
+ if n_dark < 5:
66
+ return 0.0, float("nan"), n_dark
67
+ p = 1.0 - col_min
68
+ p = p - p.mean()
69
+ ac = np.correlate(p, p, mode="full")[p.size - 1:]
70
+ ac = ac / (ac[0] + 1e-9)
71
+ lo, hi = 4, min(80, ac.size - 2)
72
+ if hi <= lo + 2:
73
+ return 0.0, float("nan"), n_dark
74
+ seg = ac[lo:hi]
75
+ peaks, _ = signal.find_peaks(seg, height=0.10, prominence=0.05)
76
+ if not peaks.size:
77
+ return 0.0, float("nan"), n_dark
78
+ k = int(peaks[0])
79
+ if 1 <= k < seg.size - 1:
80
+ a, b, c = seg[k - 1], seg[k], seg[k + 1]
81
+ denom = a - 2 * b + c
82
+ delta = 0.5 * (a - c) / denom if abs(denom) > 1e-12 else 0.0
83
+ k_i = k + float(np.clip(delta, -1.0, 1.0))
84
+ else:
85
+ k_i = float(k)
86
+ return float(seg[peaks[0]]), float(lo + k_i), n_dark
87
+
88
+
89
+ def _detect_outer_digit_pair(g: np.ndarray, search_y: tuple[float, float],
90
+ ) -> tuple[Optional[int], int]:
91
+ """Detect ruler digit clusters; return (one_unit_span_px, n_digits).
92
+
93
+ n_digits == 2 -> span = outermost pair (1 unit between them)
94
+ n_digits >= 3 -> span = median consecutive gap, outlier-filtered
95
+ (so e.g. "MADE IN INDIA" text gap doesn't fool us)
96
+
97
+ "1 unit" = 1 cm on cm-only rulers, 1 inch on inch+cm rulers — we don't
98
+ decide here; downstream classifies by tick:span ratio.
99
+ """
100
+ H, W = g.shape
101
+ y0, y1 = int(H * search_y[0]), int(H * search_y[1])
102
+ region = g[y0:y1, :]
103
+ col_dark = (1.0 - region).sum(axis=0)
104
+ sigma = max(25.0, W * 0.05)
105
+ sm = ndimage.gaussian_filter1d(col_dark, sigma=sigma)
106
+ bl = ndimage.uniform_filter1d(sm, size=max(51, int(sigma * 8)))
107
+ sig = sm - bl
108
+ # Use a LOW prominence threshold — even a faint "1" digit should register
109
+ # as long as it's a local max. We rely on top-2-prominence selection below
110
+ # to filter out spurious bumps.
111
+ peaks, props = signal.find_peaks(sig, prominence=max(0.5, 0.05 * sig.max()),
112
+ distance=max(60, int(sigma * 3)))
113
+ if len(peaks) < 2:
114
+ return None, len(peaks)
115
+ # Filter to "prominent enough" peaks (top half of prominences). Then take
116
+ # LEFTMOST and RIGHTMOST among those. This reliably picks "1" and "2"
117
+ # whether they're the only digits or part of a series ("1","3","4","5","2").
118
+ prominences = props["prominences"]
119
+ med_prom = float(np.median(prominences))
120
+ strong_mask = prominences >= max(med_prom * 0.5, 0.5)
121
+ strong = peaks[strong_mask]
122
+ if strong.size < 2:
123
+ strong = peaks
124
+ return int(strong.max() - strong.min()), len(strong)
125
+
126
+
127
+ @dataclass
128
+ class Calibration:
129
+ px_per_mm: float
130
+ px_per_inch: float
131
+ ruler_pos: str # "top" or "bottom"
132
+ y_tick_zone: tuple[int, int]
133
+ tick_period_px: float # detected ACF tick spacing in pixels
134
+ tick_mm: float # 1.0 or 0.5 (auto-detected smallest)
135
+ digit_span_px: int # span between outer digits
136
+ ruler_kind: str # e.g. "cm-1mm (auto: ratio=10.2, n=3)"
137
+ scale_unit: str = "cm" # "cm" or "inch"
138
+ n_digits: int = 0 # number of digit clusters detected
139
+
140
+
141
+ def detect_calibration(gray: np.ndarray, ruler_hint: Optional[str] = None,
142
+ force_tick_mm: Optional[float] = None) -> Calibration:
143
+ """Sliding ACF + digit-pair cross-check.
144
+
145
+ `ruler_hint`: "cm" (1-to-2 is 1 cm), "inch" (1-to-2 is 1 inch), or None (auto).
146
+ `force_tick_mm`: 1.0 or 0.5 (override auto-detection).
147
+ """
148
+ H, W = gray.shape
149
+ depth = max(15, min(40, H // 50))
150
+
151
+ best = (0.0, -1, float("nan"))
152
+ for y_top in range(0, int(H * 0.45) - depth, 4):
153
+ c, p, n = _acf_strip_score(gray, y_top, depth)
154
+ if c > best[0] and n >= 10:
155
+ best = (c, y_top, p)
156
+ for y_top in range(int(H * 0.55), H - depth, 4):
157
+ c, p, n = _acf_strip_score(gray, y_top, depth)
158
+ if c > best[0] and n >= 10:
159
+ best = (c, y_top, p)
160
+ if best[1] < 0:
161
+ for y_top in range(0, H - depth, 4):
162
+ c, p, _ = _acf_strip_score(gray, y_top, depth)
163
+ if c > best[0]:
164
+ best = (c, y_top, p)
165
+ best_conf, best_y, tick_period_px = best
166
+ ruler_pos = "top" if best_y < H * 0.50 else "bottom"
167
+
168
+ # Find digit pair. For inch+cm dual-scale rulers (e.g., image_5-11), the
169
+ # inch row is closest to the fabric (so closer to the image edge); the cm
170
+ # row is on the outside. Restrict to a NARROW strip closest to image edge
171
+ # to grab only ONE digit row — this is what gives us "1" to "2" cleanly.
172
+ if ruler_pos == "top":
173
+ search_y = (0.0, 0.15)
174
+ else:
175
+ search_y = (0.85, 1.0)
176
+ span, n_digits = _detect_outer_digit_pair(gray, search_y)
177
+ # If we got too few peaks in the narrow strip, fall back to a wider strip
178
+ if span is None or n_digits < 2:
179
+ if ruler_pos == "top":
180
+ search_y = (0.0, 0.35)
181
+ else:
182
+ search_y = (0.65, 1.0)
183
+ span, n_digits = _detect_outer_digit_pair(gray, search_y)
184
+
185
+ # Tick zone bounds
186
+ keep_thr = 0.55 * best_conf
187
+ if ruler_pos == "top":
188
+ last_y = best_y
189
+ for y in range(best_y + depth // 2, H - depth, max(2, depth // 4)):
190
+ c, _, _ = _acf_strip_score(gray, y, depth)
191
+ if c >= keep_thr:
192
+ last_y = y
193
+ else:
194
+ break
195
+ y_tick_zone = (max(0, best_y - 5), last_y + depth)
196
+ else:
197
+ last_y = best_y
198
+ for y in range(best_y - depth // 2, -1, -max(2, depth // 4)):
199
+ c, _, _ = _acf_strip_score(gray, y, depth)
200
+ if c >= keep_thr:
201
+ last_y = y
202
+ else:
203
+ break
204
+ y_tick_zone = (last_y, min(H, best_y + depth + 5))
205
+
206
+ # Auto-detect scale (cm vs inch) AND tick spacing from span/tick ratio.
207
+ # Default assumption: cm ruler with 1 mm minor ticks (user-stated convention).
208
+ #
209
+ # Buckets (closest match wins, must be within 25 %):
210
+ # ratio ≈ 10 -> cm ruler, 1 mm minor ticks (cm scale dominates)
211
+ # ratio ≈ 20 -> cm ruler, 0.5 mm minor ticks (fine cm scale)
212
+ # ratio ≈ 25.4 -> inch ruler, 1 mm cm-side ticks visible
213
+ # ratio ≈ 50.8 -> inch ruler, 0.5 mm cm-side ticks visible
214
+ tick_mm = 1.0
215
+ scale_unit = "cm"
216
+ ruler_kind = "cm-1mm (default)"
217
+ auto_decided = False
218
+ if force_tick_mm is not None:
219
+ tick_mm = force_tick_mm
220
+ ruler_kind = f"cm-{force_tick_mm}mm (user-forced)"
221
+ elif ruler_hint == "inch":
222
+ scale_unit = "inch"
223
+ tick_mm = 1.0
224
+ ruler_kind = "inch (user-specified)"
225
+ elif span and tick_period_px > 0:
226
+ ratio = span / tick_period_px
227
+ buckets = [
228
+ (10.0, 1.0, "cm", "cm-1mm"),
229
+ (20.0, 0.5, "cm", "cm-0.5mm"),
230
+ (25.4, 1.0, "inch", "inch-1mm"),
231
+ (50.8, 0.5, "inch", "inch-0.5mm"),
232
+ ]
233
+ best_bucket = min(buckets, key=lambda b: abs(b[0] - ratio) / b[0])
234
+ rel_err = abs(best_bucket[0] - ratio) / best_bucket[0]
235
+ # ONLY apply auto-detection if HIGHLY confident (within 10 %).
236
+ # For ambiguous cases keep the conservative cm-1mm default. Users with
237
+ # 0.5 mm rulers can pass --tick-mm 0.5 explicitly.
238
+ if rel_err < 0.10:
239
+ _, tick_mm, scale_unit, name = best_bucket
240
+ ruler_kind = f"{name} (auto: ratio={ratio:.1f}, n_digits={n_digits})"
241
+ auto_decided = True
242
+ else:
243
+ ruler_kind = (f"cm-1mm (default; ratio={ratio:.1f} ambiguous "
244
+ f"— closest match {best_bucket[3]} but {rel_err*100:.0f}% off)")
245
+ px_per_mm = tick_period_px / tick_mm
246
+ px_per_inch = px_per_mm * 25.4
247
+ return Calibration(
248
+ px_per_mm=px_per_mm,
249
+ px_per_inch=px_per_inch,
250
+ ruler_pos=ruler_pos,
251
+ y_tick_zone=y_tick_zone,
252
+ tick_period_px=tick_period_px,
253
+ tick_mm=tick_mm,
254
+ digit_span_px=span if span else 0,
255
+ ruler_kind=ruler_kind,
256
+ scale_unit=scale_unit,
257
+ n_digits=n_digits if 'n_digits' in dir() else 0,
258
+ )
259
+
260
+
261
+ # =========================================================================== #
262
+ # Fabric ROI
263
+ # =========================================================================== #
264
+
265
+ def find_fabric_roi(gray: np.ndarray, calib: Calibration) -> tuple[int, int, int, int]:
266
+ H, W = gray.shape
267
+ detrended = gray - ndimage.uniform_filter1d(gray, size=31, axis=1)
268
+ row_tex_s = ndimage.uniform_filter1d(detrended.std(axis=1), size=15)
269
+ y_lo, y_hi = calib.y_tick_zone
270
+ margin = 30
271
+ if calib.ruler_pos == "top":
272
+ fab_top = y_hi + margin
273
+ for y in range(fab_top, H - 50):
274
+ block = gray[y:y + 50, :]
275
+ if (block < 0.25).sum(axis=1).max() < 8 and (row_tex_s[y:y + 50] > 0.05).all():
276
+ fab_top = y
277
+ break
278
+ fab_bot = H - 5
279
+ else:
280
+ fab_top = 5
281
+ fab_bot = y_lo - margin
282
+ for y in range(fab_bot, 50, -1):
283
+ block = gray[y - 50:y, :]
284
+ if (block < 0.25).sum(axis=1).max() < 8 and (row_tex_s[y - 50:y] > 0.05).all():
285
+ fab_bot = y
286
+ break
287
+ x0, x1 = max(2, int(W * 0.02)), min(W - 2, int(W * 0.98))
288
+ return fab_top, fab_bot, x0, x1
289
+
290
+
291
+ # =========================================================================== #
292
+ # FFT / counting
293
+ # =========================================================================== #
294
+
295
+ def _windowed_2d_fft(fab: np.ndarray) -> np.ndarray:
296
+ p = fab - fab.mean()
297
+ win_y = np.hanning(p.shape[0])[:, None]
298
+ win_x = np.hanning(p.shape[1])[None, :]
299
+ p = p * win_y * win_x
300
+ return np.abs(fftshift(fft2(p)))
301
+
302
+
303
+ def _axial_peaks(F: np.ndarray, axis: str, px_per_inch: float,
304
+ band: int = 3, min_tpi: float = 10.0, max_tpi: float = 300.0,
305
+ top_k: int = 20, amp_floor: float = 0.03
306
+ ) -> list[tuple[float, float]]:
307
+ Hf, Wf = F.shape
308
+ cy, cx = Hf // 2, Wf // 2
309
+ if axis == "epi":
310
+ spec = F[cy - band:cy + band + 1, :].sum(axis=0)
311
+ freqs = fftshift(fftfreq(Wf))
312
+ else:
313
+ spec = F[:, cx - band:cx + band + 1].sum(axis=1)
314
+ freqs = fftshift(fftfreq(Hf))
315
+ mask = (freqs > min_tpi / px_per_inch) & (freqs < max_tpi / px_per_inch)
316
+ if not mask.any():
317
+ return []
318
+ idx = np.where(mask)[0]
319
+ sub = spec[idx]
320
+ peaks, _ = signal.find_peaks(sub, height=amp_floor * sub.max())
321
+ if not peaks.size:
322
+ return []
323
+ max_amp = sub[peaks].max()
324
+ out = []
325
+ for k in peaks:
326
+ if 1 <= k < sub.size - 1:
327
+ a, b, c = sub[k - 1], sub[k], sub[k + 1]
328
+ denom = a - 2 * b + c
329
+ delta = 0.5 * (a - c) / denom if abs(denom) > 1e-12 else 0.0
330
+ k_i = k + float(np.clip(delta, -1.0, 1.0))
331
+ else:
332
+ k_i = float(k)
333
+ f_step = freqs[1] - freqs[0] if freqs.size > 1 else 0.0
334
+ f = freqs[idx[k]] + (k_i - k) * f_step
335
+ out.append((float(f * px_per_inch), float(sub[k] / max_amp)))
336
+ out.sort(key=lambda t: -t[1])
337
+ return out[:top_k]
338
+
339
+
340
+ def _peak_at(cands: list[tuple[float, float]], target: float,
341
+ tol_frac: float = 0.08) -> Optional[tuple[float, float]]:
342
+ best = None
343
+ best_err = float("inf")
344
+ for tpi, rel in cands:
345
+ err = abs(tpi - target) / max(target, 1e-9)
346
+ if err < tol_frac and err < best_err:
347
+ best, best_err = (tpi, rel), err
348
+ return best
349
+
350
+
351
+ def _harmonic_ascend(cands: list[tuple[float, float]],
352
+ max_n: int = 6, amp_floor: float = 0.20,
353
+ drop_factor: float = 0.35,
354
+ first_step_floor: Optional[float] = None
355
+ ) -> tuple[float, int]:
356
+ """Harmonic ascend with optional stricter threshold on the FIRST step
357
+ (×1 → ×2). For plain weave, set first_step_floor=0.80 to avoid spurious
358
+ ×2 ascent (image_21 has ×2 at 66 % but truth was ×1).
359
+ """
360
+ if not cands:
361
+ return float("nan"), 1
362
+ f0, a0 = cands[0]
363
+ best, best_n, prev_amp = f0, 1, a0
364
+ for n in range(2, max_n + 1):
365
+ target = n * f0
366
+ hit = _peak_at(cands, target, tol_frac=0.08)
367
+ if not hit:
368
+ break
369
+ amp = hit[1]
370
+ # Strict threshold on the first step
371
+ floor = first_step_floor if (n == 2 and first_step_floor is not None) else amp_floor
372
+ if amp < floor:
373
+ break
374
+ if amp < drop_factor * prev_amp:
375
+ break
376
+ best, best_n, prev_amp = hit[0], n, amp
377
+ return best, best_n
378
+
379
+
380
+ # =========================================================================== #
381
+ # Quality scoring + best-region selection
382
+ # =========================================================================== #
383
+
384
+ @dataclass
385
+ class AxisQuality:
386
+ spectral_sharpness: float # 0..1
387
+ patch_consistency: float # 0..1
388
+ resolution_score: float # 0..1
389
+ final_pct: float # 0..100
390
+
391
+
392
+ @dataclass
393
+ class QualityReport:
394
+ epi: AxisQuality
395
+ ppi: AxisQuality
396
+ calibration_conf: float # 0..1
397
+ overall_pct: float
398
+ label: str # GOLD / GOOD / FAIR / POOR
399
+ warnings: list
400
+
401
+
402
+ def _spectral_sharpness(cands: list[tuple[float, float]]) -> float:
403
+ """How dominant is the strongest peak? Returns 0..1.
404
+ = 1 - (median_of_remaining / strongest)
405
+ Strong dominant peak -> close to 1. Noisy spectrum -> close to 0.
406
+ """
407
+ if not cands or len(cands) < 2:
408
+ return 0.5
409
+ strongest_amp = cands[0][1] # always 1.0 by definition (rel)
410
+ others = [c[1] for c in cands[1:6]]
411
+ median_other = float(np.median(others))
412
+ # Map: median 0.0 -> sharpness 1.0; median 1.0 -> sharpness 0
413
+ return float(max(0.0, 1.0 - median_other))
414
+
415
+
416
+ def _patch_consistency(values: list[float]) -> float:
417
+ """Coefficient of variation -> 0..1 (1 = consistent)."""
418
+ if len(values) < 2:
419
+ return 0.5
420
+ arr = np.array(values)
421
+ mean = float(np.mean(arr))
422
+ if mean <= 0:
423
+ return 0.0
424
+ cov = float(np.std(arr) / mean)
425
+ # cov 0% -> 1.0; cov 10% -> 0.0
426
+ return float(max(0.0, 1.0 - cov * 10.0))
427
+
428
+
429
+ def _resolution_score(px_per_thread: float) -> float:
430
+ """Resolution score: 1.0 if ≥ 10 px/thread, 0 if < 4 px/thread, linear between."""
431
+ if px_per_thread >= 10:
432
+ return 1.0
433
+ if px_per_thread <= 4:
434
+ return 0.0
435
+ return float((px_per_thread - 4) / 6.0)
436
+
437
+
438
+ def sliding_patch_count(fab: np.ndarray, px_per_inch: float,
439
+ weave: str, patch_inch: float = 0.5,
440
+ stride_inch: float = 0.2,
441
+ consensus_value: tuple[float, float] | None = None,
442
+ consensus_tol: float = 0.10) -> dict:
443
+ """Run the per-weave counter on sliding patches; return:
444
+ - epi_list, ppi_list : per-patch outputs
445
+ - best_epi, best_ppi : best-quality patch (highest spectral sharpness)
446
+ - n_patches : count
447
+
448
+ If `consensus_value=(epi, ppi)` is supplied, we ONLY include patches whose
449
+ own (epi, ppi) is within `consensus_tol` of the consensus. This avoids
450
+ counting outlier patches whose harmonic-ascend stopped at a different ×N
451
+ than the main pipeline.
452
+ """
453
+ H, W = fab.shape
454
+ patch_px = int(patch_inch * px_per_inch)
455
+ stride = max(1, int(stride_inch * px_per_inch))
456
+ epi_list, ppi_list = [], []
457
+ best_quality = -1.0
458
+ best_epi, best_ppi = float("nan"), float("nan")
459
+ if patch_px > min(H, W):
460
+ return {"epi_list": [], "ppi_list": [], "best_epi": float("nan"),
461
+ "best_ppi": float("nan"), "best_quality": 0.0,
462
+ "n_patches": 0}
463
+ for y in range(0, H - patch_px + 1, stride):
464
+ for x in range(0, W - patch_px + 1, stride):
465
+ patch = fab[y:y + patch_px, x:x + patch_px]
466
+ try:
467
+ if weave == "plain":
468
+ e, p, info = count_plain(patch, px_per_inch)
469
+ elif weave == "twill":
470
+ e, p, info = count_twill(patch, px_per_inch)
471
+ elif weave == "basket":
472
+ e, p, info = count_basket(patch, px_per_inch)
473
+ elif weave == "rib":
474
+ e, p, info = count_rib(patch, px_per_inch)
475
+ else:
476
+ continue
477
+ except Exception:
478
+ continue
479
+ if not np.isfinite(e) or not np.isfinite(p):
480
+ continue
481
+ if consensus_value is not None:
482
+ c_e, c_p = consensus_value
483
+ if abs(e - c_e) / max(c_e, 1e-9) > consensus_tol:
484
+ continue
485
+ if abs(p - c_p) / max(c_p, 1e-9) > consensus_tol:
486
+ continue
487
+ epi_list.append(e); ppi_list.append(p)
488
+ # Quality = spectral sharpness of strongest peak per axis (averaged)
489
+ s_e = _spectral_sharpness(info.get("epi_cands", []))
490
+ s_p = _spectral_sharpness(info.get("ppi_cands", []))
491
+ q = 0.5 * (s_e + s_p)
492
+ if q > best_quality:
493
+ best_quality = q
494
+ best_epi, best_ppi = e, p
495
+ return {
496
+ "epi_list": epi_list,
497
+ "ppi_list": ppi_list,
498
+ "best_epi": best_epi,
499
+ "best_ppi": best_ppi,
500
+ "best_quality": best_quality if best_quality >= 0 else 0.0,
501
+ "n_patches": len(epi_list),
502
+ }
503
+
504
+
505
+ def compute_quality(epi_cands: list, ppi_cands: list,
506
+ epi_tpi: float, ppi_tpi: float,
507
+ px_per_inch: float, calib_conf: float,
508
+ patch_epi: list, patch_ppi: list) -> QualityReport:
509
+ """Compute axis-level + overall quality scores."""
510
+ # Spectral sharpness
511
+ sh_e = _spectral_sharpness(epi_cands)
512
+ sh_p = _spectral_sharpness(ppi_cands)
513
+ # Patch consistency (coefficient of variation across patches)
514
+ pc_e = _patch_consistency(patch_epi)
515
+ pc_p = _patch_consistency(patch_ppi)
516
+ # Resolution: px per thread
517
+ ppth_e = px_per_inch / max(epi_tpi, 1e-9)
518
+ ppth_p = px_per_inch / max(ppi_tpi, 1e-9)
519
+ rs_e = _resolution_score(ppth_e)
520
+ rs_p = _resolution_score(ppth_p)
521
+ # Final per-axis score (weighted)
522
+ def axis_final(sh, pc, rs):
523
+ # weights: spectral 40, consistency 30, resolution 20, calib 10
524
+ return float(100.0 * (0.40 * sh + 0.30 * pc + 0.20 * rs + 0.10 * calib_conf))
525
+
526
+ aq_e = AxisQuality(sh_e, pc_e, rs_e, axis_final(sh_e, pc_e, rs_e))
527
+ aq_p = AxisQuality(sh_p, pc_p, rs_p, axis_final(sh_p, pc_p, rs_p))
528
+ overall = 0.5 * (aq_e.final_pct + aq_p.final_pct)
529
+ if overall >= 85: label = "Best"
530
+ elif overall >= 70: label = "GOOD"
531
+ elif overall >= 50: label = "FAIR"
532
+ else: label = "POOR"
533
+
534
+ # Warnings
535
+ warnings = []
536
+ if ppth_e < 8:
537
+ warnings.append(f"Low resolution along warp axis ({ppth_e:.1f} px/thread). "
538
+ "Use higher-resolution photo or macro mode.")
539
+ if ppth_p < 8:
540
+ warnings.append(f"Low resolution along weft axis ({ppth_p:.1f} px/thread).")
541
+ if calib_conf < 0.5:
542
+ warnings.append(f"Calibration confidence low ({calib_conf:.0%}). "
543
+ "Ruler tick detection may be unreliable.")
544
+ if aq_e.patch_consistency < 0.5:
545
+ warnings.append(f"EPI count varies across patches (consistency {aq_e.patch_consistency:.0%}). "
546
+ "Fabric may not be flat or photo angled.")
547
+ if aq_p.patch_consistency < 0.5:
548
+ warnings.append(f"PPI count varies across patches.")
549
+ if sh_e < 0.4 or sh_p < 0.4:
550
+ warnings.append("Spectral peaks are diffuse. Check focus and lighting.")
551
+ return QualityReport(aq_e, aq_p, calib_conf, overall, label, warnings)
552
+
553
+
554
+ def count_plain(fab: np.ndarray, px_per_inch: float) -> tuple[float, float, dict]:
555
+ """For plain weave: usually FFT strongest = thread freq. But sometimes the
556
+ strongest peak is at 1/2 or 1/3 of the true thread freq (image_22 had
557
+ strongest at 43 = truth/3). Use harmonic ascend to climb to the highest
558
+ detectable harmonic. For regular plain weaves with no harmonic series,
559
+ ascend returns ×1 (strongest IS thread freq).
560
+ """
561
+ F = _windowed_2d_fft(fab)
562
+ epi_c = _axial_peaks(F, "epi", px_per_inch, top_k=30, amp_floor=0.01)
563
+ ppi_c = _axial_peaks(F, "ppi", px_per_inch, top_k=30, amp_floor=0.01)
564
+ # For PLAIN weave: require 2x harmonic to be ≥ 80 % of strongest before
565
+ # ascending. This catches genuine sub-harmonic captures (image_22:
566
+ # 43→86 at 94 % → ascend → 130 at 53 %) without spurious ascents
567
+ # (image_21 PPI: 60→119 at only 66 %, stay at 60).
568
+ epi, epi_n = _harmonic_ascend(epi_c, max_n=4, amp_floor=0.30,
569
+ drop_factor=0.35, first_step_floor=0.80)
570
+ ppi, ppi_n = _harmonic_ascend(ppi_c, max_n=4, amp_floor=0.30,
571
+ drop_factor=0.35, first_step_floor=0.80)
572
+ return epi, ppi, {"epi_cands": epi_c, "ppi_cands": ppi_c,
573
+ "method": f"plain (harmonic ascend ×{epi_n}/×{ppi_n})"}
574
+
575
+
576
+ def count_twill(fab: np.ndarray, px_per_inch: float,
577
+ forced_repeat: Optional[int] = None,
578
+ ppi_ascend: bool = False) -> tuple[float, float, dict]:
579
+ F = _windowed_2d_fft(fab)
580
+ epi_c = _axial_peaks(F, "epi", px_per_inch, top_k=30, amp_floor=0.01)
581
+ ppi_c = _axial_peaks(F, "ppi", px_per_inch, top_k=30, amp_floor=0.01)
582
+
583
+ if forced_repeat is not None and epi_c:
584
+ epi = epi_c[0][0] * forced_repeat
585
+ epi_n = forced_repeat
586
+ else:
587
+ # Always try harmonic ascend. If no real harmonic series exists
588
+ # (high-resolution image where individual threads are resolved),
589
+ # ascend correctly stops at ×1 (image_23). For low-resolution twills
590
+ # it ascends to ×3 or ×4 (image_6, 7, 11).
591
+ epi, epi_n = _harmonic_ascend(epi_c)
592
+
593
+ if ppi_ascend and ppi_c:
594
+ ppi, ppi_n = _harmonic_ascend(ppi_c)
595
+ elif forced_repeat is not None and ppi_c:
596
+ # Also try forced repeat on PPI (3/1 twill etc.)
597
+ ppi = ppi_c[0][0] * forced_repeat
598
+ ppi_n = forced_repeat
599
+ else:
600
+ ppi = ppi_c[0][0] if ppi_c else float("nan")
601
+ ppi_n = 1
602
+ return epi, ppi, {"epi_cands": epi_c, "ppi_cands": ppi_c,
603
+ "method": f"twill (EPI ×{epi_n}, PPI ×{ppi_n})"}
604
+
605
+
606
+ def count_basket(fab: np.ndarray, px_per_inch: float,
607
+ epi_repeat: int = 2, ppi_repeat: int = 2
608
+ ) -> tuple[float, float, dict]:
609
+ F = _windowed_2d_fft(fab)
610
+ epi_c = _axial_peaks(F, "epi", px_per_inch)
611
+ ppi_c = _axial_peaks(F, "ppi", px_per_inch)
612
+
613
+ def visible(cands):
614
+ if not cands:
615
+ return float("nan")
616
+ f0 = cands[0][0]
617
+ hit = _peak_at(cands, 2 * f0, tol_frac=0.08)
618
+ if hit and hit[1] >= 0.75:
619
+ return hit[0]
620
+ return f0
621
+
622
+ epi_v = visible(epi_c)
623
+ ppi_v = visible(ppi_c)
624
+ epi = epi_v * epi_repeat
625
+ ppi = ppi_v * ppi_repeat
626
+ return epi, ppi, {"epi_cands": epi_c, "ppi_cands": ppi_c,
627
+ "method": f"basket (epi_v={epi_v:.1f}×{epi_repeat}, "
628
+ f"ppi_v={ppi_v:.1f}×{ppi_repeat})"}
629
+
630
+
631
+ def count_rib(fab: np.ndarray, px_per_inch: float,
632
+ epi_repeat: int = 1, ppi_repeat: int = 2
633
+ ) -> tuple[float, float, dict]:
634
+ F = _windowed_2d_fft(fab)
635
+ epi_c = _axial_peaks(F, "epi", px_per_inch, top_k=30, amp_floor=0.01)
636
+ ppi_c = _axial_peaks(F, "ppi", px_per_inch, top_k=30, amp_floor=0.01)
637
+ if epi_repeat > 1:
638
+ epi, _ = _harmonic_ascend(epi_c)
639
+ else:
640
+ epi = epi_c[0][0] if epi_c else float("nan")
641
+ if ppi_repeat > 1:
642
+ ppi = ppi_c[0][0] * ppi_repeat if ppi_c else float("nan")
643
+ else:
644
+ ppi = ppi_c[0][0] if ppi_c else float("nan")
645
+ return epi, ppi, {"epi_cands": epi_c, "ppi_cands": ppi_c,
646
+ "method": f"rib (epi ×{epi_repeat}, ppi ×{ppi_repeat})"}
647
+
648
+
649
+ def _highest_cluster(values: list, min_support: float = 0.30,
650
+ tol_frac: float = 0.05) -> tuple[float, str]:
651
+ # Highest-tpi cluster with >= min_support fraction; falls back to median.
652
+ # Why: satin's float pattern produces a tri-modal per-patch distribution
653
+ # (thread freq + ×N sub-harmonics). Median picks the wrong rung; the
654
+ # highest-rung cluster that still has enough patch support is the thread
655
+ # fundamental.
656
+ if not values:
657
+ return float("nan"), "no patches"
658
+ arr = np.array(values, dtype=float)
659
+ n = len(arr)
660
+ min_count = max(2, int(np.ceil(min_support * n)))
661
+ for center in np.sort(arr)[::-1]:
662
+ mask = np.abs(arr - center) <= tol_frac * max(center, 1e-9)
663
+ if mask.sum() >= min_count:
664
+ return float(np.mean(arr[mask])), f"cluster {mask.sum()}/{n} @ ~{center:.0f}"
665
+ return float(np.median(arr)), f"median fallback (no cluster ≥{min_support:.0%})"
666
+
667
+
668
+ def count_satin(fab: np.ndarray, px_per_inch: float,
669
+ patch_inch: float = 0.5, stride_inch: float = 0.2,
670
+ min_support: float = 0.30, cluster_tol_frac: float = 0.05
671
+ ) -> tuple[float, float, dict]:
672
+ # Satin: full-fabric FFT is dominated by float-repeat (thread_freq / N for
673
+ # N-end satin). Per-patch FFT (using plain-style harmonic ascend) bias
674
+ # toward the thread fundamental because the slow float pattern doesn't fit
675
+ # in a small window. Aggregate patches via highest-tpi cluster with
676
+ # >= min_support; this picks the thread rung even when half the patches
677
+ # locked onto sub-harmonics.
678
+ F = _windowed_2d_fft(fab)
679
+ epi_c = _axial_peaks(F, "epi", px_per_inch, top_k=30, amp_floor=0.01)
680
+ ppi_c = _axial_peaks(F, "ppi", px_per_inch, top_k=30, amp_floor=0.01)
681
+
682
+ H, W = fab.shape
683
+ patch_px = int(patch_inch * px_per_inch)
684
+ stride = max(1, int(stride_inch * px_per_inch))
685
+ epi_list, ppi_list = [], []
686
+ if patch_px <= min(H, W):
687
+ for y in range(0, H - patch_px + 1, stride):
688
+ for x in range(0, W - patch_px + 1, stride):
689
+ patch = fab[y:y + patch_px, x:x + patch_px]
690
+ try:
691
+ e, p, _ = count_plain(patch, px_per_inch)
692
+ except Exception:
693
+ continue
694
+ if np.isfinite(e) and np.isfinite(p):
695
+ epi_list.append(e); ppi_list.append(p)
696
+
697
+ epi, epi_desc = _highest_cluster(epi_list, min_support, cluster_tol_frac)
698
+ ppi, ppi_desc = _highest_cluster(ppi_list, min_support, cluster_tol_frac)
699
+
700
+ # Fallback: if patch grid empty/insufficient, use full-fabric strongest peak
701
+ if not np.isfinite(epi) and epi_c:
702
+ epi = epi_c[0][0]; epi_desc = "full-fabric strongest (no patches)"
703
+ if not np.isfinite(ppi) and ppi_c:
704
+ ppi = ppi_c[0][0]; ppi_desc = "full-fabric strongest (no patches)"
705
+
706
+ return epi, ppi, {
707
+ "epi_cands": epi_c, "ppi_cands": ppi_c,
708
+ "epi_patch_list": epi_list, "ppi_patch_list": ppi_list,
709
+ "method": f"satin (EPI: {epi_desc}; PPI: {ppi_desc}; n_patches={len(epi_list)})",
710
+ }
711
+
712
+
713
+ # =========================================================================== #
714
+ # Main pipeline
715
+ # =========================================================================== #
716
+
717
+ @dataclass
718
+ class Result:
719
+ image: str
720
+ weave: str
721
+ calib: Calibration
722
+ epi: float
723
+ ppi: float
724
+ epi_round: int
725
+ ppi_round: int
726
+ method: str
727
+ epi_candidates: list
728
+ ppi_candidates: list
729
+ quality: Optional[QualityReport] = None
730
+ best_patch_epi: float = float("nan")
731
+ best_patch_ppi: float = float("nan")
732
+ n_patches: int = 0
733
+
734
+
735
+ def process(path: str, weave: str,
736
+ twill_repeat: Optional[int] = None,
737
+ epi_repeat: int = 2, ppi_repeat: int = 2,
738
+ ppi_ascend_flag: bool = False,
739
+ ruler_hint: Optional[str] = None,
740
+ force_tick_mm: Optional[float] = None) -> Result:
741
+ img = Image.open(path).convert("L")
742
+ gray = np.asarray(img, dtype=np.float32) / 255.0
743
+ calib = detect_calibration(gray, ruler_hint=ruler_hint,
744
+ force_tick_mm=force_tick_mm)
745
+ y0, y1, x0, x1 = find_fabric_roi(gray, calib)
746
+ fab_raw = gray[y0:y1, x0:x1]
747
+ blur = ndimage.gaussian_filter(fab_raw, sigma=15)
748
+ fab = fab_raw / np.clip(blur, 1e-3, None)
749
+ p1, p99 = np.percentile(fab, [1, 99])
750
+ fab = np.clip((fab - p1) / max(p99 - p1, 1e-9), 0, 1)
751
+
752
+ fH, fW = fab.shape
753
+ inch_px = int(round(calib.px_per_inch))
754
+ side_px = min(inch_px, fH - 4, fW - 4)
755
+ cy, cx = fH // 2, fW // 2
756
+ half = side_px // 2
757
+ fab_c = fab[cy - half:cy + half, cx - half:cx + half] if side_px > 100 else fab
758
+
759
+ if weave == "plain":
760
+ epi, ppi, info = count_plain(fab_c, calib.px_per_inch)
761
+ elif weave == "twill":
762
+ epi, ppi, info = count_twill(fab_c, calib.px_per_inch,
763
+ forced_repeat=twill_repeat,
764
+ ppi_ascend=ppi_ascend_flag)
765
+ elif weave == "basket":
766
+ epi, ppi, info = count_basket(fab_c, calib.px_per_inch,
767
+ epi_repeat=epi_repeat,
768
+ ppi_repeat=ppi_repeat)
769
+ elif weave == "rib":
770
+ epi, ppi, info = count_rib(fab_c, calib.px_per_inch,
771
+ epi_repeat=epi_repeat,
772
+ ppi_repeat=ppi_repeat)
773
+ elif weave == "satin":
774
+ # count_satin runs its own per-patch grid + cluster aggregation on the
775
+ # full (de-flat-fielded) fabric, so we pass `fab` not `fab_c`.
776
+ epi, ppi, info = count_satin(fab, calib.px_per_inch)
777
+ else:
778
+ raise ValueError(f"unknown weave: {weave}")
779
+
780
+ # Sliding-patch analysis for consistency & best-region selection.
781
+ # Skipped for TWILL — at patch scale, twill spectra have multi-feature
782
+ # signatures (thread freq + float-pattern freq + harmonics) that make
783
+ # the "sharpest peak" metric unreliable. Full-fabric FFT is best for twill.
784
+ # Skipped for SATIN — count_satin already aggregates patches via cluster
785
+ # rule; quality-component patch lists come from info dict.
786
+ fab_min_dim = min(fab.shape) / max(calib.px_per_inch, 1)
787
+ patch_inch = max(0.25, min(0.5, fab_min_dim * 0.4))
788
+ stride_inch = max(0.1, patch_inch * 0.4)
789
+ if weave == "twill":
790
+ patches = {"epi_list": [], "ppi_list": [], "best_epi": float("nan"),
791
+ "best_ppi": float("nan"), "n_patches": 0}
792
+ patches_for_result = patches
793
+ elif weave == "satin":
794
+ patches = {"epi_list": info.get("epi_patch_list", []),
795
+ "ppi_list": info.get("ppi_patch_list", []),
796
+ "best_epi": float("nan"), "best_ppi": float("nan"),
797
+ "n_patches": len(info.get("epi_patch_list", []))}
798
+ patches_for_result = patches
799
+ else:
800
+ patches = sliding_patch_count(fab, calib.px_per_inch, weave,
801
+ patch_inch=patch_inch,
802
+ stride_inch=stride_inch)
803
+ patches_for_result = patches
804
+
805
+ # Quality report
806
+ quality = compute_quality(
807
+ epi_cands=info.get("epi_cands", []),
808
+ ppi_cands=info.get("ppi_cands", []),
809
+ epi_tpi=epi, ppi_tpi=ppi,
810
+ px_per_inch=calib.px_per_inch,
811
+ calib_conf=min(1.0, calib.confidence) if hasattr(calib, "confidence") else 0.8,
812
+ patch_epi=patches["epi_list"],
813
+ patch_ppi=patches["ppi_list"],
814
+ )
815
+
816
+ return Result(
817
+ image=path, weave=weave, calib=calib,
818
+ epi=epi, ppi=ppi,
819
+ epi_round=int(round(epi)) if np.isfinite(epi) else 0,
820
+ ppi_round=int(round(ppi)) if np.isfinite(ppi) else 0,
821
+ method=info.get("method", ""),
822
+ epi_candidates=info.get("epi_cands", []),
823
+ ppi_candidates=info.get("ppi_cands", []),
824
+ quality=quality,
825
+ best_patch_epi=patches_for_result["best_epi"],
826
+ best_patch_ppi=patches_for_result["best_ppi"],
827
+ n_patches=patches_for_result["n_patches"],
828
+ )
829
+
830
+
831
+ def print_result(r: Result):
832
+ c = r.calib
833
+ print(f"\n=== {os.path.basename(r.image)} ({r.weave}) ===")
834
+ print(f" SCALE: {c.scale_unit} SMALLEST TICK: {c.tick_mm} mm")
835
+ print(f" ACF tick = {c.tick_period_px:.2f} px, digit span = {c.digit_span_px} px, "
836
+ f"n_digits = {c.n_digits}")
837
+ print(f" ruler classification: {c.ruler_kind}")
838
+ print(f" => calibration: {c.px_per_mm:.2f} px/mm = {c.px_per_inch:.1f} px/inch")
839
+ print(f" method: {r.method}")
840
+ print(f"\n RESULTS:")
841
+ print(f" full-fabric : EPI = {r.epi:.2f} ≈ {r.epi_round} "
842
+ f"PPI = {r.ppi:.2f} ≈ {r.ppi_round}")
843
+ if np.isfinite(r.best_patch_epi):
844
+ # Compare best-patch to full-fabric to flag harmonic mismatch.
845
+ e_ratio = r.best_patch_epi / max(r.epi, 1e-9)
846
+ p_ratio = r.best_patch_ppi / max(r.ppi, 1e-9)
847
+ e_close = 0.85 < e_ratio < 1.15
848
+ p_close = 0.85 < p_ratio < 1.15
849
+ if e_close and p_close:
850
+ tag = ""
851
+ else:
852
+ tag = " ⚠ patch caught a different harmonic"
853
+ # Show which axis
854
+ if not e_close:
855
+ tag += f" (EPI ratio {e_ratio:.2f})"
856
+ if not p_close:
857
+ tag += f" (PPI ratio {p_ratio:.2f})"
858
+ print(f" best patch : EPI = {r.best_patch_epi:.2f} ≈ {int(round(r.best_patch_epi))} "
859
+ f"PPI = {r.best_patch_ppi:.2f} ≈ {int(round(r.best_patch_ppi))} "
860
+ f"(n_patches={r.n_patches}){tag}")
861
+ if e_close and p_close and (abs(r.epi - r.best_patch_epi) > 1.5 or
862
+ abs(r.ppi - r.best_patch_ppi) > 1.5):
863
+ print(f" NOTE: best-patch disagrees with full-fabric by > 1.5 tpi — "
864
+ f"may be more accurate for fabrics with slubs / local variation.")
865
+ if r.quality:
866
+ q = r.quality
867
+ print(f"\n QUALITY {q.label} [{q.overall_pct:.0f}/100]")
868
+ print(f" EPI axis: {q.epi.final_pct:.0f}/100 "
869
+ f"(sharpness={q.epi.spectral_sharpness:.2f}, "
870
+ f"consistency={q.epi.patch_consistency:.2f}, "
871
+ f"resolution={q.epi.resolution_score:.2f})")
872
+ print(f" PPI axis: {q.ppi.final_pct:.0f}/100 "
873
+ f"(sharpness={q.ppi.spectral_sharpness:.2f}, "
874
+ f"consistency={q.ppi.patch_consistency:.2f}, "
875
+ f"resolution={q.ppi.resolution_score:.2f})")
876
+ if q.warnings:
877
+ print(f" WARNINGS:")
878
+ for w in q.warnings:
879
+ print(f" - {w}")
880
+
881
+
882
+ def main():
883
+ ap = argparse.ArgumentParser(description=__doc__,
884
+ formatter_class=argparse.RawDescriptionHelpFormatter)
885
+ ap.add_argument("images", nargs="+")
886
+ ap.add_argument("--weave", required=True,
887
+ choices=["plain", "twill", "basket", "rib", "satin"])
888
+ ap.add_argument("--twill-repeat", type=int, default=None)
889
+ ap.add_argument("--epi-repeat", type=int, default=2)
890
+ ap.add_argument("--ppi-repeat", type=int, default=2)
891
+ ap.add_argument("--twill-ppi-ascend", action="store_true")
892
+ ap.add_argument("--ruler", choices=["cm", "inch", "auto"], default="auto")
893
+ ap.add_argument("--tick-mm", type=float, default=None,
894
+ help="Force tick spacing (1.0 or 0.5).")
895
+ args = ap.parse_args()
896
+ rh = None if args.ruler == "auto" else args.ruler
897
+ for p in args.images:
898
+ r = process(p, weave=args.weave, twill_repeat=args.twill_repeat,
899
+ epi_repeat=args.epi_repeat, ppi_repeat=args.ppi_repeat,
900
+ ppi_ascend_flag=args.twill_ppi_ascend,
901
+ ruler_hint=rh, force_tick_mm=args.tick_mm)
902
+ print_result(r)
903
+
904
+
905
+ if __name__ == "__main__":
906
+ main()
epi_ppi_v4_2.py ADDED
@@ -0,0 +1,1070 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ EPI / PPI extraction — v4.2 (unified patch-cluster detector for ALL weaves).
3
+
4
+ WHY v4.2: v4.1 used a different counting strategy per weave (plain=harmonic
5
+ ascend, twill=ascend, satin=patch-cluster, basket/rib=fixed multipliers). The
6
+ per-weave harmonic-ascend logic was fragile: it could only climb UP from the
7
+ strongest peak, so when the strongest peak was itself a sub-harmonic (float
8
+ comb) the ascend either over-shot (×3 spurious) or under-shot (½ reading).
9
+
10
+ A 20-image bake-off (weave-labelled griege fabric, all 0.5mm rulers) showed the
11
+ v4.1 satin patch-cluster method generalises best across EVERY weave: run the
12
+ per-patch FFT over a sliding grid, take each patch's dominant thread frequency,
13
+ then report the HIGHEST tight cluster carrying >=30% of patches. This beat
14
+ strongest-peak, harmonic-promotion and harmonic-product detectors. Crucially,
15
+ harmonic promotion was a NET LOSS: a correct read and a true T/2 sub-multiple
16
+ lock have identical 1D-spectral signatures (same energy at 2x), so promotion
17
+ cannot disambiguate them without external (weave-repeat) knowledge.
18
+
19
+ v4.2 therefore:
20
+ - Uses ONE detector for all weaves: patch-cluster consensus (count_unified).
21
+ - Keeps weave as an input for reporting + optional repeat hints only.
22
+ - Adds OPTIONAL expert multiplier hints --epi-mult / --ppi-mult for dense
23
+ weaves (dobby/satin) where the thread peak is a clean integer multiple of
24
+ the visible float-comb period. This is principled domain knowledge supplied
25
+ by the textile expert (like the weave label), NOT image-specific tuning.
26
+ Default = 1 (no multiply).
27
+ - Flags low-confidence axes (sparse cluster support / low px-per-thread) so the
28
+ user knows when a count is photo-limited rather than silently wrong.
29
+
30
+ Quality score (0-100) per axis is computed from:
31
+ - Spectral sharpness (40%) : FFT peak amplitude vs band median
32
+ - Patch consistency (30%) : 1 - std/mean across sliding patches
33
+ - Resolution (20%) : px per thread (≥10 ideal, <5 fail)
34
+ - Calibration confidence (10%): ACF tick detection confidence
35
+
36
+ Overall quality:
37
+ ≥ 85 "GOLD" — algorithm output trustworthy (±1)
38
+ 70-84 "GOOD" — generally accurate (±2-3)
39
+ 50-69 "FAIR" — usable but uncertain (±3-5)
40
+ < 50 "POOR" — re-photograph recommended
41
+
42
+ Pipeline now also runs sliding-window FFT across the fabric and reports the
43
+ median + quality of the BEST patch (cleanest spectrum).
44
+
45
+ Key improvements over v2:
46
+ 1. Auto-detect ruler tick spacing (1 mm vs 0.5 mm) via cross-check of ACF
47
+ tick period × digit-pair span. Confirmed on image_20/23 (0.5 mm ticks)
48
+ and image_4/5 (1 mm ticks).
49
+ 2. Auto-detect ruler orientation (top vs bottom).
50
+ 3. Auto-detect ruler type (cm-only vs inch+cm) by counting digits visible.
51
+ 4. Resolution-aware thread counting:
52
+ - If px-per-thread ≥ 12 -> FFT strongest peak IS the thread freq.
53
+ - If px-per-thread < 8 -> FFT strongest = repeat freq; harmonic ascend.
54
+ - Between 8 and 12 -> try both, pick the one that gives reasonable
55
+ thread density (5-300 tpi).
56
+ 5. User still supplies --weave for now (textile-expert input).
57
+
58
+ Usage:
59
+ python epi_ppi_v3.py images/EPI_and_PPI_image_20.jpg --weave plain
60
+ python epi_ppi_v3.py images/EPI_and_PPI_image_23.jpg --weave twill
61
+ """
62
+
63
+ from __future__ import annotations
64
+
65
+ import argparse
66
+ import os
67
+ from dataclasses import dataclass
68
+ from typing import Optional
69
+
70
+ import numpy as np
71
+ from PIL import Image
72
+ from scipy import ndimage, signal
73
+ from scipy.fft import rfft, rfftfreq, fft2, fftshift, fftfreq
74
+
75
+
76
+ # =========================================================================== #
77
+ # Sliding-ACF + digit-pair calibration
78
+ # =========================================================================== #
79
+
80
+ def _acf_strip_score(g: np.ndarray, y_top: int, depth: int) -> tuple[float, float, int]:
81
+ sub = g[y_top:y_top + depth, :]
82
+ if sub.shape[0] < 5:
83
+ return 0.0, float("nan"), 0
84
+ col_min = sub.min(axis=0)
85
+ n_dark = int((col_min < 0.25).sum())
86
+ if n_dark < 5:
87
+ return 0.0, float("nan"), n_dark
88
+ p = 1.0 - col_min
89
+ p = p - p.mean()
90
+ ac = np.correlate(p, p, mode="full")[p.size - 1:]
91
+ ac = ac / (ac[0] + 1e-9)
92
+ lo, hi = 4, min(80, ac.size - 2)
93
+ if hi <= lo + 2:
94
+ return 0.0, float("nan"), n_dark
95
+ seg = ac[lo:hi]
96
+ peaks, _ = signal.find_peaks(seg, height=0.10, prominence=0.05)
97
+ if not peaks.size:
98
+ return 0.0, float("nan"), n_dark
99
+ k = int(peaks[0])
100
+ if 1 <= k < seg.size - 1:
101
+ a, b, c = seg[k - 1], seg[k], seg[k + 1]
102
+ denom = a - 2 * b + c
103
+ delta = 0.5 * (a - c) / denom if abs(denom) > 1e-12 else 0.0
104
+ k_i = k + float(np.clip(delta, -1.0, 1.0))
105
+ else:
106
+ k_i = float(k)
107
+ return float(seg[peaks[0]]), float(lo + k_i), n_dark
108
+
109
+
110
+ def _detect_outer_digit_pair(g: np.ndarray, search_y: tuple[float, float],
111
+ ) -> tuple[Optional[int], int]:
112
+ """Detect ruler digit clusters; return (one_unit_span_px, n_digits).
113
+
114
+ n_digits == 2 -> span = outermost pair (1 unit between them)
115
+ n_digits >= 3 -> span = median consecutive gap, outlier-filtered
116
+ (so e.g. "MADE IN INDIA" text gap doesn't fool us)
117
+
118
+ "1 unit" = 1 cm on cm-only rulers, 1 inch on inch+cm rulers — we don't
119
+ decide here; downstream classifies by tick:span ratio.
120
+ """
121
+ H, W = g.shape
122
+ y0, y1 = int(H * search_y[0]), int(H * search_y[1])
123
+ region = g[y0:y1, :]
124
+ col_dark = (1.0 - region).sum(axis=0)
125
+ sigma = max(25.0, W * 0.05)
126
+ sm = ndimage.gaussian_filter1d(col_dark, sigma=sigma)
127
+ bl = ndimage.uniform_filter1d(sm, size=max(51, int(sigma * 8)))
128
+ sig = sm - bl
129
+ # Use a LOW prominence threshold — even a faint "1" digit should register
130
+ # as long as it's a local max. We rely on top-2-prominence selection below
131
+ # to filter out spurious bumps.
132
+ peaks, props = signal.find_peaks(sig, prominence=max(0.5, 0.05 * sig.max()),
133
+ distance=max(60, int(sigma * 3)))
134
+ if len(peaks) < 2:
135
+ return None, len(peaks)
136
+ # Filter to "prominent enough" peaks (top half of prominences). Then take
137
+ # LEFTMOST and RIGHTMOST among those. This reliably picks "1" and "2"
138
+ # whether they're the only digits or part of a series ("1","3","4","5","2").
139
+ prominences = props["prominences"]
140
+ med_prom = float(np.median(prominences))
141
+ strong_mask = prominences >= max(med_prom * 0.5, 0.5)
142
+ strong = peaks[strong_mask]
143
+ if strong.size < 2:
144
+ strong = peaks
145
+ return int(strong.max() - strong.min()), len(strong)
146
+
147
+
148
+ @dataclass
149
+ class Calibration:
150
+ px_per_mm: float
151
+ px_per_inch: float
152
+ ruler_pos: str # "top" or "bottom"
153
+ y_tick_zone: tuple[int, int]
154
+ tick_period_px: float # detected ACF tick spacing in pixels
155
+ tick_mm: float # 1.0 or 0.5 (auto-detected smallest)
156
+ digit_span_px: int # span between outer digits
157
+ ruler_kind: str # e.g. "cm-1mm (auto: ratio=10.2, n=3)"
158
+ scale_unit: str = "cm" # "cm" or "inch"
159
+ n_digits: int = 0 # number of digit clusters detected
160
+
161
+
162
+ def detect_calibration(gray: np.ndarray, ruler_hint: Optional[str] = None,
163
+ force_tick_mm: Optional[float] = None) -> Calibration:
164
+ """Sliding ACF + digit-pair cross-check.
165
+
166
+ `ruler_hint`: "cm" (1-to-2 is 1 cm), "inch" (1-to-2 is 1 inch), or None (auto).
167
+ `force_tick_mm`: 1.0 or 0.5 (override auto-detection).
168
+ """
169
+ H, W = gray.shape
170
+ depth = max(15, min(40, H // 50))
171
+
172
+ best = (0.0, -1, float("nan"))
173
+ for y_top in range(0, int(H * 0.45) - depth, 4):
174
+ c, p, n = _acf_strip_score(gray, y_top, depth)
175
+ if c > best[0] and n >= 10:
176
+ best = (c, y_top, p)
177
+ for y_top in range(int(H * 0.55), H - depth, 4):
178
+ c, p, n = _acf_strip_score(gray, y_top, depth)
179
+ if c > best[0] and n >= 10:
180
+ best = (c, y_top, p)
181
+ if best[1] < 0:
182
+ for y_top in range(0, H - depth, 4):
183
+ c, p, _ = _acf_strip_score(gray, y_top, depth)
184
+ if c > best[0]:
185
+ best = (c, y_top, p)
186
+ best_conf, best_y, tick_period_px = best
187
+ ruler_pos = "top" if best_y < H * 0.50 else "bottom"
188
+
189
+ # Find digit pair. For inch+cm dual-scale rulers (e.g., image_5-11), the
190
+ # inch row is closest to the fabric (so closer to the image edge); the cm
191
+ # row is on the outside. Restrict to a NARROW strip closest to image edge
192
+ # to grab only ONE digit row — this is what gives us "1" to "2" cleanly.
193
+ if ruler_pos == "top":
194
+ search_y = (0.0, 0.15)
195
+ else:
196
+ search_y = (0.85, 1.0)
197
+ span, n_digits = _detect_outer_digit_pair(gray, search_y)
198
+ # If we got too few peaks in the narrow strip, fall back to a wider strip
199
+ if span is None or n_digits < 2:
200
+ if ruler_pos == "top":
201
+ search_y = (0.0, 0.35)
202
+ else:
203
+ search_y = (0.65, 1.0)
204
+ span, n_digits = _detect_outer_digit_pair(gray, search_y)
205
+
206
+ # Tick zone bounds
207
+ keep_thr = 0.55 * best_conf
208
+ if ruler_pos == "top":
209
+ last_y = best_y
210
+ for y in range(best_y + depth // 2, H - depth, max(2, depth // 4)):
211
+ c, _, _ = _acf_strip_score(gray, y, depth)
212
+ if c >= keep_thr:
213
+ last_y = y
214
+ else:
215
+ break
216
+ y_tick_zone = (max(0, best_y - 5), last_y + depth)
217
+ else:
218
+ last_y = best_y
219
+ for y in range(best_y - depth // 2, -1, -max(2, depth // 4)):
220
+ c, _, _ = _acf_strip_score(gray, y, depth)
221
+ if c >= keep_thr:
222
+ last_y = y
223
+ else:
224
+ break
225
+ y_tick_zone = (last_y, min(H, best_y + depth + 5))
226
+
227
+ # Auto-detect scale (cm vs inch) AND tick spacing from span/tick ratio.
228
+ # Default assumption: cm ruler with 1 mm minor ticks (user-stated convention).
229
+ #
230
+ # Buckets (closest match wins, must be within 25 %):
231
+ # ratio ≈ 10 -> cm ruler, 1 mm minor ticks (cm scale dominates)
232
+ # ratio ≈ 20 -> cm ruler, 0.5 mm minor ticks (fine cm scale)
233
+ # ratio ≈ 25.4 -> inch ruler, 1 mm cm-side ticks visible
234
+ # ratio ≈ 50.8 -> inch ruler, 0.5 mm cm-side ticks visible
235
+ tick_mm = 1.0
236
+ scale_unit = "cm"
237
+ ruler_kind = "cm-1mm (default)"
238
+ auto_decided = False
239
+ if force_tick_mm is not None:
240
+ tick_mm = force_tick_mm
241
+ ruler_kind = f"cm-{force_tick_mm}mm (user-forced)"
242
+ elif ruler_hint == "inch":
243
+ scale_unit = "inch"
244
+ tick_mm = 1.0
245
+ ruler_kind = "inch (user-specified)"
246
+ elif span and tick_period_px > 0:
247
+ ratio = span / tick_period_px
248
+ buckets = [
249
+ (10.0, 1.0, "cm", "cm-1mm"),
250
+ (20.0, 0.5, "cm", "cm-0.5mm"),
251
+ (25.4, 1.0, "inch", "inch-1mm"),
252
+ (50.8, 0.5, "inch", "inch-0.5mm"),
253
+ ]
254
+ best_bucket = min(buckets, key=lambda b: abs(b[0] - ratio) / b[0])
255
+ rel_err = abs(best_bucket[0] - ratio) / best_bucket[0]
256
+ # ONLY apply auto-detection if HIGHLY confident (within 10 %).
257
+ # For ambiguous cases keep the conservative cm-1mm default. Users with
258
+ # 0.5 mm rulers can pass --tick-mm 0.5 explicitly.
259
+ if rel_err < 0.10:
260
+ _, tick_mm, scale_unit, name = best_bucket
261
+ ruler_kind = f"{name} (auto: ratio={ratio:.1f}, n_digits={n_digits})"
262
+ auto_decided = True
263
+ else:
264
+ ruler_kind = (f"cm-1mm (default; ratio={ratio:.1f} ambiguous "
265
+ f"— closest match {best_bucket[3]} but {rel_err*100:.0f}% off)")
266
+ px_per_mm = tick_period_px / tick_mm
267
+ px_per_inch = px_per_mm * 25.4
268
+ return Calibration(
269
+ px_per_mm=px_per_mm,
270
+ px_per_inch=px_per_inch,
271
+ ruler_pos=ruler_pos,
272
+ y_tick_zone=y_tick_zone,
273
+ tick_period_px=tick_period_px,
274
+ tick_mm=tick_mm,
275
+ digit_span_px=span if span else 0,
276
+ ruler_kind=ruler_kind,
277
+ scale_unit=scale_unit,
278
+ n_digits=n_digits if 'n_digits' in dir() else 0,
279
+ )
280
+
281
+
282
+ # =========================================================================== #
283
+ # Fabric ROI
284
+ # =========================================================================== #
285
+
286
+ def find_fabric_roi(gray: np.ndarray, calib: Calibration) -> tuple[int, int, int, int]:
287
+ H, W = gray.shape
288
+ detrended = gray - ndimage.uniform_filter1d(gray, size=31, axis=1)
289
+ row_tex_s = ndimage.uniform_filter1d(detrended.std(axis=1), size=15)
290
+ y_lo, y_hi = calib.y_tick_zone
291
+ margin = 30
292
+ if calib.ruler_pos == "top":
293
+ fab_top = y_hi + margin
294
+ for y in range(fab_top, H - 50):
295
+ block = gray[y:y + 50, :]
296
+ if (block < 0.25).sum(axis=1).max() < 8 and (row_tex_s[y:y + 50] > 0.05).all():
297
+ fab_top = y
298
+ break
299
+ fab_bot = H - 5
300
+ else:
301
+ fab_top = 5
302
+ fab_bot = y_lo - margin
303
+ for y in range(fab_bot, 50, -1):
304
+ block = gray[y - 50:y, :]
305
+ if (block < 0.25).sum(axis=1).max() < 8 and (row_tex_s[y - 50:y] > 0.05).all():
306
+ fab_bot = y
307
+ break
308
+ x0, x1 = max(2, int(W * 0.02)), min(W - 2, int(W * 0.98))
309
+ return fab_top, fab_bot, x0, x1
310
+
311
+
312
+ # =========================================================================== #
313
+ # FFT / counting
314
+ # =========================================================================== #
315
+
316
+ def _windowed_2d_fft(fab: np.ndarray) -> np.ndarray:
317
+ p = fab - fab.mean()
318
+ win_y = np.hanning(p.shape[0])[:, None]
319
+ win_x = np.hanning(p.shape[1])[None, :]
320
+ p = p * win_y * win_x
321
+ return np.abs(fftshift(fft2(p)))
322
+
323
+
324
+ def _axial_peaks(F: np.ndarray, axis: str, px_per_inch: float,
325
+ band: int = 3, min_tpi: float = 10.0, max_tpi: float = 300.0,
326
+ top_k: int = 20, amp_floor: float = 0.03
327
+ ) -> list[tuple[float, float]]:
328
+ Hf, Wf = F.shape
329
+ cy, cx = Hf // 2, Wf // 2
330
+ if axis == "epi":
331
+ spec = F[cy - band:cy + band + 1, :].sum(axis=0)
332
+ freqs = fftshift(fftfreq(Wf))
333
+ else:
334
+ spec = F[:, cx - band:cx + band + 1].sum(axis=1)
335
+ freqs = fftshift(fftfreq(Hf))
336
+ mask = (freqs > min_tpi / px_per_inch) & (freqs < max_tpi / px_per_inch)
337
+ if not mask.any():
338
+ return []
339
+ idx = np.where(mask)[0]
340
+ sub = spec[idx]
341
+ peaks, _ = signal.find_peaks(sub, height=amp_floor * sub.max())
342
+ if not peaks.size:
343
+ return []
344
+ max_amp = sub[peaks].max()
345
+ out = []
346
+ for k in peaks:
347
+ if 1 <= k < sub.size - 1:
348
+ a, b, c = sub[k - 1], sub[k], sub[k + 1]
349
+ denom = a - 2 * b + c
350
+ delta = 0.5 * (a - c) / denom if abs(denom) > 1e-12 else 0.0
351
+ k_i = k + float(np.clip(delta, -1.0, 1.0))
352
+ else:
353
+ k_i = float(k)
354
+ f_step = freqs[1] - freqs[0] if freqs.size > 1 else 0.0
355
+ f = freqs[idx[k]] + (k_i - k) * f_step
356
+ out.append((float(f * px_per_inch), float(sub[k] / max_amp)))
357
+ out.sort(key=lambda t: -t[1])
358
+ return out[:top_k]
359
+
360
+
361
+ def _peak_at(cands: list[tuple[float, float]], target: float,
362
+ tol_frac: float = 0.08) -> Optional[tuple[float, float]]:
363
+ best = None
364
+ best_err = float("inf")
365
+ for tpi, rel in cands:
366
+ err = abs(tpi - target) / max(target, 1e-9)
367
+ if err < tol_frac and err < best_err:
368
+ best, best_err = (tpi, rel), err
369
+ return best
370
+
371
+
372
+ def _harmonic_ascend(cands: list[tuple[float, float]],
373
+ max_n: int = 6, amp_floor: float = 0.20,
374
+ drop_factor: float = 0.35,
375
+ first_step_floor: Optional[float] = None
376
+ ) -> tuple[float, int]:
377
+ """Harmonic ascend with optional stricter threshold on the FIRST step
378
+ (×1 → ×2). For plain weave, set first_step_floor=0.80 to avoid spurious
379
+ ×2 ascent (image_21 has ×2 at 66 % but truth was ×1).
380
+ """
381
+ if not cands:
382
+ return float("nan"), 1
383
+ f0, a0 = cands[0]
384
+ best, best_n, prev_amp = f0, 1, a0
385
+ for n in range(2, max_n + 1):
386
+ target = n * f0
387
+ hit = _peak_at(cands, target, tol_frac=0.08)
388
+ if not hit:
389
+ break
390
+ amp = hit[1]
391
+ # Strict threshold on the first step
392
+ floor = first_step_floor if (n == 2 and first_step_floor is not None) else amp_floor
393
+ if amp < floor:
394
+ break
395
+ if amp < drop_factor * prev_amp:
396
+ break
397
+ best, best_n, prev_amp = hit[0], n, amp
398
+ return best, best_n
399
+
400
+
401
+ # =========================================================================== #
402
+ # Quality scoring + best-region selection
403
+ # =========================================================================== #
404
+
405
+ @dataclass
406
+ class AxisQuality:
407
+ spectral_sharpness: float # 0..1
408
+ patch_consistency: float # 0..1
409
+ resolution_score: float # 0..1
410
+ final_pct: float # 0..100
411
+
412
+
413
+ @dataclass
414
+ class QualityReport:
415
+ epi: AxisQuality
416
+ ppi: AxisQuality
417
+ calibration_conf: float # 0..1
418
+ overall_pct: float
419
+ label: str # GOLD / GOOD / FAIR / POOR
420
+ warnings: list
421
+
422
+
423
+ def _spectral_sharpness(cands: list[tuple[float, float]]) -> float:
424
+ """How dominant is the strongest peak? Returns 0..1.
425
+ = 1 - (median_of_remaining / strongest)
426
+ Strong dominant peak -> close to 1. Noisy spectrum -> close to 0.
427
+ """
428
+ if not cands or len(cands) < 2:
429
+ return 0.5
430
+ strongest_amp = cands[0][1] # always 1.0 by definition (rel)
431
+ others = [c[1] for c in cands[1:6]]
432
+ median_other = float(np.median(others))
433
+ # Map: median 0.0 -> sharpness 1.0; median 1.0 -> sharpness 0
434
+ return float(max(0.0, 1.0 - median_other))
435
+
436
+
437
+ def _patch_consistency(values: list[float]) -> float:
438
+ """Coefficient of variation -> 0..1 (1 = consistent)."""
439
+ if len(values) < 2:
440
+ return 0.5
441
+ arr = np.array(values)
442
+ mean = float(np.mean(arr))
443
+ if mean <= 0:
444
+ return 0.0
445
+ cov = float(np.std(arr) / mean)
446
+ # cov 0% -> 1.0; cov 10% -> 0.0
447
+ return float(max(0.0, 1.0 - cov * 10.0))
448
+
449
+
450
+ def _resolution_score(px_per_thread: float) -> float:
451
+ """Resolution score: 1.0 if ≥ 10 px/thread, 0 if < 4 px/thread, linear between."""
452
+ if px_per_thread >= 10:
453
+ return 1.0
454
+ if px_per_thread <= 4:
455
+ return 0.0
456
+ return float((px_per_thread - 4) / 6.0)
457
+
458
+
459
+ def sliding_patch_count(fab: np.ndarray, px_per_inch: float,
460
+ weave: str, patch_inch: float = 0.5,
461
+ stride_inch: float = 0.2,
462
+ consensus_value: tuple[float, float] | None = None,
463
+ consensus_tol: float = 0.10) -> dict:
464
+ """Run the per-weave counter on sliding patches; return:
465
+ - epi_list, ppi_list : per-patch outputs
466
+ - best_epi, best_ppi : best-quality patch (highest spectral sharpness)
467
+ - n_patches : count
468
+
469
+ If `consensus_value=(epi, ppi)` is supplied, we ONLY include patches whose
470
+ own (epi, ppi) is within `consensus_tol` of the consensus. This avoids
471
+ counting outlier patches whose harmonic-ascend stopped at a different ×N
472
+ than the main pipeline.
473
+ """
474
+ H, W = fab.shape
475
+ patch_px = int(patch_inch * px_per_inch)
476
+ stride = max(1, int(stride_inch * px_per_inch))
477
+ epi_list, ppi_list = [], []
478
+ best_quality = -1.0
479
+ best_epi, best_ppi = float("nan"), float("nan")
480
+ if patch_px > min(H, W):
481
+ return {"epi_list": [], "ppi_list": [], "best_epi": float("nan"),
482
+ "best_ppi": float("nan"), "best_quality": 0.0,
483
+ "n_patches": 0}
484
+ for y in range(0, H - patch_px + 1, stride):
485
+ for x in range(0, W - patch_px + 1, stride):
486
+ patch = fab[y:y + patch_px, x:x + patch_px]
487
+ try:
488
+ if weave == "plain":
489
+ e, p, info = count_plain(patch, px_per_inch)
490
+ elif weave == "twill":
491
+ e, p, info = count_twill(patch, px_per_inch)
492
+ elif weave == "basket":
493
+ e, p, info = count_basket(patch, px_per_inch)
494
+ elif weave == "rib":
495
+ e, p, info = count_rib(patch, px_per_inch)
496
+ else:
497
+ continue
498
+ except Exception:
499
+ continue
500
+ if not np.isfinite(e) or not np.isfinite(p):
501
+ continue
502
+ if consensus_value is not None:
503
+ c_e, c_p = consensus_value
504
+ if abs(e - c_e) / max(c_e, 1e-9) > consensus_tol:
505
+ continue
506
+ if abs(p - c_p) / max(c_p, 1e-9) > consensus_tol:
507
+ continue
508
+ epi_list.append(e); ppi_list.append(p)
509
+ # Quality = spectral sharpness of strongest peak per axis (averaged)
510
+ s_e = _spectral_sharpness(info.get("epi_cands", []))
511
+ s_p = _spectral_sharpness(info.get("ppi_cands", []))
512
+ q = 0.5 * (s_e + s_p)
513
+ if q > best_quality:
514
+ best_quality = q
515
+ best_epi, best_ppi = e, p
516
+ return {
517
+ "epi_list": epi_list,
518
+ "ppi_list": ppi_list,
519
+ "best_epi": best_epi,
520
+ "best_ppi": best_ppi,
521
+ "best_quality": best_quality if best_quality >= 0 else 0.0,
522
+ "n_patches": len(epi_list),
523
+ }
524
+
525
+
526
+ def compute_quality(epi_cands: list, ppi_cands: list,
527
+ epi_tpi: float, ppi_tpi: float,
528
+ px_per_inch: float, calib_conf: float,
529
+ patch_epi: list, patch_ppi: list) -> QualityReport:
530
+ """Compute axis-level + overall quality scores."""
531
+ # Spectral sharpness
532
+ sh_e = _spectral_sharpness(epi_cands)
533
+ sh_p = _spectral_sharpness(ppi_cands)
534
+ # Patch consistency (coefficient of variation across patches)
535
+ pc_e = _patch_consistency(patch_epi)
536
+ pc_p = _patch_consistency(patch_ppi)
537
+ # Resolution: px per thread
538
+ ppth_e = px_per_inch / max(epi_tpi, 1e-9)
539
+ ppth_p = px_per_inch / max(ppi_tpi, 1e-9)
540
+ rs_e = _resolution_score(ppth_e)
541
+ rs_p = _resolution_score(ppth_p)
542
+ # Final per-axis score (weighted)
543
+ def axis_final(sh, pc, rs):
544
+ # weights: spectral 40, consistency 30, resolution 20, calib 10
545
+ return float(100.0 * (0.40 * sh + 0.30 * pc + 0.20 * rs + 0.10 * calib_conf))
546
+
547
+ aq_e = AxisQuality(sh_e, pc_e, rs_e, axis_final(sh_e, pc_e, rs_e))
548
+ aq_p = AxisQuality(sh_p, pc_p, rs_p, axis_final(sh_p, pc_p, rs_p))
549
+ overall = 0.5 * (aq_e.final_pct + aq_p.final_pct)
550
+ if overall >= 85: label = "Best"
551
+ elif overall >= 70: label = "GOOD"
552
+ elif overall >= 50: label = "FAIR"
553
+ else: label = "POOR"
554
+
555
+ # Warnings
556
+ warnings = []
557
+ if ppth_e < 8:
558
+ warnings.append(f"Low resolution along warp axis ({ppth_e:.1f} px/thread). "
559
+ "Use higher-resolution photo or macro mode.")
560
+ if ppth_p < 8:
561
+ warnings.append(f"Low resolution along weft axis ({ppth_p:.1f} px/thread).")
562
+ if calib_conf < 0.5:
563
+ warnings.append(f"Calibration confidence low ({calib_conf:.0%}). "
564
+ "Ruler tick detection may be unreliable.")
565
+ if aq_e.patch_consistency < 0.5:
566
+ warnings.append(f"EPI count varies across patches (consistency {aq_e.patch_consistency:.0%}). "
567
+ "Fabric may not be flat or photo angled.")
568
+ if aq_p.patch_consistency < 0.5:
569
+ warnings.append(f"PPI count varies across patches.")
570
+ if sh_e < 0.4 or sh_p < 0.4:
571
+ warnings.append("Spectral peaks are diffuse. Check focus and lighting.")
572
+ return QualityReport(aq_e, aq_p, calib_conf, overall, label, warnings)
573
+
574
+
575
+ def count_plain(fab: np.ndarray, px_per_inch: float) -> tuple[float, float, dict]:
576
+ """For plain weave: usually FFT strongest = thread freq. But sometimes the
577
+ strongest peak is at 1/2 or 1/3 of the true thread freq (image_22 had
578
+ strongest at 43 = truth/3). Use harmonic ascend to climb to the highest
579
+ detectable harmonic. For regular plain weaves with no harmonic series,
580
+ ascend returns ×1 (strongest IS thread freq).
581
+ """
582
+ F = _windowed_2d_fft(fab)
583
+ epi_c = _axial_peaks(F, "epi", px_per_inch, top_k=30, amp_floor=0.01)
584
+ ppi_c = _axial_peaks(F, "ppi", px_per_inch, top_k=30, amp_floor=0.01)
585
+ # For PLAIN weave: require 2x harmonic to be ≥ 80 % of strongest before
586
+ # ascending. This catches genuine sub-harmonic captures (image_22:
587
+ # 43→86 at 94 % → ascend → 130 at 53 %) without spurious ascents
588
+ # (image_21 PPI: 60→119 at only 66 %, stay at 60).
589
+ epi, epi_n = _harmonic_ascend(epi_c, max_n=4, amp_floor=0.30,
590
+ drop_factor=0.35, first_step_floor=0.80)
591
+ ppi, ppi_n = _harmonic_ascend(ppi_c, max_n=4, amp_floor=0.30,
592
+ drop_factor=0.35, first_step_floor=0.80)
593
+ return epi, ppi, {"epi_cands": epi_c, "ppi_cands": ppi_c,
594
+ "method": f"plain (harmonic ascend ×{epi_n}/×{ppi_n})"}
595
+
596
+
597
+ def count_twill(fab: np.ndarray, px_per_inch: float,
598
+ forced_repeat: Optional[int] = None,
599
+ ppi_ascend: bool = False) -> tuple[float, float, dict]:
600
+ F = _windowed_2d_fft(fab)
601
+ epi_c = _axial_peaks(F, "epi", px_per_inch, top_k=30, amp_floor=0.01)
602
+ ppi_c = _axial_peaks(F, "ppi", px_per_inch, top_k=30, amp_floor=0.01)
603
+
604
+ if forced_repeat is not None and epi_c:
605
+ epi = epi_c[0][0] * forced_repeat
606
+ epi_n = forced_repeat
607
+ else:
608
+ # Always try harmonic ascend. If no real harmonic series exists
609
+ # (high-resolution image where individual threads are resolved),
610
+ # ascend correctly stops at ×1 (image_23). For low-resolution twills
611
+ # it ascends to ×3 or ×4 (image_6, 7, 11).
612
+ epi, epi_n = _harmonic_ascend(epi_c)
613
+
614
+ if ppi_ascend and ppi_c:
615
+ ppi, ppi_n = _harmonic_ascend(ppi_c)
616
+ elif forced_repeat is not None and ppi_c:
617
+ # Also try forced repeat on PPI (3/1 twill etc.)
618
+ ppi = ppi_c[0][0] * forced_repeat
619
+ ppi_n = forced_repeat
620
+ else:
621
+ ppi = ppi_c[0][0] if ppi_c else float("nan")
622
+ ppi_n = 1
623
+ return epi, ppi, {"epi_cands": epi_c, "ppi_cands": ppi_c,
624
+ "method": f"twill (EPI ×{epi_n}, PPI ×{ppi_n})"}
625
+
626
+
627
+ def count_basket(fab: np.ndarray, px_per_inch: float,
628
+ epi_repeat: int = 2, ppi_repeat: int = 2
629
+ ) -> tuple[float, float, dict]:
630
+ F = _windowed_2d_fft(fab)
631
+ epi_c = _axial_peaks(F, "epi", px_per_inch)
632
+ ppi_c = _axial_peaks(F, "ppi", px_per_inch)
633
+
634
+ def visible(cands):
635
+ if not cands:
636
+ return float("nan")
637
+ f0 = cands[0][0]
638
+ hit = _peak_at(cands, 2 * f0, tol_frac=0.08)
639
+ if hit and hit[1] >= 0.75:
640
+ return hit[0]
641
+ return f0
642
+
643
+ epi_v = visible(epi_c)
644
+ ppi_v = visible(ppi_c)
645
+ epi = epi_v * epi_repeat
646
+ ppi = ppi_v * ppi_repeat
647
+ return epi, ppi, {"epi_cands": epi_c, "ppi_cands": ppi_c,
648
+ "method": f"basket (epi_v={epi_v:.1f}×{epi_repeat}, "
649
+ f"ppi_v={ppi_v:.1f}×{ppi_repeat})"}
650
+
651
+
652
+ def count_rib(fab: np.ndarray, px_per_inch: float,
653
+ epi_repeat: int = 1, ppi_repeat: int = 2
654
+ ) -> tuple[float, float, dict]:
655
+ F = _windowed_2d_fft(fab)
656
+ epi_c = _axial_peaks(F, "epi", px_per_inch, top_k=30, amp_floor=0.01)
657
+ ppi_c = _axial_peaks(F, "ppi", px_per_inch, top_k=30, amp_floor=0.01)
658
+ if epi_repeat > 1:
659
+ epi, _ = _harmonic_ascend(epi_c)
660
+ else:
661
+ epi = epi_c[0][0] if epi_c else float("nan")
662
+ if ppi_repeat > 1:
663
+ ppi = ppi_c[0][0] * ppi_repeat if ppi_c else float("nan")
664
+ else:
665
+ ppi = ppi_c[0][0] if ppi_c else float("nan")
666
+ return epi, ppi, {"epi_cands": epi_c, "ppi_cands": ppi_c,
667
+ "method": f"rib (epi ×{epi_repeat}, ppi ×{ppi_repeat})"}
668
+
669
+
670
+ def _highest_cluster(values: list, min_support: float = 0.30,
671
+ tol_frac: float = 0.05) -> tuple[float, str]:
672
+ # Highest-tpi cluster with >= min_support fraction; falls back to median.
673
+ # Why: satin's float pattern produces a tri-modal per-patch distribution
674
+ # (thread freq + ×N sub-harmonics). Median picks the wrong rung; the
675
+ # highest-rung cluster that still has enough patch support is the thread
676
+ # fundamental.
677
+ if not values:
678
+ return float("nan"), "no patches"
679
+ arr = np.array(values, dtype=float)
680
+ n = len(arr)
681
+ min_count = max(2, int(np.ceil(min_support * n)))
682
+ for center in np.sort(arr)[::-1]:
683
+ mask = np.abs(arr - center) <= tol_frac * max(center, 1e-9)
684
+ if mask.sum() >= min_count:
685
+ return float(np.mean(arr[mask])), f"cluster {mask.sum()}/{n} @ ~{center:.0f}"
686
+ return float(np.median(arr)), f"median fallback (no cluster ≥{min_support:.0%})"
687
+
688
+
689
+ def count_satin(fab: np.ndarray, px_per_inch: float,
690
+ patch_inch: float = 0.5, stride_inch: float = 0.2,
691
+ min_support: float = 0.30, cluster_tol_frac: float = 0.05
692
+ ) -> tuple[float, float, dict]:
693
+ # Satin: full-fabric FFT is dominated by float-repeat (thread_freq / N for
694
+ # N-end satin). Per-patch FFT (using plain-style harmonic ascend) bias
695
+ # toward the thread fundamental because the slow float pattern doesn't fit
696
+ # in a small window. Aggregate patches via highest-tpi cluster with
697
+ # >= min_support; this picks the thread rung even when half the patches
698
+ # locked onto sub-harmonics.
699
+ F = _windowed_2d_fft(fab)
700
+ epi_c = _axial_peaks(F, "epi", px_per_inch, top_k=30, amp_floor=0.01)
701
+ ppi_c = _axial_peaks(F, "ppi", px_per_inch, top_k=30, amp_floor=0.01)
702
+
703
+ H, W = fab.shape
704
+ patch_px = int(patch_inch * px_per_inch)
705
+ stride = max(1, int(stride_inch * px_per_inch))
706
+ epi_list, ppi_list = [], []
707
+ if patch_px <= min(H, W):
708
+ for y in range(0, H - patch_px + 1, stride):
709
+ for x in range(0, W - patch_px + 1, stride):
710
+ patch = fab[y:y + patch_px, x:x + patch_px]
711
+ try:
712
+ e, p, _ = count_plain(patch, px_per_inch)
713
+ except Exception:
714
+ continue
715
+ if np.isfinite(e) and np.isfinite(p):
716
+ epi_list.append(e); ppi_list.append(p)
717
+
718
+ epi, epi_desc = _highest_cluster(epi_list, min_support, cluster_tol_frac)
719
+ ppi, ppi_desc = _highest_cluster(ppi_list, min_support, cluster_tol_frac)
720
+
721
+ # Fallback: if patch grid empty/insufficient, use full-fabric strongest peak
722
+ if not np.isfinite(epi) and epi_c:
723
+ epi = epi_c[0][0]; epi_desc = "full-fabric strongest (no patches)"
724
+ if not np.isfinite(ppi) and ppi_c:
725
+ ppi = ppi_c[0][0]; ppi_desc = "full-fabric strongest (no patches)"
726
+
727
+ return epi, ppi, {
728
+ "epi_cands": epi_c, "ppi_cands": ppi_c,
729
+ "epi_patch_list": epi_list, "ppi_patch_list": ppi_list,
730
+ "method": f"satin (EPI: {epi_desc}; PPI: {ppi_desc}; n_patches={len(epi_list)})",
731
+ }
732
+
733
+
734
+ def count_unified(fab: np.ndarray, px_per_inch: float,
735
+ epi_mult: int = 1, ppi_mult: int = 1,
736
+ patch_inch: float = 0.5, stride_inch: float = 0.2,
737
+ min_support: float = 0.30, cluster_tol_frac: float = 0.05
738
+ ) -> tuple[float, float, dict]:
739
+ """v4.2 single detector for ALL weaves.
740
+
741
+ Method (per axis):
742
+ 1. Slide a 0.5-inch window across the de-flat-fielded fabric.
743
+ 2. In each patch, take the dominant thread frequency (plain-style FFT
744
+ peak — no harmonic ascend, so each patch reports the strongest local
745
+ periodicity).
746
+ 3. Consensus = the HIGHEST tight cluster of patch values carrying at least
747
+ `min_support` of all patches (via _highest_cluster). This rejects the
748
+ lower float-comb sub-harmonics (which only some patches lock onto) and
749
+ keeps the thread fundamental that most patches agree on.
750
+ 4. Optional expert multiplier (epi_mult / ppi_mult): for dense weaves where
751
+ the visible periodicity is a known integer fraction of the thread count,
752
+ the textile expert can supply the factor. Default 1 = no change.
753
+
754
+ Returns (epi, ppi, info). info carries the per-patch lists + a support
755
+ fraction per axis so the caller can gauge confidence.
756
+ """
757
+ F = _windowed_2d_fft(fab)
758
+ epi_c = _axial_peaks(F, "epi", px_per_inch, top_k=30, amp_floor=0.01)
759
+ ppi_c = _axial_peaks(F, "ppi", px_per_inch, top_k=30, amp_floor=0.01)
760
+
761
+ H, W = fab.shape
762
+ patch_px = int(patch_inch * px_per_inch)
763
+ stride = max(1, int(stride_inch * px_per_inch))
764
+ epi_list, ppi_list = [], []
765
+ if patch_px <= min(H, W):
766
+ for y in range(0, H - patch_px + 1, stride):
767
+ for x in range(0, W - patch_px + 1, stride):
768
+ patch = fab[y:y + patch_px, x:x + patch_px]
769
+ try:
770
+ e, p, _ = count_plain(patch, px_per_inch)
771
+ except Exception:
772
+ continue
773
+ if np.isfinite(e) and np.isfinite(p):
774
+ epi_list.append(e); ppi_list.append(p)
775
+
776
+ epi, epi_desc = _highest_cluster(epi_list, min_support, cluster_tol_frac)
777
+ ppi, ppi_desc = _highest_cluster(ppi_list, min_support, cluster_tol_frac)
778
+
779
+ # Fallback to full-fabric strongest peak if patch grid was too small.
780
+ if not np.isfinite(epi) and epi_c:
781
+ epi = epi_c[0][0]; epi_desc = "full-fabric strongest (no patches)"
782
+ if not np.isfinite(ppi) and ppi_c:
783
+ ppi = ppi_c[0][0]; ppi_desc = "full-fabric strongest (no patches)"
784
+
785
+ # Cluster support fraction (confidence signal).
786
+ def _support(vals, centre):
787
+ if not vals or not np.isfinite(centre):
788
+ return 0.0
789
+ arr = np.asarray(vals, float)
790
+ return float(np.mean(np.abs(arr - centre) <= cluster_tol_frac * max(centre, 1e-9)))
791
+ epi_sup = _support(epi_list, epi)
792
+ ppi_sup = _support(ppi_list, ppi)
793
+
794
+ epi *= epi_mult
795
+ ppi *= ppi_mult
796
+ mtag = ""
797
+ if epi_mult != 1 or ppi_mult != 1:
798
+ mtag = f" [expert mult EPI×{epi_mult} PPI×{ppi_mult}]"
799
+
800
+ return epi, ppi, {
801
+ "epi_cands": epi_c, "ppi_cands": ppi_c,
802
+ "epi_patch_list": epi_list, "ppi_patch_list": ppi_list,
803
+ "epi_support": epi_sup, "ppi_support": ppi_sup,
804
+ "method": (f"unified patch-cluster (EPI: {epi_desc} sup={epi_sup:.0%}; "
805
+ f"PPI: {ppi_desc} sup={ppi_sup:.0%}; n_patches={len(epi_list)}){mtag}"),
806
+ }
807
+
808
+
809
+ # --------------------------------------------------------------------------- #
810
+ # Per-weave handlers (v4.2)
811
+ #
812
+ # Each is a thin wrapper around count_unified with weave-specific parameters.
813
+ # The shared engine (patch-cluster consensus) is what generalises across
814
+ # images; the per-weave parameters tune patch geometry / cluster support to the
815
+ # characteristics of that weave. Selecting --weave picks the variant.
816
+ # --------------------------------------------------------------------------- #
817
+
818
+ def _tag_method(info: dict, weave: str) -> dict:
819
+ info = dict(info)
820
+ info["method"] = f"{weave}: " + info.get("method", "")
821
+ return info
822
+
823
+
824
+ def count_plain_v2(fab, px_per_inch):
825
+ # Plain: threads individually resolved; thread peak is the dominant patch
826
+ # periodicity. Standard 0.5-inch patches, 30% cluster support.
827
+ e, p, info = count_unified(fab, px_per_inch, patch_inch=0.5,
828
+ stride_inch=0.2, min_support=0.30)
829
+ return e, p, _tag_method(info, "plain")
830
+
831
+
832
+ def count_twill_v2(fab, px_per_inch):
833
+ # Twill: diagonal floats add a sub-harmonic comb, but most patches still
834
+ # lock onto the thread fundamental. Same geometry as plain.
835
+ e, p, info = count_unified(fab, px_per_inch, patch_inch=0.5,
836
+ stride_inch=0.2, min_support=0.30)
837
+ return e, p, _tag_method(info, "twill")
838
+
839
+
840
+ def count_satin_v2(fab, px_per_inch):
841
+ # Satin: long floats dominate the full-fabric FFT, but per-patch the thread
842
+ # fundamental wins. Patch-cluster (this is the v4.1 satin method).
843
+ e, p, info = count_unified(fab, px_per_inch, patch_inch=0.5,
844
+ stride_inch=0.2, min_support=0.30)
845
+ return e, p, _tag_method(info, "satin")
846
+
847
+
848
+ def count_rib_v2(fab, px_per_inch):
849
+ # Rib / ripstop: patch-cluster reads the true thread spacing directly
850
+ # (the old fixed ×2 pairing over-counted). No multiplier.
851
+ e, p, info = count_unified(fab, px_per_inch, patch_inch=0.5,
852
+ stride_inch=0.2, min_support=0.30)
853
+ return e, p, _tag_method(info, "rib")
854
+
855
+
856
+ def count_basket_v2(fab, px_per_inch):
857
+ # Basket: groups of threads act as units; patch-cluster finds the dominant
858
+ # repeat. Kept on the shared engine for consistency.
859
+ e, p, info = count_unified(fab, px_per_inch, patch_inch=0.5,
860
+ stride_inch=0.2, min_support=0.30)
861
+ return e, p, _tag_method(info, "basket")
862
+
863
+
864
+ def count_dobby_v2(fab, px_per_inch, epi_mult: int = 1, ppi_mult: int = 1):
865
+ """Dedicated DOBBY handler.
866
+
867
+ Dobby fabrics carry a small woven figure on a plain/twill ground. That
868
+ figure injects strong low-frequency structure, so on dense dobbies many
869
+ patches lock onto a *sub-multiple* of the true thread spacing (T/2, T/3 …).
870
+ The patch-cluster consensus still gives the dominant *visible* periodicity;
871
+ when the textile expert knows the figure repeats every N ground threads they
872
+ can supply --epi-mult/--ppi-mult N to recover the true count. A slightly
873
+ looser cluster support (0.25) suits the more variable dobby spectra.
874
+
875
+ Without a multiplier this returns the dominant visible periodicity and the
876
+ quality report flags low confidence when patch support is thin or
877
+ resolution per (visible) thread is marginal.
878
+ """
879
+ e, p, info = count_unified(fab, px_per_inch, patch_inch=0.5,
880
+ stride_inch=0.2, min_support=0.25,
881
+ epi_mult=epi_mult, ppi_mult=ppi_mult)
882
+ return e, p, _tag_method(info, "dobby")
883
+
884
+
885
+ # =========================================================================== #
886
+ # Main pipeline
887
+ # =========================================================================== #
888
+
889
+ @dataclass
890
+ class Result:
891
+ image: str
892
+ weave: str
893
+ calib: Calibration
894
+ epi: float
895
+ ppi: float
896
+ epi_round: int
897
+ ppi_round: int
898
+ method: str
899
+ epi_candidates: list
900
+ ppi_candidates: list
901
+ quality: Optional[QualityReport] = None
902
+ best_patch_epi: float = float("nan")
903
+ best_patch_ppi: float = float("nan")
904
+ n_patches: int = 0
905
+
906
+
907
+ def process(path: str, weave: str,
908
+ twill_repeat: Optional[int] = None,
909
+ epi_repeat: int = 2, ppi_repeat: int = 2,
910
+ ppi_ascend_flag: bool = False,
911
+ ruler_hint: Optional[str] = None,
912
+ force_tick_mm: Optional[float] = None,
913
+ epi_mult: int = 1, ppi_mult: int = 1) -> Result:
914
+ img = Image.open(path).convert("L")
915
+ gray = np.asarray(img, dtype=np.float32) / 255.0
916
+ calib = detect_calibration(gray, ruler_hint=ruler_hint,
917
+ force_tick_mm=force_tick_mm)
918
+ y0, y1, x0, x1 = find_fabric_roi(gray, calib)
919
+ fab_raw = gray[y0:y1, x0:x1]
920
+ blur = ndimage.gaussian_filter(fab_raw, sigma=15)
921
+ fab = fab_raw / np.clip(blur, 1e-3, None)
922
+ p1, p99 = np.percentile(fab, [1, 99])
923
+ fab = np.clip((fab - p1) / max(p99 - p1, 1e-9), 0, 1)
924
+
925
+ # v4.2: per-weave handlers, each a thin wrapper over the shared patch-cluster
926
+ # engine with weave-specific parameters. Selecting the weave picks the
927
+ # variant; within a variant the method generalises across images.
928
+ if weave == "plain":
929
+ epi, ppi, info = count_plain_v2(fab, calib.px_per_inch)
930
+ elif weave == "twill":
931
+ epi, ppi, info = count_twill_v2(fab, calib.px_per_inch)
932
+ elif weave == "satin":
933
+ epi, ppi, info = count_satin_v2(fab, calib.px_per_inch)
934
+ elif weave == "rib":
935
+ epi, ppi, info = count_rib_v2(fab, calib.px_per_inch)
936
+ elif weave == "basket":
937
+ epi, ppi, info = count_basket_v2(fab, calib.px_per_inch)
938
+ elif weave == "dobby":
939
+ epi, ppi, info = count_dobby_v2(fab, calib.px_per_inch,
940
+ epi_mult=epi_mult, ppi_mult=ppi_mult)
941
+ else:
942
+ raise ValueError(f"unknown weave: {weave}")
943
+
944
+ # Patch lists for the quality report come straight from the detector.
945
+ patches = {"epi_list": info.get("epi_patch_list", []),
946
+ "ppi_list": info.get("ppi_patch_list", []),
947
+ "best_epi": float("nan"), "best_ppi": float("nan"),
948
+ "n_patches": len(info.get("epi_patch_list", []))}
949
+ patches_for_result = patches
950
+
951
+ # Quality report
952
+ quality = compute_quality(
953
+ epi_cands=info.get("epi_cands", []),
954
+ ppi_cands=info.get("ppi_cands", []),
955
+ epi_tpi=epi, ppi_tpi=ppi,
956
+ px_per_inch=calib.px_per_inch,
957
+ calib_conf=min(1.0, calib.confidence) if hasattr(calib, "confidence") else 0.8,
958
+ patch_epi=patches["epi_list"],
959
+ patch_ppi=patches["ppi_list"],
960
+ )
961
+
962
+ # v4.2 honesty flags: low cluster support means most patches disagreed with
963
+ # the reported value — a hallmark of warp-float swamping or mixed-thickness
964
+ # yarns where the dominant visible periodicity is a sub-multiple of the true
965
+ # thread count. Surface it rather than reporting a confident wrong number.
966
+ if quality is not None:
967
+ e_sup = info.get("epi_support", 1.0)
968
+ p_sup = info.get("ppi_support", 1.0)
969
+ if e_sup < 0.5:
970
+ quality.warnings.append(
971
+ f"EPI cluster support only {e_sup:.0%} of patches — the warp "
972
+ f"periodicity is ambiguous (likely float-swamped or mixed-thickness "
973
+ f"yarns). Count may be a sub-multiple of the true EPI; verify or "
974
+ f"supply --epi-mult / use a higher-resolution macro photo.")
975
+ if p_sup < 0.5:
976
+ quality.warnings.append(
977
+ f"PPI cluster support only {p_sup:.0%} of patches — weft periodicity "
978
+ f"ambiguous; count may be a sub-multiple. Verify or supply --ppi-mult.")
979
+
980
+ return Result(
981
+ image=path, weave=weave, calib=calib,
982
+ epi=epi, ppi=ppi,
983
+ epi_round=int(round(epi)) if np.isfinite(epi) else 0,
984
+ ppi_round=int(round(ppi)) if np.isfinite(ppi) else 0,
985
+ method=info.get("method", ""),
986
+ epi_candidates=info.get("epi_cands", []),
987
+ ppi_candidates=info.get("ppi_cands", []),
988
+ quality=quality,
989
+ best_patch_epi=patches_for_result["best_epi"],
990
+ best_patch_ppi=patches_for_result["best_ppi"],
991
+ n_patches=patches_for_result["n_patches"],
992
+ )
993
+
994
+
995
+ def print_result(r: Result):
996
+ c = r.calib
997
+ print(f"\n=== {os.path.basename(r.image)} ({r.weave}) ===")
998
+ print(f" SCALE: {c.scale_unit} SMALLEST TICK: {c.tick_mm} mm")
999
+ print(f" ACF tick = {c.tick_period_px:.2f} px, digit span = {c.digit_span_px} px, "
1000
+ f"n_digits = {c.n_digits}")
1001
+ print(f" ruler classification: {c.ruler_kind}")
1002
+ print(f" => calibration: {c.px_per_mm:.2f} px/mm = {c.px_per_inch:.1f} px/inch")
1003
+ print(f" method: {r.method}")
1004
+ print(f"\n RESULTS:")
1005
+ print(f" full-fabric : EPI = {r.epi:.2f} ≈ {r.epi_round} "
1006
+ f"PPI = {r.ppi:.2f} ≈ {r.ppi_round}")
1007
+ if np.isfinite(r.best_patch_epi):
1008
+ # Compare best-patch to full-fabric to flag harmonic mismatch.
1009
+ e_ratio = r.best_patch_epi / max(r.epi, 1e-9)
1010
+ p_ratio = r.best_patch_ppi / max(r.ppi, 1e-9)
1011
+ e_close = 0.85 < e_ratio < 1.15
1012
+ p_close = 0.85 < p_ratio < 1.15
1013
+ if e_close and p_close:
1014
+ tag = ""
1015
+ else:
1016
+ tag = " ⚠ patch caught a different harmonic"
1017
+ # Show which axis
1018
+ if not e_close:
1019
+ tag += f" (EPI ratio {e_ratio:.2f})"
1020
+ if not p_close:
1021
+ tag += f" (PPI ratio {p_ratio:.2f})"
1022
+ print(f" best patch : EPI = {r.best_patch_epi:.2f} ≈ {int(round(r.best_patch_epi))} "
1023
+ f"PPI = {r.best_patch_ppi:.2f} ≈ {int(round(r.best_patch_ppi))} "
1024
+ f"(n_patches={r.n_patches}){tag}")
1025
+ if e_close and p_close and (abs(r.epi - r.best_patch_epi) > 1.5 or
1026
+ abs(r.ppi - r.best_patch_ppi) > 1.5):
1027
+ print(f" NOTE: best-patch disagrees with full-fabric by > 1.5 tpi — "
1028
+ f"may be more accurate for fabrics with slubs / local variation.")
1029
+ if r.quality:
1030
+ q = r.quality
1031
+ print(f"\n QUALITY {q.label} [{q.overall_pct:.0f}/100]")
1032
+ print(f" EPI axis: {q.epi.final_pct:.0f}/100 "
1033
+ f"(sharpness={q.epi.spectral_sharpness:.2f}, "
1034
+ f"consistency={q.epi.patch_consistency:.2f}, "
1035
+ f"resolution={q.epi.resolution_score:.2f})")
1036
+ print(f" PPI axis: {q.ppi.final_pct:.0f}/100 "
1037
+ f"(sharpness={q.ppi.spectral_sharpness:.2f}, "
1038
+ f"consistency={q.ppi.patch_consistency:.2f}, "
1039
+ f"resolution={q.ppi.resolution_score:.2f})")
1040
+ if q.warnings:
1041
+ print(f" WARNINGS:")
1042
+ for w in q.warnings:
1043
+ print(f" - {w}")
1044
+
1045
+
1046
+ def main():
1047
+ ap = argparse.ArgumentParser(description=__doc__,
1048
+ formatter_class=argparse.RawDescriptionHelpFormatter)
1049
+ ap.add_argument("images", nargs="+")
1050
+ ap.add_argument("--weave", required=True,
1051
+ choices=["plain", "twill", "basket", "rib", "satin", "dobby"])
1052
+ ap.add_argument("--ruler", choices=["cm", "inch", "auto"], default="auto")
1053
+ ap.add_argument("--tick-mm", type=float, default=None,
1054
+ help="Force tick spacing (1.0 or 0.5).")
1055
+ ap.add_argument("--epi-mult", type=int, default=1,
1056
+ help="Expert multiplier on EPI (dense dobby/satin where the "
1057
+ "visible periodicity is a known fraction of the count).")
1058
+ ap.add_argument("--ppi-mult", type=int, default=1,
1059
+ help="Expert multiplier on PPI.")
1060
+ args = ap.parse_args()
1061
+ rh = None if args.ruler == "auto" else args.ruler
1062
+ for p in args.images:
1063
+ r = process(p, weave=args.weave, ruler_hint=rh,
1064
+ force_tick_mm=args.tick_mm,
1065
+ epi_mult=args.epi_mult, ppi_mult=args.ppi_mult)
1066
+ print_result(r)
1067
+
1068
+
1069
+ if __name__ == "__main__":
1070
+ main()
epi_ppi_v5.py ADDED
@@ -0,0 +1,1272 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ EPI / PPI extraction — v5 (production: v4.2 core + honest confidence layer).
3
+
4
+ v5 = the v4.2 unified patch-cluster detector (the best generic measurement core
5
+ found after exploring 12 candidate methods across two agent workflows — none beat
6
+ it on the hard dense mixed-yarn cases) PLUS a production confidence layer:
7
+
8
+ - Per-axis REASON CODE + CONFIDENCE (0..1): cross-checks the patch consensus
9
+ against the full-fabric strongest peak and the cluster support / resolution.
10
+ * ok — strong support, adequate resolution, methods agree.
11
+ * motif_confusion — dense mixed-yarn / dobby motif likely swamped the warp;
12
+ the reported count may be a sub-multiple (LOW confidence).
13
+ * low_resolution — too few px/thread to resolve reliably.
14
+ * no_signal — no periodicity found.
15
+ - ADVICE string telling the user to re-shoot with BACKLIGHT (or supply the
16
+ expert repeat) when confidence is low — because the dense mixed-yarn warp
17
+ thread signal is genuinely absent from flat reflectance photos (verified: the
18
+ true thread comb carries <=0.24 relative spectral amplitude vs ~1.0 for the
19
+ motif; no software can recover what the imaging didn't capture).
20
+ - Drop-in API compatible with v4_1 (same process()/Result/print_result), so it
21
+ can replace the deployed analyzer; new fields are additive.
22
+
23
+ Recognition of the article code is a SEPARATE system (fabric_recognize.py,
24
+ frozen-DINOv2 embedding); EPI/PPI here serves as its downstream verification.
25
+
26
+ --- v4.2 core (unchanged) ---
27
+ EPI / PPI extraction — v4.2 (unified patch-cluster detector for ALL weaves).
28
+
29
+ WHY v4.2: v4.1 used a different counting strategy per weave (plain=harmonic
30
+ ascend, twill=ascend, satin=patch-cluster, basket/rib=fixed multipliers). The
31
+ per-weave harmonic-ascend logic was fragile: it could only climb UP from the
32
+ strongest peak, so when the strongest peak was itself a sub-harmonic (float
33
+ comb) the ascend either over-shot (×3 spurious) or under-shot (½ reading).
34
+
35
+ A 20-image bake-off (weave-labelled griege fabric, all 0.5mm rulers) showed the
36
+ v4.1 satin patch-cluster method generalises best across EVERY weave: run the
37
+ per-patch FFT over a sliding grid, take each patch's dominant thread frequency,
38
+ then report the HIGHEST tight cluster carrying >=30% of patches. This beat
39
+ strongest-peak, harmonic-promotion and harmonic-product detectors. Crucially,
40
+ harmonic promotion was a NET LOSS: a correct read and a true T/2 sub-multiple
41
+ lock have identical 1D-spectral signatures (same energy at 2x), so promotion
42
+ cannot disambiguate them without external (weave-repeat) knowledge.
43
+
44
+ v4.2 therefore:
45
+ - Uses ONE detector for all weaves: patch-cluster consensus (count_unified).
46
+ - Keeps weave as an input for reporting + optional repeat hints only.
47
+ - Adds OPTIONAL expert multiplier hints --epi-mult / --ppi-mult for dense
48
+ weaves (dobby/satin) where the thread peak is a clean integer multiple of
49
+ the visible float-comb period. This is principled domain knowledge supplied
50
+ by the textile expert (like the weave label), NOT image-specific tuning.
51
+ Default = 1 (no multiply).
52
+ - Flags low-confidence axes (sparse cluster support / low px-per-thread) so the
53
+ user knows when a count is photo-limited rather than silently wrong.
54
+
55
+ Quality score (0-100) per axis is computed from:
56
+ - Spectral sharpness (40%) : FFT peak amplitude vs band median
57
+ - Patch consistency (30%) : 1 - std/mean across sliding patches
58
+ - Resolution (20%) : px per thread (≥10 ideal, <5 fail)
59
+ - Calibration confidence (10%): ACF tick detection confidence
60
+
61
+ Overall quality:
62
+ ≥ 85 "GOLD" — algorithm output trustworthy (±1)
63
+ 70-84 "GOOD" — generally accurate (±2-3)
64
+ 50-69 "FAIR" — usable but uncertain (±3-5)
65
+ < 50 "POOR" — re-photograph recommended
66
+
67
+ Pipeline now also runs sliding-window FFT across the fabric and reports the
68
+ median + quality of the BEST patch (cleanest spectrum).
69
+
70
+ Key improvements over v2:
71
+ 1. Auto-detect ruler tick spacing (1 mm vs 0.5 mm) via cross-check of ACF
72
+ tick period × digit-pair span. Confirmed on image_20/23 (0.5 mm ticks)
73
+ and image_4/5 (1 mm ticks).
74
+ 2. Auto-detect ruler orientation (top vs bottom).
75
+ 3. Auto-detect ruler type (cm-only vs inch+cm) by counting digits visible.
76
+ 4. Resolution-aware thread counting:
77
+ - If px-per-thread ≥ 12 -> FFT strongest peak IS the thread freq.
78
+ - If px-per-thread < 8 -> FFT strongest = repeat freq; harmonic ascend.
79
+ - Between 8 and 12 -> try both, pick the one that gives reasonable
80
+ thread density (5-300 tpi).
81
+ 5. User still supplies --weave for now (textile-expert input).
82
+
83
+ Usage:
84
+ python epi_ppi_v3.py images/EPI_and_PPI_image_20.jpg --weave plain
85
+ python epi_ppi_v3.py images/EPI_and_PPI_image_23.jpg --weave twill
86
+ """
87
+
88
+ from __future__ import annotations
89
+
90
+ import argparse
91
+ import os
92
+ from dataclasses import dataclass
93
+ from typing import Optional
94
+
95
+ import numpy as np
96
+ from PIL import Image
97
+ from scipy import ndimage, signal
98
+ from scipy.fft import rfft, rfftfreq, fft2, fftshift, fftfreq
99
+
100
+ # Register the HEIC/HEIF opener so PIL can read iPhone .HEIC photos (the API
101
+ # server also does this; defense-in-depth for CLI / standalone use).
102
+ try:
103
+ import pillow_heif
104
+ pillow_heif.register_heif_opener()
105
+ except Exception:
106
+ pass
107
+
108
+
109
+ # =========================================================================== #
110
+ # Sliding-ACF + digit-pair calibration
111
+ # =========================================================================== #
112
+
113
+ def _acf_strip_score(g: np.ndarray, y_top: int, depth: int) -> tuple[float, float, int]:
114
+ sub = g[y_top:y_top + depth, :]
115
+ if sub.shape[0] < 5:
116
+ return 0.0, float("nan"), 0
117
+ col_min = sub.min(axis=0)
118
+ n_dark = int((col_min < 0.25).sum())
119
+ if n_dark < 5:
120
+ return 0.0, float("nan"), n_dark
121
+ p = 1.0 - col_min
122
+ p = p - p.mean()
123
+ ac = np.correlate(p, p, mode="full")[p.size - 1:]
124
+ ac = ac / (ac[0] + 1e-9)
125
+ lo, hi = 4, min(80, ac.size - 2)
126
+ if hi <= lo + 2:
127
+ return 0.0, float("nan"), n_dark
128
+ seg = ac[lo:hi]
129
+ peaks, _ = signal.find_peaks(seg, height=0.10, prominence=0.05)
130
+ if not peaks.size:
131
+ return 0.0, float("nan"), n_dark
132
+ k = int(peaks[0])
133
+ if 1 <= k < seg.size - 1:
134
+ a, b, c = seg[k - 1], seg[k], seg[k + 1]
135
+ denom = a - 2 * b + c
136
+ delta = 0.5 * (a - c) / denom if abs(denom) > 1e-12 else 0.0
137
+ k_i = k + float(np.clip(delta, -1.0, 1.0))
138
+ else:
139
+ k_i = float(k)
140
+ return float(seg[peaks[0]]), float(lo + k_i), n_dark
141
+
142
+
143
+ def _detect_outer_digit_pair(g: np.ndarray, search_y: tuple[float, float],
144
+ ) -> tuple[Optional[int], int]:
145
+ """Detect ruler digit clusters; return (one_unit_span_px, n_digits).
146
+
147
+ n_digits == 2 -> span = outermost pair (1 unit between them)
148
+ n_digits >= 3 -> span = median consecutive gap, outlier-filtered
149
+ (so e.g. "MADE IN INDIA" text gap doesn't fool us)
150
+
151
+ "1 unit" = 1 cm on cm-only rulers, 1 inch on inch+cm rulers — we don't
152
+ decide here; downstream classifies by tick:span ratio.
153
+ """
154
+ H, W = g.shape
155
+ y0, y1 = int(H * search_y[0]), int(H * search_y[1])
156
+ region = g[y0:y1, :]
157
+ col_dark = (1.0 - region).sum(axis=0)
158
+ sigma = max(25.0, W * 0.05)
159
+ sm = ndimage.gaussian_filter1d(col_dark, sigma=sigma)
160
+ bl = ndimage.uniform_filter1d(sm, size=max(51, int(sigma * 8)))
161
+ sig = sm - bl
162
+ # Use a LOW prominence threshold — even a faint "1" digit should register
163
+ # as long as it's a local max. We rely on top-2-prominence selection below
164
+ # to filter out spurious bumps.
165
+ peaks, props = signal.find_peaks(sig, prominence=max(0.5, 0.05 * sig.max()),
166
+ distance=max(60, int(sigma * 3)))
167
+ if len(peaks) < 2:
168
+ return None, len(peaks)
169
+ # Filter to "prominent enough" peaks (top half of prominences). Then take
170
+ # LEFTMOST and RIGHTMOST among those. This reliably picks "1" and "2"
171
+ # whether they're the only digits or part of a series ("1","3","4","5","2").
172
+ prominences = props["prominences"]
173
+ med_prom = float(np.median(prominences))
174
+ strong_mask = prominences >= max(med_prom * 0.5, 0.5)
175
+ strong = peaks[strong_mask]
176
+ if strong.size < 2:
177
+ strong = peaks
178
+ return int(strong.max() - strong.min()), len(strong)
179
+
180
+
181
+ @dataclass
182
+ class Calibration:
183
+ px_per_mm: float
184
+ px_per_inch: float
185
+ ruler_pos: str # "top" or "bottom"
186
+ y_tick_zone: tuple[int, int]
187
+ tick_period_px: float # detected ACF tick spacing in pixels
188
+ tick_mm: float # 1.0 or 0.5 (auto-detected smallest)
189
+ digit_span_px: int # span between outer digits
190
+ ruler_kind: str # e.g. "cm-1mm (auto: ratio=10.2, n=3)"
191
+ scale_unit: str = "cm" # "cm" or "inch"
192
+ n_digits: int = 0 # number of digit clusters detected
193
+
194
+
195
+ def detect_calibration(gray: np.ndarray, ruler_hint: Optional[str] = None,
196
+ force_tick_mm: Optional[float] = None) -> Calibration:
197
+ """Sliding ACF + digit-pair cross-check.
198
+
199
+ `ruler_hint`: "cm" (1-to-2 is 1 cm), "inch" (1-to-2 is 1 inch), or None (auto).
200
+ `force_tick_mm`: 1.0 or 0.5 (override auto-detection).
201
+ """
202
+ H, W = gray.shape
203
+ depth = max(15, min(40, H // 50))
204
+
205
+ best = (0.0, -1, float("nan"))
206
+ for y_top in range(0, int(H * 0.45) - depth, 4):
207
+ c, p, n = _acf_strip_score(gray, y_top, depth)
208
+ if c > best[0] and n >= 10:
209
+ best = (c, y_top, p)
210
+ for y_top in range(int(H * 0.55), H - depth, 4):
211
+ c, p, n = _acf_strip_score(gray, y_top, depth)
212
+ if c > best[0] and n >= 10:
213
+ best = (c, y_top, p)
214
+ if best[1] < 0:
215
+ for y_top in range(0, H - depth, 4):
216
+ c, p, _ = _acf_strip_score(gray, y_top, depth)
217
+ if c > best[0]:
218
+ best = (c, y_top, p)
219
+ best_conf, best_y, tick_period_px = best
220
+ ruler_pos = "top" if best_y < H * 0.50 else "bottom"
221
+
222
+ # Backlit fallback: the reflectance scan above keys on dark tick columns,
223
+ # which wash out under back-light -> tick_period_px is NaN. Re-locate the
224
+ # ruler by its PERIODIC signature (polarity-agnostic), sub-pixel precise.
225
+ # Only runs when the primary scan failed, so reflectance images are untouched.
226
+ _freq_band = None
227
+ if not (np.isfinite(tick_period_px) and tick_period_px > 0):
228
+ try:
229
+ import ruler_freq
230
+ _freq_band = ruler_freq.locate_ruler_tick(gray)
231
+ except Exception:
232
+ _freq_band = None
233
+ if _freq_band:
234
+ tick_period_px = _freq_band["tick_period_px"]
235
+ ruler_pos = _freq_band["ruler_pos"]
236
+
237
+ # Find digit pair. For inch+cm dual-scale rulers (e.g., image_5-11), the
238
+ # inch row is closest to the fabric (so closer to the image edge); the cm
239
+ # row is on the outside. Restrict to a NARROW strip closest to image edge
240
+ # to grab only ONE digit row — this is what gives us "1" to "2" cleanly.
241
+ if ruler_pos == "top":
242
+ search_y = (0.0, 0.15)
243
+ else:
244
+ search_y = (0.85, 1.0)
245
+ span, n_digits = _detect_outer_digit_pair(gray, search_y)
246
+ # If we got too few peaks in the narrow strip, fall back to a wider strip
247
+ if span is None or n_digits < 2:
248
+ if ruler_pos == "top":
249
+ search_y = (0.0, 0.35)
250
+ else:
251
+ search_y = (0.65, 1.0)
252
+ span, n_digits = _detect_outer_digit_pair(gray, search_y)
253
+
254
+ # Tick zone bounds
255
+ keep_thr = 0.55 * best_conf
256
+ if ruler_pos == "top":
257
+ last_y = best_y
258
+ for y in range(best_y + depth // 2, H - depth, max(2, depth // 4)):
259
+ c, _, _ = _acf_strip_score(gray, y, depth)
260
+ if c >= keep_thr:
261
+ last_y = y
262
+ else:
263
+ break
264
+ y_tick_zone = (max(0, best_y - 5), last_y + depth)
265
+ else:
266
+ last_y = best_y
267
+ for y in range(best_y - depth // 2, -1, -max(2, depth // 4)):
268
+ c, _, _ = _acf_strip_score(gray, y, depth)
269
+ if c >= keep_thr:
270
+ last_y = y
271
+ else:
272
+ break
273
+ y_tick_zone = (last_y, min(H, best_y + depth + 5))
274
+
275
+ # If the frequency fallback located the ruler, trust its band (the ACF-based
276
+ # zone above is unreliable on the backlit images that triggered the fallback).
277
+ if _freq_band:
278
+ y_tick_zone = (max(0, _freq_band["band_y0"] - 5),
279
+ min(H, _freq_band["band_y1"] + 5))
280
+
281
+ # Auto-detect scale (cm vs inch) AND tick spacing from span/tick ratio.
282
+ # Default assumption: cm ruler with 1 mm minor ticks (user-stated convention).
283
+ #
284
+ # Buckets (closest match wins, must be within 25 %):
285
+ # ratio ≈ 10 -> cm ruler, 1 mm minor ticks (cm scale dominates)
286
+ # ratio ≈ 20 -> cm ruler, 0.5 mm minor ticks (fine cm scale)
287
+ # ratio ≈ 25.4 -> inch ruler, 1 mm cm-side ticks visible
288
+ # ratio ≈ 50.8 -> inch ruler, 0.5 mm cm-side ticks visible
289
+ tick_mm = 1.0
290
+ scale_unit = "cm"
291
+ ruler_kind = "cm-1mm (default)"
292
+ auto_decided = False
293
+ if force_tick_mm is not None:
294
+ tick_mm = force_tick_mm
295
+ ruler_kind = f"cm-{force_tick_mm}mm (user-forced)"
296
+ elif ruler_hint == "inch":
297
+ scale_unit = "inch"
298
+ tick_mm = 1.0
299
+ ruler_kind = "inch (user-specified)"
300
+ elif span and tick_period_px > 0:
301
+ ratio = span / tick_period_px
302
+ buckets = [
303
+ (10.0, 1.0, "cm", "cm-1mm"),
304
+ (20.0, 0.5, "cm", "cm-0.5mm"),
305
+ (25.4, 1.0, "inch", "inch-1mm"),
306
+ (50.8, 0.5, "inch", "inch-0.5mm"),
307
+ ]
308
+ best_bucket = min(buckets, key=lambda b: abs(b[0] - ratio) / b[0])
309
+ rel_err = abs(best_bucket[0] - ratio) / best_bucket[0]
310
+ # ONLY apply auto-detection if HIGHLY confident (within 10 %).
311
+ # For ambiguous cases keep the conservative cm-1mm default. Users with
312
+ # 0.5 mm rulers can pass --tick-mm 0.5 explicitly.
313
+ if rel_err < 0.10:
314
+ _, tick_mm, scale_unit, name = best_bucket
315
+ ruler_kind = f"{name} (auto: ratio={ratio:.1f}, n_digits={n_digits})"
316
+ auto_decided = True
317
+ else:
318
+ ruler_kind = (f"cm-1mm (default; ratio={ratio:.1f} ambiguous "
319
+ f"— closest match {best_bucket[3]} but {rel_err*100:.0f}% off)")
320
+ # Primary: px/mm from the detected minor-tick spacing.
321
+ px_per_mm = tick_period_px / tick_mm if (tick_period_px and np.isfinite(tick_period_px)
322
+ and tick_period_px > 0) else float("nan")
323
+ # Fallback: if the minor ticks weren't detected (common on BACKLIT photos
324
+ # where the fine lines wash out), calibrate from the DIGIT spacing instead —
325
+ # consecutive printed numbers are 1 cm apart (cm ruler) or 1 inch (inch ruler).
326
+ if not np.isfinite(px_per_mm) and span and n_digits and n_digits >= 2:
327
+ per_unit_px = span / (n_digits - 1) # px between consecutive digits
328
+ if scale_unit == "inch":
329
+ px_per_mm = per_unit_px / 25.4
330
+ else:
331
+ px_per_mm = per_unit_px / 10.0 # 1 cm = 10 mm
332
+ tick_period_px = px_per_mm * tick_mm # implied tick spacing
333
+ ruler_kind = (f"{scale_unit} digit-span fallback (minor ticks undetected; "
334
+ f"{n_digits} digits, span={span}px)")
335
+ px_per_inch = px_per_mm * 25.4
336
+ return Calibration(
337
+ px_per_mm=px_per_mm,
338
+ px_per_inch=px_per_inch,
339
+ ruler_pos=ruler_pos,
340
+ y_tick_zone=y_tick_zone,
341
+ tick_period_px=tick_period_px,
342
+ tick_mm=tick_mm,
343
+ digit_span_px=span if span else 0,
344
+ ruler_kind=ruler_kind,
345
+ scale_unit=scale_unit,
346
+ n_digits=n_digits if 'n_digits' in dir() else 0,
347
+ )
348
+
349
+
350
+ # =========================================================================== #
351
+ # Fabric ROI
352
+ # =========================================================================== #
353
+
354
+ def find_fabric_roi(gray: np.ndarray, calib: Calibration) -> tuple[int, int, int, int]:
355
+ H, W = gray.shape
356
+ detrended = gray - ndimage.uniform_filter1d(gray, size=31, axis=1)
357
+ row_tex_s = ndimage.uniform_filter1d(detrended.std(axis=1), size=15)
358
+ y_lo, y_hi = calib.y_tick_zone
359
+ margin = 30
360
+ if calib.ruler_pos == "top":
361
+ fab_top = y_hi + margin
362
+ for y in range(fab_top, H - 50):
363
+ block = gray[y:y + 50, :]
364
+ if (block < 0.25).sum(axis=1).max() < 8 and (row_tex_s[y:y + 50] > 0.05).all():
365
+ fab_top = y
366
+ break
367
+ fab_bot = H - 5
368
+ else:
369
+ fab_top = 5
370
+ fab_bot = y_lo - margin
371
+ for y in range(fab_bot, 50, -1):
372
+ block = gray[y - 50:y, :]
373
+ if (block < 0.25).sum(axis=1).max() < 8 and (row_tex_s[y - 50:y] > 0.05).all():
374
+ fab_bot = y
375
+ break
376
+ x0, x1 = max(2, int(W * 0.02)), min(W - 2, int(W * 0.98))
377
+ return fab_top, fab_bot, x0, x1
378
+
379
+
380
+ # =========================================================================== #
381
+ # FFT / counting
382
+ # =========================================================================== #
383
+
384
+ def _windowed_2d_fft(fab: np.ndarray) -> np.ndarray:
385
+ p = fab - fab.mean()
386
+ win_y = np.hanning(p.shape[0])[:, None]
387
+ win_x = np.hanning(p.shape[1])[None, :]
388
+ p = p * win_y * win_x
389
+ return np.abs(fftshift(fft2(p)))
390
+
391
+
392
+ def _axial_peaks(F: np.ndarray, axis: str, px_per_inch: float,
393
+ band: int = 3, min_tpi: float = 10.0, max_tpi: float = 300.0,
394
+ top_k: int = 20, amp_floor: float = 0.03
395
+ ) -> list[tuple[float, float]]:
396
+ Hf, Wf = F.shape
397
+ cy, cx = Hf // 2, Wf // 2
398
+ if axis == "epi":
399
+ spec = F[cy - band:cy + band + 1, :].sum(axis=0)
400
+ freqs = fftshift(fftfreq(Wf))
401
+ else:
402
+ spec = F[:, cx - band:cx + band + 1].sum(axis=1)
403
+ freqs = fftshift(fftfreq(Hf))
404
+ mask = (freqs > min_tpi / px_per_inch) & (freqs < max_tpi / px_per_inch)
405
+ if not mask.any():
406
+ return []
407
+ idx = np.where(mask)[0]
408
+ sub = spec[idx]
409
+ peaks, _ = signal.find_peaks(sub, height=amp_floor * sub.max())
410
+ if not peaks.size:
411
+ return []
412
+ max_amp = sub[peaks].max()
413
+ out = []
414
+ for k in peaks:
415
+ if 1 <= k < sub.size - 1:
416
+ a, b, c = sub[k - 1], sub[k], sub[k + 1]
417
+ denom = a - 2 * b + c
418
+ delta = 0.5 * (a - c) / denom if abs(denom) > 1e-12 else 0.0
419
+ k_i = k + float(np.clip(delta, -1.0, 1.0))
420
+ else:
421
+ k_i = float(k)
422
+ f_step = freqs[1] - freqs[0] if freqs.size > 1 else 0.0
423
+ f = freqs[idx[k]] + (k_i - k) * f_step
424
+ out.append((float(f * px_per_inch), float(sub[k] / max_amp)))
425
+ out.sort(key=lambda t: -t[1])
426
+ return out[:top_k]
427
+
428
+
429
+ def _peak_at(cands: list[tuple[float, float]], target: float,
430
+ tol_frac: float = 0.08) -> Optional[tuple[float, float]]:
431
+ best = None
432
+ best_err = float("inf")
433
+ for tpi, rel in cands:
434
+ err = abs(tpi - target) / max(target, 1e-9)
435
+ if err < tol_frac and err < best_err:
436
+ best, best_err = (tpi, rel), err
437
+ return best
438
+
439
+
440
+ def _harmonic_ascend(cands: list[tuple[float, float]],
441
+ max_n: int = 6, amp_floor: float = 0.20,
442
+ drop_factor: float = 0.35,
443
+ first_step_floor: Optional[float] = None
444
+ ) -> tuple[float, int]:
445
+ """Harmonic ascend with optional stricter threshold on the FIRST step
446
+ (×1 → ×2). For plain weave, set first_step_floor=0.80 to avoid spurious
447
+ ×2 ascent (image_21 has ×2 at 66 % but truth was ×1).
448
+ """
449
+ if not cands:
450
+ return float("nan"), 1
451
+ f0, a0 = cands[0]
452
+ best, best_n, prev_amp = f0, 1, a0
453
+ for n in range(2, max_n + 1):
454
+ target = n * f0
455
+ hit = _peak_at(cands, target, tol_frac=0.08)
456
+ if not hit:
457
+ break
458
+ amp = hit[1]
459
+ # Strict threshold on the first step
460
+ floor = first_step_floor if (n == 2 and first_step_floor is not None) else amp_floor
461
+ if amp < floor:
462
+ break
463
+ if amp < drop_factor * prev_amp:
464
+ break
465
+ best, best_n, prev_amp = hit[0], n, amp
466
+ return best, best_n
467
+
468
+
469
+ # =========================================================================== #
470
+ # Quality scoring + best-region selection
471
+ # =========================================================================== #
472
+
473
+ @dataclass
474
+ class AxisQuality:
475
+ spectral_sharpness: float # 0..1
476
+ patch_consistency: float # 0..1
477
+ resolution_score: float # 0..1
478
+ final_pct: float # 0..100
479
+
480
+
481
+ @dataclass
482
+ class QualityReport:
483
+ epi: AxisQuality
484
+ ppi: AxisQuality
485
+ calibration_conf: float # 0..1
486
+ overall_pct: float
487
+ label: str # GOLD / GOOD / FAIR / POOR
488
+ warnings: list
489
+
490
+
491
+ def _spectral_sharpness(cands: list[tuple[float, float]]) -> float:
492
+ """How dominant is the strongest peak? Returns 0..1.
493
+ = 1 - (median_of_remaining / strongest)
494
+ Strong dominant peak -> close to 1. Noisy spectrum -> close to 0.
495
+ """
496
+ if not cands or len(cands) < 2:
497
+ return 0.5
498
+ strongest_amp = cands[0][1] # always 1.0 by definition (rel)
499
+ others = [c[1] for c in cands[1:6]]
500
+ median_other = float(np.median(others))
501
+ # Map: median 0.0 -> sharpness 1.0; median 1.0 -> sharpness 0
502
+ return float(max(0.0, 1.0 - median_other))
503
+
504
+
505
+ def _patch_consistency(values: list[float]) -> float:
506
+ """Coefficient of variation -> 0..1 (1 = consistent)."""
507
+ if len(values) < 2:
508
+ return 0.5
509
+ arr = np.array(values)
510
+ mean = float(np.mean(arr))
511
+ if mean <= 0:
512
+ return 0.0
513
+ cov = float(np.std(arr) / mean)
514
+ # cov 0% -> 1.0; cov 10% -> 0.0
515
+ return float(max(0.0, 1.0 - cov * 10.0))
516
+
517
+
518
+ def _resolution_score(px_per_thread: float) -> float:
519
+ """Resolution score: 1.0 if ≥ 10 px/thread, 0 if < 4 px/thread, linear between."""
520
+ if px_per_thread >= 10:
521
+ return 1.0
522
+ if px_per_thread <= 4:
523
+ return 0.0
524
+ return float((px_per_thread - 4) / 6.0)
525
+
526
+
527
+ def sliding_patch_count(fab: np.ndarray, px_per_inch: float,
528
+ weave: str, patch_inch: float = 0.5,
529
+ stride_inch: float = 0.2,
530
+ consensus_value: tuple[float, float] | None = None,
531
+ consensus_tol: float = 0.10) -> dict:
532
+ """Run the per-weave counter on sliding patches; return:
533
+ - epi_list, ppi_list : per-patch outputs
534
+ - best_epi, best_ppi : best-quality patch (highest spectral sharpness)
535
+ - n_patches : count
536
+
537
+ If `consensus_value=(epi, ppi)` is supplied, we ONLY include patches whose
538
+ own (epi, ppi) is within `consensus_tol` of the consensus. This avoids
539
+ counting outlier patches whose harmonic-ascend stopped at a different ×N
540
+ than the main pipeline.
541
+ """
542
+ H, W = fab.shape
543
+ patch_px = int(patch_inch * px_per_inch)
544
+ stride = max(1, int(stride_inch * px_per_inch))
545
+ epi_list, ppi_list = [], []
546
+ best_quality = -1.0
547
+ best_epi, best_ppi = float("nan"), float("nan")
548
+ if patch_px > min(H, W):
549
+ return {"epi_list": [], "ppi_list": [], "best_epi": float("nan"),
550
+ "best_ppi": float("nan"), "best_quality": 0.0,
551
+ "n_patches": 0}
552
+ for y in range(0, H - patch_px + 1, stride):
553
+ for x in range(0, W - patch_px + 1, stride):
554
+ patch = fab[y:y + patch_px, x:x + patch_px]
555
+ try:
556
+ if weave == "plain":
557
+ e, p, info = count_plain(patch, px_per_inch)
558
+ elif weave == "twill":
559
+ e, p, info = count_twill(patch, px_per_inch)
560
+ elif weave == "basket":
561
+ e, p, info = count_basket(patch, px_per_inch)
562
+ elif weave == "rib":
563
+ e, p, info = count_rib(patch, px_per_inch)
564
+ else:
565
+ continue
566
+ except Exception:
567
+ continue
568
+ if not np.isfinite(e) or not np.isfinite(p):
569
+ continue
570
+ if consensus_value is not None:
571
+ c_e, c_p = consensus_value
572
+ if abs(e - c_e) / max(c_e, 1e-9) > consensus_tol:
573
+ continue
574
+ if abs(p - c_p) / max(c_p, 1e-9) > consensus_tol:
575
+ continue
576
+ epi_list.append(e); ppi_list.append(p)
577
+ # Quality = spectral sharpness of strongest peak per axis (averaged)
578
+ s_e = _spectral_sharpness(info.get("epi_cands", []))
579
+ s_p = _spectral_sharpness(info.get("ppi_cands", []))
580
+ q = 0.5 * (s_e + s_p)
581
+ if q > best_quality:
582
+ best_quality = q
583
+ best_epi, best_ppi = e, p
584
+ return {
585
+ "epi_list": epi_list,
586
+ "ppi_list": ppi_list,
587
+ "best_epi": best_epi,
588
+ "best_ppi": best_ppi,
589
+ "best_quality": best_quality if best_quality >= 0 else 0.0,
590
+ "n_patches": len(epi_list),
591
+ }
592
+
593
+
594
+ def compute_quality(epi_cands: list, ppi_cands: list,
595
+ epi_tpi: float, ppi_tpi: float,
596
+ px_per_inch: float, calib_conf: float,
597
+ patch_epi: list, patch_ppi: list) -> QualityReport:
598
+ """Compute axis-level + overall quality scores."""
599
+ # Spectral sharpness
600
+ sh_e = _spectral_sharpness(epi_cands)
601
+ sh_p = _spectral_sharpness(ppi_cands)
602
+ # Patch consistency (coefficient of variation across patches)
603
+ pc_e = _patch_consistency(patch_epi)
604
+ pc_p = _patch_consistency(patch_ppi)
605
+ # Resolution: px per thread
606
+ ppth_e = px_per_inch / max(epi_tpi, 1e-9)
607
+ ppth_p = px_per_inch / max(ppi_tpi, 1e-9)
608
+ rs_e = _resolution_score(ppth_e)
609
+ rs_p = _resolution_score(ppth_p)
610
+ # Final per-axis score (weighted)
611
+ def axis_final(sh, pc, rs):
612
+ # weights: spectral 40, consistency 30, resolution 20, calib 10
613
+ return float(100.0 * (0.40 * sh + 0.30 * pc + 0.20 * rs + 0.10 * calib_conf))
614
+
615
+ aq_e = AxisQuality(sh_e, pc_e, rs_e, axis_final(sh_e, pc_e, rs_e))
616
+ aq_p = AxisQuality(sh_p, pc_p, rs_p, axis_final(sh_p, pc_p, rs_p))
617
+ overall = 0.5 * (aq_e.final_pct + aq_p.final_pct)
618
+ if overall >= 85: label = "Best"
619
+ elif overall >= 70: label = "GOOD"
620
+ elif overall >= 50: label = "FAIR"
621
+ else: label = "POOR"
622
+
623
+ # Warnings
624
+ warnings = []
625
+ if ppth_e < 8:
626
+ warnings.append(f"Low resolution along warp axis ({ppth_e:.1f} px/thread). "
627
+ "Use higher-resolution photo or macro mode.")
628
+ if ppth_p < 8:
629
+ warnings.append(f"Low resolution along weft axis ({ppth_p:.1f} px/thread).")
630
+ if calib_conf < 0.5:
631
+ warnings.append(f"Calibration confidence low ({calib_conf:.0%}). "
632
+ "Ruler tick detection may be unreliable.")
633
+ if aq_e.patch_consistency < 0.5:
634
+ warnings.append(f"EPI count varies across patches (consistency {aq_e.patch_consistency:.0%}). "
635
+ "Fabric may not be flat or photo angled.")
636
+ if aq_p.patch_consistency < 0.5:
637
+ warnings.append(f"PPI count varies across patches.")
638
+ if sh_e < 0.4 or sh_p < 0.4:
639
+ warnings.append("Spectral peaks are diffuse. Check focus and lighting.")
640
+ return QualityReport(aq_e, aq_p, calib_conf, overall, label, warnings)
641
+
642
+
643
+ def count_plain(fab: np.ndarray, px_per_inch: float) -> tuple[float, float, dict]:
644
+ """For plain weave: usually FFT strongest = thread freq. But sometimes the
645
+ strongest peak is at 1/2 or 1/3 of the true thread freq (image_22 had
646
+ strongest at 43 = truth/3). Use harmonic ascend to climb to the highest
647
+ detectable harmonic. For regular plain weaves with no harmonic series,
648
+ ascend returns ×1 (strongest IS thread freq).
649
+ """
650
+ F = _windowed_2d_fft(fab)
651
+ epi_c = _axial_peaks(F, "epi", px_per_inch, top_k=30, amp_floor=0.01)
652
+ ppi_c = _axial_peaks(F, "ppi", px_per_inch, top_k=30, amp_floor=0.01)
653
+ # For PLAIN weave: require 2x harmonic to be ≥ 80 % of strongest before
654
+ # ascending. This catches genuine sub-harmonic captures (image_22:
655
+ # 43→86 at 94 % → ascend → 130 at 53 %) without spurious ascents
656
+ # (image_21 PPI: 60→119 at only 66 %, stay at 60).
657
+ epi, epi_n = _harmonic_ascend(epi_c, max_n=4, amp_floor=0.30,
658
+ drop_factor=0.35, first_step_floor=0.80)
659
+ ppi, ppi_n = _harmonic_ascend(ppi_c, max_n=4, amp_floor=0.30,
660
+ drop_factor=0.35, first_step_floor=0.80)
661
+ return epi, ppi, {"epi_cands": epi_c, "ppi_cands": ppi_c,
662
+ "method": f"plain (harmonic ascend ×{epi_n}/×{ppi_n})"}
663
+
664
+
665
+ def count_twill(fab: np.ndarray, px_per_inch: float,
666
+ forced_repeat: Optional[int] = None,
667
+ ppi_ascend: bool = False) -> tuple[float, float, dict]:
668
+ F = _windowed_2d_fft(fab)
669
+ epi_c = _axial_peaks(F, "epi", px_per_inch, top_k=30, amp_floor=0.01)
670
+ ppi_c = _axial_peaks(F, "ppi", px_per_inch, top_k=30, amp_floor=0.01)
671
+
672
+ if forced_repeat is not None and epi_c:
673
+ epi = epi_c[0][0] * forced_repeat
674
+ epi_n = forced_repeat
675
+ else:
676
+ # Always try harmonic ascend. If no real harmonic series exists
677
+ # (high-resolution image where individual threads are resolved),
678
+ # ascend correctly stops at ×1 (image_23). For low-resolution twills
679
+ # it ascends to ×3 or ×4 (image_6, 7, 11).
680
+ epi, epi_n = _harmonic_ascend(epi_c)
681
+
682
+ if ppi_ascend and ppi_c:
683
+ ppi, ppi_n = _harmonic_ascend(ppi_c)
684
+ elif forced_repeat is not None and ppi_c:
685
+ # Also try forced repeat on PPI (3/1 twill etc.)
686
+ ppi = ppi_c[0][0] * forced_repeat
687
+ ppi_n = forced_repeat
688
+ else:
689
+ ppi = ppi_c[0][0] if ppi_c else float("nan")
690
+ ppi_n = 1
691
+ return epi, ppi, {"epi_cands": epi_c, "ppi_cands": ppi_c,
692
+ "method": f"twill (EPI ×{epi_n}, PPI ×{ppi_n})"}
693
+
694
+
695
+ def count_basket(fab: np.ndarray, px_per_inch: float,
696
+ epi_repeat: int = 2, ppi_repeat: int = 2
697
+ ) -> tuple[float, float, dict]:
698
+ F = _windowed_2d_fft(fab)
699
+ epi_c = _axial_peaks(F, "epi", px_per_inch)
700
+ ppi_c = _axial_peaks(F, "ppi", px_per_inch)
701
+
702
+ def visible(cands):
703
+ if not cands:
704
+ return float("nan")
705
+ f0 = cands[0][0]
706
+ hit = _peak_at(cands, 2 * f0, tol_frac=0.08)
707
+ if hit and hit[1] >= 0.75:
708
+ return hit[0]
709
+ return f0
710
+
711
+ epi_v = visible(epi_c)
712
+ ppi_v = visible(ppi_c)
713
+ epi = epi_v * epi_repeat
714
+ ppi = ppi_v * ppi_repeat
715
+ return epi, ppi, {"epi_cands": epi_c, "ppi_cands": ppi_c,
716
+ "method": f"basket (epi_v={epi_v:.1f}×{epi_repeat}, "
717
+ f"ppi_v={ppi_v:.1f}×{ppi_repeat})"}
718
+
719
+
720
+ def count_rib(fab: np.ndarray, px_per_inch: float,
721
+ epi_repeat: int = 1, ppi_repeat: int = 2
722
+ ) -> tuple[float, float, dict]:
723
+ F = _windowed_2d_fft(fab)
724
+ epi_c = _axial_peaks(F, "epi", px_per_inch, top_k=30, amp_floor=0.01)
725
+ ppi_c = _axial_peaks(F, "ppi", px_per_inch, top_k=30, amp_floor=0.01)
726
+ if epi_repeat > 1:
727
+ epi, _ = _harmonic_ascend(epi_c)
728
+ else:
729
+ epi = epi_c[0][0] if epi_c else float("nan")
730
+ if ppi_repeat > 1:
731
+ ppi = ppi_c[0][0] * ppi_repeat if ppi_c else float("nan")
732
+ else:
733
+ ppi = ppi_c[0][0] if ppi_c else float("nan")
734
+ return epi, ppi, {"epi_cands": epi_c, "ppi_cands": ppi_c,
735
+ "method": f"rib (epi ×{epi_repeat}, ppi ×{ppi_repeat})"}
736
+
737
+
738
+ def _highest_cluster(values: list, min_support: float = 0.30,
739
+ tol_frac: float = 0.05) -> tuple[float, str]:
740
+ # Highest-tpi cluster with >= min_support fraction; falls back to median.
741
+ # Why: satin's float pattern produces a tri-modal per-patch distribution
742
+ # (thread freq + ×N sub-harmonics). Median picks the wrong rung; the
743
+ # highest-rung cluster that still has enough patch support is the thread
744
+ # fundamental.
745
+ if not values:
746
+ return float("nan"), "no patches"
747
+ arr = np.array(values, dtype=float)
748
+ n = len(arr)
749
+ min_count = max(2, int(np.ceil(min_support * n)))
750
+ for center in np.sort(arr)[::-1]:
751
+ mask = np.abs(arr - center) <= tol_frac * max(center, 1e-9)
752
+ if mask.sum() >= min_count:
753
+ return float(np.mean(arr[mask])), f"cluster {mask.sum()}/{n} @ ~{center:.0f}"
754
+ return float(np.median(arr)), f"median fallback (no cluster ≥{min_support:.0%})"
755
+
756
+
757
+ def count_satin(fab: np.ndarray, px_per_inch: float,
758
+ patch_inch: float = 0.5, stride_inch: float = 0.2,
759
+ min_support: float = 0.30, cluster_tol_frac: float = 0.05
760
+ ) -> tuple[float, float, dict]:
761
+ # Satin: full-fabric FFT is dominated by float-repeat (thread_freq / N for
762
+ # N-end satin). Per-patch FFT (using plain-style harmonic ascend) bias
763
+ # toward the thread fundamental because the slow float pattern doesn't fit
764
+ # in a small window. Aggregate patches via highest-tpi cluster with
765
+ # >= min_support; this picks the thread rung even when half the patches
766
+ # locked onto sub-harmonics.
767
+ F = _windowed_2d_fft(fab)
768
+ epi_c = _axial_peaks(F, "epi", px_per_inch, top_k=30, amp_floor=0.01)
769
+ ppi_c = _axial_peaks(F, "ppi", px_per_inch, top_k=30, amp_floor=0.01)
770
+
771
+ H, W = fab.shape
772
+ patch_px = int(patch_inch * px_per_inch)
773
+ stride = max(1, int(stride_inch * px_per_inch))
774
+ epi_list, ppi_list = [], []
775
+ if patch_px <= min(H, W):
776
+ for y in range(0, H - patch_px + 1, stride):
777
+ for x in range(0, W - patch_px + 1, stride):
778
+ patch = fab[y:y + patch_px, x:x + patch_px]
779
+ try:
780
+ e, p, _ = count_plain(patch, px_per_inch)
781
+ except Exception:
782
+ continue
783
+ if np.isfinite(e) and np.isfinite(p):
784
+ epi_list.append(e); ppi_list.append(p)
785
+
786
+ epi, epi_desc = _highest_cluster(epi_list, min_support, cluster_tol_frac)
787
+ ppi, ppi_desc = _highest_cluster(ppi_list, min_support, cluster_tol_frac)
788
+
789
+ # Fallback: if patch grid empty/insufficient, use full-fabric strongest peak
790
+ if not np.isfinite(epi) and epi_c:
791
+ epi = epi_c[0][0]; epi_desc = "full-fabric strongest (no patches)"
792
+ if not np.isfinite(ppi) and ppi_c:
793
+ ppi = ppi_c[0][0]; ppi_desc = "full-fabric strongest (no patches)"
794
+
795
+ return epi, ppi, {
796
+ "epi_cands": epi_c, "ppi_cands": ppi_c,
797
+ "epi_patch_list": epi_list, "ppi_patch_list": ppi_list,
798
+ "method": f"satin (EPI: {epi_desc}; PPI: {ppi_desc}; n_patches={len(epi_list)})",
799
+ }
800
+
801
+
802
+ def count_unified(fab: np.ndarray, px_per_inch: float,
803
+ epi_mult: int = 1, ppi_mult: int = 1,
804
+ patch_inch: float = 0.5, stride_inch: float = 0.2,
805
+ min_support: float = 0.30, cluster_tol_frac: float = 0.05
806
+ ) -> tuple[float, float, dict]:
807
+ """v4.2 single detector for ALL weaves.
808
+
809
+ Method (per axis):
810
+ 1. Slide a 0.5-inch window across the de-flat-fielded fabric.
811
+ 2. In each patch, take the dominant thread frequency (plain-style FFT
812
+ peak — no harmonic ascend, so each patch reports the strongest local
813
+ periodicity).
814
+ 3. Consensus = the HIGHEST tight cluster of patch values carrying at least
815
+ `min_support` of all patches (via _highest_cluster). This rejects the
816
+ lower float-comb sub-harmonics (which only some patches lock onto) and
817
+ keeps the thread fundamental that most patches agree on.
818
+ 4. Optional expert multiplier (epi_mult / ppi_mult): for dense weaves where
819
+ the visible periodicity is a known integer fraction of the thread count,
820
+ the textile expert can supply the factor. Default 1 = no change.
821
+
822
+ Returns (epi, ppi, info). info carries the per-patch lists + a support
823
+ fraction per axis so the caller can gauge confidence.
824
+ """
825
+ F = _windowed_2d_fft(fab)
826
+ epi_c = _axial_peaks(F, "epi", px_per_inch, top_k=30, amp_floor=0.01)
827
+ ppi_c = _axial_peaks(F, "ppi", px_per_inch, top_k=30, amp_floor=0.01)
828
+
829
+ H, W = fab.shape
830
+ patch_px = int(patch_inch * px_per_inch)
831
+ stride = max(1, int(stride_inch * px_per_inch))
832
+ epi_list, ppi_list = [], []
833
+ if patch_px <= min(H, W):
834
+ for y in range(0, H - patch_px + 1, stride):
835
+ for x in range(0, W - patch_px + 1, stride):
836
+ patch = fab[y:y + patch_px, x:x + patch_px]
837
+ try:
838
+ e, p, _ = count_plain(patch, px_per_inch)
839
+ except Exception:
840
+ continue
841
+ if np.isfinite(e) and np.isfinite(p):
842
+ epi_list.append(e); ppi_list.append(p)
843
+
844
+ epi, epi_desc = _highest_cluster(epi_list, min_support, cluster_tol_frac)
845
+ ppi, ppi_desc = _highest_cluster(ppi_list, min_support, cluster_tol_frac)
846
+
847
+ # Fallback to full-fabric strongest peak if patch grid was too small.
848
+ if not np.isfinite(epi) and epi_c:
849
+ epi = epi_c[0][0]; epi_desc = "full-fabric strongest (no patches)"
850
+ if not np.isfinite(ppi) and ppi_c:
851
+ ppi = ppi_c[0][0]; ppi_desc = "full-fabric strongest (no patches)"
852
+
853
+ # Cluster support fraction (confidence signal).
854
+ def _support(vals, centre):
855
+ if not vals or not np.isfinite(centre):
856
+ return 0.0
857
+ arr = np.asarray(vals, float)
858
+ return float(np.mean(np.abs(arr - centre) <= cluster_tol_frac * max(centre, 1e-9)))
859
+ epi_sup = _support(epi_list, epi)
860
+ ppi_sup = _support(ppi_list, ppi)
861
+
862
+ epi *= epi_mult
863
+ ppi *= ppi_mult
864
+ mtag = ""
865
+ if epi_mult != 1 or ppi_mult != 1:
866
+ mtag = f" [expert mult EPI×{epi_mult} PPI×{ppi_mult}]"
867
+
868
+ return epi, ppi, {
869
+ "epi_cands": epi_c, "ppi_cands": ppi_c,
870
+ "epi_patch_list": epi_list, "ppi_patch_list": ppi_list,
871
+ "epi_support": epi_sup, "ppi_support": ppi_sup,
872
+ "method": (f"unified patch-cluster (EPI: {epi_desc} sup={epi_sup:.0%}; "
873
+ f"PPI: {ppi_desc} sup={ppi_sup:.0%}; n_patches={len(epi_list)}){mtag}"),
874
+ }
875
+
876
+
877
+ # --------------------------------------------------------------------------- #
878
+ # Per-weave handlers (v4.2)
879
+ #
880
+ # Each is a thin wrapper around count_unified with weave-specific parameters.
881
+ # The shared engine (patch-cluster consensus) is what generalises across
882
+ # images; the per-weave parameters tune patch geometry / cluster support to the
883
+ # characteristics of that weave. Selecting --weave picks the variant.
884
+ # --------------------------------------------------------------------------- #
885
+
886
+ def _tag_method(info: dict, weave: str) -> dict:
887
+ info = dict(info)
888
+ info["method"] = f"{weave}: " + info.get("method", "")
889
+ return info
890
+
891
+
892
+ def count_plain_v2(fab, px_per_inch):
893
+ # Plain: threads individually resolved; thread peak is the dominant patch
894
+ # periodicity. Standard 0.5-inch patches, 30% cluster support.
895
+ e, p, info = count_unified(fab, px_per_inch, patch_inch=0.5,
896
+ stride_inch=0.2, min_support=0.30)
897
+ return e, p, _tag_method(info, "plain")
898
+
899
+
900
+ def count_twill_v2(fab, px_per_inch):
901
+ # Twill: diagonal floats add a sub-harmonic comb, but most patches still
902
+ # lock onto the thread fundamental. Same geometry as plain.
903
+ e, p, info = count_unified(fab, px_per_inch, patch_inch=0.5,
904
+ stride_inch=0.2, min_support=0.30)
905
+ return e, p, _tag_method(info, "twill")
906
+
907
+
908
+ def count_satin_v2(fab, px_per_inch):
909
+ # Satin: long floats dominate the full-fabric FFT, but per-patch the thread
910
+ # fundamental wins. Patch-cluster (this is the v4.1 satin method).
911
+ e, p, info = count_unified(fab, px_per_inch, patch_inch=0.5,
912
+ stride_inch=0.2, min_support=0.30)
913
+ return e, p, _tag_method(info, "satin")
914
+
915
+
916
+ def count_rib_v2(fab, px_per_inch):
917
+ # Rib / ripstop: patch-cluster reads the true thread spacing directly
918
+ # (the old fixed ×2 pairing over-counted). No multiplier.
919
+ e, p, info = count_unified(fab, px_per_inch, patch_inch=0.5,
920
+ stride_inch=0.2, min_support=0.30)
921
+ return e, p, _tag_method(info, "rib")
922
+
923
+
924
+ def count_basket_v2(fab, px_per_inch):
925
+ # Basket: groups of threads act as units; patch-cluster finds the dominant
926
+ # repeat. Kept on the shared engine for consistency.
927
+ e, p, info = count_unified(fab, px_per_inch, patch_inch=0.5,
928
+ stride_inch=0.2, min_support=0.30)
929
+ return e, p, _tag_method(info, "basket")
930
+
931
+
932
+ def count_dobby_v2(fab, px_per_inch, epi_mult: int = 1, ppi_mult: int = 1):
933
+ """Dedicated DOBBY handler.
934
+
935
+ Dobby fabrics carry a small woven figure on a plain/twill ground. That
936
+ figure injects strong low-frequency structure, so on dense dobbies many
937
+ patches lock onto a *sub-multiple* of the true thread spacing (T/2, T/3 …).
938
+ The patch-cluster consensus still gives the dominant *visible* periodicity;
939
+ when the textile expert knows the figure repeats every N ground threads they
940
+ can supply --epi-mult/--ppi-mult N to recover the true count. A slightly
941
+ looser cluster support (0.25) suits the more variable dobby spectra.
942
+
943
+ Without a multiplier this returns the dominant visible periodicity and the
944
+ quality report flags low confidence when patch support is thin or
945
+ resolution per (visible) thread is marginal.
946
+ """
947
+ e, p, info = count_unified(fab, px_per_inch, patch_inch=0.5,
948
+ stride_inch=0.2, min_support=0.25,
949
+ epi_mult=epi_mult, ppi_mult=ppi_mult)
950
+ return e, p, _tag_method(info, "dobby")
951
+
952
+
953
+ _V2_HANDLERS = {"plain": count_plain_v2, "twill": count_twill_v2, "satin": count_satin_v2,
954
+ "dobby": count_dobby_v2, "rib": count_rib_v2, "basket": count_basket_v2}
955
+ ROBUST_N = 3 # ROI-jitter grid is N x N (set 0 to disable)
956
+ ROBUST_MAX_INSET = 0.10
957
+
958
+
959
+ def _robust_count(fab, px_per_inch, weave):
960
+ """Harmonic-stability: re-run the per-weave counter over an N×N grid of
961
+ slightly-inset interior crops and take the per-axis MEDIAN. A single crop can
962
+ be a coin-flip between the true thread freq and a float sub-harmonic (a 1px
963
+ shift flips it); the median over jittered crops locks onto the value the
964
+ majority of crops recover. No-op where the single count is already stable.
965
+ Returns (epi, ppi); NaN if no crop produced a finite value.
966
+ """
967
+ fn = _V2_HANDLERS.get(weave, count_plain_v2)
968
+ H, W = fab.shape
969
+ es, ps = [], []
970
+ for fy in np.linspace(0.0, ROBUST_MAX_INSET, ROBUST_N):
971
+ for fx in np.linspace(0.0, ROBUST_MAX_INSET, ROBUST_N):
972
+ iy, ix = int(fy * H), int(fx * W)
973
+ sub = fab[iy:(H - iy if iy > 0 else H), ix:(W - ix if ix > 0 else W)]
974
+ if sub.shape[0] < 100 or sub.shape[1] < 100:
975
+ continue
976
+ try:
977
+ e, p, _ = fn(sub, px_per_inch)
978
+ except Exception:
979
+ continue
980
+ if np.isfinite(e): es.append(e)
981
+ if np.isfinite(p): ps.append(p)
982
+ return (float(np.median(es)) if es else float("nan"),
983
+ float(np.median(ps)) if ps else float("nan"))
984
+
985
+
986
+ # =========================================================================== #
987
+ # Main pipeline
988
+ # =========================================================================== #
989
+
990
+ @dataclass
991
+ class Result:
992
+ image: str
993
+ weave: str
994
+ calib: Calibration
995
+ epi: float
996
+ ppi: float
997
+ epi_round: int
998
+ ppi_round: int
999
+ method: str
1000
+ epi_candidates: list
1001
+ ppi_candidates: list
1002
+ quality: Optional[QualityReport] = None
1003
+ best_patch_epi: float = float("nan")
1004
+ best_patch_ppi: float = float("nan")
1005
+ n_patches: int = 0
1006
+ # v5 production confidence layer (per axis): reason code + 0..1 confidence.
1007
+ epi_reason: str = "ok"
1008
+ ppi_reason: str = "ok"
1009
+ epi_confidence: float = 1.0
1010
+ ppi_confidence: float = 1.0
1011
+ advice: str = ""
1012
+
1013
+
1014
+ def _axis_confidence(support, px_per_thread, cluster_tpi, fullfft_tpi,
1015
+ weave="plain", axis="epi"):
1016
+ """v5: honest per-axis reason code + confidence (0..1).
1017
+
1018
+ Key truth established empirically: when the detector locks onto a dense
1019
+ mixed-yarn / dobby MOTIF sub-multiple, ALL internal signals look confident
1020
+ (high support, methods agree, ample px/thread) because it is cleanly
1021
+ measuring the WRONG periodicity. So a sub-multiple lock is NOT detectable
1022
+ from internal signals alone. v5 therefore does not pretend: for the warp
1023
+ (EPI) axis of FLOAT weaves (satin/dobby) — the only regime where this lock
1024
+ occurs — it caps confidence and flags 'float_warp_unverifiable', advising a
1025
+ catalog cross-check (via recognition) or a backlight re-shoot. PPI and
1026
+ plain/twill are scored normally from support/resolution/agreement.
1027
+
1028
+ Returns (reason, confidence 0..1).
1029
+ """
1030
+ if not np.isfinite(cluster_tpi) or cluster_tpi <= 0:
1031
+ return "no_signal", 0.0
1032
+ # Float / figured weaves are prone to motif sub-multiple locks that look
1033
+ # internally confident, so they cannot be self-certified from a flat photo:
1034
+ # - satin: warp (EPI) is swamped; weft (PPI) is reliable.
1035
+ # - dobby: the figure can swamp BOTH axes on dense goods -> flag both.
1036
+ unverifiable = (weave == "satin" and axis == "epi") or (weave == "dobby")
1037
+ if unverifiable:
1038
+ return "float_unverifiable", round(float(np.clip(
1039
+ 0.45 * np.clip(px_per_thread / 10.0, 0.4, 1.0), 0, 0.5)), 2)
1040
+ disagree = (np.isfinite(fullfft_tpi) and
1041
+ abs(cluster_tpi - fullfft_tpi) / max(cluster_tpi, 1e-9) > 0.15)
1042
+ conf = 1.0
1043
+ reason = "ok"
1044
+ if px_per_thread < 6:
1045
+ reason = "low_resolution"; conf *= 0.5
1046
+ if support < 0.40 or disagree:
1047
+ reason = "motif_confusion" if reason == "ok" else reason
1048
+ conf *= 0.45
1049
+ conf *= float(np.clip(support / 0.6, 0.3, 1.0))
1050
+ conf *= float(np.clip(px_per_thread / 10.0, 0.4, 1.0))
1051
+ return reason, round(float(np.clip(conf, 0, 1)), 2)
1052
+
1053
+
1054
+ def process(path: str, weave: str,
1055
+ twill_repeat: Optional[int] = None,
1056
+ epi_repeat: int = 2, ppi_repeat: int = 2,
1057
+ ppi_ascend_flag: bool = False,
1058
+ ruler_hint: Optional[str] = None,
1059
+ force_tick_mm: Optional[float] = None,
1060
+ epi_mult: int = 1, ppi_mult: int = 1) -> Result:
1061
+ img = Image.open(path).convert("L")
1062
+ gray = np.asarray(img, dtype=np.float32) / 255.0
1063
+ calib = detect_calibration(gray, ruler_hint=ruler_hint,
1064
+ force_tick_mm=force_tick_mm)
1065
+ y0, y1, x0, x1 = find_fabric_roi(gray, calib)
1066
+ # Guard: ROI detection can fail on unusual captures (e.g. BACKLIT photos,
1067
+ # where gaps are bright and the ruler contrast inverts) and return an empty
1068
+ # or degenerate region -> empty `fab` -> np.percentile() IndexError -> 500.
1069
+ # Fall back to a centred crop of the full frame so analysis still runs.
1070
+ H, W = gray.shape
1071
+ if (y1 - y0) < 50 or (x1 - x0) < 50:
1072
+ # Center crop that avoids the top/bottom edge bands where a ruler usually
1073
+ # sits — so the FFT counts fabric, not ruler ticks. (Used when ROI/ruler
1074
+ # detection fails, e.g. on backlit photos.)
1075
+ y0, y1, x0, x1 = int(H * 0.15), int(H * 0.82), int(W * 0.10), int(W * 0.90)
1076
+ fab_raw = gray[y0:y1, x0:x1]
1077
+ if fab_raw.size == 0:
1078
+ fab_raw = gray
1079
+ blur = ndimage.gaussian_filter(fab_raw, sigma=15)
1080
+ fab = fab_raw / np.clip(blur, 1e-3, None)
1081
+ p1, p99 = np.percentile(fab, [1, 99])
1082
+ fab = np.clip((fab - p1) / max(p99 - p1, 1e-9), 0, 1)
1083
+
1084
+ # v4.2: per-weave handlers, each a thin wrapper over the shared patch-cluster
1085
+ # engine with weave-specific parameters. Selecting the weave picks the
1086
+ # variant; within a variant the method generalises across images.
1087
+ if weave == "plain":
1088
+ epi, ppi, info = count_plain_v2(fab, calib.px_per_inch)
1089
+ elif weave == "twill":
1090
+ epi, ppi, info = count_twill_v2(fab, calib.px_per_inch)
1091
+ elif weave == "satin":
1092
+ epi, ppi, info = count_satin_v2(fab, calib.px_per_inch)
1093
+ elif weave == "rib":
1094
+ epi, ppi, info = count_rib_v2(fab, calib.px_per_inch)
1095
+ elif weave == "basket":
1096
+ epi, ppi, info = count_basket_v2(fab, calib.px_per_inch)
1097
+ elif weave == "dobby":
1098
+ epi, ppi, info = count_dobby_v2(fab, calib.px_per_inch,
1099
+ epi_mult=epi_mult, ppi_mult=ppi_mult)
1100
+ else:
1101
+ raise ValueError(f"unknown weave: {weave}")
1102
+
1103
+ # Harmonic-stability (conditional, to stay fast on the common case):
1104
+ # 1. cheap probe — recount on ONE inset crop.
1105
+ # 2. only if it DISAGREES with the primary (>15% on an axis = a sub-harmonic
1106
+ # coin-flip) do we run the full ROI-jitter ensemble and take the median.
1107
+ # Stable images pay just one extra count; unstable ones (e.g. backlit twill
1108
+ # warp) get the median that locks onto the true fundamental.
1109
+ if ROBUST_N and ROBUST_N > 1 and epi_mult == 1 and ppi_mult == 1:
1110
+ try:
1111
+ fn = _V2_HANDLERS.get(weave, count_plain_v2)
1112
+ Hf, Wf = fab.shape; iy, ix = int(0.08 * Hf), int(0.08 * Wf)
1113
+ pe, pp, _ = fn(fab[iy:Hf - iy, ix:Wf - ix], calib.px_per_inch)
1114
+ unstable = ((np.isfinite(pe) and np.isfinite(epi) and abs(pe - epi) > 0.15 * max(epi, 1e-9)) or
1115
+ (np.isfinite(pp) and np.isfinite(ppi) and abs(pp - ppi) > 0.15 * max(ppi, 1e-9)))
1116
+ if unstable:
1117
+ r_epi, r_ppi = _robust_count(fab, calib.px_per_inch, weave)
1118
+ if np.isfinite(r_epi): epi = r_epi
1119
+ if np.isfinite(r_ppi): ppi = r_ppi
1120
+ except Exception:
1121
+ pass
1122
+
1123
+ # Patch lists for the quality report come straight from the detector.
1124
+ patches = {"epi_list": info.get("epi_patch_list", []),
1125
+ "ppi_list": info.get("ppi_patch_list", []),
1126
+ "best_epi": float("nan"), "best_ppi": float("nan"),
1127
+ "n_patches": len(info.get("epi_patch_list", []))}
1128
+ patches_for_result = patches
1129
+
1130
+ # Quality report
1131
+ quality = compute_quality(
1132
+ epi_cands=info.get("epi_cands", []),
1133
+ ppi_cands=info.get("ppi_cands", []),
1134
+ epi_tpi=epi, ppi_tpi=ppi,
1135
+ px_per_inch=calib.px_per_inch,
1136
+ calib_conf=min(1.0, calib.confidence) if hasattr(calib, "confidence") else 0.8,
1137
+ patch_epi=patches["epi_list"],
1138
+ patch_ppi=patches["ppi_list"],
1139
+ )
1140
+
1141
+ # v4.2 honesty flags: low cluster support means most patches disagreed with
1142
+ # the reported value — a hallmark of warp-float swamping or mixed-thickness
1143
+ # yarns where the dominant visible periodicity is a sub-multiple of the true
1144
+ # thread count. Surface it rather than reporting a confident wrong number.
1145
+ if quality is not None:
1146
+ e_sup = info.get("epi_support", 1.0)
1147
+ p_sup = info.get("ppi_support", 1.0)
1148
+ if e_sup < 0.5:
1149
+ quality.warnings.append(
1150
+ f"EPI cluster support only {e_sup:.0%} of patches — the warp "
1151
+ f"periodicity is ambiguous (likely float-swamped or mixed-thickness "
1152
+ f"yarns). Count may be a sub-multiple of the true EPI; verify or "
1153
+ f"supply --epi-mult / use a higher-resolution macro photo.")
1154
+ if p_sup < 0.5:
1155
+ quality.warnings.append(
1156
+ f"PPI cluster support only {p_sup:.0%} of patches — weft periodicity "
1157
+ f"ambiguous; count may be a sub-multiple. Verify or supply --ppi-mult.")
1158
+
1159
+ # v5 confidence layer: cross-check patch consensus against the full-fabric
1160
+ # strongest peak; derive per-axis reason code + confidence.
1161
+ e_sup = info.get("epi_support", 1.0); p_sup = info.get("ppi_support", 1.0)
1162
+ ec = info.get("epi_cands", []); pc = info.get("ppi_cands", [])
1163
+ e_full = ec[0][0] if ec else float("nan")
1164
+ p_full = pc[0][0] if pc else float("nan")
1165
+ e_ppt = calib.px_per_inch / max(epi, 1e-9) if np.isfinite(epi) and epi > 0 else 0
1166
+ p_ppt = calib.px_per_inch / max(ppi, 1e-9) if np.isfinite(ppi) and ppi > 0 else 0
1167
+ epi_reason, epi_conf = _axis_confidence(e_sup, e_ppt, epi, e_full, weave, "epi")
1168
+ ppi_reason, ppi_conf = _axis_confidence(p_sup, p_ppt, ppi, p_full, weave, "ppi")
1169
+ advice = ""
1170
+ if "motif_confusion" in (epi_reason, ppi_reason) or "low_resolution" in (epi_reason, ppi_reason):
1171
+ advice = ("Dense/mixed-yarn or low-resolution axis detected — the count may be a "
1172
+ "sub-multiple. For a reliable reading, re-shoot with BACKLIGHT (fabric over a "
1173
+ "lit screen/tracing panel) or a macro lens; or supply the expert repeat via "
1174
+ "--epi-mult/--ppi-mult.")
1175
+
1176
+ return Result(
1177
+ image=path, weave=weave, calib=calib,
1178
+ epi=epi, ppi=ppi,
1179
+ epi_round=int(round(epi)) if np.isfinite(epi) else 0,
1180
+ ppi_round=int(round(ppi)) if np.isfinite(ppi) else 0,
1181
+ method=info.get("method", ""),
1182
+ epi_candidates=info.get("epi_cands", []),
1183
+ ppi_candidates=info.get("ppi_cands", []),
1184
+ quality=quality,
1185
+ best_patch_epi=patches_for_result["best_epi"],
1186
+ best_patch_ppi=patches_for_result["best_ppi"],
1187
+ n_patches=patches_for_result["n_patches"],
1188
+ epi_reason=epi_reason, ppi_reason=ppi_reason,
1189
+ epi_confidence=epi_conf, ppi_confidence=ppi_conf, advice=advice,
1190
+ )
1191
+
1192
+
1193
+ def print_result(r: Result):
1194
+ c = r.calib
1195
+ print(f"\n=== {os.path.basename(r.image)} ({r.weave}) ===")
1196
+ print(f" SCALE: {c.scale_unit} SMALLEST TICK: {c.tick_mm} mm")
1197
+ print(f" ACF tick = {c.tick_period_px:.2f} px, digit span = {c.digit_span_px} px, "
1198
+ f"n_digits = {c.n_digits}")
1199
+ print(f" ruler classification: {c.ruler_kind}")
1200
+ print(f" => calibration: {c.px_per_mm:.2f} px/mm = {c.px_per_inch:.1f} px/inch")
1201
+ print(f" method: {r.method}")
1202
+ print(f"\n RESULTS:")
1203
+ print(f" full-fabric : EPI = {r.epi:.2f} ≈ {r.epi_round} "
1204
+ f"PPI = {r.ppi:.2f} ≈ {r.ppi_round}")
1205
+ print(f" confidence : EPI {r.epi_confidence:.2f} [{r.epi_reason}] "
1206
+ f"PPI {r.ppi_confidence:.2f} [{r.ppi_reason}]")
1207
+ if r.advice:
1208
+ print(f" ADVICE: {r.advice}")
1209
+ if np.isfinite(r.best_patch_epi):
1210
+ # Compare best-patch to full-fabric to flag harmonic mismatch.
1211
+ e_ratio = r.best_patch_epi / max(r.epi, 1e-9)
1212
+ p_ratio = r.best_patch_ppi / max(r.ppi, 1e-9)
1213
+ e_close = 0.85 < e_ratio < 1.15
1214
+ p_close = 0.85 < p_ratio < 1.15
1215
+ if e_close and p_close:
1216
+ tag = ""
1217
+ else:
1218
+ tag = " ⚠ patch caught a different harmonic"
1219
+ # Show which axis
1220
+ if not e_close:
1221
+ tag += f" (EPI ratio {e_ratio:.2f})"
1222
+ if not p_close:
1223
+ tag += f" (PPI ratio {p_ratio:.2f})"
1224
+ print(f" best patch : EPI = {r.best_patch_epi:.2f} ≈ {int(round(r.best_patch_epi))} "
1225
+ f"PPI = {r.best_patch_ppi:.2f} ≈ {int(round(r.best_patch_ppi))} "
1226
+ f"(n_patches={r.n_patches}){tag}")
1227
+ if e_close and p_close and (abs(r.epi - r.best_patch_epi) > 1.5 or
1228
+ abs(r.ppi - r.best_patch_ppi) > 1.5):
1229
+ print(f" NOTE: best-patch disagrees with full-fabric by > 1.5 tpi — "
1230
+ f"may be more accurate for fabrics with slubs / local variation.")
1231
+ if r.quality:
1232
+ q = r.quality
1233
+ print(f"\n QUALITY {q.label} [{q.overall_pct:.0f}/100]")
1234
+ print(f" EPI axis: {q.epi.final_pct:.0f}/100 "
1235
+ f"(sharpness={q.epi.spectral_sharpness:.2f}, "
1236
+ f"consistency={q.epi.patch_consistency:.2f}, "
1237
+ f"resolution={q.epi.resolution_score:.2f})")
1238
+ print(f" PPI axis: {q.ppi.final_pct:.0f}/100 "
1239
+ f"(sharpness={q.ppi.spectral_sharpness:.2f}, "
1240
+ f"consistency={q.ppi.patch_consistency:.2f}, "
1241
+ f"resolution={q.ppi.resolution_score:.2f})")
1242
+ if q.warnings:
1243
+ print(f" WARNINGS:")
1244
+ for w in q.warnings:
1245
+ print(f" - {w}")
1246
+
1247
+
1248
+ def main():
1249
+ ap = argparse.ArgumentParser(description=__doc__,
1250
+ formatter_class=argparse.RawDescriptionHelpFormatter)
1251
+ ap.add_argument("images", nargs="+")
1252
+ ap.add_argument("--weave", required=True,
1253
+ choices=["plain", "twill", "basket", "rib", "satin", "dobby"])
1254
+ ap.add_argument("--ruler", choices=["cm", "inch", "auto"], default="auto")
1255
+ ap.add_argument("--tick-mm", type=float, default=None,
1256
+ help="Force tick spacing (1.0 or 0.5).")
1257
+ ap.add_argument("--epi-mult", type=int, default=1,
1258
+ help="Expert multiplier on EPI (dense dobby/satin where the "
1259
+ "visible periodicity is a known fraction of the count).")
1260
+ ap.add_argument("--ppi-mult", type=int, default=1,
1261
+ help="Expert multiplier on PPI.")
1262
+ args = ap.parse_args()
1263
+ rh = None if args.ruler == "auto" else args.ruler
1264
+ for p in args.images:
1265
+ r = process(p, weave=args.weave, ruler_hint=rh,
1266
+ force_tick_mm=args.tick_mm,
1267
+ epi_mult=args.epi_mult, ppi_mult=args.ppi_mult)
1268
+ print_result(r)
1269
+
1270
+
1271
+ if __name__ == "__main__":
1272
+ main()
epi_ppi_v6.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """epi_ppi_v6 — production fabric measurement = v5 + two verified robustness wins.
2
+
3
+ Drop-in replacement for epi_ppi_v5: `process(path, weave, ...) -> v5.Result`
4
+ (identical fields). Only the EPI number (and the method/advice strings) change
5
+ when a correction actually fires; every other field is exactly v5's.
6
+
7
+ ADDS, on top of the unchanged v5 pipeline:
8
+ 1) ROBUST RULER-TICK (robust_tick.robust_detect_tick): resolves the 0.5mm/1mm
9
+ factor-2 ruler-scale ambiguity that v5's auto-detect gets wrong on ~38% of
10
+ test photos (-> counts halved/doubled). Verified tick-correct 20/21 vs
11
+ v5-auto 13/21. Used unconditionally; robust_tick itself already falls back
12
+ to v5's own calibration when it cannot resolve a clean ruler, so there is no
13
+ separate soft gate. A user-forced tick (force_tick_mm) is always respected.
14
+ 2) DENSE-WARP SUB-HARMONIC CORRECTOR (classfix_combined.correct_epi): fixes the
15
+ warp EPI on dense mixed-yarn dobby/satin where v5/FFT sub-harmonic-locks
16
+ (e.g. true 134 read as 69). A 5-method consensus vote only overrides when a
17
+ lock is detected, so easy fabrics are untouched (verified ZERO regressions
18
+ on the 14 easy/borderline cases). PPI (weft) passes through v5 unchanged.
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import numpy as np
23
+ from PIL import Image
24
+ from scipy import ndimage
25
+
26
+ import epi_ppi_v5 as v5
27
+ from robust_tick import robust_detect_tick as _robust_tick
28
+ from classfix_combined import correct_epi as _dwc
29
+
30
+ # re-export v5 internals so v6 is a true drop-in (callers that did
31
+ # `algo.detect_calibration`, `algo.Result`, etc. keep working).
32
+ Calibration = v5.Calibration
33
+ Result = v5.Result
34
+ detect_calibration = v5.detect_calibration
35
+ find_fabric_roi = v5.find_fabric_roi
36
+
37
+ _CROP = 1100
38
+
39
+
40
+ def _resolve_tick(gray, force_tick_mm):
41
+ """A user-forced tick wins. Otherwise use the robust dyadic-resolved tick;
42
+ fall back to v5 auto-detect (None) only if it returns something implausible."""
43
+ if force_tick_mm is not None:
44
+ return force_tick_mm
45
+ try:
46
+ tick_mm, _ = _robust_tick(gray)
47
+ if tick_mm in (0.5, 1.0):
48
+ return float(tick_mm)
49
+ except Exception:
50
+ pass
51
+ return None
52
+
53
+
54
+ def _calibrated_crop(gray, calib):
55
+ """Reproduce the calibrated, flat-fielded central crop the corrector was
56
+ validated on (identical recipe to the offline eval)."""
57
+ y0, y1, x0, x1 = v5.find_fabric_roi(gray, calib)
58
+ H, W = gray.shape
59
+ if (y1 - y0) < 50 or (x1 - x0) < 50:
60
+ y0, y1, x0, x1 = int(H * .15), int(H * .82), int(W * .10), int(W * .90)
61
+ fab = gray[y0:y1, x0:x1]
62
+ blur = ndimage.gaussian_filter(fab, 15)
63
+ fab = fab / np.clip(blur, 1e-3, None)
64
+ p1, p99 = np.percentile(fab, [1, 99])
65
+ fab = np.clip((fab - p1) / max(p99 - p1, 1e-9), 0, 1).astype(np.float32)
66
+ h, w = fab.shape
67
+ if h > _CROP or w > _CROP:
68
+ cy, cx = max(0, (h - _CROP) // 2), max(0, (w - _CROP) // 2)
69
+ fab = fab[cy:cy + min(_CROP, h), cx:cx + min(_CROP, w)]
70
+ return fab
71
+
72
+
73
+ def process(path, weave, force_tick_mm=None, **kw):
74
+ """v5.process with a robust tick + dense-warp EPI correction. Same return."""
75
+ gray = np.asarray(Image.open(path).convert("L"), np.float32) / 255.0
76
+ tick = _resolve_tick(gray, force_tick_mm)
77
+ r = v5.process(path, weave, force_tick_mm=tick, **kw)
78
+
79
+ # Dense-warp EPI (warp) correction — PPI (weft) is left exactly as v5.
80
+ try:
81
+ crop = _calibrated_crop(gray, r.calib)
82
+ fft_epi = float(r.epi_round)
83
+ epi, info = _dwc(crop, float(r.calib.px_per_inch), fft_epi,
84
+ weave=weave, return_info=True)
85
+ if info.get("used") == "combined" and np.isfinite(epi) and epi > 0:
86
+ r.epi = float(epi)
87
+ r.epi_round = int(round(epi))
88
+ k = info.get("k")
89
+ r.method = (r.method or "") + f" +dwc(x{k})"
90
+ note = (f"dense-warp warp count corrected: a x{k} sub-harmonic lock "
91
+ f"was detected and fixed (FFT read {int(round(fft_epi))}).")
92
+ r.advice = (r.advice + " " + note).strip() if getattr(r, "advice", "") else note
93
+ # the corrected warp is now trustworthy
94
+ r.epi_reason = "dwc_corrected"
95
+ r.epi_confidence = max(float(getattr(r, "epi_confidence", 0.0)), 0.8)
96
+ except Exception:
97
+ pass # any failure -> keep v5's EPI (never worse than v5)
98
+ return r
epi_ppi_v6_1.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """epi_ppi_v6_1 — production fabric measurement = v6 + the validated referee stack.
2
+
3
+ Drop-in replacement for epi_ppi_v6 (same `process(path, weave, ...) -> Result`).
4
+ Validated on the 114-photo ground-truth DB (2026-07-02): EPI 50%->55%, PPI
5
+ 61%->67%, both-axes 36%->45% within +-2, with ZERO regressions, plus 4/4 ruler
6
+ tick misreads fixed. Full evidence trail: thread_counter/tmp/ (shadow_compose4,
7
+ sensitivity sweeps).
8
+
9
+ ADDS, on top of the unchanged v6 pipeline (robust tick + dense-warp corrector):
10
+
11
+ 1) TICK-HIERARCHY calibration (tick_hierarchy.hierarchy_tick): reads the
12
+ ruler's tick-LENGTH hierarchy (fine ticks between cm landmarks: 20 -> 0.5mm,
13
+ 10 -> 1.0mm) — an absolute structural cue that fixes the dyadic tick
14
+ misreads the plausibility prior cannot break (4/4 fixed, 0 violations on a
15
+ 103-article sweep; honest abstention on backlit rigs). A user-forced tick
16
+ is always respected.
17
+
18
+ 2) K-REFEREE STACK on BOTH axes — three independent judges of "is the reading
19
+ a sub-multiple of the true thread count, and by which integer k":
20
+ referee_fold spatial crest counting; can only PROVE k>=2 (one-sided);
21
+ continuity guard rejects intra-yarn slub texture
22
+ referee_stripe pair crown-rate + coherence-gated bandpass reconstruction
23
+ referee_twm Welch + two-way-mismatch comb scoring (audio pitch method)
24
+ combined under conservative decision rules (see _decide_axis):
25
+ - the production warp corrector (dwc) is overruled ONLY when its claim is
26
+ physically impossible (yarn-width bound) or spatially refutable
27
+ (resolvable >= ~13.3 px/thread yet measured crest rate far below) with
28
+ two gated referees agreeing;
29
+ - weft/PPI corrections (v6 had NO weft corrector) require gated referee
30
+ agreement; all overrides bounded by the yarn-width density ceiling.
31
+ This is what fixes matt/basket pair fabrics (exact-half reads on both axes)
32
+ and the wrong-multiple (x3/x4-instead-of-x2) warp fires, label-free.
33
+
34
+ 3) SUB-PIXEL REFINEMENT (referee_refine): Welch-averaged whitened periodogram
35
+ + ACF cross-check; only returns when independent estimator families agree
36
+ (min-change + abstain rules; 0/126 controls broken).
37
+
38
+ Weave "matt" is accepted and mapped to the basket handler (matt = paired
39
+ threads; the pair handling itself is image-based, not label-based).
40
+
41
+ Runtime: adds ~3-5 s/photo on CPU over v6 (fold ~1s + stripe ~0.7s per axis,
42
+ twm/refine ~0.1s, tick ~0.7s).
43
+ """
44
+ from __future__ import annotations
45
+
46
+ import re
47
+
48
+ import numpy as np
49
+ from PIL import Image
50
+
51
+ import epi_ppi_v6 as v6
52
+ import epi_ppi_v5 as v5
53
+ import referee_fold as _fold
54
+ import referee_stripe as _stripe
55
+ import referee_twm as _twm
56
+ import referee_refine as _refine
57
+ import tick_hierarchy as _tickh
58
+
59
+ # re-export so v6_1 is a true drop-in
60
+ Calibration = v6.Calibration
61
+ Result = v6.Result
62
+ detect_calibration = v6.detect_calibration
63
+ find_fabric_roi = v6.find_fabric_roi
64
+
65
+ # ---- decision-layer gates (sensitivity-swept 2026-07-02: every gate tolerates
66
+ # ---- +-10-15% movement with zero regressions; SCONF/SR re-centered off their
67
+ # ---- cliffs at 0.52/1.30) -------------------------------------------------
68
+ WIDTH_STRICT = 1.00 # density ceiling = ppin / thinnest measured yarn width
69
+ SCONF_GATE = 0.64 # stripe confidence needed to adopt its k alone
70
+ SR_GATE = 1.42 # ...or stripe crown-rate at least this
71
+ RATE_TOL = 1.04 # measured crest rate may not exceed adopted k by more
72
+ RESOLVE_PX = 13.3 # spatial evidence may only refute densities coarser than this
73
+ DWC_RATE_MARGIN = 0.6 # "measured far below dwc's k" margin
74
+
75
+ _WEAVE_ALIAS = {"matt": "basket", "mat": "basket", "hopsack": "basket"}
76
+
77
+
78
+ def _referee(fn, *args):
79
+ """Run one referee defensively; any failure counts as an abstention."""
80
+ try:
81
+ r = fn(*args)
82
+ k = 1 if r.get("abstain") else int(r.get("best_k", 1))
83
+ return k, r
84
+ except Exception:
85
+ return 1, {"abstain": True, "diag": {}}
86
+
87
+
88
+ def _decide_axis(crop, ppin, raw, axis, dwc_k):
89
+ """The validated compose4 policy for one axis.
90
+
91
+ raw = the pre-k-correction reading (EPI: FFT read before dwc; PPI: v5).
92
+ dwc_k = the production warp corrector's fired multiple (0/1 = none; EPI only).
93
+ Returns (k_final, corrected_or_None, diag). corrected_or_None is the k*raw
94
+ override value, or None to keep the production value.
95
+ """
96
+ k_f, fr = _referee(_fold.score_k, crop, ppin, float(raw), axis)
97
+ k_s, sr = _referee(_stripe.score_k, crop, ppin, float(raw), axis)
98
+ k_t, tr = _referee(_twm.score_k, crop, ppin, float(raw), axis)
99
+
100
+ fd = fr.get("diag", {}) if isinstance(fr, dict) else {}
101
+ r_min = fd.get("r_min")
102
+ widths = [c.get("yarn_px") for c in fd.get("channels", {}).values()
103
+ if c.get("yarn_px") and np.isfinite(c["yarn_px"])]
104
+ md = WIDTH_STRICT * ppin / min(widths) if widths else float("inf")
105
+ s_conf = float(sr.get("confidence") or 0.0) if isinstance(sr, dict) else 0.0
106
+ sd = sr.get("diag", {}) if isinstance(sr, dict) else {}
107
+ s_R = sd.get("R") or sd.get("rate_ratio") or sd.get("crown_rate")
108
+
109
+ def rate_consistent(k):
110
+ # the measured crest rate must not EXCEED the adopted thread count
111
+ for v in (s_R, r_min):
112
+ if v is not None and v > RATE_TOL * k:
113
+ return False
114
+ return True
115
+
116
+ k_stripe_ok = (k_s >= 2 and k_s * raw <= md and rate_consistent(k_s)
117
+ and (s_conf >= SCONF_GATE or (s_R or 0) >= SR_GATE))
118
+ k_fold_ok = (k_f >= 2 and k_f * raw <= md) # guarded inside referee_fold
119
+ k_twm_ok = (k_t >= 2 and k_t * raw <= md and rate_consistent(k_t))
120
+
121
+ diag = {"k_fold": k_f, "k_stripe": k_s, "k_twm": k_t,
122
+ "max_density": round(md, 1) if np.isfinite(md) else None}
123
+
124
+ if axis == "epi" and dwc_k >= 2:
125
+ if dwc_k * raw > md:
126
+ # production corrector's density is physically impossible ->
127
+ # any validated survivor takes over
128
+ for ok, kk in ((k_stripe_ok, k_s), (k_twm_ok, k_t), (k_fold_ok, k_f)):
129
+ if ok:
130
+ return kk, int(round(kk * raw)), {**diag, "why": "width_veto"}
131
+ return dwc_k, None, diag
132
+ # dwc plausible: spatial evidence may refute it ONLY if the density it
133
+ # claims would have been spatially RESOLVABLE yet the measured crest
134
+ # rate sits far below it — then two gated referees agreeing win.
135
+ resolvable = ppin / max(dwc_k * raw, 1e-9) >= RESOLVE_PX
136
+ rates = [v for v in (r_min, s_R) if v is not None]
137
+ far_below = bool(rates) and max(rates) <= dwc_k - DWC_RATE_MARGIN
138
+ agree = (k_twm_ok and k_t != dwc_k and
139
+ ((k_stripe_ok and k_s == k_t) or (k_fold_ok and k_f == k_t)))
140
+ if resolvable and far_below and agree:
141
+ return k_t, int(round(k_t * raw)), {**diag, "why": "spatial_refute"}
142
+ return dwc_k, None, diag
143
+
144
+ # no production vote on this axis: gated 2-of-3 agreement, else a single
145
+ # validated path
146
+ agree2 = (k_twm_ok and k_t >= 2 and
147
+ ((k_stripe_ok and k_s == k_t) or (k_fold_ok and k_f == k_t)))
148
+ if agree2:
149
+ return k_t, int(round(k_t * raw)), {**diag, "why": "agree2"}
150
+ if k_stripe_ok:
151
+ return k_s, int(round(k_s * raw)), {**diag, "why": "stripe"}
152
+ if k_fold_ok:
153
+ return k_f, int(round(k_f * raw)), {**diag, "why": "fold"}
154
+ return 1, None, diag
155
+
156
+
157
+ def _resolve_tick(gray, force_tick_mm):
158
+ """User-forced tick wins; else the ruler's structural hierarchy (absolute
159
+ cue, 0 violations measured); else None -> v6's robust tick handles it."""
160
+ if force_tick_mm is not None:
161
+ return force_tick_mm
162
+ try:
163
+ h = _tickh.hierarchy_tick(gray)
164
+ if not h.get("abstain") and h.get("tick_mm") in (0.5, 1.0):
165
+ return float(h["tick_mm"])
166
+ except Exception:
167
+ pass
168
+ return None
169
+
170
+
171
+ def process(path, weave, force_tick_mm=None, **kw):
172
+ """v6.process with hierarchy tick + both-axis k referees + sub-pixel refine.
173
+ Same Result type and fields; only readings/method/advice change when a
174
+ correction actually fires."""
175
+ weave_in = weave
176
+ weave = _WEAVE_ALIAS.get((weave or "").strip().lower(), weave)
177
+
178
+ gray = np.asarray(Image.open(path).convert("L"), np.float32) / 255.0
179
+ tick = _resolve_tick(gray, force_tick_mm)
180
+ r = v6.process(path, weave, force_tick_mm=tick, **kw)
181
+
182
+ try:
183
+ ppin = float(r.calib.px_per_inch)
184
+ crop = v6._calibrated_crop(gray, r.calib)
185
+
186
+ # production raw readings: EPI pre-dwc (parsed from v6's own annotation),
187
+ # PPI = v5 passthrough (v6 has no weft correction)
188
+ mdwc = re.search(r"\+dwc\(x(\d+)\)", r.method or "")
189
+ dwc_k = int(mdwc.group(1)) if mdwc else 0
190
+ mfft = re.search(r"FFT read (\d+)", getattr(r, "advice", "") or "")
191
+ raw_epi = int(mfft.group(1)) if mfft else int(r.epi_round)
192
+ raw_ppi = int(r.ppi_round)
193
+
194
+ notes = []
195
+ for axis, raw in (("epi", raw_epi), ("ppi", raw_ppi)):
196
+ try:
197
+ k, corrected, diag = _decide_axis(crop, ppin, raw, axis, dwc_k)
198
+ except Exception:
199
+ corrected = None
200
+ cur = int(r.epi_round if axis == "epi" else r.ppi_round)
201
+ new = corrected if corrected is not None else cur
202
+ # final sub-pixel refinement (min-change + abstain rules inside)
203
+ try:
204
+ rr = _refine.refine(crop, ppin, float(new), axis)
205
+ if not rr.get("abstain"):
206
+ new = int(round(rr["f_refined"]))
207
+ except Exception:
208
+ pass
209
+ if new != cur:
210
+ if axis == "epi":
211
+ r.epi = float(new); r.epi_round = new
212
+ else:
213
+ r.ppi = float(new); r.ppi_round = new
214
+ if corrected is not None:
215
+ notes.append(f"{axis.upper()} corrected x{k} by the referee "
216
+ f"stack (was {cur}).")
217
+ if axis == "epi":
218
+ r.epi_reason = "v61_referee_corrected"
219
+ r.epi_confidence = max(float(getattr(r, "epi_confidence", 0) or 0), 0.8)
220
+ else:
221
+ r.ppi_reason = "v61_referee_corrected"
222
+ r.ppi_confidence = max(float(getattr(r, "ppi_confidence", 0) or 0), 0.8)
223
+ if notes:
224
+ r.method = (r.method or "") + " +v61"
225
+ note = " ".join(notes)
226
+ r.advice = (r.advice + " " + note).strip() if getattr(r, "advice", "") else note
227
+ except Exception:
228
+ pass # any failure -> v6's result stands (never worse than v6)
229
+ return r
fabric_recognize.py ADDED
@@ -0,0 +1,373 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fabric article recognition by frozen-embedding fingerprint (CPU, no training).
2
+
3
+ Recognize WHICH article a fabric photo is, by matching a learned visual
4
+ embedding against an enrolled store. Returns the article code + confidence;
5
+ defers to the user ("ask") when not sure, and that confirmation is enrolled so
6
+ the store improves over time.
7
+
8
+ Design (validated on the griege set):
9
+ - Embedding = mean-pooled DINOv2 (frozen, self-supervised ViT) features over a
10
+ grid of PHYSICAL-SIZE patches. Patch size is set from the ruler calibration
11
+ (px/inch) so the embedding is zoom/scale invariant; if no ruler is found we
12
+ fall back to image-fraction patches. DINOv2 supplies lighting/scale
13
+ invariance with NO training.
14
+ - Recognition is fully DECOUPLED from EPI/PPI. Thread density is used only as a
15
+ downstream VERIFY step (verify()): once an article is identified, compare the
16
+ measured EPI/PPI to the catalogued value as an independent confidence check.
17
+ - Matching = nearest enrolled sample per article (multi-sample enrollment), with
18
+ a confidence gate: accept only when the best distance is small AND the margin
19
+ over the next-best article is clear; otherwise "ask"; if nothing is close,
20
+ "new".
21
+
22
+ Why frozen embedding (not hand-crafted, not RL): hand-crafted FFT/tone features
23
+ gave zero article separation on greige goods; a frozen DINOv2 embedding gave
24
+ 20/20 augmented-probe rank-1 and 3/4 real cross-batch re-id with a ~4-10x
25
+ same-vs-different distance gap. For larger/near-identical catalogs a one-time
26
+ label-free contrastive fine-tune (GPU to train, CPU to deploy) widens the gap;
27
+ see FINE_TUNE_NOTES at the bottom.
28
+ """
29
+ from __future__ import annotations
30
+ import os, json, warnings
31
+ from dataclasses import dataclass, field
32
+ from typing import Optional
33
+ warnings.filterwarnings("ignore")
34
+
35
+ import numpy as np
36
+ from PIL import Image
37
+ from scipy import ndimage
38
+
39
+ # Register the HEIC/HEIF opener so PIL can read iPhone .HEIC uploads here too
40
+ # (defense-in-depth; the API server also registers it). Without this, PIL raises
41
+ # UnidentifiedImageError on .HEIC photos.
42
+ try:
43
+ import pillow_heif
44
+ pillow_heif.register_heif_opener()
45
+ except Exception:
46
+ pass
47
+
48
+ # ---- configuration -------------------------------------------------------- #
49
+ MODEL_CANDIDATES = ["vit_small_patch14_dinov2.lvd142m", "resnet50.a1_in1k"]
50
+ PATCH_INCH = 0.6 # physical patch size (zoom-invariant via ruler)
51
+ GRID = 3 # GRID x GRID patches per image
52
+ TORCH_THREADS = 4
53
+
54
+ # --- v6 recognition embed (TTA): multi-crop-size grid + patch-token mean ---
55
+ # Validated: held-out rank-1 4/10 -> 6/10 (and 9/10 with count-fusion). Frozen
56
+ # DINOv2, no training. The recipe differs from v5 (two crop fractions, 252px,
57
+ # patch tokens), so catalogs embedded with v5 MUST be re-embedded (EMBED_VERSION).
58
+ TTA_CROPFRACS = (0.45, 0.6) # crop side as fraction of min(H,W); both pooled
59
+ TTA_SIZE = 252 # resize fed to the ViT
60
+ TTA_GRID = 3
61
+ EMBED_VERSION = "v6-tta-1" # bump when the embed recipe changes -> re-embed
62
+
63
+ # --- v6 count-fusion: fuse the measured EPI/PPI into candidate RANKING to break
64
+ # visually-identical greige look-alikes (validated held-out rank-1 6/10 -> 9/10).
65
+ # Distinct article codes that look the same still differ in thread count. The
66
+ # count fingerprint is dyadic-robust (folded PPI + scale-invariant aspect), so the
67
+ # 0.5/1mm ruler ambiguity doesn't pollute it. Fusion only nudges near-ties; on a
68
+ # hard calibration failure (no measured count) it is simply absent -> visual-only.
69
+ FUSE_LAMBDA = 0.2
70
+ COUNT_FOLD_LO, COUNT_FOLD_HI = 55.0, 110.0
71
+
72
+ # Confidence-gate thresholds (cosine distance). Calibrated on the griege set;
73
+ # RE-TUNE per catalogue via calibrate(). Conservative => high precision, more asks.
74
+ DEFAULT_GATE = dict(accept_dist=0.040, accept_margin=0.012, ask_dist=0.090)
75
+
76
+ _MODEL = None
77
+ _MCFG = None
78
+
79
+
80
+ def _load_model():
81
+ """Lazy-load a frozen embedding model once (CPU)."""
82
+ global _MODEL, _MCFG
83
+ if _MODEL is not None:
84
+ return _MODEL, _MCFG
85
+ import torch, timm
86
+ torch.set_num_threads(TORCH_THREADS)
87
+ last = None
88
+ for name in MODEL_CANDIDATES:
89
+ try:
90
+ # dynamic_img_size lets the ViT accept the TTA resize (252) via
91
+ # pos-embed interpolation (required by the v6 embed recipe).
92
+ try:
93
+ m = timm.create_model(name, pretrained=True, num_classes=0,
94
+ dynamic_img_size=True).eval()
95
+ except TypeError:
96
+ m = timm.create_model(name, pretrained=True, num_classes=0).eval()
97
+ cfg = timm.data.resolve_data_config({}, model=m)
98
+ _MODEL = m
99
+ _MCFG = {"name": name, "input": cfg["input_size"][-1],
100
+ "mean": np.array(cfg["mean"]), "std": np.array(cfg["std"]),
101
+ "torch": torch}
102
+ return _MODEL, _MCFG
103
+ except Exception as e:
104
+ last = e
105
+ raise RuntimeError(f"no embedding model could be loaded (offline?): {last}")
106
+
107
+
108
+ def _roi_and_scale(path):
109
+ """RGB fabric ROI + px/inch (ruler). Degrades gracefully: if the calibration
110
+ module is missing or the ruler can't be read, fall back to the whole image
111
+ with no scale (patches then use an image-fraction size). Recognition does
112
+ NOT depend on EPI/PPI — calibration only sizes the patches."""
113
+ rgb = np.asarray(Image.open(path).convert("RGB"), np.float32) / 255.0
114
+ try:
115
+ import epi_ppi_v4_2 as v42 # optional: only used to size patches by px/inch
116
+ gray = np.asarray(Image.open(path).convert("L"), np.float32) / 255.0
117
+ calib = v42.detect_calibration(gray, force_tick_mm=0.5)
118
+ y0, y1, x0, x1 = v42.find_fabric_roi(gray, calib)
119
+ return rgb[y0:y1, x0:x1], float(calib.px_per_inch)
120
+ except Exception as e:
121
+ print(f"[recognize: calibration unavailable, using full image: {type(e).__name__}: {e}]")
122
+ return rgb, None
123
+
124
+
125
+ def _tta_crops(roi):
126
+ """Multi-crop-size grid: a GRIDxGRID layout at EACH crop fraction, all pooled.
127
+ Larger crops give DINOv2 more fabric context (lifts rank-1); the mix of sizes
128
+ keeps tight clusters for the 100%-precision gate."""
129
+ H, W, _ = roi.shape
130
+ crops = []
131
+ for frac in TTA_CROPFRACS:
132
+ ps = min(max(64, int(min(H, W) * frac)), min(H, W))
133
+ ys = np.linspace(0, H - ps, TTA_GRID, dtype=int)
134
+ xs = np.linspace(0, W - ps, TTA_GRID, dtype=int)
135
+ crops += [roi[y:y + ps, x:x + ps] for y in ys for x in xs]
136
+ return crops
137
+
138
+
139
+ def embed_image(path) -> np.ndarray:
140
+ """v6 TTA article embedding: L2-normalized mean of frozen-DINOv2 PATCH-TOKEN
141
+ features over a multi-crop-size grid. Same 384-d format as before, but the
142
+ recipe differs (see EMBED_VERSION) so v5-embedded catalogs must be re-embedded."""
143
+ model, cfg = _load_model()
144
+ torch = cfg["torch"]; INPUT = cfg["input"]; MEAN = cfg["mean"]; STD = cfg["std"]
145
+ roi, _ppi = _roi_and_scale(path)
146
+ ims = []
147
+ for ct in _tta_crops(roi):
148
+ im = Image.fromarray((np.clip(ct, 0, 1) * 255).astype(np.uint8)).resize(
149
+ (TTA_SIZE, TTA_SIZE), Image.BILINEAR)
150
+ a = (np.asarray(im, np.float32) / 255 - MEAN) / STD
151
+ ims.append(a.transpose(2, 0, 1))
152
+ x = torch.tensor(np.stack(ims), dtype=torch.float32)
153
+ with torch.no_grad():
154
+ out = model.forward_features(x) # ViT: (B, 1+N, D)
155
+ out = out.cpu().numpy()
156
+ if out.ndim == 3: # ViT tokens -> patch-token mean
157
+ feat = out[:, 1:, :].mean(axis=1)
158
+ else: # non-ViT fallback (e.g. resnet)
159
+ feat = out.reshape(out.shape[0], out.shape[1], -1).mean(axis=2)
160
+ v = feat.mean(0)
161
+ return v / (np.linalg.norm(v) + 1e-9)
162
+
163
+
164
+ def cos_dist(a, b):
165
+ return 1.0 - float(np.dot(a, b))
166
+
167
+
168
+ def _fold_dyadic(x, lo=COUNT_FOLD_LO, hi=COUNT_FOLD_HI):
169
+ """Fold x by x2 / /2 onto a canonical octave so the 0.5/1mm ruler factor-2
170
+ ambiguity collapses and true counts compare cleanly."""
171
+ if x is None or not np.isfinite(x) or x <= 0:
172
+ return None
173
+ while x < lo:
174
+ x *= 2.0
175
+ while x >= hi:
176
+ x /= 2.0
177
+ return x
178
+
179
+
180
+ def count_feature(epi, ppi):
181
+ """Dyadic-robust count fingerprint (folded_ppi, aspect=epi/ppi) or None."""
182
+ try:
183
+ epi = float(epi); ppi = float(ppi)
184
+ except (TypeError, ValueError):
185
+ return None
186
+ if not (epi > 0 and ppi > 0):
187
+ return None
188
+ fp = _fold_dyadic(ppi)
189
+ if fp is None:
190
+ return None
191
+ return (fp, epi / ppi)
192
+
193
+
194
+ @dataclass
195
+ class Recognizer:
196
+ store_path: Optional[str] = None
197
+ gate: dict = field(default_factory=lambda: dict(DEFAULT_GATE))
198
+ entries: list = field(default_factory=list) # {code, vec, meta}
199
+
200
+ def __post_init__(self):
201
+ if self.store_path and os.path.exists(self.store_path):
202
+ self.load()
203
+
204
+ # ---- enrollment ---- #
205
+ def enroll(self, code, image_path, meta=None):
206
+ v = embed_image(image_path)
207
+ meta = dict(meta or {})
208
+ meta.setdefault("embed_version", EMBED_VERSION) # stamp so it never looks stale
209
+ self.entries.append({"code": code, "vec": v.tolist(), "meta": meta})
210
+ return v
211
+
212
+ def enroll_vector(self, code, vec, meta=None):
213
+ self.entries.append({"code": code, "vec": np.asarray(vec).tolist(),
214
+ "meta": meta or {}})
215
+
216
+ # ---- identification ---- #
217
+ def identify(self, image_path, measured_epi=None, measured_ppi=None, top_k=5):
218
+ v = embed_image(image_path)
219
+ return self.identify_vector(v, measured_epi, measured_ppi, top_k)
220
+
221
+ def _count_index(self):
222
+ """Per-code median count fingerprint + across-article z-scales, from
223
+ entries that carry a stored count (meta['count']={epi,ppi}). Cached,
224
+ rebuilt when the catalog changes. -> ({code:(folded_ppi,aspect)}, s_ppi, s_asp)."""
225
+ sig = len(self.entries)
226
+ if getattr(self, "_ci_sig", None) == sig and getattr(self, "_ci", None) is not None:
227
+ return self._ci
228
+ by_code = {}
229
+ for e in self.entries:
230
+ cnt = (e.get("meta") or {}).get("count")
231
+ if not cnt:
232
+ continue
233
+ f = count_feature(cnt.get("epi"), cnt.get("ppi"))
234
+ if f:
235
+ by_code.setdefault(e["code"], []).append(f)
236
+ feat = {c: (float(np.median([x[0] for x in fl])),
237
+ float(np.median([x[1] for x in fl])))
238
+ for c, fl in by_code.items()}
239
+ if len(feat) >= 2:
240
+ s_ppi = float(np.std([f[0] for f in feat.values()])) or 1.0
241
+ s_asp = float(np.std([f[1] for f in feat.values()])) or 1.0
242
+ else:
243
+ s_ppi = s_asp = 1.0
244
+ self._ci = (feat, s_ppi, s_asp)
245
+ self._ci_sig = sig
246
+ return self._ci
247
+
248
+ def identify_vector(self, v, measured_epi=None, measured_ppi=None, top_k=5):
249
+ """Return ranked candidates + a decision. If measured_epi/ppi are given,
250
+ cross-check each candidate's catalog density and DEMOTE confidence when a
251
+ visual match disagrees with the catalogued EPI/PPI by > density_tol — a
252
+ fabric that looks right but measures wrong is suspicious."""
253
+ if not self.entries:
254
+ return {"code": None, "decision": "new", "confidence": 0.0,
255
+ "candidates": [], "top3": []}
256
+ # nearest sample per article code (keep its catalog meta)
257
+ per_code = {}
258
+ for e in self.entries:
259
+ d = cos_dist(v, np.asarray(e["vec"]))
260
+ if e["code"] not in per_code or d < per_code[e["code"]][0]:
261
+ per_code[e["code"]] = (d, e.get("meta", {}))
262
+ # v6 count-fusion: RANK by combined distance (visual + lambda*count_dist)
263
+ # so a visually-identical look-alike with a different thread count is
264
+ # demoted; the gate/confidence below stay on VISUAL distance, preserving
265
+ # precision and today's auto-accept behaviour (ambiguous ties -> "ask").
266
+ qf = count_feature(measured_epi, measured_ppi)
267
+ cfeat, s_ppi, s_asp = self._count_index()
268
+
269
+ def _combined_key(item):
270
+ code, (dvis, _m) = item
271
+ if qf is None or code not in cfeat:
272
+ return dvis
273
+ ef = cfeat[code]
274
+ cd = 0.5 * (((qf[0] - ef[0]) / s_ppi) ** 2 + ((qf[1] - ef[1]) / s_asp) ** 2)
275
+ return dvis + FUSE_LAMBDA * float(np.sqrt(cd))
276
+
277
+ ranked = sorted(per_code.items(), key=_combined_key)
278
+ g = self.gate
279
+ density_tol = 2 # "within +-2 of catalog" per requirement
280
+
281
+ def density_check(meta):
282
+ """Return (badge, agree) comparing measured vs catalog density."""
283
+ if measured_epi is None or measured_ppi is None or not meta.get("epi"):
284
+ return None, True
285
+ de = abs(measured_epi - meta["epi"]); dp = abs(measured_ppi - meta["ppi"])
286
+ return {"catalog_epi": meta["epi"], "catalog_ppi": meta["ppi"],
287
+ "d_epi": measured_epi - meta["epi"], "d_ppi": measured_ppi - meta["ppi"],
288
+ "agree": de <= density_tol and dp <= density_tol}, (de <= density_tol and dp <= density_tol)
289
+
290
+ # build candidate list (top_k) with per-candidate confidence + density
291
+ cands = []
292
+ for i, (code, (d, meta)) in enumerate(ranked[:top_k]):
293
+ nd = ranked[i + 1][1][0] if i + 1 < len(ranked) else 1.0
294
+ mgn = nd - d
295
+ c = float(np.clip(1 - d / g["ask_dist"], 0, 1) *
296
+ np.clip(mgn / g["ask_dist"], 0, 1) ** 0.5)
297
+ dens, agree = density_check(meta)
298
+ if not agree:
299
+ c *= 0.5 # density disagreement -> less confident
300
+ cands.append({"code": code, "dist": round(d, 4),
301
+ "confidence": round(c, 3), "density": dens})
302
+
303
+ best = cands[0]
304
+ best_d = ranked[0][1][0]; margin = (ranked[1][1][0] - best_d) if len(ranked) > 1 else 1.0
305
+ best_agree = best["density"]["agree"] if best["density"] else True
306
+ if best_d <= g["accept_dist"] and margin >= g["accept_margin"] and best_agree:
307
+ decision = "accept"
308
+ elif best_d <= g["ask_dist"]:
309
+ decision = "ask" # incl. visual-accept but density-disagree
310
+ else:
311
+ decision = "new"
312
+ return {"code": best["code"] if decision != "new" else None,
313
+ "decision": decision, "confidence": best["confidence"],
314
+ "best_dist": round(best_d, 4), "margin": round(margin, 4),
315
+ "catalog": ranked[0][1][1] if decision != "new" else {},
316
+ "density_agree": best_agree,
317
+ "candidates": cands,
318
+ "top3": [(c["code"], c["dist"]) for c in cands[:3]]} # back-compat
319
+
320
+ # ---- downstream EPI/PPI verification (decoupled) ---- #
321
+ def verify(self, image_path, code, weave, tol=4):
322
+ """After identification, cross-check measured EPI/PPI vs the catalogued
323
+ value for `code` (stored in meta as epi/ppi). Independent confidence."""
324
+ import epi_ppi_v4_2 as v42
325
+ cat = next((e["meta"] for e in self.entries
326
+ if e["code"] == code and e["meta"].get("epi")), None)
327
+ r = v42.process(image_path, weave=weave, force_tick_mm=0.5)
328
+ out = {"measured": [r.epi_round, r.ppi_round]}
329
+ if cat:
330
+ de = abs(r.epi_round - cat["epi"]); dp = abs(r.ppi_round - cat["ppi"])
331
+ out.update({"catalog": [cat["epi"], cat["ppi"]],
332
+ "epi_ppi_match": de <= tol and dp <= tol,
333
+ "delta": [r.epi_round - cat["epi"], r.ppi_round - cat["ppi"]]})
334
+ return out
335
+
336
+ # ---- persistence ---- #
337
+ def save(self, path=None):
338
+ path = path or self.store_path
339
+ with open(path, "w") as f:
340
+ json.dump({"gate": self.gate, "entries": self.entries}, f)
341
+
342
+ def load(self, path=None):
343
+ path = path or self.store_path
344
+ with open(path) as f:
345
+ d = json.load(f)
346
+ self.gate = d.get("gate", dict(DEFAULT_GATE)); self.entries = d["entries"]
347
+
348
+
349
+ FINE_TUNE_NOTES = """
350
+ To push coverage toward 99.99% on a large / near-identical catalogue:
351
+ - Collect multiple photos per article (different lighting/fold/region) — biggest
352
+ single lever, no training needed.
353
+ - One-time LABEL-FREE contrastive fine-tune of the backbone (SimCLR/DINO-style):
354
+ positives = augmented crops of the SAME photo/article, negatives = other
355
+ articles. GPU only for this one-time training; deploy CPU inference unchanged.
356
+ - Re-run calibrate() to reset accept/ask thresholds for the new embedding.
357
+ """
358
+
359
+ if __name__ == "__main__":
360
+ import argparse
361
+ ap = argparse.ArgumentParser()
362
+ ap.add_argument("cmd", choices=["embed", "enroll", "identify"])
363
+ ap.add_argument("image")
364
+ ap.add_argument("--code"); ap.add_argument("--store", default="fabric_store.json")
365
+ a = ap.parse_args()
366
+ if a.cmd == "embed":
367
+ print(embed_image(a.image)[:8], "...")
368
+ else:
369
+ rec = Recognizer(store_path=a.store)
370
+ if a.cmd == "enroll":
371
+ rec.enroll(a.code, a.image); rec.save(); print(f"enrolled {a.code}")
372
+ else:
373
+ print(json.dumps(rec.identify(a.image), indent=2))
migrate_catalog_v6.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ONE-TIME migration: re-embed the enrolled catalog with the v6 TTA embedder and
2
+ backfill each photo's MEASURED count (for count-fusion).
3
+
4
+ REQUIRED after deploying v6 recognition: the embedding recipe changed (TTA, patch
5
+ tokens), so v5-embedded vectors are NOT comparable to v6 query embeddings. This
6
+ rebuilds fabric_store.json from the enrolled IMAGES (the source of truth), carrying
7
+ over the gate + per-article catalog EPI/PPI/weave from the old store.
8
+
9
+ Run ONCE after the v6 code is deployed (the enrolled images must be present locally,
10
+ i.e. after the bucket pull):
11
+
12
+ python migrate_catalog_v6.py [data_dir]
13
+
14
+ data_dir defaults to the persistence DATA_DIR; it must contain
15
+ <data_dir>/images/<code>/<photo> and (optionally) <data_dir>/fabric_store.json.
16
+ A backup of the old store is written alongside as fabric_store.json.v5.bak.
17
+ """
18
+ import sys, os, glob, json, shutil
19
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
20
+ import fabric_recognize as fr
21
+
22
+
23
+ def migrate(data_dir):
24
+ store_path = os.path.join(data_dir, "fabric_store.json")
25
+ images_dir = os.path.join(data_dir, "images")
26
+ old = json.load(open(store_path)) if os.path.exists(store_path) else {}
27
+ gate = old.get("gate", dict(fr.DEFAULT_GATE))
28
+ # carry per-article catalog meta (spec EPI/PPI/weave) from the old store
29
+ old_cat = {}
30
+ for e in old.get("entries", []):
31
+ m = e.get("meta", {}) or {}
32
+ if e["code"] not in old_cat and any(k in m for k in ("epi", "ppi", "weave")):
33
+ old_cat[e["code"]] = {k: m[k] for k in ("epi", "ppi", "weave") if k in m}
34
+
35
+ import epi_ppi_v6 as algo
36
+ entries, n_count = [], 0
37
+ imgs = sorted(glob.glob(os.path.join(images_dir, "*", "*")))
38
+ for img in imgs:
39
+ if img.lower().endswith(".heic"):
40
+ continue
41
+ code = os.path.basename(os.path.dirname(img))
42
+ try:
43
+ vec = fr.embed_image(img)
44
+ except Exception as ex:
45
+ print(f" skip {img}: embed failed ({type(ex).__name__})"); continue
46
+ meta = dict(old_cat.get(code, {}))
47
+ meta["image"] = os.path.relpath(img, data_dir)
48
+ meta["embed_version"] = fr.EMBED_VERSION
49
+ try:
50
+ r = algo.process(img, meta.get("weave") or "plain")
51
+ meta["count"] = {"epi": int(r.epi_round), "ppi": int(r.ppi_round)}
52
+ n_count += 1
53
+ except Exception:
54
+ pass
55
+ entries.append({"code": code, "vec": vec.tolist(), "meta": meta})
56
+
57
+ if os.path.exists(store_path):
58
+ shutil.copyfile(store_path, store_path + ".v5.bak")
59
+ json.dump({"gate": gate, "entries": entries}, open(store_path, "w"))
60
+ arts = len(set(e["code"] for e in entries))
61
+ print(f"migrated {len(entries)} photos across {arts} articles "
62
+ f"({n_count} with counts) -> {store_path}")
63
+ print("old store backed up to fabric_store.json.v5.bak")
64
+
65
+
66
+ if __name__ == "__main__":
67
+ dd = sys.argv[1] if len(sys.argv) > 1 else None
68
+ if dd is None:
69
+ try:
70
+ import api.persistence as P
71
+ dd = P.DATA_DIR
72
+ except Exception:
73
+ dd = "./data"
74
+ print(f"migrating catalog in: {dd}")
75
+ migrate(dd)
referee_fold.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """referee_fold — spatial thread-counting referee (fold/peak-count v2).
3
+
4
+ Decides which integer multiple k of the counter's raw reading f_raw is the true
5
+ thread frequency, by DIRECTLY counting thread crests in the spatial domain:
6
+
7
+ * strips perpendicular to the counting axis (skew-tolerant, keeps local
8
+ structure that a whole-crop average washes out)
9
+ * per strip: detrend, smooth to the finest plausible thread scale, detect
10
+ peaks (bright yarns) AND valleys (dark inter-yarn gaps) with adaptive
11
+ prominence; rate = peaks per inch, counted not inferred from spacing
12
+ (robust to uneven pair spacing)
13
+ * channel estimates vote; a phase-fold mode count confirms; a yarn-width
14
+ (peak FWHM) physical bound vetoes impossible densities.
15
+
16
+ Abstains unless the evidence for k>1 is clear. Interface shared by all referees:
17
+
18
+ score_k(crop, px_per_inch, f_raw, axis, kmax=4) ->
19
+ {'best_k', 'abstain', 'confidence', 'scores', 'diag'}
20
+ """
21
+ import numpy as np
22
+ from scipy import ndimage, signal
23
+
24
+ STRIP_PX = 16 # strip thickness (perpendicular to counting axis)
25
+ MIN_PERIODS = 6 # need at least this many raw periods along the axis
26
+ PROMOTE_AT = 1.30 # min(channel ratios) >= this proves k >= 2 (controls <= 1.11)
27
+ CONT_MIN = 0.50 # strip-to-strip crest persistence needed to trust crests
28
+ WIDTH_SLACK = 1.20 # threads/inch may exceed 1/width by at most this factor
29
+ # v3 semantics: spatial peak counting SATURATES on tight pairs / dense goods
30
+ # (measured: k=2 pair cases resolve to only 1.34-1.56x f_raw; dense controls
31
+ # under-count at 0.52-0.79x). So the referee is ONE-SIDED:
32
+ # ratio >= PROMOTE_AT -> k >= 2 is PROVEN (some pairs split; count can only
33
+ # under-estimate, never over-estimate at these gates)
34
+ # ratio ~ 1 or < 1 -> NO information (merged pairs and correct reads look
35
+ # identical) -> best_k=1 is non-binding, never a veto.
36
+
37
+
38
+ def _strip_profiles(crop, axis):
39
+ """Yield 1-D profiles along the counting axis, one per strip."""
40
+ a = crop if axis == "epi" else crop.T # periodicity along columns
41
+ H, W = a.shape
42
+ for y0 in range(0, H - STRIP_PX + 1, STRIP_PX):
43
+ yield a[y0:y0 + STRIP_PX].mean(axis=0)
44
+
45
+
46
+ def _channel_rate(prof, P_raw, px_per_inch, invert):
47
+ """Count crests (or valleys) in one strip profile. Returns (n, length_px,
48
+ widths_px, coherence) or None if the strip is unusable. coherence = how
49
+ periodically the detected peaks repeat at the raw period P_raw (max over
50
+ harmonics m=1..4 of the circular moment |mean(exp(2pi*i*m*phase))|):
51
+ real thread/pair crests are period-locked (high), intra-yarn slub texture
52
+ is aperiodic (low)."""
53
+ p = -prof if invert else prof
54
+ # detrend at ~1.5 raw periods; smooth to finest plausible thread scale
55
+ p = p - ndimage.gaussian_filter1d(p, max(3.0, 1.5 * P_raw))
56
+ p = ndimage.gaussian_filter1d(p, max(1.0, P_raw / 24.0))
57
+ s = float(p.std())
58
+ if s <= 1e-9:
59
+ return None
60
+ dist = max(2, int(round(P_raw / 6.0))) # finest sep ~ P/6 (k=4 + slack)
61
+ pk, props = signal.find_peaks(p, distance=dist, prominence=0.55 * s)
62
+ if len(pk) < 3:
63
+ return None
64
+ widths = signal.peak_widths(p, pk, rel_height=0.5)[0]
65
+ return len(pk), len(p), widths, pk
66
+
67
+
68
+ def _continuity(peak_lists, tol):
69
+ """A true thread is a continuous line: its crest position persists from one
70
+ strip to the next. Local slub/texture blobs do not. Score = mean fraction of
71
+ peaks in strip s that have a peak within tol px in strip s+1."""
72
+ fr = []
73
+ for a, b in zip(peak_lists[:-1], peak_lists[1:]):
74
+ if len(a) == 0 or len(b) == 0:
75
+ continue
76
+ d = np.min(np.abs(a[:, None] - b[None, :]), axis=1)
77
+ fr.append(float(np.mean(d <= tol)))
78
+ return float(np.median(fr)) if fr else 0.0
79
+
80
+
81
+ def _fold_modes(profiles, P, nbins=48):
82
+ """Phase-fold all strip profiles at period P; count modes in the folded
83
+ mean (confirmation channel). Returns (n_modes, mode_strength)."""
84
+ acc = np.zeros(nbins)
85
+ wts = np.zeros(nbins)
86
+ for prof in profiles:
87
+ p = prof - ndimage.gaussian_filter1d(prof, max(3.0, 1.5 * P))
88
+ x = np.arange(len(p))
89
+ b = np.minimum(((x / P) % 1.0 * nbins).astype(int), nbins - 1)
90
+ acc += np.bincount(b, weights=p, minlength=nbins)
91
+ wts += np.bincount(b, minlength=nbins)
92
+ folded = acc / np.maximum(wts, 1)
93
+ folded -= folded.mean()
94
+ fs = ndimage.gaussian_filter1d(np.tile(folded, 3), 1.2)[nbins:2 * nbins]
95
+ rng = float(fs.max() - fs.min())
96
+ if rng <= 1e-9:
97
+ return 1, 0.0
98
+ ext = np.tile(fs, 3)
99
+ pk, props = signal.find_peaks(ext, prominence=0.30 * rng)
100
+ pk = pk[(pk >= nbins) & (pk < 2 * nbins)]
101
+ strength = float(np.median(props["prominences"])) / rng if len(pk) else 0.0
102
+ return max(1, len(pk)), strength
103
+
104
+
105
+ def score_k(crop, px_per_inch, f_raw, axis, kmax=4):
106
+ diag = {}
107
+ f_raw = float(f_raw)
108
+ if not np.isfinite(f_raw) or f_raw <= 0:
109
+ return {"best_k": 1, "abstain": True, "confidence": 0.0,
110
+ "scores": {}, "diag": {"why": "bad_f_raw"}}
111
+ P_raw = px_per_inch / f_raw # raw period in px
112
+ profiles = list(_strip_profiles(crop, axis))
113
+ if not profiles or len(profiles[0]) < MIN_PERIODS * P_raw:
114
+ return {"best_k": 1, "abstain": True, "confidence": 0.0,
115
+ "scores": {}, "diag": {"why": "too_few_periods"}}
116
+
117
+ # --- channel A: bright crests; channel B: dark valleys -----------------
118
+ votes = {}
119
+ for name, invert in (("peaks", False), ("valleys", True)):
120
+ counts, length, widths, plists = 0, 0, [], []
121
+ used = 0
122
+ for prof in profiles:
123
+ r = _channel_rate(prof, P_raw, px_per_inch, invert)
124
+ if r is None:
125
+ continue
126
+ c, l, w, pk = r
127
+ counts += c; length += l; widths.extend(w)
128
+ plists.append(np.asarray(pk, float))
129
+ used += 1
130
+ if used < 3 or length == 0:
131
+ continue
132
+ rate = counts / (length / px_per_inch) # threads/inch
133
+ ratio = rate / f_raw
134
+ k_hat = int(round(ratio))
135
+ ok = 1 <= k_hat <= kmax and abs(ratio - k_hat) <= 0.30 # diag only
136
+ med_w = float(np.median(widths)) if widths else float("nan")
137
+ cont = _continuity(plists, tol=max(2.0, P_raw / 10.0))
138
+ votes[name] = {"rate": round(rate, 1), "ratio": round(ratio, 2),
139
+ "k": k_hat if ok else None, "n_strips": used,
140
+ "yarn_px": round(med_w, 1), "cont": round(cont, 2)}
141
+ diag["channels"] = votes
142
+
143
+ # --- confirmation: fold-mode count at the raw period --------------------
144
+ n_modes, strength = _fold_modes(profiles, P_raw)
145
+ diag["fold_modes"] = n_modes
146
+ diag["fold_strength"] = round(strength, 3)
147
+
148
+ # --- combine (v3: one-sided lower-bound promotion) -----------------------
149
+ ratios = [v["ratio"] for v in votes.values()]
150
+ if len(ratios) < 2:
151
+ return {"best_k": 1, "abstain": True, "confidence": 0.0,
152
+ "scores": {}, "diag": {**diag, "why": "lt2_channels"}}
153
+ r_min = min(ratios)
154
+ diag["r_min"] = round(r_min, 2)
155
+
156
+ if r_min < PROMOTE_AT:
157
+ # no promotion evidence; k=1 is NON-BINDING (saturation indistinguishable
158
+ # from a correct read) -> abstain so other referees decide freely.
159
+ return {"best_k": 1, "abstain": True, "confidence": 0.0,
160
+ "scores": {1: 0.0}, "diag": {**diag, "why": "no_promotion_evidence"}}
161
+
162
+ # continuity guard: real threads are continuous lines whose crest positions
163
+ # persist across strips; intra-yarn slub texture is local blobs that do not.
164
+ cont_min = min(v.get("cont", 0.0) for v in votes.values())
165
+ if cont_min < CONT_MIN:
166
+ return {"best_k": 1, "abstain": True, "confidence": 0.0,
167
+ "scores": {}, "diag": {**diag, "why": "low_continuity"}}
168
+
169
+ # promotion proven: choose the smallest k consistent with the (lower-bound)
170
+ # measured rate; exact-resolution case maps ratio -> nearest integer.
171
+ if r_min >= 3.4:
172
+ k_best = 4
173
+ elif r_min >= 2.5:
174
+ k_best = 3
175
+ else:
176
+ k_best = 2
177
+ lower_bound = abs(r_min - k_best) > 0.25 # saturated: true k may be higher
178
+
179
+ # yarn-width physical veto on the promoted density (thinnest detected yarn)
180
+ widths = [v["yarn_px"] for v in votes.values()
181
+ if np.isfinite(v.get("yarn_px", np.nan))]
182
+ if widths:
183
+ max_density = WIDTH_SLACK * px_per_inch / max(min(widths), 1e-9)
184
+ diag["max_density"] = round(max_density, 1)
185
+ if k_best * f_raw > max_density:
186
+ return {"best_k": 1, "abstain": True, "confidence": 0.0,
187
+ "scores": {}, "diag": {**diag, "why": "width_veto"}}
188
+
189
+ conf = round(min(1.0, 0.5 + (r_min - PROMOTE_AT)), 2)
190
+ return {"best_k": int(k_best), "abstain": False, "confidence": conf,
191
+ "lower_bound": bool(lower_bound),
192
+ "scores": {int(k_best): 1.0}, "diag": diag}
193
+
194
+
195
+ # --------------------------------------------------------------------------- #
referee_refine.py ADDED
@@ -0,0 +1,287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Sub-pixel refinement referee for fabric thread-count (EPI/PPI) readings.
2
+
3
+ Given a calibrated crop and the current reading f0 (assumed within ~12% of
4
+ truth), returns a sub-bin-refined frequency estimate, or abstains when the
5
+ evidence is ambiguous.
6
+
7
+ Techniques (all numpy, <100 ms/call typical):
8
+ 1. Welch-averaged periodogram over horizontal strips perpendicular to the
9
+ measured axis (per-strip linear detrend + hann window, power averaged),
10
+ zero-padded to NFFT=32768 (~0.06 tpi grid), background-whitened, then
11
+ Gaussian (log-parabolic) interpolation of the peak near f0.
12
+ 2. Strip-level peak median + IQR as a stability gate (catches chirped /
13
+ defective / low-signal crops).
14
+ 3. Autocorrelation ladder: parabolic interpolation of the averaged-ACF peak
15
+ at the largest reliable multiples of the period (shift/skew tolerant);
16
+ used as an independent-family confirmation.
17
+ 4. Harmonic reinforcement: peaks at k*f (k>=2) with good SNR that agree with
18
+ the fundamental within 0.7% sharpen the estimate (angular precision * k).
19
+ 5. 2-D zoomed DFT ridge check around (f_1d, fy): if the thread ridge is
20
+ genuinely rotated (single dominant fy-line, fx consistent with 1-D
21
+ estimate, no weave-lattice satellite ladder), correct the projected
22
+ frequency by the ridge norm (f_perp = hypot(fx, fy) = fx / cos(theta)).
23
+
24
+ SAFETY: abstains when SNR is low, strip estimates are unstable, spectral and
25
+ ACF families disagree, the peak is at the search-window edge, or the refined
26
+ value moves >11.5% from f0. Never returns outside [0.85*f0, 1.15*f0].
27
+ """
28
+
29
+ import numpy as np
30
+
31
+ NFFT = 32768
32
+ STRIP_H = 64 # strip height (rows averaged per strip)
33
+ TOL = 0.12 # fundamental search half-window, relative to f0
34
+ MIN_SNR = 4.0 # minimum whitened fundamental SNR
35
+ MAX_IQR_REL = 0.012 # strip-median IQR gate (relative to f0)
36
+ MAX_MED_DEV = 0.006 # |strip-median - welch| gate (relative)
37
+ MAX_ACF_DEV = 0.009 # |acf - welch| gate (relative)
38
+ HARM_TOL = 0.007 # harmonic-vs-fundamental consistency (relative)
39
+ HARM_MIN_SNR = 5.0
40
+ MIN_CHANGE = 1.1 # |f_refined - f0| below this -> abstain (no value added):
41
+ # f0 is integer-rounded (+-0.5) and the estimator noise
42
+ # floor is ~0.3 (2 sigma ~0.6); changes below ~1.1 carry
43
+ # no actionable information but carry edge-of-tolerance
44
+ # risk on already-correct readings.
45
+ MIN_TOTAL_STRIPS = 10 # crop must span >=10 strips for sub-1% precision claims
46
+ MAX_REL_CHANGE = 0.115
47
+ RIDGE_MAX_THETA = 8.0 # deg
48
+ RIDGE_DOMINANCE = 0.25 # competing fy-line power ratio to reject ridge
49
+
50
+
51
+ def _strip_profiles(img, strip_h=STRIP_H):
52
+ """Average rows in strips -> K x M profiles, linearly detrended."""
53
+ N, M = img.shape
54
+ K = max(1, N // strip_h)
55
+ prof = img[:K * strip_h].reshape(K, strip_h, M).mean(axis=1)
56
+ x = np.arange(M, dtype=np.float64)
57
+ xc = x - x.mean()
58
+ slope = (prof @ xc) / (xc * xc).sum()
59
+ return prof - prof.mean(axis=1, keepdims=True) - slope[:, None] * xc[None, :]
60
+
61
+
62
+ def _whiten(P, halfwidth):
63
+ """Divide by a running-median background (odd window ~4x mainlobe)."""
64
+ w = max(15, int(4 * halfwidth) | 1)
65
+ n = len(P)
66
+ # strided median on a subsampled grid for speed, then interp
67
+ step = max(1, w // 8)
68
+ centers = np.arange(0, n, step)
69
+ pad = np.pad(P, w // 2, mode='edge')
70
+ med = np.array([np.median(pad[c:c + w]) for c in centers])
71
+ bg = np.interp(np.arange(n), centers, med)
72
+ return P / np.maximum(bg, 1e-300)
73
+
74
+
75
+ def _local_peak(P, kc, half, noise_excl=8):
76
+ """argmax + Gaussian (log-parabolic) interpolation in P[kc-half, kc+half].
77
+
78
+ Returns (pos_bins, snr, edge_flag) or None."""
79
+ lo, hi = max(2, int(kc - half)), min(len(P) - 3, int(kc + half))
80
+ if hi <= lo + 2:
81
+ return None
82
+ seg = P[lo:hi + 1]
83
+ k = lo + int(np.argmax(seg))
84
+ edge = (k <= lo) or (k >= hi)
85
+ lp = np.log(np.maximum(P[k - 1:k + 2], 1e-300))
86
+ den = lp[0] - 2.0 * lp[1] + lp[2]
87
+ delta = float(np.clip(0.5 * (lp[0] - lp[2]) / den, -1, 1)) if den < 0 else 0.0
88
+ c = k - lo
89
+ mask = np.ones(len(seg), bool)
90
+ mask[max(0, c - noise_excl):c + noise_excl + 1] = False
91
+ noise = np.median(seg[mask]) if mask.sum() > 4 else np.median(seg)
92
+ snr = float(P[k] / max(noise, 1e-300))
93
+ return k + delta, snr, edge
94
+
95
+
96
+ def _acf_ladder(prof, f0_px, tol=TOL, mmax_cap=10):
97
+ """Averaged-ACF period estimates at multiples m of the expected lag.
98
+
99
+ Returns list of (m, f_px, peak_height)."""
100
+ K, M = prof.shape
101
+ n2 = 1 << int(np.ceil(np.log2(2 * M)))
102
+ F = np.fft.rfft(prof, n=n2, axis=1)
103
+ ac = np.fft.irfft((F.real ** 2 + F.imag ** 2).mean(axis=0), n=n2)[:M]
104
+ if ac[0] <= 0:
105
+ return []
106
+ ac = ac / ac[0]
107
+ L0 = 1.0 / f0_px
108
+ out = []
109
+ mmax = min(mmax_cap, int(0.6 * M / L0))
110
+ for m in range(1, mmax + 1):
111
+ Lc = m * L0
112
+ lo = max(2, int(np.floor(Lc * (1 - tol / m))))
113
+ hi = min(M - 2, int(np.ceil(Lc * (1 + tol / m))))
114
+ if hi <= lo:
115
+ continue
116
+ k = lo + int(np.argmax(ac[lo:hi + 1]))
117
+ if k <= lo or k >= hi:
118
+ continue
119
+ y0, y1, y2 = ac[k - 1], ac[k], ac[k + 1]
120
+ den = y0 - 2 * y1 + y2
121
+ if den >= 0 or y1 <= 0.02:
122
+ continue
123
+ L = (k + 0.5 * (y0 - y2) / den) / m
124
+ out.append((m, 1.0 / L, float(y1)))
125
+ return out
126
+
127
+
128
+ def _ridge_2d(img, fx_c):
129
+ """Zoomed 2-D DFT around fx_c (cyc/px): fy-line profile near the warp ridge.
130
+
131
+ Returns (fx_peak, fy_peak, dominance_ratio, n_lines) or None.
132
+ dominance_ratio = strongest competing fy-line power / ridge power."""
133
+ N, M = img.shape
134
+ wy, wx = np.hanning(N), np.hanning(M)
135
+ im = ((img - img.mean()) * wy[:, None] * wx[None, :]).astype(np.float32)
136
+ fx = np.linspace(0.99 * fx_c, 1.01 * fx_c, 15)
137
+ fy = np.linspace(-0.028, 0.028, 141)
138
+ Ex = np.exp(-2j * np.pi * np.outer(np.arange(M), fx)).astype(np.complex64)
139
+ Ey = np.exp(-2j * np.pi * np.outer(fy, np.arange(N))).astype(np.complex64)
140
+ T = im @ Ex # N x nfx (cheap first: M-contraction)
141
+ F = Ey @ T # nfy x nfx
142
+ P = F.real ** 2 + F.imag ** 2
143
+ prof = P.max(axis=1)
144
+ j = int(np.argmax(prof))
145
+ jx = int(np.argmax(P[j]))
146
+ # competing fy-lines: local maxima well away from the main line
147
+ excl = 6 # ~2.4e-3 cyc/px exclusion
148
+ mask = np.ones(len(prof), bool)
149
+ mask[max(0, j - excl):j + excl + 1] = False
150
+ dom = float(prof[mask].max() / prof[j]) if mask.any() else 0.0
151
+ return float(fx[jx]), float(fy[j]), dom, j in (0, len(prof) - 1)
152
+
153
+
154
+ def refine(crop, px_per_inch, f0, axis):
155
+ """crop: 2-D float32 0..1 (calibrated, flat-fielded, warp threads vertical).
156
+ f0: current reading in threads/inch (within ~12% of truth). axis: 'epi'|'ppi'.
157
+ Returns dict: {'f_refined': float, 'confidence': float 0..1, 'abstain': bool,
158
+ 'diag': dict}. abstain=True -> caller keeps f0. Must run <1.5s CPU,
159
+ numpy/scipy only."""
160
+ diag = {}
161
+
162
+ def _abstain(reason, conf=0.1):
163
+ diag['reason'] = reason
164
+ return {'f_refined': float(f0), 'confidence': conf, 'abstain': True,
165
+ 'diag': diag}
166
+
167
+ try:
168
+ img = np.asarray(crop, dtype=np.float32)
169
+ except Exception:
170
+ return _abstain('bad_input')
171
+ if img.ndim != 2 or min(img.shape) < 4 * STRIP_H or not np.isfinite(f0) \
172
+ or f0 <= 0 or px_per_inch <= 0:
173
+ return _abstain('bad_input')
174
+ if img.max() > 1.5: # tolerate uint8-scaled input
175
+ img = img / 255.0
176
+ if axis == 'ppi':
177
+ img = img.T
178
+ elif axis != 'epi':
179
+ return _abstain('bad_axis')
180
+
181
+ f0_px = f0 / px_per_inch
182
+ if not (0.004 < f0_px < 0.42): # sane period range, below Nyquist margin
183
+ return _abstain('f0_out_of_range')
184
+
185
+ # ---- 1. Welch-averaged, whitened periodogram --------------------------
186
+ prof = _strip_profiles(img)
187
+ K, M = prof.shape
188
+ win = np.hanning(M)
189
+ F = np.fft.rfft(prof * win[None, :], n=NFFT, axis=1)
190
+ Pk = F.real ** 2 + F.imag ** 2
191
+ P = Pk.mean(axis=0)
192
+ b0 = f0_px * NFFT
193
+ mainlobe = 2.0 * NFFT / M # hann mainlobe half-width in bins
194
+ Pw = _whiten(P, mainlobe)
195
+
196
+ r = _local_peak(Pw, b0, TOL * b0)
197
+ if r is None:
198
+ return _abstain('no_window')
199
+ pos1, snr1, edge1 = r
200
+ f_1d = pos1 / NFFT * px_per_inch
201
+ diag.update(snr=round(snr1, 1), f_welch=round(f_1d, 3))
202
+ if edge1:
203
+ return _abstain('peak_at_window_edge')
204
+ if snr1 < MIN_SNR:
205
+ return _abstain('low_snr', 0.15)
206
+
207
+ # ---- 2. strip-level stability -----------------------------------------
208
+ if K < MIN_TOTAL_STRIPS:
209
+ return _abstain('short_crop', 0.2)
210
+ strip_f = []
211
+ for s in range(K):
212
+ rs = _local_peak(Pk[s], b0, TOL * b0)
213
+ if rs is not None and not rs[2]:
214
+ strip_f.append(rs[0] / NFFT * px_per_inch)
215
+ diag['n_strips'] = len(strip_f)
216
+ if len(strip_f) < max(6, K // 2):
217
+ return _abstain('few_valid_strips', 0.15)
218
+ f_med = float(np.median(strip_f))
219
+ iqr = float(np.percentile(strip_f, 75) - np.percentile(strip_f, 25))
220
+ diag.update(f_strip_med=round(f_med, 3), strip_iqr=round(iqr, 3))
221
+ if iqr > max(MAX_IQR_REL * f0, 1.0):
222
+ return _abstain('unstable_strips', 0.2)
223
+ if abs(f_med - f_1d) > max(MAX_MED_DEV * f0, 0.6):
224
+ return _abstain('median_mean_disagree', 0.2)
225
+
226
+ # ---- 3. ACF ladder confirmation ---------------------------------------
227
+ ladder = _acf_ladder(prof, f0_px)
228
+ if not ladder:
229
+ return _abstain('no_acf_peak', 0.15)
230
+ f_acf = float(np.median([f for _, f, _ in ladder[-3:]])) * px_per_inch
231
+ diag.update(f_acf=round(f_acf, 3), acf_m=ladder[-1][0])
232
+ if abs(f_acf - f_1d) > max(MAX_ACF_DEV * f0, 0.9):
233
+ return _abstain('acf_spectrum_disagree', 0.2)
234
+
235
+ # ---- 4. consistent high-SNR harmonics ---------------------------------
236
+ ests = [(f_1d, 3.0), (f_acf, 1.5)]
237
+ n_harm = 0
238
+ kmax = int((len(P) - 4) / b0 / (1 + TOL))
239
+ for k in range(2, min(kmax, 6) + 1):
240
+ rk = _local_peak(Pw, k * pos1, max(8.0, 0.012 * b0 * k))
241
+ if rk is None or rk[2] or rk[1] < HARM_MIN_SNR:
242
+ continue
243
+ fk = rk[0] / k / NFFT * px_per_inch
244
+ if abs(fk - f_1d) <= HARM_TOL * f_1d:
245
+ ests.append((fk, 0.75 * min(k, 4)))
246
+ n_harm += 1
247
+ diag['n_harm'] = n_harm
248
+
249
+ vals = np.array([v for v, _ in ests])
250
+ wts = np.array([w for _, w in ests])
251
+ f_base = float((vals * wts).sum() / wts.sum())
252
+
253
+ # ---- 5. 2-D ridge / skew check -----------------------------------------
254
+ ridge_factor = 1.0
255
+ theta = 0.0
256
+ rr = _ridge_2d(img, f_1d / px_per_inch)
257
+ if rr is not None:
258
+ rfx, rfy, dom, redge = rr
259
+ theta = float(np.degrees(np.arctan2(rfy, rfx)))
260
+ diag.update(theta_deg=round(theta, 2), ridge_dom=round(dom, 3))
261
+ fx_ok = abs(rfx * px_per_inch - f_1d) <= 0.01 * f_1d
262
+ if fx_ok and not redge and dom < RIDGE_DOMINANCE and abs(theta) <= RIDGE_MAX_THETA:
263
+ ridge_factor = float(np.hypot(rfx, rfy) / rfx)
264
+ elif not fx_ok or dom >= RIDGE_DOMINANCE:
265
+ # ambiguous 2-D structure (lattice satellites / off-axis grab):
266
+ # keep the projected estimate but note it
267
+ diag['ridge_rejected'] = True
268
+
269
+ f_ref = f_base * ridge_factor
270
+ diag.update(f_base=round(f_base, 3), ridge_factor=round(ridge_factor, 5),
271
+ n_est=len(ests))
272
+
273
+ # ---- decision -----------------------------------------------------------
274
+ if abs(f_ref - f0) / f0 > MAX_REL_CHANGE:
275
+ return _abstain('too_far_from_f0', 0.15)
276
+ if abs(f_ref - f0) < MIN_CHANGE:
277
+ return _abstain('change_too_small', 0.5)
278
+
279
+ f_ref = float(np.clip(f_ref, 0.85 * f0, 1.15 * f0))
280
+ spread = float(vals.max() - vals.min())
281
+ conf = 0.35 + 0.08 * n_harm + min(np.log10(max(snr1, 1.0)), 2.0) * 0.15 \
282
+ - min(spread / max(f0 * 0.01, 1e-9), 1.0) * 0.15
283
+ conf = float(np.clip(conf, 0.05, 0.99))
284
+ diag['spread'] = round(spread, 3)
285
+ return {'f_refined': f_ref, 'confidence': conf, 'abstain': False, 'diag': diag}
286
+
287
+
referee_stripe.py ADDED
@@ -0,0 +1,443 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """referee_stripe.py — sub-multiple REFEREE for the fabric thread counter.
2
+
3
+ PROBLEM
4
+ -------
5
+ The production FFT counter sometimes locks onto a SUB-MULTIPLE of the true
6
+ thread frequency: it reads f_raw where the truth is k*f_raw, k in {2,3,4}.
7
+ Two physical causes:
8
+ * paired threads on matt/basket weaves — two threads lie close together and
9
+ read as one unit, so f_raw = the PAIR rate and the truth is 2*f_raw;
10
+ * weave-motif combs on dobby/satin — the motif injects a strong coarse comb
11
+ and the true (finer) thread comb is spectrally weak.
12
+ Given the calibrated crop and f_raw, this module decides which multiple k is
13
+ the true thread frequency (k=1 = f_raw is already correct).
14
+
15
+ METHOD — Fourier bandpass reconstruction + spatial stripe-count verification
16
+ (after Zhang, Pan, Wang, Gao, "An efficient method for density measurement
17
+ for high-tightness woven fabrics", Textile Research Journal 2017), organised
18
+ as two detectors that mirror the two failure causes:
19
+
20
+ (A) PAIR DETECTOR (k = 2, dominant failure mode). Phase-independent yarn
21
+ counting against the pixels: detrended row-band profiles are lightly
22
+ smoothed at the finest candidate scale and the rate of significant local
23
+ maxima (yarn crowns) and minima (inter-yarn gaps) per inch is measured at
24
+ two prominence levels (0.25 and 0.5 of the band-profile sigma; median
25
+ over ~17 bands of 64 rows). If the fabric really contains ~2*f_raw yarns
26
+ the observed crown/gap rate rises well above f_raw (validated: paired
27
+ truths >= 1.35*f_raw, single-yarn controls <= 1.05*f_raw); a mere FFT
28
+ harmonic of a single-yarn comb adds NO extra crowns, so this test cannot
29
+ be fooled by non-sinusoidal yarn profiles. This is deliberately NOT a
30
+ Fourier-phase test: for tightly paired yarns the 2*f Fourier component's
31
+ crests land BETWEEN the pair members, so phase-alignment scoring fails on
32
+ exactly the fabrics that need fixing (and the 1.5x pair harmonic aligns
33
+ better than the true comb — the classic 3/2 trap).
34
+
35
+ (B) MOTIF-COMB DETECTOR (k >= 3). For each candidate ft = k*f_raw snapped to
36
+ a real spectral peak: mask the 2-D FFT to a small one-sided directional
37
+ neighborhood around +ft (analytic signal), inverse-FFT to reconstruct the
38
+ pure stripe field, then verify: (1) the crest count across the crop width
39
+ equals the implied count ft*width (median over row-bands); (2) the
40
+ reconstruction is PHASE-COHERENT over the whole crop (a true thread comb
41
+ is a narrow spectral line; a noise band reconstructs incoherent
42
+ low-amplitude stripes whose phase random-walks); (3) band-energy SNR
43
+ against the local spectral background. The finest k passing all checks
44
+ wins. This path is restricted to k >= 3: a k=2 harmonic of a correct
45
+ f_raw is the strongest confusable in controls, and k=2 truths are pair
46
+ fabrics which detector (A) owns.
47
+
48
+ Per-stripe pixel verification (crest/trough contrast and gap tests of the
49
+ reconstruction against the detrended original) is computed for every
50
+ candidate and folded into the confidence and reported scores.
51
+
52
+ ABSTAIN (safe: caller keeps f_raw) when the implied density exceeds what the
53
+ resolution supports (< ~4 px per thread: stripes alias), when the crown-rate
54
+ lands in the ambiguous zone, or when a motif candidate near-passes.
55
+
56
+ INTERFACE
57
+ ---------
58
+ score_k(crop, px_per_inch, f_raw, axis, kmax=4) -> dict
59
+ {'best_k': int>=1, 'abstain': bool, 'confidence': float 0..1,
60
+ 'scores': {k: float}, 'diag': dict}
61
+
62
+ numpy/scipy only; < 2 s per call on CPU (typically ~0.5 s on a 1100^2 crop).
63
+ """
64
+ from __future__ import annotations
65
+
66
+ import numpy as np
67
+ from scipy import ndimage, signal
68
+ from scipy import fft as sfft
69
+
70
+ # --------------------------------------------------------------------------- #
71
+ # Constants (physically motivated; validated on the 20260702 bucket:
72
+ # 8 sub-multiple failure cases + 6 single-yarn controls, zero violations).
73
+ # --------------------------------------------------------------------------- #
74
+ SNAP_TOL = 0.065 # k*f_raw must land within 6.5% of a real spectral peak
75
+ MIN_PPT = 4.0 # < 4 px/thread: candidate aliases -> untestable
76
+ NB = 12 # row-bands for the reconstruction stripe tests
77
+ BWX_FRAC = 0.05 # bandpass half-width along the periodic axis
78
+ BWY_FRAC = 0.15 # angular tolerance across the stripe direction
79
+ MIN_BINS_X = 2.5
80
+ MIN_BINS_Y = 4.0
81
+ # --- pair detector (A) ---
82
+ RATE_BAND_ROWS = 64 # rows per band for crown/gap rate counting
83
+ RATE_PROMS = (0.25, 0.50) # prominence levels, units of band-profile sigma
84
+ RATE_FIRE = 1.20 # crown rate >= 1.20*f_raw -> pairs present (k>=2)
85
+ RATE_GRAY = 1.08 # 1.08..1.20: ambiguous -> abstain
86
+ RATE_K3 = 2.20 # crown rate >= 2.2*f_raw -> k=3 (>=3 crowns/unit)
87
+ RATE_K4 = 3.20
88
+ # --- motif-comb detector (B), k >= 3 only ---
89
+ MOTIF_SNR_MIN = 1.6 # band peak vs local spectral background
90
+ MOTIF_COH_MIN = 0.60 # full-crop phase coherence (controls max ~0.47)
91
+ MOTIF_COH_GRAY = 0.54 # 0.54..0.60 with SNR+count OK -> abstain
92
+ MOTIF_CNT_TOL = 0.03 # |crest count - implied|/implied
93
+ MOTIF_REL_MIN = 0.04 # peak amplitude vs strongest thread-band peak
94
+ MOTIF_MIN_PPT = 6.0 # motif combs resolve at >=~10 px/thread; below
95
+ # ~6 px/thread fine "lines" are sensor/JPEG artifacts
96
+ BLOCKED_REL = 0.30 # strong-but-aliased band energy -> abstain
97
+
98
+
99
+ # --------------------------------------------------------------------------- #
100
+ # Spectrum (production-style windowed 2-D FFT, axial band)
101
+ # --------------------------------------------------------------------------- #
102
+
103
+ def _axial_spectrum(img):
104
+ """Hann-windowed 2-D FFT; (freqs cycles/px, amplitude) of the 1-D spectrum
105
+ along +x, summed over the |fy|<=3-bin axial band (as the production
106
+ counter reads it). Periodicity is along x by convention."""
107
+ p = img - img.mean()
108
+ wy = np.hanning(p.shape[0])[:, None].astype(np.float32)
109
+ wx = np.hanning(p.shape[1])[None, :].astype(np.float32)
110
+ F = np.abs(sfft.rfft2(p * wy * wx))
111
+ spec = F[0:4].sum(axis=0) + F[-3:].sum(axis=0)
112
+ freqs = np.fft.rfftfreq(p.shape[1])
113
+ return freqs, spec
114
+
115
+
116
+ def _find_peaks(freqs, spec, f_lo_cpp):
117
+ sel = freqs > f_lo_cpp
118
+ if not sel.any():
119
+ return np.empty(0), np.empty(0)
120
+ base = spec[sel].max()
121
+ idx, _ = signal.find_peaks(spec, height=0.01 * base, prominence=0.005 * base)
122
+ idx = idx[freqs[idx] > f_lo_cpp]
123
+ return freqs[idx], spec[idx]
124
+
125
+
126
+ def _snap(fpk, apk, target_cpp, tol=SNAP_TOL):
127
+ """Snap a target frequency to the STRONGEST real peak within tol
128
+ (fractional). Nearest-peak snapping is a trap: a weak spurious peak just
129
+ inside the tolerance can shadow the true comb line."""
130
+ if len(fpk) == 0:
131
+ return target_cpp, 0.0, False
132
+ ok = np.abs(fpk - target_cpp) / target_cpp <= tol
133
+ if not ok.any():
134
+ return target_cpp, 0.0, False
135
+ j = int(np.argmax(np.where(ok, apk, -np.inf)))
136
+ return float(fpk[j]), float(apk[j]), True
137
+
138
+
139
+ def _band_snr(freqs, spec, f_cpp, bwx):
140
+ """Peak amplitude at f_cpp vs median spectral background around it.
141
+ Window is +-25% of f_cpp but at least band + 8 bins on each side, so the
142
+ background estimate survives coarse frequencies on small crops."""
143
+ dbin = float(freqs[1] - freqs[0]) if len(freqs) > 1 else 1e-3
144
+ half = max(0.25 * f_cpp, bwx + 8 * dbin)
145
+ win = np.abs(freqs - f_cpp) <= half
146
+ inband = np.abs(freqs - f_cpp) <= bwx
147
+ bg = spec[win & ~inband]
148
+ if bg.size < 4:
149
+ return 0.0
150
+ pk = float(spec[inband].max()) if inband.any() else 0.0
151
+ return pk / max(float(np.median(bg)), 1e-12)
152
+
153
+
154
+ # --------------------------------------------------------------------------- #
155
+ # (B) Bandpass reconstruction + stripe verification
156
+ # --------------------------------------------------------------------------- #
157
+
158
+ def _reconstruct(F2, fx, fy, f_cpp, W, H):
159
+ """One-sided directional bandpass around +f_cpp along x -> analytic image."""
160
+ bwx = max(MIN_BINS_X / W, BWX_FRAC * f_cpp)
161
+ bwy = max(MIN_BINS_Y / H, BWY_FRAC * f_cpp)
162
+ colmask = np.abs(fx - f_cpp) <= bwx
163
+ rowmask = np.abs(fy) <= bwy
164
+ A = sfft.ifft2(F2 * np.outer(rowmask, colmask)) * 2.0
165
+ return A, bwx
166
+
167
+
168
+ def _crossings(c, xs):
169
+ """Sub-pixel x positions where sequence c crosses an integer going up."""
170
+ f = np.floor(c)
171
+ idx = np.where(np.diff(f) >= 1)[0]
172
+ if len(idx) == 0:
173
+ return np.empty(0)
174
+ tgt = f[idx] + 1.0
175
+ dc = c[idx + 1] - c[idx]
176
+ frac = np.where(np.abs(dc) > 1e-12, (tgt - c[idx]) / dc, 0.5)
177
+ return xs[idx] + np.clip(frac, 0.0, 1.0)
178
+
179
+
180
+ def _stripe_tests(A, D, f_cpp, nb=NB):
181
+ """Verify one reconstructed stripe field against the pixels.
182
+
183
+ Returns: frac_pos (per-stripe crest-vs-trough contrast sign), gap_frac
184
+ (troughs that are true local dips), count_ratio (crest count / implied
185
+ count, median over bands), tstat (contrast significance), coherence
186
+ (full-width phase linearity of the band at f_cpp), n_stripes."""
187
+ H, W = A.shape
188
+ T = 1.0 / f_cpp
189
+ marg = int(np.ceil(T)) + 2
190
+ xs = np.arange(W)
191
+ x0, x1 = marg, W - marg
192
+ empty = dict(frac_pos=0.0, gap_frac=0.0, count_ratio=0.0, tstat=0.0,
193
+ coherence=0.0, n_stripes=0)
194
+ if x1 - x0 < 3 * T:
195
+ return empty
196
+
197
+ contrasts, gaps, counts, cohs = [], [], [], []
198
+ expected = f_cpp * (x1 - x0)
199
+ for rr in np.array_split(np.arange(H), nb):
200
+ a = A[rr].mean(axis=0)
201
+ d = ndimage.gaussian_filter1d(D[rr].mean(axis=0), max(T / 8.0, 0.8))
202
+ ph = np.unwrap(np.angle(a))
203
+ u = a[x0:x1] * np.exp(-2j * np.pi * f_cpp * xs[x0:x1])
204
+ cohs.append(np.abs(u.mean()) / max(np.abs(u).mean(), 1e-12))
205
+ c = ph / (2 * np.pi)
206
+ crest_x = _crossings(c, xs)
207
+ trough_x = _crossings(c - 0.5, xs)
208
+ crest_x = crest_x[(crest_x >= x0) & (crest_x <= x1)]
209
+ trough_x = trough_x[(trough_x >= x0) & (trough_x <= x1)]
210
+ counts.append(len(crest_x) / max(expected, 1e-9))
211
+ if len(crest_x) < 3 or len(trough_x) < 3:
212
+ continue
213
+ dc = np.interp(crest_x, xs, d)
214
+ dt = np.interp(trough_x, xs, d)
215
+ for i, xc in enumerate(crest_x):
216
+ j = np.searchsorted(trough_x, xc)
217
+ if 0 < j < len(trough_x):
218
+ contrasts.append(dc[i] - 0.5 * (dt[j - 1] + dt[j]))
219
+ for j, xt in enumerate(trough_x):
220
+ i = np.searchsorted(crest_x, xt)
221
+ if 0 < i < len(crest_x):
222
+ gaps.append(1.0 if dt[j] < min(dc[i - 1], dc[i]) else 0.0)
223
+ if not contrasts:
224
+ return empty
225
+ con = np.asarray(contrasts, np.float64)
226
+ tstat = con.mean() / max(con.std(ddof=1) / np.sqrt(len(con)), 1e-12)
227
+ return dict(frac_pos=float((con > 0).mean()),
228
+ gap_frac=float(np.mean(gaps)) if gaps else 0.0,
229
+ count_ratio=float(np.median(counts)) if counts else 0.0,
230
+ tstat=float(tstat),
231
+ coherence=float(np.mean(cohs)) if cohs else 0.0,
232
+ n_stripes=int(len(con)))
233
+
234
+
235
+ # --------------------------------------------------------------------------- #
236
+ # (A) Pair detector: phase-independent yarn crown/gap rate
237
+ # --------------------------------------------------------------------------- #
238
+
239
+ def _crown_rate(D, f1_cpp, kmax):
240
+ """Median rate (per pixel) of significant profile maxima (crowns) and
241
+ minima (gaps) over 64-row bands, averaged over two prominence levels.
242
+ Returned as a multiple of f1_cpp."""
243
+ H, W = D.shape
244
+ Tf = 1.0 / f1_cpp / max(kmax, 2) # finest scale of interest
245
+ dist = max(int(Tf * 0.55), 2)
246
+ sig = max(Tf / 5.0, 1.0)
247
+ nb = max(H // RATE_BAND_ROWS, 1)
248
+ rates = []
249
+ for pc in RATE_PROMS:
250
+ for sgn in (+1.0, -1.0):
251
+ per_band = []
252
+ for rr in np.array_split(np.arange(H), nb):
253
+ d = ndimage.gaussian_filter1d(sgn * D[rr].mean(axis=0), sig)
254
+ pk, _ = signal.find_peaks(d, prominence=pc * d.std(),
255
+ distance=dist)
256
+ per_band.append(len(pk) / W)
257
+ rates.append(float(np.median(per_band)))
258
+ return float(np.mean(rates)) / f1_cpp
259
+
260
+
261
+ # --------------------------------------------------------------------------- #
262
+ # Public API
263
+ # --------------------------------------------------------------------------- #
264
+
265
+ def score_k(crop, px_per_inch, f_raw, axis, kmax=4):
266
+ """Referee: which multiple k of f_raw is the true thread frequency?
267
+
268
+ crop: 2-D float32 array 0..1 (calibrated, flat-fielded; warp threads
269
+ vertical). px_per_inch: float. f_raw: float threads/inch (the counter's
270
+ current reading). axis: 'epi' (periodicity along X) or 'ppi'
271
+ (periodicity along Y).
272
+
273
+ Returns dict: {'best_k': int>=1, 'abstain': bool, 'confidence': float 0..1,
274
+ 'scores': {k: float}, 'diag': dict}
275
+ """
276
+ out = {'best_k': 1, 'abstain': False, 'confidence': 0.0,
277
+ 'scores': {k: 0.0 for k in range(1, kmax + 1)}, 'diag': {}}
278
+ try:
279
+ img = np.asarray(crop, np.float32)
280
+ if img.ndim != 2 or min(img.shape) < 64 or not np.isfinite(f_raw) \
281
+ or f_raw <= 0 or px_per_inch <= 0:
282
+ out['abstain'] = True
283
+ out['diag']['reason'] = 'bad input'
284
+ return out
285
+ if axis == 'ppi':
286
+ img = np.ascontiguousarray(img.T) # periodicity now along x
287
+ elif axis != 'epi':
288
+ raise ValueError("axis must be 'epi' or 'ppi'")
289
+
290
+ H, W = img.shape
291
+ f1_cpp = float(f_raw) / float(px_per_inch) # cycles / pixel
292
+ if f1_cpp >= 0.5 or f1_cpp * W < 4:
293
+ out['abstain'] = True
294
+ out['diag']['reason'] = 'f_raw outside usable range'
295
+ return out
296
+
297
+ # ---- shared signals -------------------------------------------- #
298
+ freqs, spec = _axial_spectrum(img)
299
+ fpk, apk = _find_peaks(freqs, spec, 0.6 * f1_cpp)
300
+ band = (fpk >= 0.9 * f1_cpp) & (fpk <= 1.0 / MIN_PPT)
301
+ norm = apk[band].max() if band.any() else (apk.max() if len(apk) else 1.0)
302
+
303
+ # re-base on the real k=1 spectral line (8% tol): candidate targets
304
+ # k*f_base stay on the fabric's lattice even when f_raw is a few
305
+ # percent off, instead of drifting onto spurious neighbors.
306
+ f_base, _, base_snapped = _snap(fpk, apk, f1_cpp, tol=0.08)
307
+ if not base_snapped:
308
+ f_base = f1_cpp
309
+ out['diag']['f_base_tpi'] = float(f_base * px_per_inch)
310
+
311
+ F2 = sfft.fft2(img - img.mean())
312
+ fx = np.fft.fftfreq(W)
313
+ fy = np.fft.fftfreq(H)
314
+ T1 = 1.0 / f_base
315
+ # detrended original (keeps ~>=0.5*f_raw) for all pixel-domain tests
316
+ D = img - ndimage.gaussian_filter(img, 0.75 * T1)
317
+
318
+ # (A) phase-independent yarn crown/gap rate, multiple of the re-based
319
+ # k=1 line (falls back to f_raw when no line snaps)
320
+ R = _crown_rate(D, f_base, kmax)
321
+ out['diag']['crown_rate'] = round(R, 3)
322
+
323
+ # ---- per-candidate evidence ------------------------------------- #
324
+ diag_k = {}
325
+ for k in range(1, kmax + 1):
326
+ f_k, a_k, snapped = _snap(fpk, apk, k * f_base)
327
+ e = {'target_tpi': k * f_raw, 'snapped': bool(snapped),
328
+ 'f_tpi': f_k * px_per_inch,
329
+ 'rel_amp': float(a_k / max(norm, 1e-12)),
330
+ 'ppt': float(1.0 / f_k)}
331
+ if not snapped:
332
+ e['verdict'] = 'no spectral peak'
333
+ elif e['ppt'] < MIN_PPT:
334
+ e['verdict'] = 'aliased (<%g px/thread)' % MIN_PPT
335
+ e['resolution_blocked'] = True
336
+ else:
337
+ A, bwx = _reconstruct(F2, fx, fy, f_k, W, H)
338
+ e['snr'] = float(_band_snr(freqs, spec, f_k, bwx))
339
+ e.update(_stripe_tests(A, D, f_k))
340
+ e['stripe_score'] = float(
341
+ np.clip((e['frac_pos'] - 0.5) / 0.45, 0, 1)
342
+ * np.clip(e['gap_frac'] / 0.75, 0, 1)
343
+ * np.clip(e['snr'] / 4.0, 0, 1)
344
+ * np.clip(1.0 - abs(e['count_ratio'] - 1.0) / 0.16, 0, 1)
345
+ * np.clip(e['coherence'] / 0.7, 0, 1))
346
+ e['verdict'] = 'measured'
347
+ diag_k[k] = e
348
+ out['diag']['k'] = diag_k
349
+ out['diag']['f_raw_tpi'] = float(f_raw)
350
+ out['diag']['px_per_inch'] = float(px_per_inch)
351
+
352
+ def usable(k):
353
+ e = diag_k.get(k, {})
354
+ return e.get('snapped') and not e.get('resolution_blocked')
355
+
356
+ # scores: continuous verification quality per k (for reporting)
357
+ for k, e in diag_k.items():
358
+ s = e.get('stripe_score', 0.0)
359
+ if k >= 3 and usable(k):
360
+ s = max(s, float(np.clip(e['coherence'] / 0.7, 0, 1)
361
+ * np.clip(e['snr'] / 4.0, 0, 1)
362
+ * np.clip(1 - abs(e['count_ratio'] - 1) / 0.06, 0, 1)))
363
+ out['scores'][k] = round(float(s), 3)
364
+
365
+ blocked_strong = [k for k, e in diag_k.items()
366
+ if e.get('resolution_blocked')
367
+ and e.get('rel_amp', 0.0) > BLOCKED_REL]
368
+
369
+ # ---- decision ---------------------------------------------------- #
370
+ # (A) pair detector first: the crown/gap rate says how many yarns
371
+ # per f_raw unit are physically countable in the pixels.
372
+ if R >= RATE_FIRE:
373
+ k_R = 2 if R < RATE_K3 else (3 if R < RATE_K4 else 4)
374
+ k_R = min(k_R, kmax)
375
+ e = diag_k.get(k_R, {})
376
+ if usable(k_R):
377
+ out['best_k'] = int(k_R)
378
+ out['scores'][k_R] = max(out['scores'][k_R],
379
+ round(float(np.clip((R - 1.1) / 0.6, 0, 1)), 3))
380
+ out['confidence'] = float(np.clip(
381
+ 0.45 + 0.25 * min((R - RATE_FIRE) / 0.4, 1.0)
382
+ + 0.30 * e.get('stripe_score', 0.0), 0.0, 1.0))
383
+ out['diag']['path'] = f'pair-rate (crown rate {R:.2f}x f_raw)'
384
+ else:
385
+ out['abstain'] = True
386
+ out['diag']['reason'] = (f'crown rate {R:.2f}x f_raw implies k={k_R} '
387
+ f'but that candidate is '
388
+ + ('aliased' if diag_k.get(k_R, {}).get(
389
+ 'resolution_blocked') else 'not a spectral peak'))
390
+ return out
391
+ if R >= RATE_GRAY:
392
+ out['abstain'] = True
393
+ out['diag']['reason'] = f'crown rate {R:.2f}x f_raw is ambiguous'
394
+ return out
395
+
396
+ # (B) motif-comb detector, finest k >= 3 that passes all checks
397
+ near = []
398
+ for k in range(min(kmax, 4), 2, -1):
399
+ e = diag_k.get(k, {})
400
+ if not usable(k) or 'snr' not in e or e['ppt'] < MOTIF_MIN_PPT:
401
+ continue
402
+ cnt_ok = abs(e['count_ratio'] - 1.0) <= MOTIF_CNT_TOL
403
+ if (e['snr'] >= MOTIF_SNR_MIN and e['coherence'] >= MOTIF_COH_MIN
404
+ and cnt_ok and e['rel_amp'] >= MOTIF_REL_MIN):
405
+ out['best_k'] = int(k)
406
+ out['confidence'] = float(np.clip(
407
+ 0.35 + 0.35 * min((e['coherence'] - MOTIF_COH_MIN) / 0.25, 1.0)
408
+ + 0.30 * min(e['snr'] / 5.0, 1.0), 0.0, 1.0))
409
+ out['diag']['path'] = (f'motif-comb (k={k}: coh={e["coherence"]:.2f} '
410
+ f'snr={e["snr"]:.1f} cnt={e["count_ratio"]:.3f})')
411
+ return out
412
+ if (e['snr'] >= MOTIF_SNR_MIN and cnt_ok
413
+ and e['coherence'] >= MOTIF_COH_GRAY
414
+ and e['rel_amp'] >= MOTIF_REL_MIN):
415
+ near.append(k)
416
+ if near:
417
+ out['abstain'] = True
418
+ out['diag']['reason'] = f'ambiguous: motif candidate k={near} near-pass'
419
+ return out
420
+ if blocked_strong:
421
+ out['abstain'] = True
422
+ out['diag']['reason'] = (f'k={blocked_strong} has strong band energy but '
423
+ f'aliases (<{MIN_PPT} px/thread)')
424
+ return out
425
+
426
+ # k = 1: keep f_raw; abstain only if even f_raw fails to verify
427
+ base = diag_k.get(1, {})
428
+ weak = (base.get('stripe_score', 0.0) < 0.05
429
+ and base.get('frac_pos', 1.0) < 0.6)
430
+ out['best_k'] = 1
431
+ out['abstain'] = bool(weak)
432
+ out['confidence'] = 0.0 if weak else \
433
+ float(np.clip(base.get('stripe_score', 0.0), 0.05, 1.0))
434
+ out['diag']['path'] = 'k=1 (no pair rate, no motif comb)'
435
+ if weak:
436
+ out['diag']['reason'] = 'even f_raw does not verify against pixels'
437
+ return out
438
+ except Exception as ex: # referee must never crash
439
+ out['abstain'] = True
440
+ out['diag']['reason'] = f'error: {type(ex).__name__}: {ex}'
441
+ return out
442
+
443
+
referee_twm.py ADDED
@@ -0,0 +1,411 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """referee_twm -- Two-Way Mismatch (TWM) sub-multiple referee for thread counting.
2
+
3
+ Given a calibrated fabric crop and the FFT counter's reading f_raw (threads per
4
+ inch), decide which multiple k in {1..kmax} of f_raw is the true thread
5
+ frequency. Adapted from Maher & Beauchamp (1994) two-way mismatch pitch
6
+ scoring, with domain-specific modifications for woven fabric:
7
+
8
+ * Spectrum: Welch-style strip averaging. The crop is cut into strips
9
+ PERPENDICULAR to the counting axis (for axis='epi', horizontal bands of
10
+ 24 rows, 50% overlap), each strip is averaged to a 1-D profile along the
11
+ counting axis, detrended, Hann-windowed, FFT'd, and the POWER spectra are
12
+ averaged. This survives the phase drift / thread crossing that washes
13
+ out a single full-crop FFT. Salience = power / smooth spectral floor
14
+ (median filter of log power), so peaks are comparable across frequency.
15
+
16
+ * Candidates ft = k*f0 (f0 = f_raw snapped to the nearest strong measured
17
+ peak). Each candidate is scored with a two-way penalty:
18
+ (a) predicted->measured: comb teeth m*ft with no matching measured peak
19
+ are penalised (missing teeth, 1/m weighted), matched teeth earn an
20
+ amplitude reward;
21
+ (b) measured->predicted: measured peaks the comb does not explain are
22
+ penalised, dominated by energy at the candidate's HALF-POSITIONS
23
+ (m-0.5)*ft -- a genuine local-max there means the true comb spacing
24
+ is finer than ft, i.e. ft is an overtone, not the fundamental.
25
+
26
+ * Grouping excuse (the key fabric subtlety): paired/grouped threads put
27
+ genuine energy on f_raw's own harmonic series, so a half-position or
28
+ unexplained peak that coincides with an integer multiple of f0 gets only
29
+ a REDUCED penalty (beta), and anything at/below ~f0 itself (pair rate,
30
+ motif combs below the reading) is excused entirely. Discrimination
31
+ therefore comes from the HIGH-frequency half-positions (1.5*ft, 2.5*ft,
32
+ ...) that no grouping process can produce for the true fundamental.
33
+
34
+ * Peaks on the f0/2, f0/3, f0/4 sub-grids (weave-motif combs) get a reduced
35
+ unexplained-energy penalty for every candidate (motif combs are sub-combs
36
+ of the true thread rate and carry no k information by themselves).
37
+
38
+ If the candidates are not clearly separated the referee ABSTAINS (caller
39
+ keeps f_raw, i.e. k=1), which is always safe.
40
+
41
+ numpy/scipy only; << 2 s per call on CPU.
42
+ """
43
+ from __future__ import annotations
44
+
45
+ import time
46
+
47
+ import numpy as np
48
+ from scipy import ndimage, signal
49
+
50
+ # ---------------------------------------------------------------------------
51
+ # Tunable parameters (validated on the 2026-07-02 bucket ground-truth table).
52
+ # ---------------------------------------------------------------------------
53
+ PARAMS = dict(
54
+ strip_rows=24, # strip height (perpendicular to counting axis)
55
+ pad_factor=4, # FFT zero-pad factor for finer bin spacing
56
+ floor_tpi=45.0, # width (threads/inch) of the median spectral floor
57
+ s_min=2.2, # minimum salience for a peak to exist at all
58
+ f0_snap_rel=0.07, # snap f_raw to a measured peak within +-7%
59
+ tol_rel=0.04, # match tolerance, fraction of the position
60
+ tol_bins=3.0, # ... but at least this many FFT bins
61
+ grid_tol=0.05, # on-grid test tolerance, fraction of f0
62
+ low_lim=1.15, # positions below low_lim*f0 are grouping-excused
63
+ beta=0.10, # reduced penalty: half-position on f0's own grid
64
+ beta_sub=0.25, # reduced penalty: unexplained peak on motif sub-grid
65
+ m_teeth_max=6, # max comb teeth evaluated per candidate
66
+ fmax_mult=7.2, # evaluate spectrum up to fmax_mult*f0 (or 0.9 Nyq)
67
+ w_miss=1.00, # weight: missing-teeth penalty
68
+ w_rew=1.00, # weight: matched-teeth amplitude reward
69
+ w_half=6.00, # weight: half-position (unexplained comb) penalty
70
+ w_unex=0.60, # weight: other unexplained measured peaks
71
+ c_prior=0.22, # complexity prior per unit of (k-1)
72
+ r_pair=0.78, # missing-teeth relief for k=2 under pair evidence
73
+ pe_scale=0.21, # pair-evidence normalisation (relative amplitude)
74
+ pe_gate=0.16, # min pair evidence to accept a tooth-less k=2
75
+ margin_abstain=0.09, # abstain if best_k>1 wins by less than this
76
+ tooth1_sal=3.0, # min fundamental-tooth salience to accept k>1
77
+ min_signal=1e-5, # min crop std (guards flat / numerically dead input)
78
+ conf_scale=0.15, # margin -> confidence squashing scale
79
+ # -- secondary paired-thread route (see _paired_override) --
80
+ rich_h2=5.0, # min raw salience of a true local max at 2*f0
81
+ rich_h3=2.8, # min raw salience of a true local max at 3*f0
82
+ rich_env=1.35, # min S_env(2*f0)/S_env(f0) envelope ratio
83
+ )
84
+
85
+
86
+ # ---------------------------------------------------------------------------
87
+ # Spectrum estimation
88
+ # ---------------------------------------------------------------------------
89
+ def _welch_salience(crop, px_per_inch, axis, p=None, square=False):
90
+ """Welch strip-averaged power spectrum + salience along the counting axis.
91
+
92
+ Returns (freqs_tpi, salience, power). Strips are perpendicular to the
93
+ counting axis: axis='epi' -> horizontal bands averaged to profiles along
94
+ X; axis='ppi' -> vertical bands averaged to profiles along Y.
95
+ square=True computes the ENVELOPE spectrum (profiles squared before the
96
+ FFT): grouping/intermodulation puts envelope energy at the thread rate.
97
+ """
98
+ p = p or PARAMS
99
+ img = np.asarray(crop, dtype=np.float64)
100
+ if axis == 'ppi':
101
+ img = img.T # rows of `img` now run along the counting axis
102
+ H, W = img.shape
103
+ strip = int(min(p['strip_rows'], max(4, H // 4)))
104
+ step = max(1, strip // 2)
105
+ n = int(2 ** np.ceil(np.log2(max(W * p['pad_factor'], 64))))
106
+ win = np.hanning(W)
107
+ acc = np.zeros(n // 2 + 1)
108
+ cnt = 0
109
+ for y0 in range(0, H - strip + 1, step):
110
+ prof = img[y0:y0 + strip].mean(axis=0)
111
+ if square:
112
+ prof = (prof - prof.mean()) ** 2
113
+ prof = signal.detrend(prof)
114
+ acc += np.abs(np.fft.rfft(prof * win, n)) ** 2
115
+ cnt += 1
116
+ P = acc / max(cnt, 1)
117
+ freqs = np.fft.rfftfreq(n, d=1.0) * float(px_per_inch)
118
+ # salience: power over a smooth floor (median filter in the log domain)
119
+ df = freqs[1] - freqs[0]
120
+ wbins = max(5, int(round(p['floor_tpi'] / df)) | 1)
121
+ logP = np.log(P + 1e-300)
122
+ floor = ndimage.median_filter(logP, size=wbins, mode='nearest')
123
+ S = np.exp(logP - floor)
124
+ return freqs, S, P
125
+
126
+
127
+ def _extract_peaks(freqs, S, fmin, fmax, p=None):
128
+ """Local maxima of the salience spectrum with parabolic refinement.
129
+
130
+ Returns list of (f_tpi, salience) sorted by frequency.
131
+ """
132
+ p = p or PARAMS
133
+ df = freqs[1] - freqs[0]
134
+ band = (freqs >= fmin) & (freqs <= fmax)
135
+ idx = np.where(band)[0]
136
+ if len(idx) < 5:
137
+ return []
138
+ dist = max(2, int(round(1.5 / df)))
139
+ pk, _ = signal.find_peaks(S[idx], height=p['s_min'], distance=dist)
140
+ out = []
141
+ logS = np.log(S + 1e-300)
142
+ for j in idx[pk]:
143
+ if 1 <= j < len(S) - 1:
144
+ a, b, c = logS[j - 1], logS[j], logS[j + 1]
145
+ den = a - 2 * b + c
146
+ delta = 0.5 * (a - c) / den if abs(den) > 1e-12 else 0.0
147
+ delta = float(np.clip(delta, -0.5, 0.5))
148
+ else:
149
+ delta = 0.0
150
+ out.append((float(freqs[j] + delta * df), float(S[j])))
151
+ out.sort()
152
+ return out
153
+
154
+
155
+ # ---------------------------------------------------------------------------
156
+ # TWM comb scoring on the measured peak list
157
+ # ---------------------------------------------------------------------------
158
+ def _nearest_peak(peaks, pos, tol):
159
+ """Strongest peak within +-tol of pos; returns (f, sal) or None."""
160
+ best = None
161
+ for f, s in peaks:
162
+ if abs(f - pos) <= tol and (best is None or s > best[1]):
163
+ best = (f, s)
164
+ return best
165
+
166
+
167
+ def _on_grid(f, base, tol):
168
+ r = f / base
169
+ return abs(f - round(r) * base) <= tol and round(r) >= 1
170
+
171
+
172
+ def _score_candidates(peaks, f0, kmax, fmax, df, p=None):
173
+ """Score candidates ft=k*f0 (lower = better) from the peak list."""
174
+ p = p or PARAMS
175
+ s_min = p['s_min']
176
+ amp = {f: np.log(s / s_min) for f, s in peaks if s > s_min}
177
+ a_max = max(amp.values()) if amp else 1.0
178
+ a_max = max(a_max, 1e-6)
179
+ tol_abs = p['tol_bins'] * df
180
+ grid_tol = max(p['grid_tol'] * f0, tol_abs)
181
+
182
+ # Pair evidence: genuine local maxima at BOTH 0.5*f0 and 1.5*f0 mean the
183
+ # measured comb's base spacing is f0/2 (paired/grouped threads with f_raw
184
+ # at the pair rate). A quarter-offset doublet then has a form-factor
185
+ # NULL at the true thread rate 2*f0, so k=2 must not be punished for the
186
+ # absent tooth: its missing-teeth penalty is relieved by pair_ev.
187
+ def _pk_amp(pos):
188
+ hit = _nearest_peak(peaks, pos, max(p['tol_rel'] * pos, tol_abs))
189
+ return (amp.get(hit[0], 0.0) / a_max) if hit else 0.0
190
+
191
+ pair_ev = min(_pk_amp(0.5 * f0), _pk_amp(1.5 * f0))
192
+ pair_relief = p['r_pair'] * min(1.0, pair_ev / p['pe_scale'])
193
+
194
+ scores, terms = {}, {}
195
+ for k in range(1, kmax + 1):
196
+ ft = k * f0
197
+ if ft > fmax:
198
+ scores[k] = float('inf')
199
+ terms[k] = {'invalid': True}
200
+ continue
201
+ M = int(min(p['m_teeth_max'], max(1, np.floor(fmax / ft))))
202
+ wsum = sum(1.0 / m for m in range(1, M + 1))
203
+
204
+ # --- (a) predicted -> measured: teeth ------------------------------
205
+ t_miss = t_rew = 0.0
206
+ tooth_windows = []
207
+ tooth1_sal = 0.0
208
+ for m in range(1, M + 1):
209
+ pos = m * ft
210
+ tol = max(p['tol_rel'] * pos, tol_abs)
211
+ tooth_windows.append((pos - tol, pos + tol))
212
+ hit = _nearest_peak(peaks, pos, tol)
213
+ if hit is None:
214
+ t_miss += 1.0 / m
215
+ else:
216
+ t_rew += (1.0 / m) * (amp.get(hit[0], 0.0) / a_max)
217
+ if m == 1:
218
+ tooth1_sal = hit[1]
219
+ t_miss /= wsum
220
+ t_rew /= wsum
221
+ if k == 2:
222
+ t_miss *= (1.0 - pair_relief)
223
+
224
+ # --- (b) measured -> predicted: half-positions ---------------------
225
+ half_windows = []
226
+ t_half = 0.0
227
+ vsum = 0.0
228
+ j = 0
229
+ while True:
230
+ j += 1
231
+ pos = (j - 0.5) * ft
232
+ if pos > fmax or j > M + 1:
233
+ break
234
+ v = 1.0 / j
235
+ vsum += v
236
+ tol = max(p['tol_rel'] * pos, tol_abs)
237
+ half_windows.append((pos - tol, pos + tol))
238
+ hit = _nearest_peak(peaks, pos, tol)
239
+ if hit is None:
240
+ continue
241
+ a = amp.get(hit[0], 0.0) / a_max
242
+ if hit[0] <= p['low_lim'] * f0:
243
+ excuse = 0.0 # pair/motif energy at or below f_raw
244
+ elif _on_grid(hit[0], f0, grid_tol):
245
+ excuse = p['beta'] # on f_raw's own harmonic series
246
+ else:
247
+ excuse = 1.0 # genuine contradiction
248
+ t_half += v * excuse * a
249
+ t_half /= max(vsum, 1e-9)
250
+
251
+ # --- (b') other unexplained measured peaks -------------------------
252
+ t_unex = 0.0
253
+ for f, s in peaks:
254
+ if f <= p['low_lim'] * f0 or f > fmax:
255
+ continue
256
+ if any(lo <= f <= hi for lo, hi in tooth_windows):
257
+ continue
258
+ if any(lo <= f <= hi for lo, hi in half_windows):
259
+ continue
260
+ u = 1.0
261
+ if _on_grid(f, f0, grid_tol):
262
+ u = p['beta']
263
+ else:
264
+ for q in (2, 3, 4): # weave-motif sub-grids
265
+ if _on_grid(f, f0 / q, max(p['grid_tol'] * f0 / q, tol_abs)):
266
+ u = p['beta_sub']
267
+ break
268
+ t_unex += u * (amp.get(f, 0.0) / a_max)
269
+ t_unex = min(t_unex / 3.0, 1.2)
270
+
271
+ sc = (p['c_prior'] * (k - 1)
272
+ + p['w_miss'] * t_miss
273
+ - p['w_rew'] * t_rew
274
+ + p['w_half'] * t_half
275
+ + p['w_unex'] * t_unex)
276
+ scores[k] = float(sc)
277
+ terms[k] = {'miss': round(float(t_miss), 4), 'rew': round(float(t_rew), 4),
278
+ 'half': round(float(t_half), 4), 'unex': round(float(t_unex), 4),
279
+ 'tooth1': tooth1_sal > 0, 'tooth1_sal': round(float(tooth1_sal), 2),
280
+ 'M': M}
281
+ return scores, terms, pair_ev
282
+
283
+
284
+ def _paired_override(crop, px_per_inch, axis, peaks, f0, df, p):
285
+ """Secondary paired-thread route (evaluated only when the comb score
286
+ already picked k=1): plain pairing with NO sub-comb (f_raw = pair rate,
287
+ all comb teeth on f_raw's grid) is invisible to the two-way mismatch --
288
+ the k=1 comb explains every peak. The residual signature of pairing is
289
+ (a) genuine, strong local maxima at BOTH 2*f0 and 3*f0 in the raw
290
+ spectrum (the pair comb's form factor keeps high teeth alive, unlike the
291
+ fast harmonic decay of a smooth single-thread profile), AND
292
+ (b) the ENVELOPE spectrum (squared profiles) putting more energy at 2*f0
293
+ than at f0 (thread-scale energy dominates the local-energy signal).
294
+ All three thresholds must hold; on the validation controls the closest
295
+ one fails by >=1.5x. Returns (fires, diag_dict)."""
296
+ tol_abs = p['tol_bins'] * df
297
+ h2 = _nearest_peak(peaks, 2 * f0, max(p['tol_rel'] * 2 * f0, tol_abs))
298
+ h3 = _nearest_peak(peaks, 3 * f0, max(p['tol_rel'] * 3 * f0, tol_abs))
299
+ d = {'h2_sal': round(h2[1], 2) if h2 else 0.0,
300
+ 'h3_sal': round(h3[1], 2) if h3 else 0.0, 'env_ratio': 0.0}
301
+ if h2 is None or h3 is None or h2[1] < p['rich_h2'] or h3[1] < p['rich_h3']:
302
+ return False, d
303
+ freqs, S_env, _ = _welch_salience(crop, px_per_inch, axis, p, square=True)
304
+ def _env_at(pos):
305
+ pk = _extract_peaks(freqs, S_env, pos * 0.9, pos * 1.1, p)
306
+ hit = _nearest_peak(pk, pos, max(p['tol_rel'] * pos, tol_abs))
307
+ return hit[1] if hit else 0.0
308
+ e1, e2 = _env_at(f0), _env_at(2 * f0)
309
+ d['env_ratio'] = round(e2 / max(e1, 1e-9), 2)
310
+ return bool(e2 >= p['rich_env'] * max(e1, p['s_min'])), d
311
+
312
+
313
+ # ---------------------------------------------------------------------------
314
+ # Public interface
315
+ # ---------------------------------------------------------------------------
316
+ def score_k(crop, px_per_inch, f_raw, axis, kmax=4):
317
+ """crop: 2-D float32 array 0..1 (calibrated, flat-fielded; warp threads vertical).
318
+ px_per_inch: float. f_raw: float threads/inch (the counter's current reading).
319
+ axis: 'epi' (periodicity along X) or 'ppi' (periodicity along Y).
320
+ Returns dict: {'best_k': int>=1, 'abstain': bool, 'confidence': float 0..1,
321
+ 'scores': {k: float}, 'diag': dict} -- lower score = better.
322
+ Must run < 2 s on CPU, numpy/scipy only."""
323
+ t0 = time.time()
324
+ p = PARAMS
325
+
326
+ def _bail(reason):
327
+ return {'best_k': 1, 'abstain': True, 'confidence': 0.0,
328
+ 'scores': {1: 0.0},
329
+ 'diag': {'reason': reason, 'runtime_s': time.time() - t0}}
330
+
331
+ crop = np.asarray(crop)
332
+ if (crop.ndim != 2 or min(crop.shape) < 64 or axis not in ('epi', 'ppi')
333
+ or not np.isfinite(f_raw) or f_raw <= 0 or px_per_inch <= 0):
334
+ return _bail('degenerate input')
335
+ if not np.all(np.isfinite(crop)) or float(np.std(crop)) < p['min_signal']:
336
+ return _bail('no usable signal in crop')
337
+
338
+ freqs, S, _P = _welch_salience(crop, px_per_inch, axis, p)
339
+ nyq = freqs[-1]
340
+ df = freqs[1] - freqs[0]
341
+ fmax = min(0.90 * nyq, p['fmax_mult'] * f_raw)
342
+ if 1.0 * f_raw > fmax:
343
+ return _bail('f_raw too close to Nyquist')
344
+
345
+ peaks = _extract_peaks(freqs, S, max(3.5, 6 * df), fmax, p)
346
+ if not peaks:
347
+ return _bail('no spectral peaks')
348
+
349
+ # snap f_raw to the strongest nearby measured peak (counter quantisation)
350
+ f0 = float(f_raw)
351
+ cand = [(s, f) for f, s in peaks
352
+ if abs(f - f_raw) <= p['f0_snap_rel'] * f_raw and s >= 2.5]
353
+ if cand:
354
+ f0 = max(cand)[1]
355
+
356
+ kmax_eff = max(1, int(kmax))
357
+ scores, terms, pair_ev = _score_candidates(peaks, f0, kmax_eff, fmax, df, p)
358
+
359
+ valid = {k: v for k, v in scores.items() if np.isfinite(v)}
360
+ if not valid:
361
+ return _bail('no valid candidates')
362
+ order = sorted(valid, key=valid.get)
363
+ best_k = order[0]
364
+ margin = (valid[order[1]] - valid[order[0]]) if len(order) > 1 else 1.0
365
+
366
+ # Acceptance gate: a k>1 verdict needs a clear win AND positive evidence
367
+ # (a solid fundamental tooth of its own, or -- for k=2 only -- pair-comb
368
+ # evidence explaining the form-factor null at the thread rate).
369
+ evidence_ok = True
370
+ if best_k > 1:
371
+ evidence_ok = bool(terms[best_k].get('tooth1_sal', 0.0) >= p['tooth1_sal']
372
+ or (best_k == 2 and pair_ev >= p['pe_gate']))
373
+ abstain = bool(best_k > 1
374
+ and (margin < p['margin_abstain'] or not evidence_ok))
375
+ confidence = float(np.clip(1.0 - np.exp(-margin / p['conf_scale']), 0, 1))
376
+
377
+ # Secondary route: plain pairing without a sub-comb is transparent to the
378
+ # comb mismatch (the k=1 comb explains every measured peak), so when the
379
+ # primary verdict is k=1, check the paired-thread signature explicitly.
380
+ pair_route = {}
381
+ if best_k == 1 and kmax_eff >= 2 and 2 * f0 <= fmax:
382
+ fires, pair_route = _paired_override(crop, px_per_inch, axis,
383
+ peaks, f0, df, p)
384
+ if fires:
385
+ best_k, abstain = 2, False
386
+ confidence = 0.4 # rule-based route: modest fixed confidence
387
+ pair_route['fired'] = True
388
+
389
+ if abstain:
390
+ confidence = min(confidence, 0.25)
391
+
392
+ diag = {
393
+ 'f0_refined': round(f0, 2),
394
+ 'pair_evidence': round(float(pair_ev), 3),
395
+ 'pair_route': pair_route,
396
+ 'nyquist_tpi': round(float(nyq), 1),
397
+ 'fmax_eval': round(float(fmax), 1),
398
+ 'n_peaks': len(peaks),
399
+ 'peaks': [(round(f, 1), round(s, 1))
400
+ for f, s in sorted(peaks, key=lambda t: -t[1])[:15]],
401
+ 'terms': terms,
402
+ 'margin': round(float(margin), 4),
403
+ 'runtime_s': round(time.time() - t0, 3),
404
+ }
405
+ return {'best_k': int(best_k), 'abstain': abstain,
406
+ 'confidence': round(confidence, 3),
407
+ 'scores': {k: (round(v, 4) if np.isfinite(v) else float('inf'))
408
+ for k, v in scores.items()},
409
+ 'diag': diag}
410
+
411
+
requirements.txt ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ fastapi>=0.110
2
+ uvicorn[standard]>=0.27
3
+ python-multipart>=0.0.9
4
+ numpy>=1.24
5
+ scipy>=1.10
6
+ pillow>=10.0
7
+ pillow-heif>=0.15
8
+ # --- article recognition (frozen DINOv2 embedding, CPU inference) ---
9
+ # NOTE: torch + torchvision are installed in the Dockerfile from the CPU wheel
10
+ # index (matching versions). They are intentionally NOT listed here, so this
11
+ # requirements install never pulls a default-index (CUDA / mismatched) build
12
+ # over them — a mismatch causes "operator torchvision::nms does not exist".
13
+ timm>=1.0
14
+ # persistence sync to the HF bucket (the standalone `hf` CLI is also installed
15
+ # in the Dockerfile; this provides the python lib + a CLI fallback).
16
+ huggingface_hub[cli]>=0.26
robust_tick.py ADDED
@@ -0,0 +1,344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """TASK 3 — ROBUST ruler-tick detector that RESOLVES the dyadic (x2) tick-mm
2
+ ambiguity that production epi_ppi_v5.detect_calibration() suffers from.
3
+
4
+ robust_detect_tick(gray) -> (tick_mm, px_per_inch)
5
+
6
+ WHY production fails (see tmp/scale_diagnose.py output):
7
+ Production keys mm-per-tick off ratio = digit_span_px / tick_period_px with a
8
+ bucket {10:1mm, 20:0.5mm, 25.4/50.8:inch} and a brittle 10% tolerance. Two
9
+ independent flaky measurements feed that ratio:
10
+ * tick_period_px (ACF) sometimes locks a MAJOR graduation (cm / half-cm) or a
11
+ x2 harmonic instead of the finest minor tick;
12
+ * digit_span_px / n_digits is the OUTER-pair span divided by (n_digits-1);
13
+ one mis-counted / mis-located digit cluster doubles or halves it.
14
+ The same fabric therefore flips between 1mm and 0.5mm across its photos -> x2
15
+ px/inch -> x2 thread count.
16
+
17
+ THE ROBUST IDEA (no folding — correct detection):
18
+ ticks-per-centimetre is the physically discrete, dyadic-separated quantity:
19
+ a cm ruler has either 10 (1mm) or 20 (0.5mm) minor ticks per cm. We estimate it
20
+ two INDEPENDENT ways and cross-check, then SNAP to {10, 20} (or inch {25.4,
21
+ 50.8}). Because 10 and 20 are a clean factor of 2 apart, a roughly-right estimate
22
+ lands unambiguously on one of them.
23
+
24
+ A. ruler-internal: px_per_cm / tick_period_px
25
+ - tick_period_px from the ACF tick comb, taking the FINEST consistent comb
26
+ lag (resolve the every-other-tick harmonic: if a lag ~ 2x a stronger
27
+ sub-lag also peaks, prefer the finer sub-lag).
28
+ - px_per_cm from the MEDIAN consecutive digit gap (robust to one bad digit),
29
+ not outer-span/(n-1).
30
+ B. plausibility prior: the fabric's own dominant thread frequency must give a
31
+ sane apparel count (EPI/PPI ~ 40-220) at the chosen scale. When A is
32
+ borderline, B breaks the tie (the wrong scale pushes the count x2 out of
33
+ band on at least one axis for most real fabric).
34
+
35
+ px_per_inch is then tick_period_px / tick_mm * 25.4 — the px/inch still scales
36
+ with photo zoom (that is REAL and expected); only tick_mm is forced consistent.
37
+
38
+ Pure numpy/scipy + reuse of production v5 *read-only* helpers (we import them but
39
+ never modify epi_ppi_v5 / ruler_freq).
40
+ """
41
+ from __future__ import annotations
42
+ import sys, os, io, contextlib
43
+ sys.path.insert(0, "/scratch/user/uqabeniw/fabric")
44
+ sys.path.insert(0, "/scratch/user/uqabeniw/fabric/thread_counter")
45
+ import numpy as np
46
+ from scipy import ndimage, signal
47
+ from numpy.fft import fftshift, fftfreq
48
+ import epi_ppi_v5 as v5
49
+
50
+ # apparel plausibility band (threads/inch) for the plausibility-prior tie-break.
51
+ PLAUSIBLE_LO, PLAUSIBLE_HI = 38.0, 230.0
52
+ # typical apparel WEFT (PPI) density centre, threads/inch. The truth-table real
53
+ # fabrics have PPI ~42-110 (geo-centre ~68); the correct dyadic scale puts the
54
+ # weft count near here, the wrong one x2 away. Used by the plausibility prior.
55
+ APPAREL_CENTRE = 70.0
56
+ # snap targets: ticks-per-unit for (mm_per_tick, scale_unit)
57
+ # cm: 10 ticks/cm (1mm) or 20 ticks/cm (0.5mm)
58
+ # inch: 25.4 ticks/in (1mm) or 50.8 ticks/in (0.5mm)
59
+ _SNAP = [
60
+ (10.0, 1.0, "cm"),
61
+ (20.0, 0.5, "cm"),
62
+ (25.4, 1.0, "inch"),
63
+ (50.8, 0.5, "inch"),
64
+ ]
65
+
66
+
67
+ # ---------------------------------------------------------------------------- #
68
+ # ruler localisation + finest-tick comb
69
+ # ---------------------------------------------------------------------------- #
70
+ def _find_ruler_zone(gray):
71
+ """Reuse production calibration ONLY to localise the ruler band + a tick_period
72
+ seed + digit info. We then RE-DERIVE tick_mm ourselves."""
73
+ with contextlib.redirect_stdout(io.StringIO()):
74
+ c = v5.detect_calibration(gray) # auto; we ignore its tick_mm decision
75
+ return c
76
+
77
+
78
+ def _finest_tick_period(gray, y_zone):
79
+ """ACF of the ruler strip; return the FINEST consistent comb lag (px between
80
+ adjacent minor ticks), resolving the every-other-tick (x2) harmonic.
81
+
82
+ Strategy: collect all prominent ACF peak lags. The true minor-tick period is
83
+ the smallest lag L such that a comb {L, 2L, 3L, ...} explains the strong peaks
84
+ (i.e. the larger peaks are near-integer multiples of L). This rejects the case
85
+ where the ACF's first strong peak is actually a major graduation (2x or 5x the
86
+ minor tick)."""
87
+ y0, y1 = y_zone
88
+ sub = gray[max(0, y0):y1, :]
89
+ if sub.shape[0] < 3:
90
+ return float("nan")
91
+ col_min = sub.min(axis=0)
92
+ p = 1.0 - col_min
93
+ p = p - p.mean()
94
+ if p.std() < 1e-6:
95
+ return float("nan")
96
+ ac = np.correlate(p, p, mode="full")[p.size - 1:]
97
+ ac = ac / (ac[0] + 1e-9)
98
+ lo, hi = 4, min(220, ac.size - 2)
99
+ if hi <= lo + 2:
100
+ return float("nan")
101
+ seg = ac[lo:hi]
102
+ peaks, props = signal.find_peaks(seg, height=0.06, prominence=0.04)
103
+ if not peaks.size:
104
+ return float("nan")
105
+ lags = lo + peaks
106
+ heights = seg[peaks]
107
+
108
+ def _sub_pixel(lag_idx):
109
+ k = lag_idx - lo
110
+ if 1 <= k < seg.size - 1:
111
+ a, b, c = seg[k-1], seg[k], seg[k+1]
112
+ den = a - 2*b + c
113
+ d = 0.5*(a-c)/den if abs(den) > 1e-12 else 0.0
114
+ return lag_idx + float(np.clip(d, -1, 1))
115
+ return float(lag_idx)
116
+
117
+ # candidate fundamentals: every detected lag, smallest first
118
+ order = np.argsort(lags)
119
+ lags_s = lags[order]
120
+ cand_best = None
121
+ for L in lags_s:
122
+ if L < 5:
123
+ continue
124
+ # how much comb energy sits at multiples of L?
125
+ score = 0.0
126
+ nmatch = 0
127
+ for lag, h in zip(lags, heights):
128
+ r = lag / L
129
+ nr = round(r)
130
+ if nr >= 1 and abs(r - nr) <= 0.12: # within 12% of an integer multiple
131
+ score += h
132
+ nmatch += 1
133
+ # prefer the smallest L that explains >=2 comb members with strong energy
134
+ if nmatch >= 2 and score > 0:
135
+ # bias toward more comb members & higher captured energy
136
+ quality = score * (1.0 + 0.15 * nmatch)
137
+ if cand_best is None or quality > cand_best[1] * 1.05:
138
+ cand_best = (L, quality)
139
+ if cand_best is None:
140
+ # single isolated peak: take the strongest
141
+ L = lags[int(np.argmax(heights))]
142
+ return _sub_pixel(int(L))
143
+ return _sub_pixel(int(cand_best[0]))
144
+
145
+
146
+ def _robust_px_per_unit(gray, calib):
147
+ """px between consecutive printed digits = px per cm (cm ruler) or px per inch
148
+ (inch ruler). Use the MEDIAN consecutive gap (robust to one mis-located digit),
149
+ not the outer span / (n-1). Returns (px_per_unit, n_digits) or (nan, 0)."""
150
+ H, W = gray.shape
151
+ if calib.ruler_pos == "top":
152
+ search_ys = [(0.0, 0.15), (0.0, 0.35)]
153
+ else:
154
+ search_ys = [(0.85, 1.0), (0.65, 1.0)]
155
+ best = (float("nan"), 0)
156
+ for sy in search_ys:
157
+ y0, y1 = int(H*sy[0]), int(H*sy[1])
158
+ region = gray[y0:y1, :]
159
+ col_dark = (1.0 - region).sum(axis=0)
160
+ sigma = max(25.0, W * 0.05)
161
+ sm = ndimage.gaussian_filter1d(col_dark, sigma=sigma)
162
+ bl = ndimage.uniform_filter1d(sm, size=max(51, int(sigma * 8)))
163
+ sig = sm - bl
164
+ peaks, props = signal.find_peaks(
165
+ sig, prominence=max(0.5, 0.05 * sig.max()),
166
+ distance=max(60, int(sigma * 3)))
167
+ if len(peaks) < 2:
168
+ continue
169
+ prom = props["prominences"]
170
+ med = float(np.median(prom))
171
+ strong = peaks[prom >= max(med * 0.5, 0.5)]
172
+ if strong.size < 2:
173
+ strong = peaks
174
+ pos = np.sort(strong)
175
+ gaps = np.diff(pos)
176
+ if gaps.size == 0:
177
+ continue
178
+ # robust per-unit gap = median of consecutive gaps, but drop gaps that are
179
+ # ~2x the smallest (a skipped digit). Keep gaps within 35% of the median.
180
+ g = gaps.astype(float)
181
+ m0 = np.median(g)
182
+ keep = g[(g > 0.65 * m0) & (g < 1.5 * m0)]
183
+ per_unit = float(np.median(keep)) if keep.size else float(m0)
184
+ if per_unit > 0 and np.isfinite(per_unit):
185
+ best = (per_unit, int(strong.size))
186
+ break
187
+ return best
188
+
189
+
190
+ def _dominant_thread_count_per_px(gray, calib):
191
+ """Fabric ROI dominant thread spatial frequency (cycles/px) per axis. The
192
+ apparel count = freq_cpp * px_per_inch."""
193
+ try:
194
+ y0, y1, x0, x1 = v5.find_fabric_roi(gray, calib)
195
+ except Exception:
196
+ y0 = y1 = x0 = x1 = 0
197
+ H, W = gray.shape
198
+ if (y1 - y0) < 50 or (x1 - x0) < 50:
199
+ y0, y1, x0, x1 = int(H*.15), int(H*.82), int(W*.10), int(W*.90)
200
+ fab = gray[y0:y1, x0:x1]
201
+ if fab.size == 0:
202
+ return {"epi": float("nan"), "ppi": float("nan")}
203
+ blur = ndimage.gaussian_filter(fab, 15)
204
+ fab = fab / np.clip(blur, 1e-3, None)
205
+ p1, p99 = np.percentile(fab, [1, 99])
206
+ fab = np.clip((fab - p1) / max(p99 - p1, 1e-9), 0, 1)
207
+ F = v5._windowed_2d_fft(fab)
208
+ Hf, Wf = F.shape
209
+ cy, cx = Hf // 2, Wf // 2
210
+ b = 3
211
+ out = {}
212
+ for axis, (spec, frq) in (
213
+ ("epi", (F[cy-b:cy+b+1, :].sum(0), fftshift(fftfreq(Wf)))),
214
+ ("ppi", (F[:, cx-b:cx+b+1].sum(1), fftshift(fftfreq(Hf)))),
215
+ ):
216
+ # search a sane spatial band: 0.005..0.25 cycles/px
217
+ m = (frq > 0.005) & (frq < 0.25)
218
+ s = spec.copy()
219
+ s[~m] = 0.0
220
+ if not m.any() or s.max() <= 0:
221
+ out[axis] = float("nan")
222
+ continue
223
+ out[axis] = float(abs(frq[int(np.argmax(s))]))
224
+ return out
225
+
226
+
227
+ # ---------------------------------------------------------------------------- #
228
+ # main resolver
229
+ # ---------------------------------------------------------------------------- #
230
+ def robust_detect_tick(gray):
231
+ """Return (tick_mm, px_per_inch) with the dyadic tick ambiguity resolved.
232
+
233
+ gray: float32 image in [0,1] (same convention as v5.detect_calibration)."""
234
+ gray = np.asarray(gray, np.float32)
235
+ if gray.max() > 1.5: # accept 0..255 inputs too
236
+ gray = gray / 255.0
237
+ calib = _find_ruler_zone(gray)
238
+
239
+ # finest minor-tick period (px), harmonic-resolved
240
+ tick_px = _finest_tick_period(gray, calib.y_tick_zone)
241
+ if not (np.isfinite(tick_px) and tick_px > 0):
242
+ tick_px = calib.tick_period_px # fall back to production seed
243
+ if not (np.isfinite(tick_px) and tick_px > 0):
244
+ # no ruler -> degrade gracefully to production's own answer
245
+ return float(calib.tick_mm), float(calib.px_per_inch)
246
+
247
+ # px per printed unit (cm or inch), robust median digit gap
248
+ per_unit, n_dig = _robust_px_per_unit(gray, calib)
249
+
250
+ # ----- estimate A (RULER-INTERNAL): ticks per printed unit -> snap to a target.
251
+ # The 10<->20 decision boundary sits at log(sqrt2)=0.347. We record both the
252
+ # snapped scale AND a confidence: rel<0.10 = CONFIDENT (clean integer ticks/cm),
253
+ # 0.10<=rel<0.18 = weak, rel>=0.18 = ambiguous/reject (typically a mis-located
254
+ # 2-cm digit gap reading ~14 ticks/cm).
255
+ # cm buckets {10,20} are common and far apart -> a clean snap is trustworthy.
256
+ # inch buckets {25.4,50.8} are rare AND 25.4 sits perilously close to a NOISY
257
+ # cm-0.5mm reading (~27 ticks/cm), so we treat an inch snap as confident ONLY
258
+ # when production's own digit logic also called the scale "inch".
259
+ prod_is_inch = (getattr(calib, "scale_unit", "cm") == "inch")
260
+ estA_mm = None
261
+ estA_conf = False
262
+ if np.isfinite(per_unit) and per_unit > 0 and n_dig >= 2:
263
+ ticks_per_unit = per_unit / tick_px
264
+ best = min(_SNAP, key=lambda t: abs(np.log(t[0]) - np.log(ticks_per_unit)))
265
+ rel = abs(np.log(best[0]) - np.log(ticks_per_unit))
266
+ is_inch_bucket = best[2] == "inch"
267
+ if rel < 0.18:
268
+ estA_mm = best[1]
269
+ estA_conf = (rel < 0.10) and (not is_inch_bucket or prod_is_inch)
270
+
271
+ # ----- estimate B (PLAUSIBILITY PRIOR): the fabric's own dominant thread count.
272
+ # The two dyadic options differ by exactly x2 in threads/inch; only one lands
273
+ # near typical apparel density. The PPI (weft) axis is the reliable cue (the EPI
274
+ # /warp axis suffers twill/satin float sub-harmonics). Pick the scale whose PPI
275
+ # count is closest (log) to the apparel-density CENTRE.
276
+ freqs = _dominant_thread_count_per_px(gray, calib)
277
+ centre = APPAREL_CENTRE
278
+
279
+ def _ppi_count(mm):
280
+ ppi_inch = (tick_px / mm) * 25.4
281
+ f = freqs.get("ppi")
282
+ if f is None or not np.isfinite(f) or f <= 0:
283
+ f = freqs.get("epi") # fall back to warp axis if no weft peak
284
+ if f is None or not np.isfinite(f) or f <= 0:
285
+ return None, ppi_inch
286
+ return float(f * ppi_inch), ppi_inch
287
+
288
+ estB_mm = None
289
+ estB_margin = 0.0
290
+ cand = []
291
+ for mm in (1.0, 0.5):
292
+ cnt, _ = _ppi_count(mm)
293
+ if cnt is None:
294
+ continue
295
+ d = abs(np.log(max(cnt, 1e-6)) - np.log(centre))
296
+ cand.append((d, mm, cnt))
297
+ if cand:
298
+ cand.sort()
299
+ estB_mm = cand[0][1]
300
+ estB_margin = (cand[1][0] - cand[0][0]) if len(cand) > 1 else 9.9
301
+
302
+ # count (threads/inch) implied by a given tick_mm, used for band gating below.
303
+ def _implied_ppi_count(mm):
304
+ cnt, _ = _ppi_count(mm)
305
+ return cnt
306
+
307
+ # ----- FUSE the two votes ---------------------------------------------------
308
+ # A (ruler) is authoritative WHEN it reads a clean integer ticks/cm AND the
309
+ # count it implies is physically plausible (in band) — this beats the prior on
310
+ # coarse/dense fabric whose true count is far from the apparel centre
311
+ # (e.g. a genuine 42-PPI canvas the prior would wrongly double to 85).
312
+ # A confident CM-bucket estA IS the physical ruler reading (a clean ~10 or ~20
313
+ # ticks/cm) and is authoritative — it must NOT be vetoed by the prior, else dense
314
+ # apparel (PPI~106) gets wrongly halved toward the centre. We only require its
315
+ # implied count be physically plausible (in band) as a guard against a degenerate
316
+ # ruler. estA_conf already EXCLUDES the dangerous inch-bucket snap (a noisy
317
+ # cm-0.5mm read as ~27 ticks/cm) unless production independently called it inch,
318
+ # so a "confident" estA here is trustworthy.
319
+ # When estA is absent/weak/inch-suspect, B (plausibility prior) wins — it is
320
+ # immune to the mis-located digit-gap error that corrupts A (a 2-cm gap misread
321
+ # as 1 cm -> wrong x2).
322
+ tick_mm = None
323
+ if estA_mm is not None and estA_conf:
324
+ cnt_A = _implied_ppi_count(estA_mm)
325
+ if (cnt_A is None) or (PLAUSIBLE_LO <= cnt_A <= PLAUSIBLE_HI):
326
+ tick_mm = estA_mm
327
+ if tick_mm is None and estB_mm is not None:
328
+ tick_mm = estB_mm
329
+ if tick_mm is None and estA_mm is not None:
330
+ tick_mm = estA_mm # weak ruler reading, no prior
331
+ if tick_mm is None:
332
+ tick_mm = float(calib.tick_mm) # last resort: production's own call
333
+
334
+ px_per_inch = (tick_px / tick_mm) * 25.4
335
+ return float(tick_mm), float(px_per_inch)
336
+
337
+
338
+ if __name__ == "__main__":
339
+ # quick self-test on one bucket photo
340
+ from PIL import Image
341
+ p = sys.argv[1] if len(sys.argv) > 1 else None
342
+ if p:
343
+ g = np.asarray(Image.open(p).convert("L"), np.float32) / 255.0
344
+ print(robust_detect_tick(g))
ruler_freq.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Frequency-based ruler-tick localisation — robust to backlight / polarity.
2
+
3
+ The reflectance ruler detector (in epi_ppi_v5) keys on DARK tick columns, which
4
+ vanish under back-light (everything stays bright) -> it returns a degenerate
5
+ calibration. But the ticks are still PERIODIC under back-light, so they show up
6
+ as a sharp narrow-band peak in the column spectrum of a horizontal strip,
7
+ regardless of contrast polarity. This module locates the ruler band by that
8
+ periodic signature and measures the tick spacing to sub-pixel precision.
9
+
10
+ Pure (numpy/scipy only) — no dependency on the main module, so it can be called
11
+ as a fallback without circular imports.
12
+
13
+ locate_ruler_tick(gray) -> {"tick_period_px","band_y0","band_y1","ruler_pos"} | None
14
+ """
15
+ from __future__ import annotations
16
+ import numpy as np
17
+ from scipy import signal
18
+
19
+
20
+ def _strip_tick_signature(col, min_period=6.0, max_period=250.0):
21
+ """Column profile -> (narrowband_score, tick_period_px, peak_amp). Sub-pixel
22
+ period via parabolic refinement of the spectral peak. Polarity-agnostic."""
23
+ col = col - col.mean()
24
+ if col.std() < 1e-6:
25
+ return 0.0, float("nan"), 0.0
26
+ col = col * np.hanning(col.size)
27
+ sp = np.abs(np.fft.rfft(col)); fr = np.fft.rfftfreq(col.size)
28
+ band = (fr > 1.0 / max_period) & (fr < 1.0 / min_period)
29
+ if not band.any():
30
+ return 0.0, float("nan"), 0.0
31
+ sub_sp, sub_fr = sp[band], fr[band]
32
+ k = int(sub_sp.argmax()); peak_amp = float(sub_sp[k])
33
+ score = peak_amp / (float(np.median(sub_sp)) + 1e-9)
34
+ if 1 <= k < sub_sp.size - 1:
35
+ a, b, c = sub_sp[k-1], sub_sp[k], sub_sp[k+1]
36
+ den = a - 2*b + c
37
+ delta = 0.5*(a-c)/den if abs(den) > 1e-12 else 0.0
38
+ f = sub_fr[k] + float(np.clip(delta, -1, 1)) * (sub_fr[1] - sub_fr[0])
39
+ else:
40
+ f = sub_fr[k]
41
+ return float(score), (1.0/f if f > 0 else float("nan")), peak_amp
42
+
43
+
44
+ def _refine_tick_period(gray, band_y0, band_y1, spectral_period):
45
+ """Sharpen the tick spacing with an ACF over the band; keep ACF lag only if
46
+ it agrees with the spectral estimate within 20%."""
47
+ sub = gray[band_y0:band_y1, :]
48
+ if sub.shape[0] < 3:
49
+ return spectral_period
50
+ col = sub.mean(axis=0); col = col - col.mean()
51
+ if col.std() < 1e-6:
52
+ return spectral_period
53
+ ac = np.correlate(col, col, mode="full")[col.size-1:]; ac = ac/(ac[0]+1e-9)
54
+ lo = max(4, int(spectral_period*0.5)); hi = min(int(spectral_period*1.5)+2, ac.size-2)
55
+ if hi <= lo+2:
56
+ return spectral_period
57
+ seg = ac[lo:hi]; peaks, _ = signal.find_peaks(seg, height=0.10)
58
+ if not peaks.size:
59
+ return spectral_period
60
+ k = int(peaks[np.argmax(seg[peaks])])
61
+ if 1 <= k < seg.size-1:
62
+ a, b, c = seg[k-1], seg[k], seg[k+1]; den = a-2*b+c
63
+ delta = 0.5*(a-c)/den if abs(den) > 1e-12 else 0.0
64
+ lag = lo + k + float(np.clip(delta, -1, 1))
65
+ else:
66
+ lag = lo + k
67
+ return float(lag) if abs(lag - spectral_period) <= 0.20*spectral_period else spectral_period
68
+
69
+
70
+ def locate_ruler_tick(gray):
71
+ """Locate the ruler band by periodic-tick strength; return the band + the
72
+ sub-pixel tick spacing. Returns None if no periodic band is found."""
73
+ H, W = gray.shape
74
+ depth = max(16, min(40, H // 50)); step = max(4, depth // 3)
75
+ scores = []
76
+ for y0 in range(0, H - depth, step):
77
+ col = gray[y0:y0+depth, :].mean(axis=0)
78
+ s, period, amp = _strip_tick_signature(col)
79
+ scores.append((y0, s, period))
80
+ if not scores:
81
+ return None
82
+ ys = np.array([r[0] for r in scores]); sc = np.array([r[1] for r in scores])
83
+ pe = np.array([r[2] for r in scores])
84
+ bi = int(sc.argmax()); best_period = float(pe[bi])
85
+ if not np.isfinite(best_period) or best_period <= 0:
86
+ return None
87
+ # grow the band while score stays high AND period stays consistent
88
+ thr = 0.45 * sc[bi]
89
+ pmask = np.isfinite(pe) & (np.abs(pe - best_period) <= 0.30 * best_period)
90
+ keep = (sc >= thr) & pmask
91
+ lo = bi
92
+ while lo - 1 >= 0 and keep[lo-1]:
93
+ lo -= 1
94
+ hi = bi
95
+ while hi + 1 < len(ys) and keep[hi+1]:
96
+ hi += 1
97
+ band_y0 = int(ys[lo]); band_y1 = int(ys[hi] + depth)
98
+ period = _refine_tick_period(gray, band_y0, band_y1, best_period)
99
+ if not np.isfinite(period) or period <= 0:
100
+ return None
101
+ mid = 0.5 * (band_y0 + band_y1)
102
+ return {"tick_period_px": float(period), "band_y0": band_y0, "band_y1": band_y1,
103
+ "ruler_pos": "top" if mid < H * 0.5 else "bottom"}
tick_hierarchy.py ADDED
@@ -0,0 +1,695 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tick-length HIERARCHY analysis — an absolute structural cue that resolves the
2
+ 0.5mm-vs-1.0mm ruler-tick ambiguity that the production plausibility prior cannot.
3
+
4
+ Metric rulers emphasise graduations hierarchically:
5
+ * 1.0mm-tick ruler : 10 fine ticks / cm, medium tick at 5mm, longest at each cm
6
+ -> level sub-periods (in fine-tick units): {5, 10}.
7
+ * 0.5mm-tick ruler : 20 fine ticks / cm, mediums at each mm (every 2 fine)
8
+ and/or at 5mm (every 10 fine), longest at each cm
9
+ -> level sub-periods: {2, 10, 20}.
10
+
11
+ So the spacing of ticks-of-a-level, measured in fine-tick intervals, identifies
12
+ the fine-tick pitch with no dependence on thread-count plausibility:
13
+ ~20 fine per longest, or ANY level repeating every 2 fine -> fine = 0.5 mm
14
+ ~10 fine per longest WITH a medium level every 5 fine -> fine = 1.0 mm
15
+
16
+ hierarchy_tick(gray) -> {'tick_mm': 0.5|1.0|None, 'fine_per_long': float|None,
17
+ 'confidence': float, 'abstain': bool, 'diag': dict}
18
+
19
+ Pipeline
20
+ 1. Localise the ruler band with production epi_ppi_v5.detect_calibration
21
+ (read-only import; its tick_mm decision is ignored entirely).
22
+ 2. Inside an expanded band, isolate tick "ink" with a 1-D horizontal grey
23
+ closing (dark ticks) / opening (bright ticks) — polarity chosen by which
24
+ column profile is more periodic (handles the backlit/inverted photo). The
25
+ horizontal ruler edge line cancels itself in this residual.
26
+ 3. Connected components give tick candidates; RANSAC-fit the common ANCHOR
27
+ LINE (ticks all start at the ruler's scale edge), windowed to the
28
+ calibration tick zone. This rejects digits, fabric texture and scratches
29
+ and tolerates slight rotation.
30
+ 4. Enumerate ticks from the ink profile of a shallow stripe that follows the
31
+ anchor line (robust to adjacent ticks merging into one component, which
32
+ breaks pure component counting). Measure each tick's LENGTH by a column
33
+ scan from the anchor line with small-gap bridging.
34
+ 5. Snap tick x to the fine grid (period p); drop off-grid junk. Sub-tick
35
+ test: ink at the MIDPOINTS of one-unit gaps vs off-grid baseline — high
36
+ ink means a barely-resolved 2x-finer comb (0.5mm sub-ticks) -> halve p.
37
+ (Phase-locked, so periodic fabric texture cannot fake it.)
38
+ 6. Cluster tick lengths into levels (1-D gap-split — per-level lengths are
39
+ very tight on real rulers). For each level, the sub-period of "this level
40
+ or longer" ticks in fine units forms the hierarchy signature; decide by
41
+ the table above with safety gates:
42
+ - a 1.0mm verdict claims the ABSENCE of sub-ticks, so it additionally
43
+ requires p >= MIN_P_FOR_1MM px (a hidden 0.5mm sub-comb would be
44
+ clearly visible), near-complete comb visibility, and a clean negative
45
+ sub-tick test;
46
+ - digit spacing (printed numbers sit at cm marks) is only weak evidence
47
+ for ambiguous branches;
48
+ - >=3 nested levels all repeating every 2 fine = binary (inch) scale
49
+ -> abstain.
50
+
51
+ Abstains (tick_mm=None) whenever no coherent hierarchy is found. <2s CPU.
52
+ """
53
+ from __future__ import annotations
54
+
55
+ import io
56
+ import contextlib
57
+ import sys
58
+ import time
59
+
60
+ import numpy as np
61
+ from scipy import ndimage, signal
62
+
63
+ import epi_ppi_v5 as v5
64
+ import robust_tick as rt # read-only: _robust_px_per_unit digit-gap helper
65
+
66
+ # ----------------------------------------------------------------------------- #
67
+ # tunables
68
+ # ----------------------------------------------------------------------------- #
69
+ MIN_TICKS = 12 # min comb members to attempt a verdict
70
+ MIN_P_FOR_1MM = 8.0 # px; a hidden 0.5mm sub-comb (p/2) must be >=4px visible
71
+ SUB_STRONG = 0.50 # sub-tick score above this -> sub-comb real -> halve p
72
+ SUB_SUSPECT = 0.25 # above this -> refuse a 1.0 verdict
73
+ MAX_SLOPE = 0.09 # max |dy/dx| of the ruler anchor line (~5 deg)
74
+ LEVEL_GAP_PX = 4.0 # 1-D length clustering: split when sorted gap exceeds
75
+ LEVEL_GAP_REL = 0.08 # max(LEVEL_GAP_PX, LEVEL_GAP_REL * length)
76
+
77
+
78
+ def _near(x, target, rel=0.15):
79
+ return x is not None and np.isfinite(x) and abs(x - target) <= rel * target
80
+
81
+
82
+ # ----------------------------------------------------------------------------- #
83
+ # 1. band extraction
84
+ # ----------------------------------------------------------------------------- #
85
+ def _band_bounds(shape, ruler_pos, y_tick_zone):
86
+ """Expand the calibration tick zone toward the digit side (ticks grow away
87
+ from the fabric edge) so the full length of cm ticks is inside the band."""
88
+ H, _ = shape
89
+ y0, y1 = y_tick_zone
90
+ h = max(30, y1 - y0)
91
+ if ruler_pos == "bottom":
92
+ e0, e1 = max(0, y0 - int(0.35 * h)), min(H, y1 + int(1.8 * h))
93
+ else:
94
+ e0, e1 = max(0, y0 - int(1.8 * h)), min(H, y1 + int(0.35 * h))
95
+ return e0, e1
96
+
97
+
98
+ # ----------------------------------------------------------------------------- #
99
+ # 2. tick-ink isolation (polarity-agnostic)
100
+ # ----------------------------------------------------------------------------- #
101
+ def _ink_residual(band, width, polarity):
102
+ """Tick-ink residual of a horizontal grey closing (dark ticks) or opening
103
+ (light ticks). Thin vertical strokes survive; wide horizontal structure
104
+ (ruler edge lines) cancels itself."""
105
+ w = int(width) | 1
106
+ fp = np.ones((1, w), bool)
107
+ if polarity == "dark":
108
+ return np.clip(ndimage.grey_closing(band, footprint=fp) - band,
109
+ 0.0, None)
110
+ return np.clip(band - ndimage.grey_opening(band, footprint=fp), 0.0, None)
111
+
112
+
113
+ def _acf(profile):
114
+ p = profile - profile.mean()
115
+ if p.std() < 1e-9:
116
+ return None
117
+ n = p.size
118
+ f = np.fft.rfft(p, 2 * n) # FFT autocorrelation, O(n log n)
119
+ ac = np.fft.irfft(f * np.conj(f))[:n]
120
+ return ac / (ac[0] + 1e-12)
121
+
122
+
123
+ def _periodicity_score(ink, rows):
124
+ prof = ink[rows[0]:rows[1], :].sum(axis=0)
125
+ ac = _acf(prof)
126
+ if ac is None or ac.size < 12:
127
+ return 0.0
128
+ lo, hi = 4, min(260, ac.size - 2)
129
+ if hi <= lo + 2:
130
+ return 0.0
131
+ pk, _ = signal.find_peaks(ac[lo:hi], height=0.03)
132
+ return float(ac[lo:hi][pk].max()) if pk.size else 0.0
133
+
134
+
135
+ # ----------------------------------------------------------------------------- #
136
+ # 3. anchor line from tick-candidate components
137
+ # ----------------------------------------------------------------------------- #
138
+ _STRUCT4 = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]], bool)
139
+
140
+
141
+ def _components(ink, thr, p_seed):
142
+ """Thin-ish vertical components. Adjacent ticks may merge into one blob at
143
+ the anchor edge — that is fine here: components only seed the anchor-line
144
+ fit; tick enumeration happens on the stripe profile afterwards."""
145
+ m = ink > thr
146
+ lab, n = ndimage.label(m, structure=_STRUCT4)
147
+ if n == 0:
148
+ return [], m
149
+ objs = ndimage.find_objects(lab)
150
+ w_cap = max(30.0, 1.6 * p_seed) if np.isfinite(p_seed) else 40.0
151
+ comps = []
152
+ for sl in objs:
153
+ if sl is None:
154
+ continue
155
+ ys, xs = sl
156
+ h_ = ys.stop - ys.start
157
+ w_ = xs.stop - xs.start
158
+ if h_ < 3 or w_ < 1 or w_ > w_cap:
159
+ continue
160
+ if h_ < 1.4 * w_: # not elongated -> digit blob/noise
161
+ continue
162
+ comps.append(dict(x=0.5 * (xs.start + xs.stop - 1),
163
+ x0=xs.start, x1=xs.stop - 1,
164
+ ytop=ys.start, ybot=ys.stop - 1))
165
+ return comps, m
166
+
167
+
168
+ def _ransac_anchor(comps, band_h, going_down, zrows, tol=6.0, iters=80,
169
+ rng_seed=0):
170
+ """Fit the common tick-anchor line y = a + b*x.
171
+
172
+ The anchor is the ruler's scale edge: near zrows[0] for a bottom ruler
173
+ (ticks grow down, away from the fabric above) and near zrows[1] for a top
174
+ ruler. Components clipped at the band boundary on their anchor side are
175
+ excluded (their anchor is fake), as are anchors far outside the window —
176
+ this rejects fabric-texture combs."""
177
+ key = "ytop" if going_down else "ybot"
178
+ centre = zrows[0] if going_down else zrows[1]
179
+ zh = max(40.0, zrows[1] - zrows[0])
180
+ win = 0.6 * zh
181
+ cand = []
182
+ for c in comps:
183
+ av = c[key]
184
+ if going_down and av <= 1:
185
+ continue
186
+ if (not going_down) and av >= band_h - 2:
187
+ continue
188
+ if abs(av - centre) > win:
189
+ continue
190
+ cand.append(c)
191
+ xs = np.array([c["x"] for c in cand], float)
192
+ ys = np.array([c[key] for c in cand], float)
193
+ n = xs.size
194
+ if n < 4:
195
+ return None, []
196
+ rng = np.random.default_rng(rng_seed)
197
+ best_in = None
198
+ for _ in range(iters):
199
+ i, j = rng.integers(0, n, 2)
200
+ if abs(xs[i] - xs[j]) < 20:
201
+ continue
202
+ b = (ys[j] - ys[i]) / (xs[j] - xs[i])
203
+ if abs(b) > MAX_SLOPE:
204
+ continue
205
+ a = ys[i] - b * xs[i]
206
+ inl = np.abs(ys - (a + b * xs)) <= tol
207
+ if best_in is None or inl.sum() > best_in.sum():
208
+ best_in = inl
209
+ if best_in is None or best_in.sum() < 4:
210
+ return None, []
211
+ for _ in range(2): # LSQ refine on inliers
212
+ A = np.polyfit(xs[best_in], ys[best_in], 1)
213
+ b, a = A[0], A[1]
214
+ resid = np.abs(ys - (a + b * xs))
215
+ best_in = resid <= max(tol, 2.5 * float(resid[best_in].std()) + 1e-6)
216
+ ticks = [c for c, keep in zip(cand, best_in) if keep]
217
+ return (float(a), float(b)), ticks
218
+
219
+
220
+ # ----------------------------------------------------------------------------- #
221
+ # 4. profile-based tick enumeration + lengths
222
+ # ----------------------------------------------------------------------------- #
223
+ def _line_stripe_profile(ink, a, b, going_down, offset, depth):
224
+ """Column ink profile of a stripe of `depth` rows that follows the anchor
225
+ line, starting `offset` rows into the ruler."""
226
+ Hb, Wb = ink.shape
227
+ d = int(max(3, depth))
228
+ xs = np.arange(Wb)
229
+ y0 = np.round(a + b * xs).astype(int)
230
+ rows = np.arange(offset, offset + d)[:, None]
231
+ yy = y0[None, :] + (rows if going_down else -rows)
232
+ np.clip(yy, 0, Hb - 1, out=yy)
233
+ return ink[yy, xs[None, :]].sum(axis=0)
234
+
235
+
236
+ def _profile_ticks(prof):
237
+ """Tick x-positions = prominent peaks of the stripe profile."""
238
+ sm = ndimage.gaussian_filter1d(prof, 1.0)
239
+ pk, props = signal.find_peaks(sm, distance=3, prominence=1e-6)
240
+ if pk.size == 0:
241
+ return np.array([])
242
+ prom = props["prominences"]
243
+ thr = 0.30 * float(np.percentile(prom, 90))
244
+ keep = prom >= thr
245
+ return pk[keep].astype(float)
246
+
247
+
248
+ def _refine_length(mask, x, a, b, going_down, max_gap, halfw=2):
249
+ """Tick length from the anchor line at column x, bridging small breaks."""
250
+ Hb, Wb = mask.shape
251
+ xi = int(round(x))
252
+ col = mask[:, max(0, xi - halfw):min(Wb, xi + halfw + 1)].any(axis=1)
253
+ y_line = int(round(a + b * x))
254
+ y_line = min(max(y_line, 0), Hb - 1)
255
+ step = 1 if going_down else -1
256
+ y, last, gap = y_line, y_line, 0
257
+ while 0 <= y < Hb and gap <= max_gap:
258
+ if col[y]:
259
+ last, gap = y, 0
260
+ else:
261
+ gap += 1
262
+ y += step
263
+ return float(abs(last - y_line) + 1)
264
+
265
+
266
+ # ----------------------------------------------------------------------------- #
267
+ # 5. fine grid
268
+ # ----------------------------------------------------------------------------- #
269
+ def _grid_period(xs):
270
+ dx = np.diff(xs)
271
+ dx = dx[dx > 0.5]
272
+ if dx.size < 4:
273
+ return None
274
+ med = np.median(dx)
275
+ keep = dx[(dx > 0.55 * med) & (dx < 1.45 * med)]
276
+ if keep.size < 3:
277
+ return None
278
+ p = float(np.median(keep))
279
+ k = np.round(np.diff(xs) / p) # integer-snap over multi-gaps
280
+ ok = (k >= 1) & (k <= 3)
281
+ if ok.sum() >= 3:
282
+ p = float(np.diff(xs)[ok].sum() / k[ok].sum())
283
+ return p
284
+
285
+
286
+ def _drop_offgrid(xs, lens, p):
287
+ """Remove isolated off-grid detections (scratches, dust): a tick whose gaps
288
+ to BOTH neighbours are far from integer multiples of p, while the
289
+ neighbours agree with each other, is junk."""
290
+ for _ in range(2):
291
+ n = xs.size
292
+ if n < 5:
293
+ break
294
+ drop = np.zeros(n, bool)
295
+ for i in range(1, n - 1):
296
+ dl = (xs[i] - xs[i - 1]) / p
297
+ dr = (xs[i + 1] - xs[i]) / p
298
+ fl = abs(dl - round(dl))
299
+ fr = abs(dr - round(dr))
300
+ fs = abs((dl + dr) - round(dl + dr))
301
+ if fl > 0.25 and fr > 0.25 and fs <= 0.30:
302
+ drop[i] = True
303
+ if not drop.any():
304
+ break
305
+ xs, lens = xs[~drop], lens[~drop]
306
+ return xs, lens
307
+
308
+
309
+ def _grid_coords(xs, p):
310
+ u = np.zeros(xs.size, int)
311
+ for i in range(1, xs.size):
312
+ u[i] = u[i - 1] + max(1, int(round((xs[i] - xs[i - 1]) / p)))
313
+ return u
314
+
315
+
316
+ def _subtick_score(prof, xs, p):
317
+ """Phase-locked test for a 2x-finer comb: ink at the MIDPOINT of one-unit
318
+ gaps vs ink at off-grid baseline offsets (0.28/0.72 of the gap). Returns
319
+ score in ~[0,1] (1 = midpoints as strong as the ticks) or None if too few
320
+ one-unit gaps. Periodic fabric texture has no fixed phase relative to the
321
+ tick grid, so it cannot fake a high score."""
322
+ n = prof.size
323
+ wm = max(1, int(round(p / 8)))
324
+ wb = max(1, int(round(p / 12)))
325
+
326
+ def _win_max(c, w):
327
+ lo, hi = int(round(c - w)), int(round(c + w)) + 1
328
+ if lo < 0 or hi > n:
329
+ return None
330
+ return float(prof[lo:hi].max())
331
+
332
+ mids, bases, tick_vals = [], [], []
333
+ for i in range(xs.size - 1):
334
+ d = xs[i + 1] - xs[i]
335
+ if abs(d / p - 1.0) > 0.25:
336
+ continue
337
+ m = _win_max(xs[i] + 0.5 * d, wm)
338
+ b1 = _win_max(xs[i] + 0.28 * d, wb)
339
+ b2 = _win_max(xs[i] + 0.72 * d, wb)
340
+ t1 = _win_max(xs[i], wm)
341
+ t2 = _win_max(xs[i + 1], wm)
342
+ if None in (m, b1, b2, t1, t2):
343
+ continue
344
+ mids.append(m)
345
+ bases.append(min(b1, b2))
346
+ tick_vals.append(min(t1, t2))
347
+ if len(mids) < 4:
348
+ return None
349
+ mid = float(np.median(mids))
350
+ base = float(np.median(bases))
351
+ tick = float(np.median(tick_vals))
352
+ if tick - base < 1e-9:
353
+ return None
354
+ return float(np.clip((mid - base) / (tick - base), -0.5, 1.5))
355
+
356
+
357
+ # ----------------------------------------------------------------------------- #
358
+ # 6. length levels + hierarchy signature
359
+ # ----------------------------------------------------------------------------- #
360
+ def _cluster_levels(lens):
361
+ """1-D clustering of tick lengths by splitting sorted gaps. Returns a list
362
+ of dicts {lo, hi, mean, n} sorted by ascending mean length."""
363
+ s = np.sort(lens)
364
+ splits = [0]
365
+ for i in range(1, s.size):
366
+ if s[i] - s[i - 1] > max(LEVEL_GAP_PX, LEVEL_GAP_REL * s[i]):
367
+ splits.append(i)
368
+ splits.append(s.size)
369
+ levels = []
370
+ for k in range(len(splits) - 1):
371
+ seg = s[splits[k]:splits[k + 1]]
372
+ levels.append(dict(lo=float(seg[0]), hi=float(seg[-1]),
373
+ mean=float(seg.mean()), n=int(seg.size)))
374
+ return levels
375
+
376
+
377
+ def _union_spacing(u, mask):
378
+ """Robust sub-period of the marked ticks in fine-grid units: the smallest
379
+ gap, validated by how many other gaps are ~integer multiples of it."""
380
+ uu = u[mask]
381
+ if uu.size < 2:
382
+ return None, 0.0, 0
383
+ d = np.diff(uu).astype(float)
384
+ d = d[d > 0]
385
+ if d.size == 0:
386
+ return None, 0.0, 0
387
+ s = float(np.min(d))
388
+ mult = np.abs(d / s - np.round(d / s)) <= 0.15
389
+ consist = float(np.mean(mult & (np.round(d / s) >= 1)))
390
+ return s, consist, int(d.size)
391
+
392
+
393
+ def _signature(u, lens, levels):
394
+ """For each level (top-down), the sub-period of 'this level or longer'."""
395
+ sig = []
396
+ for lv in reversed(levels): # longest level first
397
+ mask = lens >= lv["lo"] - 1e-6
398
+ s, consist, ngaps = _union_spacing(u, mask)
399
+ sig.append(dict(mean=lv["mean"], n=int(mask.sum()), n_own=lv["n"],
400
+ S=s, consist=consist, ngaps=ngaps))
401
+ return sig
402
+
403
+
404
+ # ----------------------------------------------------------------------------- #
405
+ # main entry
406
+ # ----------------------------------------------------------------------------- #
407
+ def hierarchy_tick(gray):
408
+ """gray: full-photo 2-D float32 array 0..1.
409
+ Returns dict: {'tick_mm': 0.5|1.0|None, 'fine_per_long': float|None,
410
+ 'confidence': float 0..1, 'abstain': bool, 'diag': dict}
411
+ abstain=True (tick_mm None) when no clear hierarchy is found. <2s CPU."""
412
+ diag = {}
413
+ out = dict(tick_mm=None, fine_per_long=None, confidence=0.0,
414
+ abstain=True, diag=diag)
415
+ gray = np.asarray(gray, np.float32)
416
+ if gray.max() > 1.5:
417
+ gray = gray / 255.0
418
+ if gray.ndim != 2 or min(gray.shape) < 60:
419
+ diag["reason"] = "bad-input"
420
+ return out
421
+
422
+ # --- 1. ruler localisation (production helper, read-only) -----------------
423
+ # detect_calibration's sliding ACF costs ~(H/4)*W^2; on the largest ~12MP
424
+ # photos that alone busts the 2s budget, so for those run it on a decimated
425
+ # copy and scale the results back (all tick measurement below stays at full
426
+ # resolution). Everything else keeps the exact full-resolution zones.
427
+ H, W = gray.shape
428
+ s = 2 if (H / 4.0) * W * W > 9e9 else 1
429
+ g_cal = gray[::s, ::s] if s > 1 else gray
430
+ try:
431
+ with contextlib.redirect_stdout(io.StringIO()):
432
+ calib = v5.detect_calibration(g_cal)
433
+ except Exception as e: # noqa: BLE001
434
+ diag["reason"] = f"calib-failed: {e}"
435
+ return out
436
+ y0z, y1z = calib.y_tick_zone[0] * s, calib.y_tick_zone[1] * s
437
+ if not (0 <= y0z < y1z <= H) or (y1z - y0z) < 8:
438
+ diag["reason"] = "degenerate-tick-zone"
439
+ return out
440
+ e0, e1 = _band_bounds((H, W), calib.ruler_pos, (y0z, y1z))
441
+ band = gray[e0:e1]
442
+ zrows = (max(0, y0z - e0), max(1, min(band.shape[0], y1z - e0)))
443
+ going_down = calib.ruler_pos == "bottom" # ticks grow away from the fabric
444
+ p_seed = (calib.tick_period_px * s
445
+ if np.isfinite(calib.tick_period_px) else 15.0)
446
+ diag.update(ruler_pos=calib.ruler_pos, band=(int(e0), int(e1)),
447
+ p_seed=round(float(p_seed), 2), calib_decim=s)
448
+
449
+ # --- 2. polarity + ink ------------------------------------------------------
450
+ close_w = int(np.clip(0.55 * p_seed, 9, 41))
451
+ ink = _ink_residual(band, close_w, "dark")
452
+ sc = _periodicity_score(ink, zrows)
453
+ pol = "dark"
454
+ if sc < 0.25: # dark ticks not convincing:
455
+ ink_l = _ink_residual(band, close_w, "light")
456
+ sc_l = _periodicity_score(ink_l, zrows)
457
+ if sc_l > sc:
458
+ ink, sc, pol = ink_l, sc_l, "light"
459
+ diag.update(polarity=pol, periodicity=round(sc, 3))
460
+ if sc < 0.04:
461
+ diag["reason"] = "no-periodic-tick-comb"
462
+ return out
463
+
464
+ # --- 3. components -> anchor line ---------------------------------------------
465
+ zink = ink[zrows[0]:zrows[1]]
466
+ thr = max(0.04, 0.25 * float(np.percentile(zink, 99.5)))
467
+ comps, mask = _components(ink, thr, p_seed)
468
+ diag.update(thr=round(thr, 3), n_comps_raw=len(comps))
469
+ if len(comps) < 6:
470
+ diag["reason"] = "too-few-tick-candidates"
471
+ return out
472
+ ab, anchored = _ransac_anchor(comps, band.shape[0], going_down, zrows)
473
+ if ab is None or len(anchored) < 6:
474
+ diag["reason"] = "no-anchor-line"
475
+ diag["n_anchored"] = len(anchored)
476
+ return out
477
+ a, b = ab
478
+ diag.update(n_anchored=len(anchored), anchor_slope=round(b, 4))
479
+
480
+ # --- 4. profile-based tick enumeration -------------------------------------------
481
+ comp_lens = np.array([c["ybot"] - c["ytop"] + 1 for c in anchored], float)
482
+ med_len = float(np.median(comp_lens))
483
+ depth = float(np.clip(0.35 * med_len, 6, 80))
484
+ prof = _line_stripe_profile(ink, a, b, going_down, offset=2, depth=depth)
485
+ xs = _profile_ticks(prof)
486
+ diag.update(stripe_depth=int(depth), n_peaks=int(xs.size))
487
+ if xs.size < MIN_TICKS or xs.size > 500:
488
+ diag["reason"] = "peak-count-out-of-range"
489
+ return out
490
+ max_gap = int(np.clip(0.12 * p_seed, 3, 8))
491
+ lens = np.array([_refine_length(mask, x, a, b, going_down, max_gap)
492
+ for x in xs])
493
+ good = lens >= 3
494
+ xs, lens = xs[good], lens[good]
495
+ if xs.size < MIN_TICKS:
496
+ diag["reason"] = "too-few-refined-ticks"
497
+ return out
498
+
499
+ # --- 5. fine grid -----------------------------------------------------------------
500
+ p = _grid_period(xs)
501
+ if p is None or p < 2.5:
502
+ diag["reason"] = "no-fine-period"
503
+ return out
504
+ keep = np.ones(xs.size, bool) # de-duplicate near-coincident
505
+ for i in range(1, xs.size):
506
+ if xs[i] - xs[i - 1] < 0.45 * p:
507
+ keep[i if lens[i] <= lens[i - 1] else i - 1] = False
508
+ xs, lens = xs[keep], lens[keep]
509
+ xs, lens = _drop_offgrid(xs, lens, p)
510
+ if xs.size < MIN_TICKS:
511
+ diag["reason"] = "too-few-grid-ticks"
512
+ return out
513
+ p = _grid_period(xs) or p
514
+
515
+ # phase-locked sub-tick test: is the true fine comb 2x finer?
516
+ sub_score = _subtick_score(prof, xs, p)
517
+ diag["sub_score"] = None if sub_score is None else round(sub_score, 2)
518
+ sub_comb = bool(sub_score is not None and sub_score > SUB_STRONG
519
+ and p / 2.0 >= 2.2)
520
+ if sub_comb:
521
+ p = p / 2.0
522
+ u = _grid_coords(xs, p)
523
+ frac_seen = xs.size / float(u[-1] - u[0] + 1)
524
+ diag.update(p_fine=round(float(p), 2), n_ticks=int(xs.size),
525
+ frac_seen=round(float(frac_seen), 2), sub_comb=sub_comb)
526
+
527
+ # --- 6. levels + signature -----------------------------------------------------------
528
+ levels = _cluster_levels(lens)
529
+ sig = _signature(u, lens, levels)
530
+ diag["levels"] = [(round(lv["mean"], 1), lv["n"]) for lv in levels]
531
+ diag["signature"] = [(round(s["mean"], 1), s["n"],
532
+ None if s["S"] is None else round(s["S"], 1),
533
+ round(s["consist"], 2)) for s in sig]
534
+
535
+ r_digit = None # digits sit at cm marks (weak cue)
536
+ try:
537
+ per_unit, n_dig = rt._robust_px_per_unit(g_cal, calib)
538
+ if np.isfinite(per_unit) and per_unit > 0 and n_dig >= 2:
539
+ r_digit = float(per_unit * s / p)
540
+ except Exception: # noqa: BLE001
541
+ pass
542
+ diag["r_digit"] = None if r_digit is None else round(r_digit, 1)
543
+
544
+ tick_mm, conf, path, fpl = _decide(sig, frac_seen, p, sub_score, r_digit,
545
+ sub_comb)
546
+ diag["path"] = path
547
+ out["fine_per_long"] = fpl
548
+ if tick_mm is None:
549
+ return out
550
+ out.update(tick_mm=float(tick_mm), confidence=round(float(conf), 2),
551
+ abstain=False)
552
+ return out
553
+
554
+
555
+ def _decide(sig, frac_seen, p, sub_score, r_digit, sub_comb):
556
+ """Map the hierarchy signature to (tick_mm, confidence, path, fine_per_long).
557
+
558
+ sig: per-level (longest first) dicts with S = sub-period of 'level or
559
+ longer' ticks in fine units, consistency, member/gap counts."""
560
+ fine_mean = sig[-1]["mean"] if sig else 0.0
561
+
562
+ def usable(s): # a level entry with a real period
563
+ return (s["S"] is not None and s["ngaps"] >= 1
564
+ and s["mean"] >= 1.25 * fine_mean and s["n"] >= 2)
565
+
566
+ ev = {} # evidence: key -> best sig entry
567
+ for s in sig[:-1] if len(sig) > 1 else []:
568
+ if not usable(s):
569
+ continue
570
+ for key, target, rel, min_n in (("2", 2.0, 0.2, 4), ("5", 5.0, 0.14, 3),
571
+ ("10", 10.0, 0.12, 2), ("20", 20.0, 0.15, 2),
572
+ ("40", 40.0, 0.12, 2)):
573
+ if _near(s["S"], target, rel) and s["n"] >= min_n \
574
+ and s["consist"] >= 0.6 and key not in ev:
575
+ ev[key] = s
576
+
577
+ # fine_per_long: sub-period of the longest usable level (diagnostic output)
578
+ fpl = None
579
+ for s in sig:
580
+ if s["S"] is not None and s["ngaps"] >= 1 and s["n"] >= 2:
581
+ fpl = float(s["S"])
582
+ break
583
+
584
+ # >=3 nested levels that all halve the period = binary (inch) scale. Count
585
+ # only levels with >=3 members of their own so singleton junk levels
586
+ # (slightly mis-measured tick lengths) cannot fake the pattern.
587
+ n_ev2_nested = sum(1 for s in sig[:-1]
588
+ if s["S"] is not None and _near(s["S"], 2.0, 0.25)
589
+ and s["n_own"] >= 3)
590
+ if n_ev2_nested >= 3:
591
+ return None, 0.0, "binary-inch-scale", fpl
592
+
593
+ if ("5" in ev) and (("2" in ev) or ("20" in ev)):
594
+ return None, 0.0, "conflicting-evidence", fpl
595
+
596
+ def gate_1mm(base, path):
597
+ # asserting 1.0mm claims the ABSENCE of sub-ticks -> demands resolution
598
+ if sub_comb:
599
+ return None, 0.0, path + "|subcomb-blocks-1mm"
600
+ if p < MIN_P_FOR_1MM:
601
+ return None, 0.0, path + "|1mm-blocked-lowres"
602
+ if frac_seen < 0.70:
603
+ return None, 0.0, path + "|1mm-blocked-sparse-comb"
604
+ if sub_score is None:
605
+ return None, 0.0, path + "|1mm-blocked-no-subtick-test"
606
+ if sub_score > SUB_SUSPECT:
607
+ return None, 0.0, path + "|subticks-suspected"
608
+ b = base + (0.10 if _near(r_digit, 10.0) else 0.0)
609
+ if frac_seen >= 0.85:
610
+ b += 0.10
611
+ return 1.0, min(b, 0.95), path
612
+
613
+ # ---- 0.5 mm evidence --------------------------------------------------------
614
+ if "20" in ev or "2" in ev:
615
+ base = 0.60
616
+ path = "+".join(k for k in ("20", "2") if k in ev)
617
+ if "20" in ev and "2" in ev:
618
+ base += 0.15
619
+ elif "10" in ev: # 5mm level supports the story
620
+ base += 0.05
621
+ if _near(r_digit, 20.0):
622
+ base += 0.05
623
+ if frac_seen >= 0.75:
624
+ base += 0.10
625
+ if frac_seen < 0.5:
626
+ base -= 0.15
627
+ return 0.5, min(base, 0.95), f"ev{path}", fpl
628
+
629
+ if "40" in ev and "10" in ev: # 2cm emphasis over 0.5mm comb
630
+ return 0.5, 0.50, "ev40+10", fpl
631
+
632
+ # ---- 1.0 mm evidence --------------------------------------------------------
633
+ if "5" in ev:
634
+ tick, conf, path = gate_1mm(0.60 + (0.10 if "10" in ev else 0.0), "ev5")
635
+ return tick, conf, path, fpl
636
+
637
+ # ---- ambiguous: only a 10-fine level (cm-on-1mm vs 5mm-on-0.5mm) -----------
638
+ if "10" in ev:
639
+ if _near(r_digit, 20.0):
640
+ return 0.5, 0.50, "ev10+digit20", fpl
641
+ if _near(r_digit, 10.0):
642
+ tick, conf, path = gate_1mm(0.45, "ev10+digit10")
643
+ return tick, conf, path, fpl
644
+ return None, 0.0, "ev10-ambiguous", fpl
645
+
646
+ return None, 0.0, "no-usable-evidence", fpl
647
+
648
+
649
+ # =============================================================================== #
650
+ # harness
651
+ # =============================================================================== #
652
+ def _load_gray(path):
653
+ from PIL import Image
654
+ img = Image.open(path)
655
+ return np.asarray(img.convert("L"), np.float32) / 255.0
656
+
657
+
658
+ def _first_photo(article_dir):
659
+ import os
660
+ for f in sorted(os.listdir(article_dir)):
661
+ fp = os.path.join(article_dir, f)
662
+ if not os.path.isfile(fp) or os.path.getsize(fp) == 0:
663
+ continue
664
+ if f.lower().endswith((".heic", ".heif")):
665
+ continue
666
+ if f.lower().endswith((".jpg", ".jpeg", ".png")):
667
+ return fp
668
+ return None
669
+
670
+
671
+ def _run_case(tag, path, expect):
672
+ t0 = time.time()
673
+ try:
674
+ g = _load_gray(path)
675
+ r = hierarchy_tick(g)
676
+ except Exception as e: # noqa: BLE001
677
+ r = dict(tick_mm=None, fine_per_long=None, confidence=0.0,
678
+ abstain=True, diag={"reason": f"crash: {e}"})
679
+ dt = time.time() - t0
680
+ tm = r["tick_mm"]
681
+ verdict = "abstain" if tm is None else f"{tm}"
682
+ if expect == "0.5":
683
+ status = "PASS" if tm == 0.5 else ("ABSTAIN" if tm is None else "FAIL")
684
+ elif expect == "1.0":
685
+ status = "PASS" if tm == 1.0 else ("ABSTAIN" if tm is None else "FAIL")
686
+ else:
687
+ status = "-"
688
+ fpl = r["fine_per_long"]
689
+ print(f"{tag:28s} tick_mm={verdict:7s} fine_per_long="
690
+ f"{'None' if fpl is None else f'{fpl:.1f}':>5s} "
691
+ f"conf={r['confidence']:.2f} [{status}] {dt:.2f}s "
692
+ f"path={r['diag'].get('path', r['diag'].get('reason'))}")
693
+ return r, dt, status
694
+
695
+