Spaces:
Running
Running
File size: 1,746 Bytes
4ae3e44 a8f90b0 9e38f34 4ae3e44 a8f90b0 4ae3e44 a8f90b0 9e38f34 a8f90b0 4ae3e44 |
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 |
import os
import base64
import time
from io import BytesIO
from typing import Optional
from PIL import Image
from logging_helper import log as _log, log_debug as _log_debug, _log_model_response
from image_utils import _pil_image_to_base64_jpeg
from common import MODELS_MAP
try:
from openai import OpenAI
except ImportError: # pragma: no cover
OpenAI = None # type: ignore
def _run_openai_vision(image: Image.Image, prompt: str, model_name: str) -> str:
if OpenAI is None:
raise RuntimeError("openai package is not installed. Please install it to use ChatGPT 5.2 backend.")
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
raise RuntimeError("OPENAI_API_KEY environment variable is not set.")
client = OpenAI(api_key=api_key)
img_b64 = _pil_image_to_base64_jpeg(image)
_log_debug(f"Using OpenAI model: {model_name}")
_log_debug(f"Input image size: {image.size}")
start_time = time.perf_counter()
response = client.chat.completions.create(
model=model_name,
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": prompt},
{
"type": "image_url",
"image_url": {"url": f"data:image/jpeg;base64,{img_b64}"},
},
],
}
],
max_completion_tokens=4048,
)
duration = time.perf_counter() - start_time
content = response.choices[0].message.content or ""
_log_model_response(
model_name=model_name,
content=content,
duration=duration,
usage=response.usage,
pricing=MODELS_MAP,
)
return content
|