#!/usr/bin/env python3 """circle_bibi.py — auto-circle Netanyahu ("the Big Yahu") in any video. Pipeline: YOLO11n single-class detector (bibi-circle.pt) proposes boxes, InsightFace ArcFace confirms identity (cos-sim vs reference embeddings), temporal smoothing glides the circle, ffmpeg-free OpenCV output. Usage: python circle_bibi.py input.mp4 -o out.mp4 [--refs refs/*.jpg] [--gpu] python circle_bibi.py 0 -o "" --camera # webcam/screen live mode Requires: ultralytics, insightface, opencv-python, numpy (pip install them) Model: huggingface.co/minas2025/bibi-circleator (bibi-circle.pt) """ import argparse, glob, os, sys import numpy as np import cv2 REF_THRESHOLD = 0.42 # ArcFace cosine sim to count as "him" IOU_GATE = 0.30 # detection <-> confirmed face agreement SMOOTH_ALPHA = 0.35 # EMA on circle geometry (the glide) MIN_AREA_FR = 0.0008 def cos(a, b): a, b = np.array(a), np.array(b) return float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b) + 1e-12)) def load_ref_embeddings(refs_dir, use_gpu): """Reference = a few photos of him. Robust build: take ALL faces from all refs, median them, then keep only faces that agree with that median (group photos and wrong-first-faces can't poison the identity).""" from insightface.app import FaceAnalysis prov = ["CUDAExecutionProvider", "CPUExecutionProvider"] if use_gpu \ else ["CPUExecutionProvider"] app = FaceAnalysis(name="buffalo_l", providers=prov) app.prepare(ctx_id=0 if use_gpu else -1, det_size=(640, 640)) files = sorted(glob.glob(os.path.join(refs_dir, "*"))) if not files: sys.exit(f"No reference photos in {refs_dir} — drop 5-15 clear face shots there.") all_embs = [] for f in files: img = cv2.imread(f) if img is None: continue for face in app.get(img): if face.embedding is not None: all_embs.append(face.embedding / np.linalg.norm(face.embedding)) if not all_embs: sys.exit("No faces found in ANY reference photo. Fix the refs, friend.") E = np.array(all_embs) med = E.mean(axis=0); med /= np.linalg.norm(med) agree = E[(E @ med) >= 0.35] if len(agree) < 3: agree = E ref = agree.mean(axis=0); ref /= np.linalg.norm(ref) print(f"[refs] {len(E)} faces seen, identity locked on {len(agree)} agreeing faces") return app, ref def iou(a, b): ax1, ay1, ax2, ay2 = a; bx1, by1, bx2, by2 = b ix1, iy1 = max(ax1, bx1), max(ay1, by1) ix2, iy2 = min(ax2, bx2), min(ay2, by2) iw, ih = max(0, ix2 - ix1), max(0, iy2 - iy1) inter = iw * ih ua = (ax2-ax1)*(ay2-ay1) + (bx2-bx1)*(by2-by1) - inter return inter / ua if ua > 0 else 0.0 def open_source(args): """OpenCV's backend can't decode AV1/VP9 webm that yt-dlp loves to serve. File inputs stream through ffmpeg as raw BGR; --camera keeps cv2.VideoCapture.""" if args.camera: cap = cv2.VideoCapture(0) if not cap.isOpened(): sys.exit("cannot open camera") fps = cap.get(cv2.CAP_PROP_FPS) or 30 w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)); h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) return cap, None, fps, w, h import subprocess, re probe = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height,r_frame_rate", "-of", "csv=s=,:p=0", args.input], capture_output=True, text=True) if probe.returncode: sys.exit(f"ffprobe failed: {probe.stderr[:200]}") w, h, rate = probe.stdout.strip().split(",")[:3] w, h = int(w), int(h) num, _, den = rate.partition("/") fps = float(num) / float(den or 1) or 30 proc = subprocess.Popen( ["ffmpeg", "-v", "error", "-i", args.input, "-vf", f"scale={w}:{h}", "-pix_fmt", "bgr24", "-f", "rawvideo", "-"], stdout=subprocess.PIPE, bufsize=w * h * 3) return None, proc, fps, w, h def read_frame(cap, proc, w, h): if cap is not None: ok, frame = cap.read() return frame if ok else None raw = proc.stdout.read(w * h * 3) if len(raw) < w * h * 3: return None return np.frombuffer(raw, np.uint8).reshape(h, w, 3).copy() def main(): ap = argparse.ArgumentParser() ap.add_argument("input", help="video file, or device index for --camera") ap.add_argument("-o", "--output", default="circled.mp4") ap.add_argument("--model", default="bibi-circle.pt") ap.add_argument("--refs", default="refs", help="dir with reference photos") ap.add_argument("--gpu", action="store_true") ap.add_argument("--camera", action="store_true") ap.add_argument("--stride", type=int, default=1, help="process every Nth frame") ap.add_argument("--live", action="store_true", help="show on screen, no output file") ap.add_argument("--no-label", action="store_true", help="circle only, no text") args = ap.parse_args() from ultralytics import YOLO det = YOLO(args.model) face_app, ref = load_ref_embeddings(args.refs, args.gpu) cap, proc, fps, w, h = open_source(args) writer = None if not (args.camera or args.live): fourcc = cv2.VideoWriter_fourcc(*"mp4v") writer = cv2.VideoWriter(args.output, fourcc, fps, (w, h)) if args.live or args.camera: cv2.namedWindow("BIG YAHU RADAR (q to quit)", cv2.WINDOW_NORMAL) prev = None # smoothed (cx, cy, r) cache = None # last confirmed visual (cx, cy, r, pct) for skipped frames cache_age = 0 hits = total = kept = 0 while True: frame = read_frame(cap, proc, w, h) if frame is None: break total += 1 detect_now = total % max(1, args.stride) == 1 if detect_now: det_faces = face_app.get(frame) r = det.predict(frame, verbose=False, imgsz=640, conf=0.25, device=0 if args.gpu else "cpu")[0] target = None for b in r.boxes: if hasattr(b, "cls") and int(b.cls[0]) != 0: continue # v2 model: class 1 = notbibi, never draw it x1, y1, x2, y2 = b.xyxy[0].tolist() conf = float(b.conf[0]) # match full-frame faces to this box by IoU (SCRFD is unreliable # on tight crops; one face-pass per frame is also faster) best = 0.0 for f in det_faces: fb = f.bbox bx1, by1, bx2, by2 = max(x1, fb[0]), max(y1, fb[1]), min(x2, fb[2]), min(y2, fb[3]) if bx2 > bx1 and by2 > by1: ua = (x2-x1)*(y2-y1) + (fb[2]-fb[0])*(fb[3]-fb[1]) - (bx2-bx1)*(by2-by1) if ua > 0 and ((bx2-bx1)*(by2-by1)) / ua >= IOU_GATE: best = max(best, cos(f.embedding, ref)) if best >= REF_THRESHOLD: target = ((x1+x2)/2, (y1+y2)/2, (x2-x1+y2-y1)/4, conf, best) break if target is not None: cx, cy, rad, conf, sim = target prev = (cx, cy, rad) if prev is None else tuple( SMOOTH_ALPHA*n + (1-SMOOTH_ALPHA)*p for n, p in zip(target[:3], prev)) pct = round(100 * conf * (0.5 + 0.5*sim), 1) cache = prev + (pct,) hits += 1 else: prev = None cache = None # lost him on a DETECTED frame -> stop drawing if cache is not None and cache_age <= max(2, args.stride * 2): cx, cy, rad, pct = cache cache_age += 1 cv2.circle(frame, (int(cx), int(cy)), int(rad*1.35), (0, 214, 255), 4, cv2.LINE_AA) if not args.no_label: cv2.putText(frame, f"BIG YAHU {pct}%", (int(cx-rad), int(cy-rad*1.7)), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 214, 255), 2, cv2.LINE_AA) else: cache_age = 0 if writer: writer.write(frame) kept += 1 else: cv2.imshow("BIG YAHU RADAR (q to quit)", frame) if cv2.waitKey(max(1, int(1000/max(fps, 5)))) & 0xFF == ord("q"): break if cap is not None: cap.release() if proc is not None: proc.stdout.close(); proc.kill() if writer: writer.release() print(f"[done] circled him in {hits}/{kept} kept frames " f"({total} read) -> {args.output}") else: cv2.destroyAllWindows() if __name__ == "__main__": main()