Download services/gemini/client.py from modventures/room-visualizer-v2: direct link, hf CLI and curl.
- Browser
- Download file 3.83 kB
-
https://huggingface.co/spaces/modventures/room-visualizer-v2/resolve/main/services/gemini/client.py
- Command line
-
hf download hf://spaces/modventures/room-visualizer-v2/services/gemini/client.py
-
curl -L -o client.py https://huggingface.co/spaces/modventures/room-visualizer-v2/resolve/main/services/gemini/client.py
3.83 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]: | |
| 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.") | |
| request_body = { | |
| "contents": [{ | |
| "parts": [ | |
| {"text": prompt}, | |
| { | |
| "inline_data": { | |
| "mime_type": mime_type, | |
| "data": base64.b64encode(image_bytes).decode("ascii"), | |
| } | |
| }, | |
| ] | |
| }] | |
| } | |
| 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 as exc: | |
| bad_gateway(f"Gemini refinement request failed: {exc.reason}", 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 output_b64, output_mime | |
| bad_gateway("Gemini did not return a refined image.") | |