File size: 2,811 Bytes
9673228 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | import requests, re, json, base64, io, os
H = "https://huggingface.co"
from pymupdf import Document as MuDoc
from PIL import Image, ImageDraw
def norm(s):
return "".join(ch for ch in str(s) if ch.isdigit())
# download pdf + rasters for pages 79,81
pdf = requests.get(H + "/datasets/bep40/grob-products-updated/resolve/main/pdfs/imudex_2026.pdf", timeout=600).content
open("/tmp/imudex.pdf", "wb").write(pdf)
doc = MuDoc("/tmp/imudex.pdf")
pgw, pgh = 1133.86, 793.70
def raster(pgn):
key = "page_%04d.jpg" % pgn
r = requests.get(H + f"/datasets/bep40/grob-products-updated/resolve/main/catpages/imudex-2026/{key}", timeout=120)
return Image.open(io.BytesIO(r.content))
# SKU -> (pdf_page_index, row_y) use the code rows found earlier
# page 81 (index 80): 7 801 700 y=214.8, 7 804 104 y=197.2, 7 801 100 y=446
# page 79 (index 78): 7 809 104 y=232.5
targets = {
"7801700": (80, 214.8),
"7804104": (80, 197.2),
"7801100": (80, 446.0),
"7809104": (78, 232.5),
}
os.makedirs("/out", exist_ok=True)
# full pages (downscaled) for reference
for pgn, label in [(78, "page79"), (80, "page81")]:
img = raster(pgn)
img.thumbnail((1100, 1100))
img.save(f"/out/{label}_full.jpg", "JPEG", quality=80)
print("saved", label, img.size)
# for each target, crop the actual card image used + mark image bbox on a page crop
for sk, (pgn, rowy) in targets.items():
pg = doc[pgn]
# find nearest big image bbox
best = None; bd = 1e15
for ip in pg.get_image_info():
bb = ip["bbox"]; w = ip.get("width") or 0; h = ip.get("height") or 0
if w < 160 or h < 110: continue
icx = (bb[0]+bb[2])/2; icy = (bb[1]+bb[3])/2
dd = (icx-817)**2 + (icy-rowy)**2
if dd < bd: bd = dd; best = bb
img = raster(pgn)
sx = img.size[0]/pgw; sy = img.size[1]/pgh
if best:
box = (int(best[0]*sx), int(best[1]*sy), int(best[2]*sx), int(best[3]*sy))
cr = img.crop(box); cr.thumbnail((340,340), Image.LANCZOS)
cr.save(f"/out/{sk}_crop.jpg", "JPEG", quality=85)
# annotate full page region around the image + code row
region = img.crop((int(55*sx), int(60*sy), int(1100*sx), int(500*sy)))
region = region.copy()
d = ImageDraw.Draw(region)
# draw image bbox
ib = (int(best[0]*sx)-int(55*sx), int(best[1]*sy)-int(60*sy), int(best[2]*sx)-int(55*sx), int(best[3]*sy)-int(60*sy))
d.rectangle(ib, outline="red", width=6)
# code row line
cy = int(rowy*sy)-int(60*sy)
d.line([(0,cy),(region.size[0],cy)], fill="blue", width=4)
region.save(f"/out/{sk}_page.jpg", "JPEG", quality=80)
print(f"{sk}: img_bbox={[round(v) for v in best]} crop saved; page region saved")
else:
print(f"{sk}: no image found")
print("done /out")
|