Datasets:
File size: 2,854 Bytes
71a693d 7df0ef8 71a693d 7df0ef8 71a693d 7df0ef8 71a693d 7df0ef8 71a693d 7df0ef8 | 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 71 72 73 74 75 76 77 78 79 80 81 82 | import requests, re, json, os
H = "https://huggingface.co"
from pymupdf import Document as MuDoc
def norm(s): return re.sub(r'[^0-9]','',str(s))
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")
code_pat=re.compile(r'^[\d\s.]{6,}$')
def parse_page(pgn):
pg=doc[pgn]; d=pg.get_text("dict")
lines=[]
for b in d["blocks"]:
if b["type"]!=0: continue
blktext="".join(s["text"] for l in b["lines"] for s in l["spans"])
for l in b["lines"]:
txt="".join(s["text"] for s in l["spans"]).strip()
if txt:
x0,y0,x1,y1=l["bbox"]
lines.append({"x0":round(x0,1),"y0":round(y0,1),"x1":round(x1,1),"y1":round(y1,1),"t":txt,"block":blktext.strip()})
imgs=[]
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 and h>=110:
imgs.append({"x0":bb[0],"y0":bb[1],"x1":bb[2],"y1":bb[3],"w":w,"h":h})
return lines,imgs
def side_of_x(x): return 'L' if x<567 else 'R'
def nearest_img_col(side, code_y, imgs):
cand=[im for im in imgs if side_of_x((im["x0"]+im["x1"])/2)==side]
if not cand: return None
bd=1e15; best=None
for im in cand:
icy=(im["y0"]+im["y1"])/2
dd=abs(icy-code_y)
if dd<bd: bd=dd; best=im
return best
def is_footnote_code(line):
return len(line["block"]) > len(line["t"])+2
pages_cached={pgn:parse_page(pgn) for pgn in range(len(doc))}
def page_code_blocks(pgn):
lines=pages_cached[pgn][0]
codes=[]
for l in lines:
t=l["t"].strip()
if code_pat.match(t) and len(t)>=6 and not is_footnote_code(l):
codes.append(l)
codes.sort(key=lambda l:(l["x0"],l["y0"]))
blocks=[]
for c in codes:
side=side_of_x(c["x0"])
cur=None
for b in blocks:
if b["side"]==side and abs(c["y0"]-b["codes"][-1]["y0"])<22:
cur=b; break
if cur is None:
cur={"side":side,"codes":[c]}; blocks.append(cur)
else:
cur["codes"].append(c)
for b in blocks:
first=b["codes"][0]
b["img"]=nearest_img_col(b["side"], first["y0"], pages_cached[pgn][1])
return blocks
for pgn in [80, 119, 118]:
blocks=page_code_blocks(pgn)
print(f"=== PAGE {pgn+1} (pdf idx {pgn}) ===")
for b in blocks:
im=b["img"]
print(f"side={b['side']} codes={[c['t'] for c in b['codes']]} first_y={b['codes'][0]['y0']} img={[round(im['x0']),round(im['y0']),round(im['x1']),round(im['y1'])] if im else None}")
print("\n=== page 79 'Tên hàng' lines ===")
for l in pages_cached[78][0]:
if l["t"].strip()=="Tên hàng":
print(l["x0"], l["y0"])
print("DONE") |