CMVR-IOT/deploy/cvc_touch/ui-classifier/ui_classifier.py

82 lines
4.4 KiB
Python
Raw Normal View History

import argparse, json, random, time
from pathlib import Path
import torch
from torch import nn
from PIL import Image, ImageOps
from torchvision import models, transforms as T
ROOT = Path(__file__).resolve().parent
ART = ROOT / 'artifacts'
def image(path):
with Image.open(path) as im:
return ImageOps.exif_transpose(im).convert('RGB')
def transform(aug=False):
if aug:
return T.Compose([T.Resize(288), T.RandomResizedCrop(224, scale=(0.72,1.0), ratio=(1.10,1.55)), T.RandomApply([T.RandomPerspective(distortion_scale=0.12,p=1)],p=0.35), T.ColorJitter(.25,.25,.15,.025), T.ToTensor(), T.Normalize([.485,.456,.406],[.229,.224,.225])])
return T.Compose([T.Resize((224,224)),T.ToTensor(),T.Normalize([.485,.456,.406],[.229,.224,.225])])
def build():
m=models.mobilenet_v3_small(weights=None)
# Keep pretrained feature extraction; train a compact linear classification head.
return m
def features(m,x):
return m.avgpool(m.features(x)).flatten(1)
def train():
start=time.time(); random.seed(2026); torch.manual_seed(2026)
paths=sorted((ROOT/'data').glob('*.jpg'))
if len(paths)<2: raise RuntimeError('At least two labelled reference images required')
labels=[p.stem for p in paths]
m=models.mobilenet_v3_small(weights=models.MobileNet_V3_Small_Weights.DEFAULT).eval()
for p in m.parameters(): p.requires_grad=False
aug=transform(True)
def extract(count):
xx=[]; yy=[]
with torch.inference_mode():
for i,p in enumerate(paths):
im=image(p)
for s in range(0,count,16):
x=torch.stack([aug(im) for _ in range(min(16,count-s))])
xx.append(features(m,x)); yy.extend([i]*len(x))
return torch.cat(xx).clone(),torch.tensor(yy)
x,y=extract(64); vx,vy=extract(16)
mean=x.mean(0); std=x.std(0).clamp_min(.05)
x=(x-mean)/std; vx=(vx-mean)/std
head=nn.Linear(x.shape[1],len(labels))
opt=torch.optim.AdamW(head.parameters(),lr=.008,weight_decay=.02)
for epoch in range(300):
opt.zero_grad(); loss=nn.functional.cross_entropy(head(x),y); loss.backward(); opt.step()
if epoch%50==0: print(json.dumps({'epoch':epoch,'loss':round(loss.item(),5)}),flush=True)
with torch.no_grad():
a=(head(x).argmax(1)==y).float().mean().item()
va=(head(vx).argmax(1)==vy).float().mean().item()
preds=[]
for p in paths:
z=features(m,transform()(image(p))[None]); scores=head((z-mean)/std).softmax(-1)[0]; k=int(scores.argmax())
preds.append({'file':p.name,'predicted':labels[k],'correct':labels[k]==p.stem})
ART.mkdir(exist_ok=True)
torch.save({'backbone':m.state_dict(),'head':head.state_dict(),'mean':mean,'std':std,'labels':labels},ART/'mobilenet_ui.pt')
report={'model':'MobileNetV3-Small frozen ImageNet backbone + trained linear head','device':'cpu','labels':labels,'original_images':len(paths),'train_augmentations_per_original':64,'synthetic_check_augmentations_per_original':16,'training_accuracy':a,'synthetic_check_accuracy':va,'independent_test_accuracy':None,'warning':'Synthetic check uses the same source photos as training. No evidence of generalization to new photographs. Scores are uncalibrated.','reference_predictions':preds,'elapsed_seconds':round(time.time()-start,1),'torch':torch.__version__}
(ART/'training_report.json').write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding='utf-8')
print(json.dumps(report,ensure_ascii=False),flush=True)
def predict(path):
c=torch.load(ART/'mobilenet_ui.pt',map_location='cpu',weights_only=True)
m=build().eval(); m.load_state_dict(c['backbone'])
h=nn.Linear(576,len(c['labels'])); h.load_state_dict(c['head']); h.eval()
with torch.inference_mode():
z=features(m,transform()(image(path))[None]); s=h((z-c['mean'])/c['std']).softmax(-1)[0]
inds=s.argsort(descending=True)[:3]
print(json.dumps({'page':c['labels'][int(inds[0])],'needs_review':True,'top3':[{'name':c['labels'][int(k)],'softmax_score':round(float(s[k]),6)} for k in inds],'note':'Prototype; scores are uncalibrated; no independent real-photo validation yet.'},ensure_ascii=False))
if __name__=='__main__':
torch.set_num_threads(6)
p=argparse.ArgumentParser(); p.add_argument('mode',choices=['train','predict']); p.add_argument('--image'); a=p.parse_args()
if a.mode=='train': train()
else:
if not a.image: p.error('--image required')
predict(a.image)