"""Compile a vision LLM's diagnoses into bounded workflow edits, never code. The critic's rubric stays fixed. Image-specific corrections apply only to the dog actually reviewed; reusable graph settings transfer to unseen dogs. """ import hashlib import json import re DIMENSIONS=('identity','fur','body','template') TARGET=9 RULES={ 'identity':'Match the original individual face exactly: muzzle length, skull, eye shape, ears, age and asymmetric markings. Keep the face naturally lit and attached to its own neck.', 'fur':'Every visible animal surface must use the ORIGINAL dog coat distribution and texture, including forelegs, paws, hindquarters and tail. The erased template animal contributes no coat information.', 'body':'Rebuild a connected body at the original dog\'s breed, age and build. Fit the costume to that body. Use compact rounded canine paws with short grouped toes, no long fingers or human hands. Respect perspective and genuinely hidden limbs.', 'template':'Preserve the reference costume, props, artistic medium, composition and lighting. Adapt clothing to the actual dog while leaving scene details unchanged.'} def signature(value):return hashlib.sha256(json.dumps(value,sort_keys=True,separators=(',',':')).encode()).hexdigest() def dog_splits(dogs): """Honor pinned identity groups when expanding a cohort; never reshuffle holdouts.""" identity=lambda d:d.get('identity_group',d['source_sha256']) identities=sorted({identity(d) for d in dogs},key=lambda s:hashlib.sha256(('fpg-judge-split-v1/'+s).encode()).hexdigest()) if len(identities)<7:raise ValueError('Need at least seven distinct dog identities') if any('split' in d for d in dogs): split={} for d in dogs: kind=d.get('split');group=identity(d) if kind not in ('train','validation','test'):raise ValueError('Pin every dog split when extending a cohort') if group in split and split[group]!=kind:raise ValueError('One pet identity crosses evaluation splits') split[group]=kind if any(sum(k==kind for k in split.values())<2 for kind in ('validation','test')): raise ValueError('Keep at least two distinct validation and test identities') else:split={v:'test' if i<2 else 'validation' if i<4 else 'train' for i,v in enumerate(identities)} return {kind:[d['id'] for d in dogs if split[identity(d)]==kind] for kind in ('train','validation','test')} def choose_tuning_dogs(dogs,train,preferred): if any('quality_tier' in d for d in dogs.values()): eligible=sorted((d for d in dogs.values() if d['id'] in train and d.get('quality_tier')=='clear' and d.get('tuning_eligible',True)),key=lambda d:(d.get('quality_rank',100),d['id'])) selected=[];groups=set() for d in eligible: group=d.get('identity_group',d['source_sha256']) if group not in groups:selected.append(d['id']);groups.add(group) if len(selected)==2:return selected raise ValueError('Need two clear, distinct training dogs') return (([preferred] if preferred in train else [])+[d for d in train if d!=preferred])[:2] def meets_target(assessment): return (bool(assessment) and all(type(assessment.get(k)) is int and TARGET<=assessment[k]<=10 for k in DIMENSIONS) and assessment.get('confidence')=='high' and not any(d.get('severity')=='major' for d in assessment.get('defects',[]))) def result_rank(assessments): if not assessments:return (0,0) values=[a[k] for a in assessments for k in DIMENSIONS] return min(values),sum(values)/len(values) def tuning_finished(attempts,maximum,patience): if not attempts:return False if len(attempts)>=maximum or (attempts[-1]['assessments'] and all(meets_target(a) for a in attempts[-1]['assessments'])):return True ranks=[result_rank(a['assessments']) for a in attempts] best=max(range(len(ranks)),key=lambda i:ranks[i]) return len(ranks)-1-best>=patience def feedback_diagnosis(previous): """Keep concrete visual evidence and proposed corrections linked to one dog.""" result=[] for assessment in previous: dog=assessment.get('dog_id') if not dog:continue for defect in assessment.get('defects',[]): area={'face':'identity','preparation':'body'}.get(defect['area'],defect['area']) if area not in DIMENSIONS or (assessment[area]>=TARGET and defect['severity']!='major'):continue clean=lambda value:' '.join(re.sub(r'[\x00-\x1f\x7f]',' ',value).split())[:500] result.append(dict(dog_id=dog,area=area,severity=defect['severity'], evidence=clean(defect['evidence']),correction=clean(defect['correction']))) return result[:24] def next_recipe(index,previous=(),parent=None): means={k:sum(a[k] for a in previous)/len(previous) if previous else 0 for k in DIMENSIONS} ordered=sorted(DIMENSIONS,key=lambda k:means[k]) focus=[k for k in ordered if any(a[k]