integrate CoTracker3 (fallback cv2) for precise gif/webp motion
Browse filesFiles changed (2)
- app.py+131-49
- requirements.txt+1
164 unmodified lines165166167168169170171172173174315 unmodified lines490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546164 unmodified lines_HTTP_SESSION: aiohttp.ClientSession | None = None_INFERENCE_ACTIVE = 0_INFERENCE_WAITERS = 0class ServerBusyError(Exception):pass# ==================== NOISE FILTER ====================_NOISE_PATTERNS = ("not documented","standardize_rope_params","Unrecognized keys","unauthenticated requests","Invalid file descriptor","BaseEventLoop","Exception ignored","it/s]","B/s]","SiglipVisionModel","UNEXPECTED","LOAD REPORT","generation flags","AttentionMaskConverter","FutureWarning","deprecated and will be removed","Special tokens","attention mask","pad_token_id","eos_token_id")class _NoiseFilter:315 unmodified linesqs = prompt.strip()motion_hint = ""if len(frames) > 1:try:import cv2 # type: ignoresmall = [np.array(f.resize((64, 64), Image.BILINEAR).convert("L")) for f in frames]mags, dirs = [], []for i in range(1, len(small)):flow = cv2.calcOpticalFlowFarneback(small[i-1], small[i], None, 0.5, 3, 15, 3, 5, 1.2, 0)mag, ang = cv2.cartToPolar(flow[..., 0], flow[..., 1])mags.append(float(np.mean(mag)))dirs.append(float(np.median(ang) * 180 / np.pi))avg_mag = float(np.mean(mags)) if mags else 0# fallback centroid untuk sparse object (dot) dimana Farneback noisecentroid_hint = ""try:cents = []for s in small:# threshold putih di atas 200_, th = cv2.threshold(s, 200, 255, cv2.THRESH_BINARY)M = cv2.moments(th)if M["m00"] > 10:cx = M["m10"] / M["m00"]cy = M["m01"] / M["m00"]cents.append((cx, cy))if len(cents) >= 2:dx = cents[-1][0] - cents[0][0]dy = cents[-1][1] - cents[0][1]if abs(dx) > 5 or abs(dy) > 5:dir_txt = []if dx > 5: dir_txt.append("right")elif dx < -5: dir_txt.append("left")if dy > 5: dir_txt.append("down")elif dy < -5: dir_txt.append("up")centroid_hint = f" Object centroid moves {'-'.join(dir_txt)} ({dx:+.0f}px, {dy:+.0f}px)."except Exception:passif avg_mag < 0.8 and not centroid_hint:motion_hint = " Motion: mostly static with minor changes."else:bins = {"right": 0, "down": 0, "left": 0, "up": 0}for a in dirs:if 315 <= a or a < 45: bins["right"] += 1elif 45 <= a < 135: bins["down"] += 1elif 135 <= a < 225: bins["left"] += 1else: bins["up"] += 1dom = max(bins, key=bins.get) if dirs else "unknown"motion_hint = f" Motion: avg flow {avg_mag:.1f}px, dominant {dom} ({bins.get(dom,0)}/{len(dirs)}),"if centroid_hint:motion_hint += centroid_hintelse:motion_hint += " object/camera movement present."except Exception:motion_hint = " Motion: changes detected between frames."if motion_hint and motion_hint.lower().strip() not in qs.lower():qs = qs + motion_hintif "frame" not in qs.lower():164 unmodified lines165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253315 unmodified lines569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628164 unmodified lines_HTTP_SESSION: aiohttp.ClientSession | None = None_INFERENCE_ACTIVE = 0_INFERENCE_WAITERS = 0COTRACKER_MODEL = None_COTRACKER_LOCK = None # lazy init threading.Lockclass ServerBusyError(Exception):passdef _get_cotracker():global COTRACKER_MODEL, _COTRACKER_LOCKif COTRACKER_MODEL is not None:return COTRACKER_MODELimport threadingif _COTRACKER_LOCK is None:_COTRACKER_LOCK = threading.Lock()with _COTRACKER_LOCK:if COTRACKER_MODEL is not None:return COTRACKER_MODELtry:import torch as _t# torch.hub akan download scaled_offline.pth dari HF (facebook/cotracker3)_m = _t.hub.load("facebookresearch/co-tracker", "cotracker3_offline", pretrained=True, trust_repo=True)_m = _m.to(DEVICE).eval()COTRACKER_MODEL = _mlogger.info("CoTracker3 offline loaded")except Exception as e:logger.warning(f"CoTracker load failed, fallback cv2: {e}")COTRACKER_MODEL = Nonereturn COTRACKER_MODELdef _cotracker_hint(frames: List[Image.Image]) -> str:"""Return textual motion hint from CoTracker grid tracks, or '' if fail."""if len(frames) < 2:return ""m = _get_cotracker()if m is None:return ""try:import torch as _timport numpy as np# CoTracker expects (B,T,3,H,W) float, H/W ~256# downscale untuk CPU cepat: 128H = W = 128arr = np.stack([np.array(f.resize((W, H), Image.BILINEAR)) for f in frames]) # T,H,W,3video = _t.from_numpy(arr).permute(0, 3, 1, 2)[None].float().to(DEVICE) # 1,T,3,H,W# grid 5x5 =25 pointswith _t.inference_mode():tracks, vis = m(video, grid_size=5) # tracks: 1,T,N,2 vis: 1,T,N# tracks in pixel coords of 128x128tracks = tracks[0].cpu().numpy() # T,N,2vis = vis[0].cpu().numpy() if vis is not None else None# hitung displacement first->last untuk titik visibleT, N, _ = tracks.shapehints = []# bagi 4 kuadran biar deskripsi spasialfor qi, (qx, qy, qname) in enumerate([(32,32,"top-left"),(96,32,"top-right"),(32,96,"bottom-left"),(96,96,"bottom-right")]):# cari titik grid terdekat kuadran# grid points di CoTracker grid_size 5: spacing ~25px, cari nearest# sederhanakan: ambil subset tracks dan lihat rata2pass# sederhanakan: rata2 displacement semua titik visibledisp = tracks[-1] - tracks[0] # N,2 (dx,dy)if vis is not None:# hanya titik visible di kedua framemask = (vis[0] > 0.5) & (vis[-1] > 0.5)if mask.sum() > 0:disp = disp[mask]if len(disp) == 0:return ""mean_dx = float(np.mean(disp[:, 0]))mean_dy = float(np.mean(disp[:, 1]))mean_mag = float(np.mean(np.sqrt(disp[:,0]**2 + disp[:,1]**2)))if mean_mag < 2:return " CoTracker: mostly static (mean disp {:.1f}px).".format(mean_mag)dirs = []if mean_dx > 3: dirs.append("right")elif mean_dx < -3: dirs.append("left")if mean_dy > 3: dirs.append("down")elif mean_dy < -3: dirs.append("up")dir_txt = "-".join(dirs) if dirs else "mixed"return f" CoTracker: avg disp {mean_mag:.1f}px {dir_txt} (dx {mean_dx:+.0f}, dy {mean_dy:+.0f}, {len(disp)} tracks)."except Exception as e:logger.warning(f"CoTracker hint failed: {e}")return ""# ==================== NOISE FILTER ====================_NOISE_PATTERNS = ("not documented","standardize_rope_params","Unrecognized keys","unauthenticated requests","Invalid file descriptor","BaseEventLoop","Exception ignored","it/s]","B/s]","SiglipVisionModel","UNEXPECTED","LOAD REPORT","generation flags","AttentionMaskConverter","FutureWarning","deprecated and will be removed","Special tokens","attention mask","pad_token_id","eos_token_id")class _NoiseFilter:315 unmodified linesqs = prompt.strip()motion_hint = ""if len(frames) > 1:# 1) CoTracker dense (paling presisi) 2) Farneback + centroid fallbackmotion_hint = _cotracker_hint(frames)if not motion_hint:try:import cv2 # type: ignoresmall = [np.array(f.resize((64, 64), Image.BILINEAR).convert("L")) for f in frames]mags, dirs = [], []for i in range(1, len(small)):flow = cv2.calcOpticalFlowFarneback(small[i-1], small[i], None, 0.5, 3, 15, 3, 5, 1.2, 0)mag, ang = cv2.cartToPolar(flow[..., 0], flow[..., 1])mags.append(float(np.mean(mag)))dirs.append(float(np.median(ang) * 180 / np.pi))avg_mag = float(np.mean(mags)) if mags else 0# fallback centroid untuk sparse object (dot) dimana Farneback noisecentroid_hint = ""try:cents = []for s in small:# threshold putih di atas 200_, th = cv2.threshold(s, 200, 255, cv2.THRESH_BINARY)M = cv2.moments(th)if M["m00"] > 10:cx = M["m10"] / M["m00"]cy = M["m01"] / M["m00"]cents.append((cx, cy))if len(cents) >= 2:dx = cents[-1][0] - cents[0][0]dy = cents[-1][1] - cents[0][1]if abs(dx) > 5 or abs(dy) > 5:dir_txt = []if dx > 5: dir_txt.append("right")elif dx < -5: dir_txt.append("left")if dy > 5: dir_txt.append("down")elif dy < -5: dir_txt.append("up")centroid_hint = f" Object centroid moves {'-'.join(dir_txt)} ({dx:+.0f}px, {dy:+.0f}px)."except Exception:passif avg_mag < 0.8 and not centroid_hint:motion_hint = " Motion: mostly static with minor changes."else:bins = {"right": 0, "down": 0, "left": 0, "up": 0}for a in dirs:if 315 <= a or a < 45: bins["right"] += 1elif 45 <= a < 135: bins["down"] += 1elif 135 <= a < 225: bins["left"] += 1else: bins["up"] += 1dom = max(bins, key=bins.get) if dirs else "unknown"motion_hint = f" Motion: avg flow {avg_mag:.1f}px, dominant {dom} ({bins.get(dom,0)}/{len(dirs)}),"if centroid_hint:motion_hint += centroid_hintelse:motion_hint += " object/camera movement present."except Exception:motion_hint = " Motion: changes detected between frames."if motion_hint and motion_hint.lower().strip() not in qs.lower():qs = qs + motion_hintif "frame" not in qs.lower():
18 unmodified lines192021222318 unmodified linesav==13.0.0gradio==5.42.0opencv-python-headless==4.10.0.84iopath==0.1.10portalocker==2.8.218 unmodified lines19202122232418 unmodified linesav==13.0.0gradio==5.42.0opencv-python-headless==4.10.0.84cotracker @ git+https://github.com/facebookresearch/co-tracker.gitiopath==0.1.10portalocker==2.8.2
app.py+131-49
requirements.txt+1