feat: reproducibility package — scripts por máquina (runners/gppd-slurm/b200-apptainer/rtx-docker/spark-ollama) com fixes
083e9dc verified | #!/usr/bin/env python3 | |
| """ | |
| Scherm OCR — velocidade + SALVA texto extraído (pra medir acurácia depois). | |
| Compara modelos de OCR (NuMarkdown, DeepSeek-OCR, DeepSeek-OCR-2, Qwen-VL) nas MESMAS páginas. | |
| Diferença do run_ocr_pages.py: salva o markdown/texto que cada modelo extrai (pra comparar | |
| qualidade contra ground-truth). Prompt parametrizável (DeepSeek usa formato próprio). | |
| Uso: | |
| python3 run_ocr_accuracy.py --served-model deepseek-ocr --base-url http://localhost:8000/v1 \ | |
| --pages-dir ./pages --doc-sizes 1 5 50 --concurrencies 1 4 --reps 3 \ | |
| --prompt-style deepseek --out ./results --tag GPU --run-id RID | |
| """ | |
| import argparse, base64, json, os, time, urllib.request, statistics | |
| PROMPTS = { | |
| # NuMarkdown / Qwen-VL: instrução de extração | |
| "numarkdown": "Extract all text from this document page as markdown.", | |
| # DeepSeek-OCR: formato grounding (doc oficial vLLM recipes) | |
| "deepseek": "<image>\n<|grounding|>Convert the document to markdown.", | |
| } | |
| def quantiles(xs): | |
| xs=sorted(x for x in xs if x is not None) | |
| if not xs: return {} | |
| def q(p): | |
| if len(xs)==1: return xs[0] | |
| i=p*(len(xs)-1); lo=int(i); frac=i-lo | |
| return xs[lo] if lo+1>=len(xs) else xs[lo]*(1-frac)+xs[lo+1]*frac | |
| return {"median":q(0.5),"q1":q(0.25),"q3":q(0.75),"min":xs[0],"max":xs[-1]} | |
| def ocr_one_page(base_url, model, img_b64, max_tokens, prompt_text): | |
| """1 OCR. Retorna (ok, tokens_out, TEXTO_extraído).""" | |
| url=f"{base_url}/chat/completions" | |
| body={"model":model,"max_tokens":max_tokens,"temperature":0,"messages":[ | |
| {"role":"user","content":[ | |
| {"type":"text","text":prompt_text}, | |
| {"type":"image_url","image_url":{"url":f"data:image/png;base64,{img_b64}"}}]}]} | |
| last_err=None | |
| for attempt in range(3): | |
| try: | |
| req=urllib.request.Request(url,data=json.dumps(body).encode(), | |
| headers={"Content-Type":"application/json"}) | |
| with urllib.request.urlopen(req,timeout=600) as r: | |
| d=json.loads(r.read()) | |
| txt=d.get("choices",[{}])[0].get("message",{}).get("content","") | |
| return True, d.get("usage",{}).get("completion_tokens",0), txt | |
| except Exception as e: | |
| last_err=e | |
| import time as _t; _t.sleep(2*(attempt+1)) | |
| import sys; print(f"[FALHOU 3x] {repr(last_err)}", file=sys.stderr, flush=True) | |
| return False, 0, "" | |
| def main(): | |
| ap=argparse.ArgumentParser() | |
| ap.add_argument("--served-model",required=True) | |
| ap.add_argument("--base-url",required=True) | |
| ap.add_argument("--pages-dir",required=True) | |
| ap.add_argument("--doc-sizes",nargs="+",type=int,default=[1,5,50]) | |
| ap.add_argument("--concurrencies",nargs="+",type=int,default=[1,4]) | |
| ap.add_argument("--reps",type=int,default=3) | |
| ap.add_argument("--max-tokens",type=int,default=2048) # OCR markdown pode ser longo | |
| ap.add_argument("--prompt-style",choices=["numarkdown","deepseek"],default="numarkdown") | |
| ap.add_argument("--model-label",default="") # nome real do modelo (pra arquivos de texto) | |
| ap.add_argument("--out",required=True); ap.add_argument("--tag",default=""); ap.add_argument("--run-id",default="") | |
| a=ap.parse_args() | |
| os.makedirs(a.out,exist_ok=True) | |
| label=a.model_label or a.served_model.replace("/","_").replace(":","_") | |
| txtdir=os.path.join(a.out,"extracted_text",label); os.makedirs(txtdir,exist_ok=True) | |
| pngs=sorted(f for f in os.listdir(a.pages_dir) if f.endswith(".png") and not f.startswith("._")) | |
| pages_b64=[base64.b64encode(open(os.path.join(a.pages_dir,f),"rb").read()).decode() for f in pngs] | |
| prompt_text=PROMPTS[a.prompt_style] | |
| # 1) SALVAR o texto extraído de CADA página (1 vez, pra acurácia) — page-NN.md | |
| print(f"[*] {label}: extraindo texto de {len(pngs)} páginas (salvando pra acurácia)...",flush=True) | |
| for i,(fn,pb) in enumerate(zip(pngs,pages_b64)): | |
| ok,tok,txt=ocr_one_page(a.base_url,a.served_model,pb,a.max_tokens,prompt_text) | |
| outp=os.path.join(txtdir,fn.replace(".png",".md")) | |
| open(outp,"w").write(txt if ok else "[OCR_FAILED]") | |
| if i==0: print(f" {fn}: {len(txt)} chars, {tok} tokens",flush=True) | |
| print(f"[*] textos salvos em {txtdir}",flush=True) | |
| # 2) matriz de VELOCIDADE (doc N págs sequenciais × conc docs simultâneos) | |
| from concurrent.futures import ThreadPoolExecutor | |
| safe=a.served_model.replace("/","_").replace(":","_") | |
| csv_path=os.path.join(a.out,f"ocr_{a.tag}_{a.run_id}_{safe}.csv") | |
| fcsv=open(csv_path,"w") | |
| fcsv.write("gpu,model,prompt_style,doc_pages,concurrency,n_ok,doc_latency_ms_median,ms_per_page_median,total_tok_s_median\n") | |
| def proc_doc(npages): | |
| t0=time.time(); tot=0 | |
| for pb in pages_b64[:npages]: | |
| ok,tok,_=ocr_one_page(a.base_url,a.served_model,pb,a.max_tokens,prompt_text) | |
| if not ok: return None | |
| tot+=tok | |
| return (time.time()-t0)*1000.0, tot | |
| for npages in a.doc_sizes: | |
| if npages>len(pages_b64): print(f"[skip] {npages}>{len(pages_b64)}",flush=True); continue | |
| for conc in a.concurrencies: | |
| lats=[]; tps=[] | |
| for _ in range(a.reps): | |
| with ThreadPoolExecutor(max_workers=conc) as ex: | |
| res=list(ex.map(lambda _:proc_doc(npages),range(conc))) | |
| for r in res: | |
| if r: lats.append(r[0]); tps.append(r[1]/(r[0]/1000.0) if r[0]>0 else 0) | |
| ag=quantiles(lats); mlat=ag.get("median") | |
| fcsv.write(f"{a.tag},{a.served_model},{a.prompt_style},{npages},{conc},{len(lats)}," | |
| f"{mlat or ''},{(mlat/npages) if mlat else ''},{quantiles(tps).get('median','')}\n"); fcsv.flush() | |
| print(f" doc={npages}p conc={conc} n_ok={len(lats)} lat={mlat:.0f}ms" if mlat else f" doc={npages}p conc={conc} n_ok=0",flush=True) | |
| fcsv.close() | |
| print(f"[OK] {a.served_model} -> {csv_path}",flush=True) | |
| if __name__=="__main__": main() | |