ZZZ Digital Lab

Back to PDF tables to sheets

make_images.py

"""Render 1000x750 portfolio cards from real local evidence. No stock assets."""
import json,argparse
from pathlib import Path
from PIL import Image,ImageDraw,ImageFont
ROOT=Path(__file__).resolve().parent
BG='#eff3f8'; NAVY='#14283f'; MUTED='#536a80'; GREEN='#087c64'; RED='#b83f48'; AMBER='#976400'; LINE='#d8e1ec'
def font(size,bold=False,mono=False):
 names=['consola.ttf','DejaVuSansMono.ttf'] if mono else (['segoeuib.ttf','DejaVuSans-Bold.ttf'] if bold else ['segoeui.ttf','DejaVuSans.ttf'])
 for name in names:
  try: return ImageFont.truetype(name,size)
  except OSError: pass
 return ImageFont.load_default(size=size)
def text(d,xy,value,size=20,fill=NAVY,bold=False,mono=False,max_width=None):
 f=font(size,bold,mono)
 if max_width is not None:
  while d.textbbox((0,0),value,font=f)[2]>max_width and size>13: size-=1; f=font(size,bold,mono)
  if d.textbbox((0,0),value,font=f)[2]>max_width: raise ValueError('Text exceeds card: '+value)
 d.text(xy,value,font=f,fill=fill)
def card(title,subtitle):
 im=Image.new('RGB',(1000,750),BG); d=ImageDraw.Draw(im)
 d.rectangle((0,0,1000,13),fill=GREEN); text(d,(44,35),'SYNTHETIC PORTFOLIO DEMO',15,GREEN,True)
 text(d,(44,69),title,36,bold=True,max_width=912); text(d,(44,121),subtitle,19,MUTED,max_width=912)
 return im,d
def panel(d,box,fill='white'): d.rounded_rectangle(box,16,fill=fill)
def footer(d,left,right):
 d.line((44,692,956,692),fill=LINE,width=2); text(d,(44,708),left,15,MUTED,max_width=660); text(d,(752,708),right,15,GREEN,True,max_width=204)
def save(im,root,name):
 (root/'images').mkdir(exist_ok=True); im.save(root/'images'/name)
