6grid CoTracker per-cell solver (fallback moments)
Browse files539 unmodified lines540541542543544545546547548539 unmodified linesframes = sample_frames(frames, MAX_FRAMES)return framesdef describe_sync(frames: List[Image.Image], prompt: str, max_new_tokens: int) -> str:if MODEL is None or TOKENIZER is None or IMAGE_PROCESSOR is None:raise RuntimeError("model_not_loaded")# Safety: samakan ukuran semua frame (MPO thumbnail bisa beda)if len(frames) > 1:base_size = frames[0].size539 unmodified lines540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701539 unmodified linesframes = sample_frames(frames, MAX_FRAMES)return framesdef _solve_6grid(frames: List[Image.Image]) -> str | None:"""Deterministik 6grid 300x100 20-frame: CoTracker per-cell vs header, fallback moments."""try:if len(frames) != 20: return NoneW,H = frames[0].sizeif W != 300 or H != 100: return Noneimport cv2, numpy as npheader_h = int(H*0.25)grid_h = H - header_hcell_h = grid_h // 2cell_w = W // 3# Coba CoTracker dulu (paling presisi untuk translasi/rotasi)ct = _get_cotracker()if ct is not None:try:import torch as _t# siapkan header track (kanan 80px)def ct_tracks(crops):Hc,Wc = 128,128arr=np.stack([np.array(f.resize((Wc,Hc), Image.BILINEAR)) for f in crops]) # T,H,W,3video=_t.from_numpy(arr).permute(0,3,1,2)[None].float().to(DEVICE) # 1,T,3,128,128with _t.inference_mode():tracks, vis = ct(video, grid_size=5) # 1,T,N,2return tracks[0].cpu().numpy(), (vis[0].cpu().numpy() if vis is not None else None)header_crops=[f.crop((W-80,0,W,header_h)) for f in frames]h_tracks, h_vis = ct_tracks(header_crops)# h_tracks: T,N,2# hitung per-cell tracks dan bandingkan via DTW/cosinebest=None; best_score=-1e9h_disp=np.mean(np.sqrt(((h_tracks[-1]-h_tracks[0])**2).sum(axis=1)))h_traj=h_tracks.mean(axis=1) # T,2 mean trajectoryfor idx in range(1,7):r=(idx-1)//3; cc=(idx-1)%3x0=cc*cell_w; y0=header_h+r*cell_hcrops=[f.crop((x0,y0,x0+cell_w,y0+cell_h)) for f in frames]c_tracks, _ = ct_tracks(crops)c_traj=c_tracks.mean(axis=1)# similarity: Pearson correlation x+y + magnitude ratiodef corr(a,b):if np.std(a)<1e-3 or np.std(b)<1e-3: return 0return np.corrcoef(a,b)[0,1]cx=corr(h_traj[:,0], c_traj[:,0]); cy=corr(h_traj[:,1], c_traj[:,1])c_disp=np.mean(np.sqrt(((c_tracks[-1]-c_tracks[0])**2).sum(axis=1)))mag_sim=1-abs(h_disp-c_disp)/(max(h_disp,c_disp)+1e-3)score=(cx+cy)/2*0.7 + mag_sim*0.3# logger.info(f"6grid ct cell {idx} corr {cx:.2f},{cy:.2f} mag {c_disp:.1f} vs h {h_disp:.1f} score {score:.2f}")if score>best_score:best_score=score; best=idxif best is not None:logger.info(f"6grid CoTracker header disp {h_disp:.1f} -> best {best} score {best_score:.2f}")return str(best)except Exception as e:logger.warning(f"6grid CoTracker failed, fallback moments: {e}")# Fallback moments (lama)header_h = int(H*0.25)grid_h = H - header_hcell_h = grid_h // 2cell_w = W // 3# helper: untuk tiap region (list of crops per frame), hitung centroid + angle per framedef region_moments(crops):cents, angles, areas = [], [], []for f in crops:g = np.array(f.convert("L"))# icon vs white bg: <200_, th = cv2.threshold(g, 200, 255, cv2.THRESH_BINARY_INV)# clean small noisekernel = np.ones((2,2), np.uint8)th = cv2.morphologyEx(th, cv2.MORPH_OPEN, kernel)M = cv2.moments(th)if M["m00"] < 20:cents.append(None); angles.append(None); areas.append(0)continuecx = M["m10"]/M["m00"]; cy = M["m01"]/M["m00"]cents.append((cx, cy))# angle via fitEllipse or moments# use mu20 mu02 mu11mu20 = M["mu20"]/M["m00"] if M["m00"] else 0mu02 = M["mu02"]/M["m00"] if M["m00"] else 0mu11 = M["mu11"]/M["m00"] if M["m00"] else 0ang = 0.5*np.arctan2(2*mu11, mu20-mu02)*180/np.piangles.append(ang)areas.append(M["m00"])return cents, angles, areas# header icon region: cari bbox moving via diff, sudah ada header_h, tapi Q ada di x~240-295# Kita ambil header crops full lalu cari header Q bbox via variance (icon moves)header_crops = [f.crop((0,0,W,header_h)) for f in frames]# cari bbox header icon via diff vs median (seperti sebelumnya) tapi fokus ke x>180# gunakan header_crops untuk moments tapi mask ke area kanan# Untuk header, kita crop kanan 100pxheader_icon_crops = [f.crop((W-80,0,W,header_h)) for f in frames]h_cents, h_angles, h_areas = region_moments(header_icon_crops)# filter Noneh_valid = [(c,a) for c,a in zip(h_cents,h_angles) if c is not None and a is not None]if len(h_valid) < 5: return None# hitung motion type header: translasi vs rotasih_cents_f = [c for c in h_cents if c is not None]h_angles_f = [a for a in h_angles if a is not None]h_dx = max(c[0] for c in h_cents_f) - min(c[0] for c in h_cents_f)h_dy = max(c[1] for c in h_cents_f) - min(c[1] for c in h_cents_f)h_trans = np.hypot(h_dx, h_dy)h_rot = max(h_angles_f) - min(h_angles_f)h_rot_std = float(np.std(h_angles_f))# h_is_rot = rotasi dominan jika angle std >15 deg dan trans kecilh_is_rot = h_rot_std > 12 and h_trans < 8# untuk setiap cell, hitung similarlybest = Nonebest_score = -1for idx in range(1,7):r=(idx-1)//3; c=(idx-1)%3x0=c*cell_w; y0=header_h+r*cell_hcrops=[f.crop((x0,y0,x0+cell_w,y0+cell_h)) for f in frames]cents, angles, _ = region_moments(crops)cents_f=[x for x in cents if x is not None]angles_f=[a for a in angles if a is not None]if len(cents_f)<5: continuedx = max(x[0] for x in cents_f)-min(x[0] for x in cents_f)dy = max(x[1] for x in cents_f)-min(x[1] for x in cents_f)trans=np.hypot(dx,dy)rot_std=float(np.std(angles_f)) if angles_f else 0is_rot=rot_std>12 and trans<8# similarity: header rot vs cell rot, atau header trans vs cell transif h_is_rot == is_rot:# keduanya rotasi atau keduanya translasi → score tinggi# fine score: untuk rotasi, cocokkan rot_std, untuk translasi cocokkan arahif h_is_rot:score = 10 - abs(rot_std - h_rot_std) # semakin dekat std semakin tinggielse:# translasi: arah dominan# hitung arah h vs cell via dx/dyh_dir=np.arctan2(h_dy, h_dx) if h_trans>1 else 0c_dir=np.arctan2(dy, dx) if trans>1 else 0ang_diff=abs(h_dir-c_dir)ang_diff=min(ang_diff, 2*np.pi-ang_diff)score = 10 - ang_diff*2 - abs(trans-h_trans)*0.2else:score = -10# logger.debug# print(f"cell {idx} trans {trans:.1f} rot_std {rot_std:.1f} is_rot {is_rot} score {score:.1f}")if score > best_score:best_score=score; best=idxif best is not None:logger.info(f"6grid solver: header {'rot' if h_is_rot else 'trans'} trans {h_trans:.1f} rot_std {h_rot_std:.1f} -> best cell {best} score {best_score:.1f}")return str(best)return Noneexcept Exception as e:logger.warning(f"6grid solver failed: {e}", exc_info=True)return Nonedef describe_sync(frames: List[Image.Image], prompt: str, max_new_tokens: int) -> str:if MODEL is None or TOKENIZER is None or IMAGE_PROCESSOR is None:raise RuntimeError("model_not_loaded")# Fast-path untuk 6grid challenge: deterministik, bypass LLMif "GRID LAYOUT" in prompt and len(frames) > 1:grid_ans = _solve_6grid(frames)if grid_ans is not None:return grid_ans# Safety: samakan ukuran semua frame (MPO thumbnail bisa beda)if len(frames) > 1:base_size = frames[0].size
app.py+153