Spaces:
Sleeping
Sleeping
Yaz Hobooti
commited on
Commit
·
828bfe1
1
Parent(s):
e4d5933
Replace barcode reader with robust ZXing-CPP implementation
Browse files- app.py +4 -4
- barcode_reader.py +317 -0
- barcode_utils.py +0 -169
- requirements.txt +3 -2
app.py
CHANGED
|
@@ -52,7 +52,7 @@ except Exception:
|
|
| 52 |
HAS_REGEX = False
|
| 53 |
|
| 54 |
try:
|
| 55 |
-
from
|
| 56 |
HAS_BARCODE = True
|
| 57 |
except Exception:
|
| 58 |
read_barcodes_from_path = None
|
|
@@ -1117,10 +1117,10 @@ def compare_pdfs(file_a, file_b):
|
|
| 1117 |
print(f"Spell check results - A: {len(misspell_a)} boxes, B: {len(misspell_b)} boxes")
|
| 1118 |
|
| 1119 |
if HAS_BARCODE:
|
| 1120 |
-
# Use new barcode detection from
|
| 1121 |
try:
|
| 1122 |
-
codes_a = read_barcodes_from_path(file_a.name, max_pages=
|
| 1123 |
-
codes_b = read_barcodes_from_path(file_b.name, max_pages=
|
| 1124 |
|
| 1125 |
# Convert to old format for compatibility
|
| 1126 |
bar_a, info_a = [], []
|
|
|
|
| 52 |
HAS_REGEX = False
|
| 53 |
|
| 54 |
try:
|
| 55 |
+
from barcode_reader import read_barcodes_from_path
|
| 56 |
HAS_BARCODE = True
|
| 57 |
except Exception:
|
| 58 |
read_barcodes_from_path = None
|
|
|
|
| 1117 |
print(f"Spell check results - A: {len(misspell_a)} boxes, B: {len(misspell_b)} boxes")
|
| 1118 |
|
| 1119 |
if HAS_BARCODE:
|
| 1120 |
+
# Use new barcode detection from barcode_reader
|
| 1121 |
try:
|
| 1122 |
+
codes_a = read_barcodes_from_path(file_a.name, max_pages=8, raster_dpis=(400, 600, 900))
|
| 1123 |
+
codes_b = read_barcodes_from_path(file_b.name, max_pages=8, raster_dpis=(400, 600, 900))
|
| 1124 |
|
| 1125 |
# Convert to old format for compatibility
|
| 1126 |
bar_a, info_a = [], []
|
barcode_reader.py
ADDED
|
@@ -0,0 +1,317 @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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Robust barcode reader for images and PDFs.
|
| 3 |
+
|
| 4 |
+
Strategy (in order):
|
| 5 |
+
1) PDF -> extract embedded image XObjects at native resolution (no raster loss) and decode.
|
| 6 |
+
2) If nothing found, rasterize PDF page(s) at high DPI (400/600/900) and decode.
|
| 7 |
+
3) For plain images, decode directly.
|
| 8 |
+
|
| 9 |
+
Engines:
|
| 10 |
+
- Primary: ZXing-CPP (zxingcpp) -> no system packages required
|
| 11 |
+
- Fallback: OpenCV contrib barcode (if available)
|
| 12 |
+
|
| 13 |
+
Outputs are normalized dicts:
|
| 14 |
+
{ 'engine', 'source', 'page', 'type', 'text', 'polygon': [[x,y] * 4] }
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
import io
|
| 19 |
+
import os
|
| 20 |
+
from typing import Any, Dict, List, Tuple, Optional
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
from PIL import Image
|
| 24 |
+
import cv2
|
| 25 |
+
|
| 26 |
+
# ---------- Engines ----------
|
| 27 |
+
HAS_ZXING = False
|
| 28 |
+
try:
|
| 29 |
+
import zxingcpp # pip install zxing-cpp
|
| 30 |
+
HAS_ZXING = True
|
| 31 |
+
except Exception:
|
| 32 |
+
zxingcpp = None
|
| 33 |
+
HAS_ZXING = False
|
| 34 |
+
|
| 35 |
+
HAS_OCV_BARCODE = hasattr(cv2, "barcode") and hasattr(getattr(cv2, "barcode"), "BarcodeDetector")
|
| 36 |
+
|
| 37 |
+
# ---------- PDF (PyMuPDF) ----------
|
| 38 |
+
try:
|
| 39 |
+
import fitz # PyMuPDF
|
| 40 |
+
HAS_PYMUPDF = True
|
| 41 |
+
except Exception:
|
| 42 |
+
fitz = None
|
| 43 |
+
HAS_PYMUPDF = False
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
# =========================
|
| 47 |
+
# Utils
|
| 48 |
+
# =========================
|
| 49 |
+
|
| 50 |
+
def _to_bgr(img: Image.Image) -> np.ndarray:
|
| 51 |
+
arr = np.array(img.convert("RGB"))
|
| 52 |
+
return cv2.cvtColor(arr, cv2.COLOR_RGB2BGR)
|
| 53 |
+
|
| 54 |
+
def _as_gray(arr_bgr: np.ndarray) -> np.ndarray:
|
| 55 |
+
return cv2.cvtColor(arr_bgr, cv2.COLOR_BGR2GRAY)
|
| 56 |
+
|
| 57 |
+
def _preprocess_candidates(bgr: np.ndarray) -> List[np.ndarray]:
|
| 58 |
+
"""
|
| 59 |
+
Generate a small set of preprocess variants to improve 1D and 2D decoding.
|
| 60 |
+
Keep this list short—HF Spaces need to stay responsive.
|
| 61 |
+
"""
|
| 62 |
+
out = [bgr]
|
| 63 |
+
h, w = bgr.shape[:2]
|
| 64 |
+
|
| 65 |
+
# Slight sharpening helps thin 1D bars
|
| 66 |
+
k = np.array([[0, -1, 0],
|
| 67 |
+
[-1, 5, -1],
|
| 68 |
+
[0, -1, 0]], dtype=np.float32)
|
| 69 |
+
sharp = cv2.filter2D(bgr, -1, k)
|
| 70 |
+
out.append(sharp)
|
| 71 |
+
|
| 72 |
+
# CLAHE on gray
|
| 73 |
+
g = _as_gray(bgr)
|
| 74 |
+
clahe = cv2.createCLAHE(clipLimit=2.5, tileGridSize=(8, 8)).apply(g)
|
| 75 |
+
out.append(cv2.cvtColor(clahe, cv2.COLOR_GRAY2BGR))
|
| 76 |
+
|
| 77 |
+
# Slight upscale for tiny barcodes
|
| 78 |
+
if max(h, w) < 1600:
|
| 79 |
+
up = cv2.resize(bgr, (0, 0), fx=1.5, fy=1.5, interpolation=cv2.INTER_CUBIC)
|
| 80 |
+
out.append(up)
|
| 81 |
+
|
| 82 |
+
return out
|
| 83 |
+
|
| 84 |
+
def _norm_polygon(pts: Any, w: int, h: int) -> List[List[float]]:
|
| 85 |
+
"""
|
| 86 |
+
Normalize whatever the engine returns into 4 point polygon [[x,y],...].
|
| 87 |
+
If fewer than 4 points are given, approximate with a bounding box.
|
| 88 |
+
"""
|
| 89 |
+
try:
|
| 90 |
+
p = np.array(pts, dtype=np.float32).reshape(-1, 2)
|
| 91 |
+
if p.shape[0] >= 4:
|
| 92 |
+
p = p[:4]
|
| 93 |
+
else:
|
| 94 |
+
# make a box
|
| 95 |
+
x1, y1 = p.min(axis=0)
|
| 96 |
+
x2, y2 = p.max(axis=0)
|
| 97 |
+
p = np.array([[x1, y1], [x2, y1], [x2, y2], [x1, y2]], dtype=np.float32)
|
| 98 |
+
except Exception:
|
| 99 |
+
p = np.array([[0, 0], [w, 0], [w, h], [0, h]], dtype=np.float32)
|
| 100 |
+
return p.astype(float).tolist()
|
| 101 |
+
|
| 102 |
+
def _dedupe(results: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
| 103 |
+
"""
|
| 104 |
+
Deduplicate by (text, type) and polygon IoU.
|
| 105 |
+
"""
|
| 106 |
+
keep: List[Dict[str, Any]] = []
|
| 107 |
+
def iou(a, b):
|
| 108 |
+
ax = np.array(a["polygon"], dtype=np.float32)
|
| 109 |
+
bx = np.array(b["polygon"], dtype=np.float32)
|
| 110 |
+
a_min = ax.min(axis=0); a_max = ax.max(axis=0)
|
| 111 |
+
b_min = bx.min(axis=0); b_max = bx.max(axis=0)
|
| 112 |
+
inter_min = np.maximum(a_min, b_min)
|
| 113 |
+
inter_max = np.minimum(a_max, b_max)
|
| 114 |
+
wh = np.maximum(inter_max - inter_min, 0)
|
| 115 |
+
inter = wh[0] * wh[1]
|
| 116 |
+
a_area = (a_max - a_min).prod()
|
| 117 |
+
b_area = (b_max - b_min).prod()
|
| 118 |
+
union = max(a_area + b_area - inter, 1e-6)
|
| 119 |
+
return float(inter / union)
|
| 120 |
+
for r in results:
|
| 121 |
+
dup = False
|
| 122 |
+
for k in keep:
|
| 123 |
+
if r["text"] == k["text"] and r["type"] == k["type"] and iou(r, k) > 0.7:
|
| 124 |
+
dup = True
|
| 125 |
+
break
|
| 126 |
+
if not dup:
|
| 127 |
+
keep.append(r)
|
| 128 |
+
return keep
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
# =========================
|
| 132 |
+
# Decoders
|
| 133 |
+
# =========================
|
| 134 |
+
|
| 135 |
+
def _decode_zxing(bgr: np.ndarray) -> List[Dict[str, Any]]:
|
| 136 |
+
if not HAS_ZXING:
|
| 137 |
+
return []
|
| 138 |
+
hits: List[Dict[str, Any]] = []
|
| 139 |
+
# ZXing works on gray or color; we'll try a couple of variants
|
| 140 |
+
for candidate in _preprocess_candidates(bgr):
|
| 141 |
+
try:
|
| 142 |
+
res = zxingcpp.read_barcodes(candidate) # returns list
|
| 143 |
+
except Exception:
|
| 144 |
+
continue
|
| 145 |
+
for r in res or []:
|
| 146 |
+
try:
|
| 147 |
+
fmt = getattr(r.format, "name", str(r.format))
|
| 148 |
+
except Exception:
|
| 149 |
+
fmt = str(r.format)
|
| 150 |
+
poly = []
|
| 151 |
+
try:
|
| 152 |
+
pos = r.position # list of points with .x/.y
|
| 153 |
+
poly = [[float(pt.x), float(pt.y)] for pt in pos]
|
| 154 |
+
except Exception:
|
| 155 |
+
h, w = candidate.shape[:2]
|
| 156 |
+
poly = _norm_polygon([], w, h)
|
| 157 |
+
hits.append({
|
| 158 |
+
"engine": "zxingcpp",
|
| 159 |
+
"type": fmt,
|
| 160 |
+
"text": r.text or "",
|
| 161 |
+
"polygon": poly,
|
| 162 |
+
})
|
| 163 |
+
if hits:
|
| 164 |
+
break # good enough
|
| 165 |
+
return hits
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def _decode_opencv(bgr: np.ndarray) -> List[Dict[str, Any]]:
|
| 169 |
+
if not HAS_OCV_BARCODE:
|
| 170 |
+
return []
|
| 171 |
+
det = cv2.barcode.BarcodeDetector()
|
| 172 |
+
hits: List[Dict[str, Any]] = []
|
| 173 |
+
for candidate in _preprocess_candidates(bgr):
|
| 174 |
+
gray = _as_gray(candidate)
|
| 175 |
+
ok, infos, types, corners = det.detectAndDecode(gray)
|
| 176 |
+
if not ok:
|
| 177 |
+
continue
|
| 178 |
+
for txt, typ, pts in zip(infos, types, corners):
|
| 179 |
+
if not txt:
|
| 180 |
+
continue
|
| 181 |
+
h, w = candidate.shape[:2]
|
| 182 |
+
poly = _norm_polygon(pts, w, h)
|
| 183 |
+
hits.append({
|
| 184 |
+
"engine": "opencv_barcode",
|
| 185 |
+
"type": typ,
|
| 186 |
+
"text": txt,
|
| 187 |
+
"polygon": poly,
|
| 188 |
+
})
|
| 189 |
+
if hits:
|
| 190 |
+
break
|
| 191 |
+
return hits
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def _decode_any(bgr: np.ndarray) -> List[Dict[str, Any]]:
|
| 195 |
+
# Prefer ZXing; it's generally stronger across symbologies
|
| 196 |
+
res = _decode_zxing(bgr)
|
| 197 |
+
if res:
|
| 198 |
+
return res
|
| 199 |
+
return _decode_opencv(bgr)
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
# =========================
|
| 203 |
+
# Image & PDF readers
|
| 204 |
+
# =========================
|
| 205 |
+
|
| 206 |
+
def _pdf_extract_xobject_images(path: str, page_index: Optional[int] = None) -> List[Tuple[int, np.ndarray]]:
|
| 207 |
+
"""
|
| 208 |
+
Return (page, image_bgr) tuples for image XObjects extracted at native resolution.
|
| 209 |
+
"""
|
| 210 |
+
if not HAS_PYMUPDF:
|
| 211 |
+
return []
|
| 212 |
+
out: List[Tuple[int, np.ndarray]] = []
|
| 213 |
+
doc = fitz.open(path)
|
| 214 |
+
pages = range(len(doc)) if page_index is None else [page_index]
|
| 215 |
+
for pno in pages:
|
| 216 |
+
page = doc[pno]
|
| 217 |
+
for info in page.get_images(full=True):
|
| 218 |
+
xref = info[0]
|
| 219 |
+
pix = fitz.Pixmap(doc, xref)
|
| 220 |
+
# Convert to RGB if not already
|
| 221 |
+
if pix.n >= 4: # includes alpha or CMYK+alpha
|
| 222 |
+
pix = fitz.Pixmap(fitz.csRGB, pix)
|
| 223 |
+
pil = Image.open(io.BytesIO(pix.tobytes("png"))).convert("RGB")
|
| 224 |
+
out.append((pno, _to_bgr(pil)))
|
| 225 |
+
doc.close()
|
| 226 |
+
return out
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def _pdf_render_page(path: str, page: int, dpi: int) -> np.ndarray:
|
| 230 |
+
"""
|
| 231 |
+
Rasterize one page at the given DPI (for vector codes).
|
| 232 |
+
"""
|
| 233 |
+
if not HAS_PYMUPDF:
|
| 234 |
+
raise RuntimeError("PyMuPDF not available; cannot rasterize PDF.")
|
| 235 |
+
doc = fitz.open(path)
|
| 236 |
+
if page >= len(doc):
|
| 237 |
+
doc.close()
|
| 238 |
+
raise ValueError(f"Page {page} out of range; PDF has {len(doc)} pages.")
|
| 239 |
+
pg = doc[page]
|
| 240 |
+
scale = dpi / 72.0
|
| 241 |
+
mat = fitz.Matrix(scale, scale)
|
| 242 |
+
pix = pg.get_pixmap(matrix=mat, alpha=False)
|
| 243 |
+
pil = Image.open(io.BytesIO(pix.tobytes("png"))).convert("RGB")
|
| 244 |
+
doc.close()
|
| 245 |
+
return _to_bgr(pil)
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def _decode_image_path(path: str) -> List[Dict[str, Any]]:
|
| 249 |
+
pil = Image.open(path).convert("RGB")
|
| 250 |
+
bgr = _to_bgr(pil)
|
| 251 |
+
hits = _decode_any(bgr)
|
| 252 |
+
for h in hits:
|
| 253 |
+
h.update({"source": "image", "page": 0})
|
| 254 |
+
return _dedupe(hits)
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def _decode_pdf_path(path: str, max_pages: int = 8, raster_dpis: Tuple[int, ...] = (400, 600, 900)) -> List[Dict[str, Any]]:
|
| 258 |
+
results: List[Dict[str, Any]] = []
|
| 259 |
+
# 1) Try original embedded images first
|
| 260 |
+
for pno, img_bgr in _pdf_extract_xobject_images(path):
|
| 261 |
+
hits = _decode_any(img_bgr)
|
| 262 |
+
for h in hits:
|
| 263 |
+
h.update({"source": "pdf_xobject_image", "page": pno})
|
| 264 |
+
results.extend(hits)
|
| 265 |
+
if results:
|
| 266 |
+
return _dedupe(results)
|
| 267 |
+
|
| 268 |
+
# 2) Fallback: rasterize pages at increasing DPIs
|
| 269 |
+
if not HAS_PYMUPDF:
|
| 270 |
+
# No way to rasterize; return empty
|
| 271 |
+
return []
|
| 272 |
+
doc = fitz.open(path)
|
| 273 |
+
n = min(len(doc), max_pages)
|
| 274 |
+
doc.close()
|
| 275 |
+
for dpi in raster_dpis:
|
| 276 |
+
for pno in range(n):
|
| 277 |
+
img_bgr = _pdf_render_page(path, pno, dpi=dpi)
|
| 278 |
+
hits = _decode_any(img_bgr)
|
| 279 |
+
for h in hits:
|
| 280 |
+
h.update({"source": f"pdf_raster_{dpi}dpi", "page": pno})
|
| 281 |
+
results.extend(hits)
|
| 282 |
+
if results:
|
| 283 |
+
break
|
| 284 |
+
return _dedupe(results)
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
# =========================
|
| 288 |
+
# Public API
|
| 289 |
+
# =========================
|
| 290 |
+
|
| 291 |
+
def read_barcodes_from_path(path: str,
|
| 292 |
+
max_pages: int = 8,
|
| 293 |
+
raster_dpis: Tuple[int, ...] = (400, 600, 900)) -> List[Dict[str, Any]]:
|
| 294 |
+
"""
|
| 295 |
+
Auto-detect by extension, decode barcodes, and return a list of dicts:
|
| 296 |
+
{engine, source, page, type, text, polygon}
|
| 297 |
+
"""
|
| 298 |
+
ext = os.path.splitext(path.lower())[1]
|
| 299 |
+
if ext == ".pdf":
|
| 300 |
+
return _decode_pdf_path(path, max_pages=max_pages, raster_dpis=raster_dpis)
|
| 301 |
+
else:
|
| 302 |
+
return _decode_image_path(path)
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
# =========================
|
| 306 |
+
# Optional: drawing helper
|
| 307 |
+
# =========================
|
| 308 |
+
|
| 309 |
+
def draw_barcodes(bgr: np.ndarray, detections: List[Dict[str, Any]]) -> np.ndarray:
|
| 310 |
+
out = bgr.copy()
|
| 311 |
+
for d in detections:
|
| 312 |
+
poly = np.array(d["polygon"], dtype=np.int32).reshape(-1, 1, 2)
|
| 313 |
+
cv2.polylines(out, [poly], True, (0, 255, 0), 2)
|
| 314 |
+
txt = f'{d["type"]}: {d["text"]}'
|
| 315 |
+
x, y = poly[0, 0, 0], poly[0, 0, 1]
|
| 316 |
+
cv2.putText(out, txt[:48], (x, max(15, y - 6)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 50, 255), 1, cv2.LINE_AA)
|
| 317 |
+
return out
|
barcode_utils.py
DELETED
|
@@ -1,169 +0,0 @@
|
|
| 1 |
-
import io
|
| 2 |
-
import os
|
| 3 |
-
from typing import List, Dict, Any, Tuple, Optional
|
| 4 |
-
|
| 5 |
-
import cv2
|
| 6 |
-
import numpy as np
|
| 7 |
-
from PIL import Image
|
| 8 |
-
|
| 9 |
-
# PDF support via PyMuPDF (preferred for extracting original image XObjects)
|
| 10 |
-
try:
|
| 11 |
-
import fitz # PyMuPDF
|
| 12 |
-
HAS_PYMUPDF = True
|
| 13 |
-
except Exception:
|
| 14 |
-
fitz = None
|
| 15 |
-
HAS_PYMUPDF = False
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
def _ensure_contrib():
|
| 19 |
-
if not hasattr(cv2, "barcode") or not hasattr(cv2.barcode, "BarcodeDetector"):
|
| 20 |
-
raise RuntimeError(
|
| 21 |
-
"OpenCV was built without the 'barcode' module. "
|
| 22 |
-
"Install 'opencv-contrib-python-headless' (not 'opencv-python-headless')."
|
| 23 |
-
)
|
| 24 |
-
|
| 25 |
-
def _pil_to_bgr(pil: Image.Image) -> np.ndarray:
|
| 26 |
-
arr = np.array(pil.convert("RGB"))
|
| 27 |
-
return cv2.cvtColor(arr, cv2.COLOR_RGB2BGR)
|
| 28 |
-
|
| 29 |
-
def _decode_with_opencv(img_bgr: np.ndarray) -> List[Dict[str, Any]]:
|
| 30 |
-
_ensure_contrib()
|
| 31 |
-
det = cv2.barcode.BarcodeDetector()
|
| 32 |
-
|
| 33 |
-
# Try 4 orientations
|
| 34 |
-
results: List[Dict[str, Any]] = []
|
| 35 |
-
for k, rot in enumerate([0, 1, 2, 3]): # 0, 90, 180, 270
|
| 36 |
-
if rot > 0:
|
| 37 |
-
img = np.ascontiguousarray(np.rot90(img_bgr, k=rot))
|
| 38 |
-
else:
|
| 39 |
-
img = img_bgr
|
| 40 |
-
|
| 41 |
-
# Optional light preproc to help 1D codes
|
| 42 |
-
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
| 43 |
-
gray = cv2.bilateralFilter(gray, d=5, sigmaColor=50, sigmaSpace=50)
|
| 44 |
-
|
| 45 |
-
ok, decoded_info, decoded_type, corners = det.detectAndDecode(gray)
|
| 46 |
-
if not ok:
|
| 47 |
-
continue
|
| 48 |
-
|
| 49 |
-
# corners: list of Nx4x2
|
| 50 |
-
for txt, typ, pts in zip(decoded_info, decoded_type, corners):
|
| 51 |
-
if not txt:
|
| 52 |
-
continue
|
| 53 |
-
pts = np.asarray(pts, dtype=np.float32)
|
| 54 |
-
# rotate points back to original orientation
|
| 55 |
-
if rot > 0:
|
| 56 |
-
h, w = img_bgr.shape[:2]
|
| 57 |
-
if rot == 1: # 90
|
| 58 |
-
pts = np.stack([h - pts[:,1], pts[:,0]], axis=1)
|
| 59 |
-
elif rot == 2: # 180
|
| 60 |
-
pts = np.stack([w - pts[:,0], h - pts[:,1]], axis=1)
|
| 61 |
-
elif rot == 3: # 270
|
| 62 |
-
pts = np.stack([pts[:,1], w - pts[:,0]], axis=1)
|
| 63 |
-
|
| 64 |
-
results.append({
|
| 65 |
-
"text": txt,
|
| 66 |
-
"type": typ,
|
| 67 |
-
"polygon": pts.tolist(), # four points
|
| 68 |
-
"rotation_quarters": rot
|
| 69 |
-
})
|
| 70 |
-
return results
|
| 71 |
-
|
| 72 |
-
def _extract_pdf_images_bgr(path: str, page_index: Optional[int] = None) -> List[Tuple[int, np.ndarray]]:
|
| 73 |
-
"""
|
| 74 |
-
Returns list of (page_idx, img_bgr) extracted at native resolution from image XObjects.
|
| 75 |
-
"""
|
| 76 |
-
if not HAS_PYMUPDF:
|
| 77 |
-
return []
|
| 78 |
-
out: List[Tuple[int, np.ndarray]] = []
|
| 79 |
-
doc = fitz.open(path)
|
| 80 |
-
pages = range(len(doc)) if page_index is None else [page_index]
|
| 81 |
-
for pno in pages:
|
| 82 |
-
page = doc[pno]
|
| 83 |
-
for imginfo in page.get_images(full=True):
|
| 84 |
-
xref = imginfo[0]
|
| 85 |
-
pix = fitz.Pixmap(doc, xref)
|
| 86 |
-
# Convert to RGB if needed
|
| 87 |
-
if pix.n >= 4: # RGBA or CMYK+alpha
|
| 88 |
-
pix = fitz.Pixmap(fitz.csRGB, pix)
|
| 89 |
-
pil = Image.open(io.BytesIO(pix.tobytes("png"))).convert("RGB")
|
| 90 |
-
out.append((pno, _pil_to_bgr(pil)))
|
| 91 |
-
pix = None
|
| 92 |
-
doc.close()
|
| 93 |
-
return out
|
| 94 |
-
|
| 95 |
-
def _render_pdf_page_bgr(path: str, pno: int, dpi: int = 600) -> np.ndarray:
|
| 96 |
-
if not HAS_PYMUPDF:
|
| 97 |
-
raise RuntimeError("PyMuPDF not available to render PDF pages.")
|
| 98 |
-
doc = fitz.open(path)
|
| 99 |
-
if pno >= len(doc):
|
| 100 |
-
doc.close()
|
| 101 |
-
raise ValueError(f"Page {pno} out of range (PDF has {len(doc)} pages).")
|
| 102 |
-
page = doc[pno]
|
| 103 |
-
scale = dpi / 72.0
|
| 104 |
-
mat = fitz.Matrix(scale, scale)
|
| 105 |
-
pix = page.get_pixmap(matrix=mat, alpha=False)
|
| 106 |
-
pil = Image.open(io.BytesIO(pix.tobytes("png"))).convert("RGB")
|
| 107 |
-
doc.close()
|
| 108 |
-
return _pil_to_bgr(pil)
|
| 109 |
-
|
| 110 |
-
def read_barcodes_from_path(path: str, max_pages: int = 5, raster_dpi: int = 900) -> List[Dict[str, Any]]:
|
| 111 |
-
"""
|
| 112 |
-
Unified entry point:
|
| 113 |
-
- For images: decode directly with OpenCV.
|
| 114 |
-
- For PDFs: try original image XObjects first (raw), then rasterize pages at high DPI as fallback.
|
| 115 |
-
Returns a list of dicts: {source, page, type, text, polygon}
|
| 116 |
-
"""
|
| 117 |
-
ext = os.path.splitext(path.lower())[1]
|
| 118 |
-
results: List[Dict[str, Any]] = []
|
| 119 |
-
|
| 120 |
-
if ext == ".pdf":
|
| 121 |
-
# 1) Try native images embedded in the PDF
|
| 122 |
-
for pno, img in _extract_pdf_images_bgr(path):
|
| 123 |
-
hits = _decode_with_opencv(img)
|
| 124 |
-
for h in hits:
|
| 125 |
-
results.append({
|
| 126 |
-
"source": "pdf_xobject_image",
|
| 127 |
-
"page": pno,
|
| 128 |
-
**h
|
| 129 |
-
})
|
| 130 |
-
if results:
|
| 131 |
-
return results
|
| 132 |
-
|
| 133 |
-
# 2) Fallback: rasterize a few pages crisply and decode
|
| 134 |
-
if not HAS_PYMUPDF:
|
| 135 |
-
raise RuntimeError("No PyMuPDF; cannot rasterize PDF pages. Add 'pymupdf' to requirements.")
|
| 136 |
-
doc = fitz.open(path)
|
| 137 |
-
for pno in range(min(len(doc), max_pages)):
|
| 138 |
-
page_img = _render_pdf_page_bgr(path, pno, dpi=raster_dpi)
|
| 139 |
-
hits = _decode_with_opencv(page_img)
|
| 140 |
-
for h in hits:
|
| 141 |
-
results.append({
|
| 142 |
-
"source": "pdf_rasterized",
|
| 143 |
-
"page": pno,
|
| 144 |
-
**h
|
| 145 |
-
})
|
| 146 |
-
doc.close()
|
| 147 |
-
return results
|
| 148 |
-
|
| 149 |
-
else:
|
| 150 |
-
# Image path
|
| 151 |
-
pil = Image.open(path).convert("RGB")
|
| 152 |
-
img = _pil_to_bgr(pil)
|
| 153 |
-
hits = _decode_with_opencv(img)
|
| 154 |
-
for h in hits:
|
| 155 |
-
results.append({
|
| 156 |
-
"source": "image",
|
| 157 |
-
"page": 0,
|
| 158 |
-
**h
|
| 159 |
-
})
|
| 160 |
-
return results
|
| 161 |
-
|
| 162 |
-
def draw_polys(bgr: np.ndarray, polys: list) -> np.ndarray:
|
| 163 |
-
"""Draw polygons on the image for visualization"""
|
| 164 |
-
out = bgr.copy()
|
| 165 |
-
for p in polys:
|
| 166 |
-
if "polygon" in p:
|
| 167 |
-
pts = np.array(p["polygon"], dtype=np.int32).reshape(-1,1,2)
|
| 168 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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
requirements.txt
CHANGED
|
@@ -1,9 +1,10 @@
|
|
| 1 |
-
opencv-contrib-python-headless==4.10.0.84
|
| 2 |
numpy
|
| 3 |
pillow
|
|
|
|
|
|
|
|
|
|
| 4 |
pdf2image
|
| 5 |
gradio
|
| 6 |
-
PyMuPDF>=1.24
|
| 7 |
pytesseract
|
| 8 |
pyspellchecker
|
| 9 |
regex
|
|
|
|
|
|
|
| 1 |
numpy
|
| 2 |
pillow
|
| 3 |
+
pymupdf
|
| 4 |
+
opencv-contrib-python-headless==4.10.0.84
|
| 5 |
+
zxing-cpp>=2.2.0
|
| 6 |
pdf2image
|
| 7 |
gradio
|
|
|
|
| 8 |
pytesseract
|
| 9 |
pyspellchecker
|
| 10 |
regex
|