File size: 4,917 Bytes
1fe7075
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Gemini API client: decode inline images and call image refinement."""

import base64
import io
import json
import urllib.error
import urllib.parse
import urllib.request

from PIL import Image

from config.gemini import (
    GEMINI_API_BASE_URL,
    GEMINI_API_KEY,
    GEMINI_IMAGE_MODEL,
    GEMINI_TIMEOUT_SECONDS,
)
from errors import bad_gateway, bad_request, service_unavailable


def decode_inline_image_payload(image_value: str) -> tuple[bytes, str]:
    if not image_value:
        bad_request("Image is required.")

    mime_type = "image/png"
    encoded = image_value
    if image_value.startswith("data:"):
        try:
            header, encoded = image_value.split(",", 1)
        except ValueError as exc:
            bad_request("Image data URL is malformed.", exc)
        mime_type = header[5:].split(";", 1)[0] or mime_type

    try:
        image_bytes = base64.b64decode(encoded, validate=True)
    except Exception as exc:
        bad_request("Image must be base64 encoded.", exc)

    if not image_bytes:
        bad_request("Image must not be empty.")

    try:
        with Image.open(io.BytesIO(image_bytes)) as uploaded:
            uploaded.verify()
            detected_mime = Image.MIME.get(uploaded.format)
            if detected_mime:
                mime_type = detected_mime
    except Exception as exc:
        bad_request("Image must be a readable PNG, JPEG, or WebP.", exc)

    if mime_type not in {"image/png", "image/jpeg", "image/webp"}:
        bad_request("Image must be a PNG, JPEG, or WebP.")

    return image_bytes, mime_type


def call_gemini_image_refinement(image_bytes: bytes, mime_type: str, prompt: str) -> tuple[str, str]:
    """One image and one instruction in, one image out (base64, mime)."""
    output, output_mime = call_gemini_image([(image_bytes, mime_type, None)], prompt)
    return base64.b64encode(output).decode("ascii"), output_mime


def call_gemini_image(
    images: list[tuple[bytes, str, str | None]],
    prompt: str,
    *,
    aspect_ratio: str | None = None,
    image_size: str | None = None,
) -> tuple[bytes, str]:
    """Images (bytes, mime, optional caption placed before it) and an instruction in; one image out."""
    if not GEMINI_API_KEY:
        service_unavailable("Gemini refinement is not configured. Set GEMINI_API_KEY.")
    if not GEMINI_IMAGE_MODEL:
        service_unavailable("Gemini image model is not configured.")

    parts: list[dict] = [{"text": prompt}]
    for data, mime, caption in images:
        if caption:
            parts.append({"text": caption})
        parts.append({"inline_data": {"mime_type": mime, "data": base64.b64encode(data).decode("ascii")}})
    # Image only: no text answer to generate, which keeps the call short.
    generation_config: dict = {"responseModalities": ["IMAGE"]}
    image_config = {key: value for key, value in (("aspectRatio", aspect_ratio), ("imageSize", image_size)) if value}
    if image_config:
        generation_config["imageConfig"] = image_config
    request_body = {"contents": [{"parts": parts}], "generationConfig": generation_config}
    encoded_model = urllib.parse.quote(GEMINI_IMAGE_MODEL, safe="")
    url = f"{GEMINI_API_BASE_URL}/{encoded_model}:generateContent"
    request = urllib.request.Request(
        url,
        data=json.dumps(request_body).encode("utf-8"),
        headers={
            "Content-Type": "application/json",
            "x-goog-api-key": GEMINI_API_KEY,
        },
        method="POST",
    )

    try:
        with urllib.request.urlopen(request, timeout=GEMINI_TIMEOUT_SECONDS) as response:
            response_body = response.read().decode("utf-8")
    except urllib.error.HTTPError as exc:
        detail = exc.read().decode("utf-8", errors="replace")[:1000]
        bad_gateway(f"Gemini refinement failed ({exc.code}): {detail}", exc)
    except (urllib.error.URLError, TimeoutError) as exc:
        bad_gateway(f"Gemini refinement request failed: {getattr(exc, 'reason', exc)}", exc)

    try:
        data = json.loads(response_body)
    except json.JSONDecodeError as exc:
        bad_gateway("Gemini returned invalid JSON.", exc)

    for candidate in data.get("candidates", []):
        content = candidate.get("content") or {}
        for part in content.get("parts", []):
            inline_data = part.get("inlineData") or part.get("inline_data")
            if not inline_data:
                continue
            output_b64 = inline_data.get("data")
            if output_b64:
                output_mime = inline_data.get("mimeType") or inline_data.get("mime_type") or "image/png"
                return base64.b64decode(output_b64), output_mime

    reason = (data.get("promptFeedback") or {}).get("blockReason") or next(
        (c["finishReason"] for c in data.get("candidates", []) if c.get("finishReason")), "no image"
    )
    bad_gateway(f"Gemini did not return a refined image ({reason}).")