File size: 3,623 Bytes
1daa78e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
"""Deterministic OCR support for actual GUI observations, never agent narrative."""
import json,re,subprocess,tempfile,hashlib
from pathlib import Path
from PIL import Image

def gui_queue(trajectory,assets,expected):
 events=[];cache_path=assets/'gui-ocr-cache.json';cache=json.loads(cache_path.read_text()) if cache_path.exists() else {}
 for step in trajectory.get('steps',[]):
  if step.get('source')!='agent':continue
  for result in step.get('observation',{}).get('results',[]):
   for part in result.get('content',[]):
    if part.get('type')!='image':continue
    name=Path(part.get('source',{}).get('path','')).name;p=assets/'operator-screenshots'/name
    if not p.is_file():continue
    digest=hashlib.sha256(p.read_bytes()).hexdigest()
    key=name+':'+digest
    if key in cache:text=cache[key]
    else:
     with tempfile.TemporaryDirectory() as temp:
      image=Image.open(p);image.resize((image.width*2,image.height*2)).save(Path(temp)/'screen.png')
      r=subprocess.run(['tesseract',str(Path(temp)/'screen.png'),'stdout','--psm','11'],capture_output=True,text=True,timeout=20);text=' '.join(r.stdout.split()).lower()
     cache[key]=text;cache_path.write_text(json.dumps(cache))
    if 'queue' not in text and 'export' not in text:continue
    names=[n for n in expected if n.lower().replace('.mp4','') in text or n.lower() in text]
    if len(names)==len(expected):events.append({'step':step['step_id'],'names':names,'ready':any(x in text for x in ['ready','pending','queued']),'done':any(x in text for x in ['completed','done','finished']),'text':text})
 return {'batch':any(a['ready'] and b['done'] and a['step']<b['step'] for a in events for b in events),'events':events}

def viewed_sources(trajectory,assets,names):
 """Match source pixels to delivered screenshots using fixed SIFT/RANSAC thresholds."""
 import cv2,numpy as np
 paths=set()
 for step in trajectory.get('steps',[]):
  if step.get('source')!='agent':continue
  for result in step.get('observation',{}).get('results',[]):
   for part in result.get('content',[]):
    if part.get('type')=='image':paths.add(Path(part.get('source',{}).get('path','')).name)
 sift=cv2.SIFT_create(nfeatures=1500);screens=[]
 for name in sorted(paths):
  p=assets/'operator-screenshots'/name
  if not p.is_file():continue
  img=cv2.imread(str(p),cv2.IMREAD_GRAYSCALE)
  if img is None:continue
  k,d=sift.detectAndCompute(img,None)
  if d is not None:screens.append((name,k,d))
 if not screens:raise RuntimeError('No delivered screenshots available for deterministic source-view check')
 found={n:False for n in names};evidence={};matcher=cv2.BFMatcher()
 for name in names:
  capture=cv2.VideoCapture(str(assets/'reference'/name))
  for second in [0,1,2,4]:
   capture.set(cv2.CAP_PROP_POS_MSEC,second*1000);ok,img=capture.read()
   if not ok:continue
   img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY);img=cv2.resize(img,(640,round(img.shape[0]*640/img.shape[1])));k,d=sift.detectAndCompute(img,None)
   if d is None:continue
   for shot,ks,ds in screens:
    pairs=matcher.knnMatch(d,ds,k=2);good=[a for pair in pairs if len(pair)==2 for a,b in [pair] if a.distance<.70*b.distance]
    if len(good)<12:continue
    src=np.float32([k[m.queryIdx].pt for m in good]);dst=np.float32([ks[m.trainIdx].pt for m in good]);H,inliers=cv2.findHomography(src,dst,cv2.RANSAC,3)
    if H is not None and inliers is not None and int(inliers.sum())>=10 and int(inliers.sum())/len(good)>=.5:
     found[name]=True;evidence[name]={'screenshot':shot,'source_second':second,'inliers':int(inliers.sum())};break
   if found[name]:break
  capture.release()
 return found,evidence