fix(gemini): upload the source by handle, not by path
Handed a path, the SDK copies os.path.basename(path) verbatim into the X-Goog-Upload-File-Name header, and httpx encodes header values as ASCII. The downloaded file is named after the video's title, so every source titled in Japanese, Cyrillic, Arabic or Greek died with "'ascii' codec can't encode characters in position 0-4" before a byte left the container, on the three stages that upload the whole file: the silent-footage vision pass, the screencast detector and the AI editor. The user saw "the AI model did not return usable clips for this video". gemini_worker.upload_media() passes an open handle instead, which skips that header; the readable name still travels as display_name, in the JSON body, which is UTF-8. An extension the stdlib cannot place falls back to video/mp4 rather than reaching the API as octet-stream. The test reproduces the failure through the SDK's own header building and httpx, and fails if a new call site uses files.upload directly.
This commit is contained in:
parent
86bbc8b1cb
commit
ff2fd1005e
5 changed files with 117 additions and 3 deletions
|
|
@ -8,6 +8,7 @@ from google import genai
|
||||||
from google.genai import types
|
from google.genai import types
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
import gemini_worker
|
||||||
from edit_builder import build_filter_string
|
from edit_builder import build_filter_string
|
||||||
from ffmpeg_utils import video_encode_args, QUALITY, METADATA_SCRUB
|
from ffmpeg_utils import video_encode_args, QUALITY, METADATA_SCRUB
|
||||||
|
|
||||||
|
|
@ -43,7 +44,7 @@ class VideoEditor:
|
||||||
|
|
||||||
# Using 'file' keyword instead of 'path'
|
# Using 'file' keyword instead of 'path'
|
||||||
try:
|
try:
|
||||||
file_upload = self.client.files.upload(file=video_path)
|
file_upload = gemini_worker.upload_media(self.client, video_path)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"❌ Gemini Upload Error: {e}")
|
print(f"❌ Gemini Upload Error: {e}")
|
||||||
raise e
|
raise e
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
import argparse
|
import argparse
|
||||||
import json
|
import json
|
||||||
|
import mimetypes
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
from typing import List, Optional
|
from typing import List, Optional
|
||||||
|
|
@ -405,6 +406,34 @@ def _parse_json_response_text(text: str) -> dict:
|
||||||
raise ValueError(f"Failed to parse Gemini JSON response: {last_error}")
|
raise ValueError(f"Failed to parse Gemini JSON response: {last_error}")
|
||||||
|
|
||||||
|
|
||||||
|
def upload_media(client, path, mime_type=None):
|
||||||
|
"""Upload a local file to the Gemini Files API, by handle and never by path.
|
||||||
|
|
||||||
|
Handed a path, the SDK copies ``os.path.basename(path)`` verbatim into the
|
||||||
|
``X-Goog-Upload-File-Name`` header, and httpx encodes header values as
|
||||||
|
ASCII. The downloaded source is named after the video's title, so every
|
||||||
|
video whose title is written in Japanese, Cyrillic, Arabic or Greek died
|
||||||
|
before a byte left the container with ``'ascii' codec can't encode
|
||||||
|
characters in position 0-4`` (prod, 20-sep-2026) — on the three stages
|
||||||
|
that upload the whole file: the silent-footage vision pass, the screencast
|
||||||
|
detector and the AI editor. Passing an open handle skips that header
|
||||||
|
entirely; the readable name still travels as ``display_name``, which goes
|
||||||
|
in the JSON body and is UTF-8 all the way.
|
||||||
|
"""
|
||||||
|
guessed = mime_type or mimetypes.guess_type(path)[0] or ""
|
||||||
|
# Every caller uploads the source video; an extension the stdlib does not
|
||||||
|
# know (or knows as octet-stream) must not reach the API as a type it
|
||||||
|
# refuses, so fall back to the container the pipeline always writes.
|
||||||
|
if not guessed.startswith(("video/", "audio/", "image/")):
|
||||||
|
guessed = "video/mp4"
|
||||||
|
with open(path, "rb") as fh:
|
||||||
|
return client.files.upload(
|
||||||
|
file=fh,
|
||||||
|
config={"mime_type": guessed,
|
||||||
|
"display_name": os.path.basename(path)},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class GeminiBlockedError(ValueError):
|
class GeminiBlockedError(ValueError):
|
||||||
"""The API refused the request for content-policy reasons.
|
"""The API refused the request for content-policy reasons.
|
||||||
|
|
||||||
|
|
|
||||||
2
main.py
2
main.py
|
|
@ -1809,7 +1809,7 @@ def get_visual_clips(video_path, video_duration, language="en"):
|
||||||
|
|
||||||
file_upload = None
|
file_upload = None
|
||||||
try:
|
try:
|
||||||
file_upload = client.files.upload(file=video_path)
|
file_upload = gemini_worker.upload_media(client, video_path)
|
||||||
deadline = time.time() + 180
|
deadline = time.time() + 180
|
||||||
while True:
|
while True:
|
||||||
info = client.files.get(name=file_upload.name)
|
info = client.files.get(name=file_upload.name)
|
||||||
|
|
|
||||||
|
|
@ -192,7 +192,7 @@ def detect_content_ranges(video_path, video_duration):
|
||||||
file_upload = None
|
file_upload = None
|
||||||
try:
|
try:
|
||||||
client = genai.Client(api_key=api_key)
|
client = genai.Client(api_key=api_key)
|
||||||
file_upload = client.files.upload(file=video_path)
|
file_upload = gemini_worker.upload_media(client, video_path)
|
||||||
deadline = time.time() + 180
|
deadline = time.time() + 180
|
||||||
while True:
|
while True:
|
||||||
info = client.files.get(name=file_upload.name)
|
info = client.files.get(name=file_upload.name)
|
||||||
|
|
|
||||||
84
tests/test_gemini_upload_unicode_name.py
Normal file
84
tests/test_gemini_upload_unicode_name.py
Normal file
|
|
@ -0,0 +1,84 @@
|
||||||
|
"""A video whose title is not ASCII must still reach the Gemini Files API.
|
||||||
|
|
||||||
|
The SDK, handed a path, puts ``os.path.basename(path)`` into the
|
||||||
|
``X-Goog-Upload-File-Name`` header, and httpx encodes header values as ASCII.
|
||||||
|
The downloaded source is named after the video's title, so on 20-sep-2026 a
|
||||||
|
job died with ``'ascii' codec can't encode characters in position 0-4`` before
|
||||||
|
a byte was sent, and the pipeline reported it as "the AI model did not return
|
||||||
|
usable clips for this video".
|
||||||
|
"""
|
||||||
|
import io
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
import gemini_worker
|
||||||
|
|
||||||
|
|
||||||
|
def _prepared_headers(file_arg, mime_type=None):
|
||||||
|
"""The headers the real SDK would build for this upload argument."""
|
||||||
|
from google.genai import _extra_utils
|
||||||
|
http_options, _size, _mime = _extra_utils.prepare_resumable_upload(
|
||||||
|
file_arg, user_mime_type=mime_type)
|
||||||
|
return http_options.headers
|
||||||
|
|
||||||
|
|
||||||
|
class _FakeFiles:
|
||||||
|
def __init__(self):
|
||||||
|
self.calls = []
|
||||||
|
|
||||||
|
def upload(self, *, file, config=None):
|
||||||
|
self.calls.append((file, config))
|
||||||
|
# Reproduce the SDK's own header building and httpx's ASCII encoding:
|
||||||
|
# this is exactly where the prod failure happened.
|
||||||
|
httpx.Headers(_prepared_headers(file, (config or {}).get("mime_type")))
|
||||||
|
return "uploaded"
|
||||||
|
|
||||||
|
|
||||||
|
class _FakeClient:
|
||||||
|
def __init__(self):
|
||||||
|
self.files = _FakeFiles()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def unicode_video(tmp_path):
|
||||||
|
path = tmp_path / "日本語のタイトル_video.mp4"
|
||||||
|
path.write_bytes(b"\0" * 2048)
|
||||||
|
return str(path)
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_path_form_is_what_breaks(unicode_video):
|
||||||
|
"""Guard rail: if a future SDK stops sending that header, drop the helper."""
|
||||||
|
with pytest.raises(UnicodeEncodeError):
|
||||||
|
httpx.Headers(_prepared_headers(unicode_video))
|
||||||
|
|
||||||
|
|
||||||
|
def test_upload_media_survives_a_non_ascii_title(unicode_video):
|
||||||
|
client = _FakeClient()
|
||||||
|
assert gemini_worker.upload_media(client, unicode_video) == "uploaded"
|
||||||
|
file_arg, config = client.files.calls[0]
|
||||||
|
assert isinstance(file_arg, io.IOBase), "must upload by handle, not by path"
|
||||||
|
assert config["mime_type"] == "video/mp4"
|
||||||
|
# The readable name still travels — in the JSON body, which is UTF-8.
|
||||||
|
assert config["display_name"] == "日本語のタイトル_video.mp4"
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_unknown_extension_still_gets_a_mime_type(tmp_path):
|
||||||
|
path = tmp_path / "clip.bin"
|
||||||
|
path.write_bytes(b"\0" * 16)
|
||||||
|
client = _FakeClient()
|
||||||
|
gemini_worker.upload_media(client, str(path))
|
||||||
|
assert client.files.calls[0][1]["mime_type"] == "video/mp4"
|
||||||
|
|
||||||
|
|
||||||
|
def test_every_whole_file_upload_goes_through_the_helper():
|
||||||
|
"""The three stages that send Gemini the file itself, not frames."""
|
||||||
|
import pathlib
|
||||||
|
import re
|
||||||
|
root = pathlib.Path(__file__).resolve().parent.parent
|
||||||
|
offenders = []
|
||||||
|
for name in ("main.py", "editor.py", "screencast_layout.py", "thumbnail.py"):
|
||||||
|
src = (root / name).read_text()
|
||||||
|
if re.search(r"\.files\.upload\(", src):
|
||||||
|
offenders.append(name)
|
||||||
|
assert offenders == [], f"{offenders} call files.upload directly (use upload_media)"
|
||||||
Loading…
Reference in a new issue