Commit a2f0ab9
Changed files (1)
src
ai
texts
src/ai/texts/contexts.py
@@ -372,31 +372,36 @@ async def get_openai_file_id(
if params.get("max_upload_size") and message_bytes(message) > int(params["max_upload_size"]):
logger.warning(f"Message-{message.id} size {message_bytes(message)} bytes exceeds max_upload_size {params['max_upload_size']}")
return ""
- cache_day = params.get("cache_day", 30)
api_key = params["api_key"]
- key_hash = hashlib.sha256(api_key.encode()).hexdigest()
- r2_key = f"TTL/{cache_day}d/OpenAI/{message.chat.id}/{message.id}/{key_hash}-file_id"
- r2 = await head_cf_r2(r2_key)
- if file_id := glom(r2, "Metadata.file_id", default=""):
- return file_id
-
openai = AsyncOpenAI(
base_url=get_real_baseurl(),
api_key=api_key,
http_client=DefaultAsyncHttpxClient(proxy=params["proxy"]) if params.get("proxy") else None,
)
+ cache_day = params.get("cache_day", 30)
+ key_hash = hashlib.sha256(api_key.encode()).hexdigest()
+ r2_key = f"TTL/{cache_day}d/OpenAI/{message.chat.id}/{message.id}/{key_hash}-file_id"
+ r2 = await head_cf_r2(r2_key)
+ if file_id := glom(r2, "Metadata.file_id", default=""):
+ resp = await openai.files.retrieve(file_id=file_id)
+ if resp.status in ["active", "processed"]:
+ return file_id
+
if fpath is None:
fpath: str = await client.download_media(message) # ty:ignore[invalid-assignment]
try:
+ mime = guess_mime(fpath)
# hotfix: convert audio to aac
if force_audio_to_aac or (message.audio and not str(fpath).endswith(".aac")):
fpath: Path = await downsampe_audio(fpath, ext="aac", codec="aac")
resp = await openai.files.create(file=Path(fpath), purpose="user_data")
- while resp.status in ["processing", "uploaded"]:
- logger.trace(f"Upload media to OpenAI processing: {resp.model_dump()}")
- await asyncio.sleep(1)
- resp = await openai.files.retrieve(file_id=resp.id)
- if resp.status in ["active", "processed"]:
+ # skip waiting for image file
+ if not mime.startswith("image/"):
+ while resp.status in ["processing", "uploaded"]:
+ logger.trace(f"Upload media to OpenAI processing: {resp.model_dump()}")
+ await asyncio.sleep(1)
+ resp = await openai.files.retrieve(file_id=resp.id)
+ if mime.startswith("image/") or resp.status in ["active", "processed"]:
await set_cf_r2(r2_key, data=resp.model_dump(), metadata={"file_id": resp.id})
if not keep_file:
Path(fpath).unlink(missing_ok=True)