| |
| import argparse |
| import os |
| import subprocess |
| import tempfile |
| import time |
| from pathlib import Path |
|
|
| from google import genai |
|
|
|
|
| DEFAULT_PROMPT = ( |
| "Please describe the exact sequence of events in this video. " |
| "Specifically, when does the loudest sound occur in relation to the visual impact?" |
| ) |
|
|
|
|
| def run_cmd(cmd): |
| subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) |
|
|
|
|
| def make_video_only(input_video: Path, output_video: Path): |
| |
| cmd = [ |
| "ffmpeg", |
| "-y", |
| "-i", |
| str(input_video), |
| "-map", |
| "0:v:0", |
| "-an", |
| "-c:v", |
| "copy", |
| str(output_video), |
| ] |
| run_cmd(cmd) |
|
|
|
|
| def make_audio_only(input_video: Path, output_audio: Path): |
| |
| cmd = [ |
| "ffmpeg", |
| "-y", |
| "-i", |
| str(input_video), |
| "-vn", |
| "-ac", |
| "1", |
| "-ar", |
| "16000", |
| str(output_audio), |
| ] |
| run_cmd(cmd) |
|
|
|
|
| def wait_until_active(client: genai.Client, file_name: str, timeout_sec: int = 300): |
| start = time.time() |
| while True: |
| meta = client.files.get(name=file_name) |
| state = getattr(getattr(meta, "state", None), "name", None) or str(getattr(meta, "state", "")) |
| if state == "ACTIVE": |
| return |
| if state == "FAILED": |
| raise RuntimeError(f"Gemini file processing failed: {file_name}") |
| if time.time() - start > timeout_sec: |
| raise TimeoutError(f"Timed out waiting for Gemini file ACTIVE: {file_name}") |
| time.sleep(2) |
|
|
|
|
| def is_503_unavailable(exc: Exception) -> bool: |
| msg = str(exc) |
| return "503" in msg and "UNAVAILABLE" in msg |
|
|
|
|
| def generate_with_retry( |
| client: genai.Client, |
| model: str, |
| uploaded, |
| prompt: str, |
| max_retries: int, |
| retry_wait_sec: float, |
| ): |
| attempt = 0 |
| while True: |
| try: |
| return client.models.generate_content(model=model, contents=[uploaded, prompt]) |
| except Exception as exc: |
| if not is_503_unavailable(exc) or attempt >= max_retries: |
| raise |
| sleep_s = retry_wait_sec * (2 ** attempt) |
| print( |
| f"[retry] {model} busy (503). attempt {attempt + 1}/{max_retries}, " |
| f"sleep {sleep_s:.1f}s ..." |
| ) |
| time.sleep(sleep_s) |
| attempt += 1 |
|
|
|
|
| def run_case( |
| client: genai.Client, |
| model: str, |
| fallback_model: str, |
| case_name: str, |
| media_path: Path, |
| prompt: str, |
| max_retries: int, |
| retry_wait_sec: float, |
| ): |
| uploaded = client.files.upload(file=str(media_path)) |
| wait_until_active(client, uploaded.name) |
| try: |
| resp = generate_with_retry( |
| client=client, |
| model=model, |
| uploaded=uploaded, |
| prompt=prompt, |
| max_retries=max_retries, |
| retry_wait_sec=retry_wait_sec, |
| ) |
| except Exception as exc: |
| if fallback_model and is_503_unavailable(exc): |
| print(f"[fallback] switch to model: {fallback_model}") |
| resp = generate_with_retry( |
| client=client, |
| model=fallback_model, |
| uploaded=uploaded, |
| prompt=prompt, |
| max_retries=max_retries, |
| retry_wait_sec=retry_wait_sec, |
| ) |
| else: |
| raise |
| text = (resp.text or "").strip() |
| print(f"\n===== {case_name} =====") |
| print(text if text else "<empty response>") |
|
|
|
|
| def main(): |
| parser = argparse.ArgumentParser(description="Gemini AV/Video-only/Audio-only test runner.") |
| parser.add_argument("--video", required=True, help="Input video path.") |
| parser.add_argument( |
| "--model", |
| default="gemini-3.1-pro-preview", |
| help="Gemini model id.", |
| ) |
| parser.add_argument( |
| "--cases", |
| default="av,video_only,audio_only", |
| help="Comma-separated cases: av,video_only,audio_only", |
| ) |
| parser.add_argument( |
| "--fallback-model", |
| default="", |
| help="Optional fallback model if primary model returns 503.", |
| ) |
| parser.add_argument( |
| "--max-retries", |
| type=int, |
| default=5, |
| help="Retries for transient 503 errors.", |
| ) |
| parser.add_argument( |
| "--retry-wait-sec", |
| type=float, |
| default=2.0, |
| help="Base wait seconds for exponential backoff (2,4,8,...)", |
| ) |
| parser.add_argument("--prompt", default=DEFAULT_PROMPT) |
| args = parser.parse_args() |
|
|
| api_key = os.getenv("GEMINI_API_KEY") |
| if not api_key: |
| raise RuntimeError("GEMINI_API_KEY is not set.") |
|
|
| input_video = Path(args.video) |
| if not input_video.exists(): |
| raise FileNotFoundError(f"Video not found: {input_video}") |
|
|
| selected = {c.strip() for c in args.cases.split(",") if c.strip()} |
| allowed = {"av", "video_only", "audio_only"} |
| bad = selected - allowed |
| if bad: |
| raise ValueError(f"Unknown cases: {sorted(bad)}. Allowed: {sorted(allowed)}") |
|
|
| client = genai.Client(api_key=api_key) |
| print(f"Model: {args.model}") |
| print(f"Video: {input_video}") |
| print(f"Cases: {sorted(selected)}") |
|
|
| with tempfile.TemporaryDirectory(prefix="gemini_mm_") as tmpdir: |
| tmpdir = Path(tmpdir) |
| muted_video = tmpdir / "video_only.mp4" |
| audio_wav = tmpdir / "audio_only.wav" |
|
|
| if "av" in selected: |
| run_case( |
| client, |
| args.model, |
| args.fallback_model, |
| "AV (video + audio)", |
| input_video, |
| args.prompt, |
| args.max_retries, |
| args.retry_wait_sec, |
| ) |
|
|
| if "video_only" in selected: |
| make_video_only(input_video, muted_video) |
| run_case( |
| client, |
| args.model, |
| args.fallback_model, |
| "Video only (muted video)", |
| muted_video, |
| args.prompt, |
| args.max_retries, |
| args.retry_wait_sec, |
| ) |
|
|
| if "audio_only" in selected: |
| make_audio_only(input_video, audio_wav) |
| run_case( |
| client, |
| args.model, |
| args.fallback_model, |
| "Audio only (wav)", |
| audio_wav, |
| args.prompt, |
| args.max_retries, |
| args.retry_wait_sec, |
| ) |
|
|
| print("\nDone.") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|