packaging / generate_dataset.py
zak0102's picture
initial (#1)
96a2e5d
Raw
History Blame Contribute Delete
14.7 kB
import json, random, shutil, zipfile, time
from pathlib import Path
from datetime import date, timedelta
from PIL import Image, ImageDraw, ImageFont
ROOT = Path('/mnt/data/packaging_slip_donut_dataset')
ZIP_PATH = Path('/mnt/data/packaging_slip_donut_dataset.zip')
SEED = 314159
random.seed(SEED)
SPLIT_SIZES = {'train': 50, 'val': 50, 'test': 50}
# Scaled A4-like page. Good enough for Donut fine-tuning and much faster to render than 150 DPI A4.
W, H = 900, 1272
S = W / 1240.0
def sc(v): return int(round(v * S))
def font_size(v): return max(8, int(round(v * S)))
FONT_REG = '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf'
FONT_BOLD = '/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf'
FONT_MONO = '/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf'
FONT_SERIF_BOLD = '/usr/share/fonts/truetype/dejavu/DejaVuSerif-Bold.ttf'
def font(path, size): return ImageFont.truetype(path, size=font_size(size))
F = {
'title': font(FONT_SERIF_BOLD, 40), 'h1': font(FONT_BOLD, 25), 'h2': font(FONT_BOLD, 20),
'body': font(FONT_REG, 18), 'small': font(FONT_REG, 16), 'tiny': font(FONT_REG, 14),
'mono': font(FONT_MONO, 17), 'mono_small': font(FONT_MONO, 15), 'table_head': font(FONT_BOLD, 18),
}
SELLERS = [
('Apex Cartons Ltd', '4799 Highland View Drive, Sacramento, CA 95815', '+91-78778-81186'),
('Northline Supplies', '7455 Drew Court, White City, KS 66872', '+91-88390-36062'),
('BluePeak Packaging Co', '214 Pine Ridge Lane, Boulder, CO 80302', '+1-303-555-0194'),
('Crestline Box Works', '8800 Valley Crest Road, Austin, TX 78745', '+1-512-555-0176'),
('MetroWrap Logistics', '1024 Harbor Street, Newark, NJ 07105', '+1-973-555-0182'),
('Pacific Label House', '311 Ocean Park Blvd, San Diego, CA 92109', '+1-619-555-0154'),
('GreenLeaf Cartons', '58 Rosewood Avenue, Portland, OR 97205', '+1-503-555-0141'),
('Summit Packaging Hub', '1700 Market Street, Denver, CO 80202', '+1-720-555-0188'),
('PrimePack Traders', '27 Industrial Estate, Pune, MH 411045', '+91-98810-44231'),
('SilverBox Enterprises', '18 Race Course Road, Chennai, TN 600032', '+91-94444-70981'),
('UrbanCarton Supply', '91 Sector 44 Road, Gurugram, HR 122003', '+91-98122-55340'),
('EverReady Packaging', '301 Lakeside Drive, Madison, WI 53703', '+1-608-555-0139'),
]
CUSTOMERS = [
('Jeff Ritchie Stores', '980 Industrial Road, Hyderabad, TS 500081', '7455 Drew Court, White City, KS 66872'),
('Riverside Retail Group', '72 Market Square, Chennai, TN 600001', '18 Park Street, Pune, MH 411001'),
('Hilltop Office Depot', '140 Cedar Lane, Albany, NY 12207', '500 River Road, Troy, NY 12180'),
('Mason Distribution', '89 Foundry Street, Detroit, MI 48207', '44 Logistics Park, Warren, MI 48089'),
('Nova General Stores', '6 MG Road, Bengaluru, KA 560001', '42 Whitefield Main Road, Bengaluru, KA 560066'),
('Prairie Wholesale', '210 North 8th Street, Omaha, NE 68102', '95 Warehouse Avenue, Lincoln, NE 68508'),
('Sunrise Stationers', '55 Ashok Nagar, Jaipur, RJ 302001', '9 Transport Nagar, Jaipur, RJ 302003'),
('Vertex Home Mart', '312 King Street, Seattle, WA 98104', '810 Depot Road, Tacoma, WA 98421'),
('Canyon Craft Supplies', '460 Mesa Drive, Phoenix, AZ 85004', '77 South Yard Way, Tempe, AZ 85281'),
('Orbit Commerce Pvt Ltd', '404 SG Highway, Ahmedabad, GJ 380015', '22 Narol Industrial Area, Ahmedabad, GJ 382405'),
('OakBridge Market', '15 Elm Street, Boston, MA 02108', '112 Dock Road, Everett, MA 02149'),
('Central Furnishing Co', '100 Broad Avenue, Atlanta, GA 30303', '2300 Freight Drive, Marietta, GA 30060'),
]
ITEMS = [
('Shipping Label Pack', 'LBL-450'), ('Packing Tape', 'TAPE-338'), ('Product Manual', 'MAN-780'),
('Warranty Card', 'WAR-110'), ('Invoice Copy', 'INV-COPY'), ('Plastic Sleeve', 'SLV-890'),
('Printed Carton', 'CRT-670'), ('Ad Design', 'AD-DES-003'), ('Foam Insert', 'FOM-560'),
('Barcode Sticker Roll', 'BAR-244'), ('Fragile Label Set', 'FRG-112'), ('Bubble Wrap Roll', 'BUB-908'),
('Corrugated Divider', 'DIV-731'), ('Return Label Sheet', 'RTN-509'), ('Custom Poly Mailer', 'POLY-620'),
('Die Cut Insert', 'DCI-725'), ('Pallet Label Card', 'PAL-318'), ('Security Seal Strip', 'SEC-401'),
('Mailer Box Small', 'MBOX-SM'), ('Mailer Box Large', 'MBOX-LG'), ('Kraft Paper Roll', 'KRAFT-221'),
('Thermal Label Roll', 'THR-612'), ('Corner Protector', 'CRN-019'), ('Documentation Pouch', 'DOC-872'),
('Hang Tag Bundle', 'TAG-149'), ('Instruction Leaflet', 'LEAF-557'), ('Packing Slip Copy', 'PSC-391'),
('Gift Wrap Sheet', 'GFT-812'), ('Logo Sticker Pack', 'LOGO-754'), ('Moisture Guard Bag', 'MGB-309'),
]
NOTES = ['Partial shipment allowed', 'Handle cartons with care', 'Deliver during business hours', 'Use dock entrance for unloading', 'Customer signature required', 'Keep goods dry during transit', 'Verify carton count before dispatch', 'Shipment can be split by item line', 'Do not stack above five cartons', 'Priority delivery requested', 'Attach invoice copy to shipment', 'Contact buyer before final delivery']
PRICES = [10, 12, 15, 20, 25, 30, 40, 50, 60, 75, 90, 100, 125, 150, 175, 200, 225, 250]
def clean_dir(path):
if path.exists(): shutil.rmtree(path)
path.mkdir(parents=True, exist_ok=True)
def text(draw, xy, value, fnt, fill=(25,25,25)):
draw.text((sc(xy[0]), sc(xy[1])), str(value), font=fnt, fill=fill)
def line(draw, coords, fill=(70,70,70), width=1):
draw.line([sc(v) for v in coords], fill=fill, width=max(1, sc(width)))
def rect(draw, coords, outline=(70,70,70), width=1):
draw.rectangle([sc(v) for v in coords], outline=outline, width=max(1, sc(width)))
def wrapped(draw, xy, value, fnt, max_width, line_gap=4, fill=(25,25,25)):
words = str(value).split()
lines, current = [], ''
maxw = sc(max_width)
for w in words:
cand = (current + ' ' + w).strip()
bb = draw.textbbox((0,0), cand, font=fnt)
if bb[2] - bb[0] <= maxw or not current:
current = cand
else:
lines.append(current); current = w
if current: lines.append(current)
x, y = xy
lh = (draw.textbbox((0,0), 'Ag', font=fnt)[3] + sc(line_gap)) / S
for ln in lines:
text(draw, (x, y), ln, fnt, fill)
y += lh
return y
def generate_record(global_idx):
seller = random.choice(SELLERS); customer = random.choice(CUSTOMERS)
order_date = date(2026,1,15) + timedelta(days=random.randint(0,330))
n_items = random.randint(3,8)
rows=[]; qty_sum=0; subtotal=0
for sr,(desc,sku) in enumerate(random.sample(ITEMS, n_items), 1):
qty=random.randint(1,20); unit=random.choice(PRICES); total=qty*unit
qty_sum += qty; subtotal += total
rows.append({'sr_no':str(sr),'item_description':desc,'sku':sku,'quantity':str(qty),'unit_price':str(unit),'total_price':str(total)})
tax=random.choice([0,0,0,50,100,125,150,200]); freight=random.choice([0,50,75,100,125,150,200,250,300])
return {
'seller': {'company_name': seller[0], 'address': seller[1], 'phone_number': seller[2]},
'buyer': {'bill_to_name': customer[0], 'bill_to_address': customer[1], 'ship_to_name': customer[0], 'ship_to_address': customer[2]},
'document': {'package_number': f'PKG{global_idx:05d}', 'order_date': order_date.isoformat(), 'sales_order_number': str(random.randint(500000,599999)), 'po_number': f'PO-{random.randint(30000,69999)}'},
'items': rows,
'summary': {'total_quantity': str(qty_sum), 'sub_total': str(subtotal), 'tax': str(tax), 'freight': str(freight), 'grand_total': str(subtotal+tax+freight)},
'notes': random.choice(NOTES),
}
def to_donut_sequence(obj):
def tok(k,v): return f'<s_{k}>{v}</s_{k}>'
seq = '<s_packaging>'
for sec in ['seller','buyer','document']:
seq += f'<s_{sec}>' + ''.join(tok(k,v) for k,v in obj[sec].items()) + f'</s_{sec}>'
seq += '<s_items>'
for item in obj['items']:
seq += '<s_item>' + ''.join(tok(k,item[k]) for k in ['sr_no','item_description','sku','quantity','unit_price','total_price']) + '</s_item>'
seq += '</s_items><s_summary>'
seq += ''.join(tok(k,obj['summary'][k]) for k in ['total_quantity','sub_total','tax','freight','grand_total'])
seq += '</s_summary>' + tok('notes', obj['notes']) + '</s_packaging>'
return seq
def validate(obj):
qty=sum(int(i['quantity']) for i in obj['items']); subtotal=sum(int(i['total_price']) for i in obj['items'])
assert qty == int(obj['summary']['total_quantity'])
assert subtotal == int(obj['summary']['sub_total'])
assert subtotal + int(obj['summary']['tax']) + int(obj['summary']['freight']) == int(obj['summary']['grand_total'])
for i,row in enumerate(obj['items'],1):
assert row['sr_no'] == str(i)
assert int(row['quantity']) * int(row['unit_price']) == int(row['total_price'])
def render(obj, out_path):
paper=random.choice([(255,255,255),(253,253,251),(252,253,255)])
img=Image.new('RGB',(W,H),paper); d=ImageDraw.Draw(img)
black=(25,25,25); light=(226,226,226)
rect(d,[50,50,1190,1704],width=2); rect(d,[62,62,1178,1692],outline=(230,230,230))
text(d,(70,92),'PACKAGE SLIP',F['title']); text(d,(740,100),f"Package# - {obj['document']['package_number']}",F['h2'])
y=170; text(d,(70,y),obj['seller']['company_name'],F['h2']); y=wrapped(d,(70,y+32),obj['seller']['address'],F['small'],620); text(d,(70,y+3),obj['seller']['phone_number'],F['small'])
y=300; xs=[70,365,655,940]; labs=['Package #','Order Date #','Sales Order #','PO #']; vals=[obj['document']['package_number'],obj['document']['order_date'],obj['document']['sales_order_number'],obj['document']['po_number']]
for x,lab,val in zip(xs,labs,vals): text(d,(x,y),lab,F['h2']); text(d,(x,y+36),val,F['small'])
line(d,[70,405,1170,405],width=2)
text(d,(70,445),'Bill To:',F['h2']); text(d,(70,483),obj['buyer']['bill_to_name'],F['small']); wrapped(d,(70,508),obj['buyer']['bill_to_address'],F['small'],430)
text(d,(635,445),'Ship To:',F['h2']); text(d,(635,483),obj['buyer']['ship_to_name'],F['small']); wrapped(d,(635,508),obj['buyer']['ship_to_address'],F['small'],430)
line(d,[70,620,1170,620],width=2)
y=650; cols={'sr':70,'desc':155,'sku':565,'qty':750,'unit':875,'total':1050}
for key,label in [('sr','SR No.'),('desc','ITEM DESCRIPTION'),('sku','SKU'),('qty','QTY'),('unit','UNIT PRICE'),('total','TOTAL')]: text(d,(cols[key],y),label,F['table_head'])
line(d,[70,y+34,1170,y+34])
row_y=y+58
for item in obj['items']:
text(d,(cols['sr'],row_y),item['sr_no'],F['mono_small']); text(d,(cols['desc'],row_y),item['item_description'],F['small']); text(d,(cols['sku'],row_y),item['sku'],F['mono_small'])
text(d,(cols['qty']+18,row_y),item['quantity'],F['mono_small']); text(d,(cols['unit'],row_y),item['unit_price'],F['mono_small']); text(d,(cols['total'],row_y),item['total_price'],F['mono_small'])
row_y += 36
bottom=max(row_y+20,930); line(d,[70,bottom,1170,bottom],fill=light)
sy=bottom+34
for lab,key in [('Total Qty','total_quantity'),('Sub Total','sub_total'),('Tax','tax'),('Freight','freight'),('Grand Total','grand_total')]:
f=F['h2'] if lab=='Grand Total' else F['small']; text(d,(770,sy),lab,f); text(d,(1015,sy),obj['summary'][key],f); sy += 35
ny=max(bottom+210,1210); text(d,(70,ny),'Notes:',F['h2']); text(d,(70,ny+34),obj['notes'],F['small'])
if random.random()<0.25:
x=random.randint(sc(90),sc(1150)); d.line([x,sc(60),x,sc(1690)],fill=(238,238,238),width=1)
img.save(out_path, format='PNG', compress_level=1)
def write_readme(root):
readme = """# Synthetic Packaging Slip Donut Dataset
Synthetic packaging slip dataset for Donut fine-tuning.
## Contents
- `train`: 50 PNG images + labels
- `val`: 50 PNG images + labels
- `test`: 50 PNG images + labels
- Total: 150 images
Each split has:
- `metadata.jsonl`: Donut/imagefolder-ready metadata. `ground_truth` is a JSON string containing `gt_parse`.
- `annotations_with_sequences.jsonl`: structured JSON plus a pre-built Donut target sequence.
- `annotations.json`: pretty JSON version for inspection.
## Schema
```json
{
"packaging": {
"seller": {"company_name": "", "address": "", "phone_number": ""},
"buyer": {"bill_to_name": "", "bill_to_address": "", "ship_to_name": "", "ship_to_address": ""},
"document": {"package_number": "", "order_date": "", "sales_order_number": "", "po_number": ""},
"items": [{"sr_no": "", "item_description": "", "sku": "", "quantity": "", "unit_price": "", "total_price": ""}],
"summary": {"total_quantity": "", "sub_total": "", "tax": "", "freight": "", "grand_total": ""},
"notes": ""
}
}
```
## Load with Hugging Face datasets
```python
from datasets import load_dataset
dataset = load_dataset("imagefolder", data_dir="packaging_slip_donut_dataset")
print(dataset)
```
All records are synthetic. Totals are validated during generation.
"""
(root/'README.md').write_text(readme,encoding='utf-8')
def main():
t0=time.time(); clean_dir(ROOT); global_idx=1
info={'name':'synthetic_packaging_slip_donut_dataset','version':'1.0.0','splits':SPLIT_SIZES,'total_images':sum(SPLIT_SIZES.values()),'schema_root':'packaging','seed':SEED}
for split,count in SPLIT_SIZES.items():
sd=ROOT/split; sd.mkdir(parents=True,exist_ok=True); metas=[]; seqs=[]; records=[]
for _ in range(count):
obj=generate_record(global_idx); validate(obj); fname=f'package_{global_idx:05d}.png'; render(obj,sd/fname)
sequence=to_donut_sequence(obj); gt={'gt_parse':{'packaging':obj}}
metas.append(json.dumps({'file_name':fname,'ground_truth':json.dumps(gt,ensure_ascii=False)},ensure_ascii=False))
rec={'file_name':fname,'split':split,'ground_truth':{'packaging':obj},'target_sequence':sequence}
seqs.append(json.dumps(rec,ensure_ascii=False)); records.append(rec); global_idx += 1
(sd/'metadata.jsonl').write_text('\n'.join(metas)+'\n',encoding='utf-8')
(sd/'annotations_with_sequences.jsonl').write_text('\n'.join(seqs)+'\n',encoding='utf-8')
(sd/'annotations.json').write_text(json.dumps(records,ensure_ascii=False,indent=2),encoding='utf-8')
(ROOT/'dataset_info.json').write_text(json.dumps(info,indent=2),encoding='utf-8'); write_readme(ROOT)
if ZIP_PATH.exists(): ZIP_PATH.unlink()
with zipfile.ZipFile(ZIP_PATH,'w',compression=zipfile.ZIP_STORED) as z:
for p in ROOT.rglob('*'): z.write(p,arcname=p.relative_to(ROOT.parent))
print('created',ZIP_PATH,'in',round(time.time()-t0,2),'sec')
if __name__=='__main__': main()