Spaces:
Paused
Paused
Download apps/renderer/services/gemini/client.py from modventures/prevision: direct link, hf CLI and curl.
- Browser
- Download file 4.92 kB
-
https://huggingface.co/spaces/modventures/prevision/resolve/main/apps/renderer/services/gemini/client.py
- Command line
-
hf download hf://spaces/modventures/prevision/apps/renderer/services/gemini/client.py
-
curl -L -o client.py https://huggingface.co/spaces/modventures/prevision/resolve/main/apps/renderer/services/gemini/client.py
4.92 kB
| """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}).") | |