File size: 6,697 Bytes
0a4deb9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
#!/usr/bin/env python3
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):
    # Remove audio track to simulate visual-only input.
    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):
    # Extract mono wav audio for audio-only case.
    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:  # SDK raises typed errors but this keeps compatibility
            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()