product-recognition-demo/recognization/docs/research/2026-09-29-shelf-intelligence/anytime.py
tngo 0cf64a18bf Coverage-first live labelling, merged catalog, shelf-intelligence decision
The live path abstained too much: a detected product whose best candidate
missed the accept line was left blank, so a shelf where 59% of in-catalog
facings were shown read as broken. Show the best candidate immediately as
`provisional`, keep the track re-classifiable so a later attempt upgrades or
corrects it, and never blank a label already on screen.

- identity.py / identity_lanes.py: every decision now carries
  `provisional_sku` - the row the evidence supports well enough to show,
  separate from `best_sku`, which still means "cleared the gate". The accept
  line does not move: far-unknown false accepts stay at 0.066%.
- live.py: a below-gate candidate labels the track with
  `identity_level: provisional` and `confirmed = False`, so the planner and
  the crop lane keep offering it. Accepted labels stay frozen. Inherited
  provisional labels stay re-classifiable.
- Clients render provisional distinctly (amber chip, dashed box) via
  `LiveScanOverlayPolicy.isProvisional(identity)`, which now reads the wire
  level instead of only the state.
- build_stock_all.py merges stock, stock-lopia, stock-mediya and
  stock-milk150 into stock-all (111 images, 60 SKUs). The server could only
  read one folder, so anything outside it came back blank. stock-demo is
  byte-identical to mediya+milk150 and is not a source.

Measured on add/image6.jpg at live resolution: in-catalog facings shown
59.4% -> 86.0%, correct shown 38 -> 55, precision 97.4% -> 87.3%. On the
wire at 8fps 0.5x: 65 of 79 tracks labelled, 742 accepted + 309 provisional
observations, first label 1.27s.

docs/research/2026-09-29-shelf-intelligence/ carries the experiments and the
decision: group signals (combined AUC 0.991 sibling / 0.990 unrelated),
OCR scheduling (group representatives cut calls 4.4x and wall 3.3x), and the
finding that group propagation damages more labels than it rescues on this
shelf, so groups schedule compute rather than overwrite labels.

331 tests pass.
2026-09-29 13:45:14 +09:00

58 lines
4 KiB
Python

"""Policy counterfactuals on measured worker evidence arrival times.
All crops enter together; these are not camera/UI end-to-end timings.
"""
from pathlib import Path
import json
from statistics import median
from analyze import POLICIES,decide,infer_groups,propagate,metrics
DIR=Path(__file__).resolve().parent;OUT=DIR/'evidence'
def main():
frozen=json.loads((OUT/'observations.json').read_text())
data=frozen['resolutions']['live'];sig=frozen['signatures']
edges=json.loads((OUT/'analysis.json').read_text())['resolutions']['live']['guarded_edges']
events=json.loads((OUT/'anytime-events.json').read_text())
families=json.loads((DIR/'group-truth.json').read_text())['families']
report={'clock':'Measured local/OCR completion; frozen appearance edges are precomputed, grouping and transport time excluded. Diagnostic counterfactual, not live deployment.','policies':{}}
horizon=events['complete_ms']+1000
for policy in POLICIES:
for grouped in (False,True):
rows={o['id']:{**o,'rank':[],'local':{},'text':{},'read':''} for o in data['observations']}
history={i:[(0.,None)] for i in rows};snapshots={};current={i:None for i in rows}
for event in sorted(events['events'],key=lambda e:e['ms']):
for delay in (250,500,1000):
if delay<event['ms'] and str(delay) not in snapshots:snapshots[str(delay)]=metrics(list(rows.values()),current,families)
o=rows[event['id']]
if event['kind']=='local':o['rank']=event['rank']
else:o['read']=event['read'];o['text']=event['text']
obs=list(rows.values());base={i:decide(o,policy,sig) for i,o in rows.items()}
groups=infer_groups(data,edges,{i:decide(o,'strict',sig) for i,o in rows.items()})
current=propagate(obs,groups,base,sig,guarded=True)[0] if grouped else base
for i,sku in current.items():
if sku!=history[i][-1][1]:history[i].append((event['ms'],sku))
for delay in (250,500,1000):snapshots.setdefault(str(delay),metrics(list(rows.values()),current,families))
first=[];stable=[];flips=0;corrections=0;blank_ms=wrong_ms=sibling_ms=0.
for i,h in history.items():
truth=rows[i]['truth'];named=[at for at,sku in h if sku]
if named:first.append(min(named))
if h[-1][1]==truth and truth!='unknown':stable.append(h[-1][0])
previous=None
for (_,sku),(end,_) in zip(h,h[1:]+[(horizon,None)]):
if sku and previous and sku!=previous:
flips+=1;corrections+=sku==truth
if sku:previous=sku
for (at,sku),(end,_) in zip(h,h[1:]+[(horizon,None)]):
duration=end-at
if not sku:blank_ms+=duration
elif sku!=truth:
wrong_ms+=duration
if truth in families and families.get(sku)==families[truth]:sibling_ms+=duration
final=metrics(list(rows.values()),current,families)
assert final['correct']+final['wrong']==final['shown']<=109
report['policies'][policy+('/grouped' if grouped else '/individual')]={'final':final,'timed':snapshots,'first_any_ms':min(first) if first else None,'first_per_facing_p50_ms':median(first) if first else None,'time_to_final_correct_p50_ms':median(stable) if stable else None,'identity_flips':flips,'wrong_to_correct_events':corrections,'blank_facing_ms':blank_ms,'wrong_facing_ms':wrong_ms,'wrong_sibling_facing_ms':sibling_ms,'loss_proxy':(blank_ms+1.5*sibling_ms+4*(wrong_ms-sibling_ms)+200*flips)/(109*horizon),'horizon_ms':horizon}
(OUT/'anytime-policies.json').write_text(json.dumps(report,ensure_ascii=False,indent=2))
for name,r in report['policies'].items():print(name,r['final']['shown'],r['final']['correct'],round(r['first_per_facing_p50_ms'],1),r['identity_flips'],round(r['loss_proxy'],3))
if __name__=='__main__':main()