def load(root,name): return json.loads((root/name).read_text(encoding='utf-8'))
def pdf():
 import fitz
 from openpyxl import load_workbook
 root=ROOT; demo=load(root,'evidence/demo.json'); tests=load(root,'evidence/tests.json'); qa=load(root,'output/qa.json')
 preview=root/'evidence/previews'; preview.mkdir(parents=True,exist_ok=True)
 for kind in ['invoice','statement']:
  with fitz.open(root/'sources'/(kind+'.pdf')) as doc:
   for i,page in enumerate(doc): page.get_pixmap(matrix=fitz.Matrix(1.2,1.2),alpha=False).save(preview/(kind+'-page-'+str(i+1)+'.png'))
 im,d=card('PDF tables with quality evidence','Four local source pages, structured outputs and an explicit review queue')
 panel(d,(44,176,456,659)); text(d,(64,190),'ACTUAL SYNTHETIC SOURCE PAGES',15,MUTED,True)
 for i,kind in enumerate(['invoice','statement']):
  thumb=Image.open(preview/(kind+'-page-1.png')).convert('RGB'); thumb.thumbnail((180,300))
  im.paste(thumb,(63+i*193,237)); text(d,(66+i*193,494),kind+' / page 1',15,MUTED)
 text(d,(64,548),'2 invoices pages + 2 statement pages'.replace('invoices','invoice'),17,max_width=372)
 text(d,(64,581),'Generated with ReportLab.',18); text(d,(64,613),'Extracted locally with pdfplumber.',18,max_width=372)
 panel(d,(480,176,956,388)); text(d,(500,193),'ROW COMPLETENESS',17,GREEN,True)
 text(d,(500,237),'Document',18,MUTED); text(d,(704,237),'Before',18,MUTED); text(d,(830,237),'After',18,MUTED)
 for i,kind in enumerate(['invoice','statement']):
  y=279+i*48; text(d,(500,y),kind.title(),22,bold=True); text(d,(720,y),str(demo['before_rows'][kind]),24,RED,True); text(d,(842,y),str(demo['after_rows'][kind]),24,GREEN,True)
 panel(d,(480,410,956,659),NAVY); text(d,(500,428),str(qa['total_rows'])+' rows with page/row provenance',23,'white',True,max_width=436)
 text(d,(500,479),'Invoice subtotal: 550.50  PASS',21,'#9bdcca'); text(d,(500,519),'1 low-confidence amount stays blank',20,'#ffce7e',max_width=436)
 text(d,(500,563),qa['overall_quality'],24,'#ffce7e',True); text(d,(500,611),f"{tests['passed']}/{tests['passed']+tests['failed']} local regression tests pass",21,'white')
 footer(d,'Actual outputs: output/qa.json and evidence/demo.json','No OCR or uploads'); save(im,root,'01-before-after.png')
 im,d=card('A quality report that exposes uncertainty','Column controls, row arithmetic and original page/row references')
 panel(d,(44,174,956,464)); text(d,(64,190),'CONTROL',16,MUTED,True); text(d,(456,190),'KNOWN SUM',16,MUTED,True); text(d,(625,190),'SOURCE',16,MUTED,True); text(d,(779,190),'STATUS',16,MUTED,True)
 inv,st=qa['documents']; rows=[('Invoice amount',inv['totals']['Amount']),('Statement debits',st['totals']['Debit']),('Statement credits',st['totals']['Credit']),('Closing balance',st['totals']['Closing balance'])]
 for i,(label,v) in enumerate(rows):
  y=240+i*50; text(d,(64,y),label,20); text(d,(456,y),v['actual'],21,bold=True); text(d,(625,y),v['expected'],21); text(d,(779,y),v['status'],18,GREEN if v['status']=='PASS' else AMBER,True,max_width=158)
 flag=st['low_confidence_cells'][0]; panel(d,(44,489,956,665),NAVY)
 text(d,(64,505),'MANUAL REVIEW REQUIRED',18,'#ffce7e',True); text(d,(64,544),flag['provenance']+'  /  '+flag['column'],23,'white',mono=True,max_width=860)
 text(d,(64,583),'Raw source: '+flag['raw_value']+'     Exported value: blank',21,'white',mono=True,max_width=860)
 text(d,(64,624),'No guessed amount. Debit total and net movement remain incomplete.',19,'#ffce7e',max_width=860)
 footer(d,'LOW is a parsing rule flag, not a calibrated probability','20/20 tests pass'); save(im,root,'02-quality-report.png')
 # Review previews from saved workbook values/types; not a native Excel screenshot.
 wb=load_workbook(root/'output/extracted.xlsx')
 for ws in wb:
  values=list(ws.values); widths=[]
  for col in range(ws.max_column):
   longest=max(len(str(row[col] if col<len(row) and row[col] is not None else '')) for row in values)
   widths.append(min(580,max(115,longest*8+20)))
  w=sum(widths)+40; h=100+len(values)*38; view=Image.new('RGB',(w,h),'white'); vd=ImageDraw.Draw(view)
  text(vd,(20,16),'SYNTHETIC '+ws.title+' | saved workbook values preview (Pillow)',18,bold=True)
  for ri,row in enumerate(values):
   x=20; y=64+ri*38
   for ci,value in enumerate(row):
    vd.rectangle((x,y,x+widths[ci],y+38),fill=NAVY if ri==0 else ('#fff1cc' if ws.title=='statement' and ri==4 else '#f4f7fb'),outline=LINE)
    display='' if value is None else str(value)
    text(vd,(x+8,y+8),display,15,'white' if ri==0 else NAVY,max_width=widths[ci]-16); x+=widths[ci]
  view.save(preview/('workbook-'+ws.title+'.png'))
 wb.close(); return root


if __name__=='__main__':
    pdf()
    print('Rendered two evidence-based PNGs, 1000x750, in images/')