Isaac Quarenta
fix: openrouter nemotron→gemini-2.0, mistral timeout 20s+connect, groq payload truncate, factual question gate
628112f Download modules/google_image_gen.py from akra35567/Akiragpu: direct link, hf CLI and curl.
- Browser
- Download file 8.34 kB
-
https://huggingface.co/spaces/akra35567/Akiragpu/resolve/main/modules/google_image_gen.py
- Command line
-
hf download hf://spaces/akra35567/Akiragpu/modules/google_image_gen.py
-
curl -L -o google_image_gen.py https://huggingface.co/spaces/akra35567/Akiragpu/resolve/main/modules/google_image_gen.py
8.34 kB
| import os | |
| import base64 | |
| import requests | |
| from loguru import logger | |
| from typing import Optional, Dict, Any | |
| try: | |
| from google import genai | |
| from google.genai import types | |
| HAS_GENAI = True | |
| except ImportError: | |
| HAS_GENAI = False | |
| class GoogleImageGenerator: | |
| """ | |
| Gerador de imagens via Google. | |
| Chain interna: Imagen 3 (predict) -> Gemini 2.0 Flash nativo -> fallback factory | |
| """ | |
| IMAGEN_MODELS = [ | |
| "imagen-3.0-generate-001", | |
| "imagen-3.0-fast-001", | |
| ] | |
| def __init__(self, api_key: Optional[str] = None): | |
| self.api_key = api_key or os.getenv("GEMINI_API_KEY") or os.getenv("GOOGLE_API_KEY") | |
| self.client = None | |
| if HAS_GENAI and self.api_key: | |
| try: | |
| self.client = genai.Client(api_key=self.api_key) | |
| import google.genai as genai_mod | |
| logger.info(f"✅ Google GenAI SDK v{getattr(genai_mod, '__version__', 'unknown')} inicializado") | |
| except Exception as e: | |
| logger.error(f"❌ Falha ao inicializar Google GenAI Client: {e}") | |
| def generate(self, prompt: str, aspect_ratio: str = "1:1", model: str = "flux") -> Dict[str, Any]: | |
| if not self.client: | |
| return {"success": False, "error": "Google GenAI não disponível"} | |
| valid_ratios = ["1:1", "4:3", "3:4", "16:9", "9:16"] | |
| if aspect_ratio not in valid_ratios: | |
| aspect_ratio = "1:1" | |
| logger.info(f"🎨 [GOOGLE] Gerando imagem: '{prompt[:50]}...' [{aspect_ratio}]") | |
| # --- TENTATIVA 1: Imagen 3 via predict --- | |
| result = self._try_imagen(prompt, aspect_ratio) | |
| if result: | |
| return result | |
| # --- TENTATIVA 2: Gemini 2.0 Flash com geração nativa de imagem --- | |
| result = self._try_gemini_native(prompt, aspect_ratio) | |
| if result: | |
| return result | |
| return {"success": False, "error": "Google Imagen e Gemini nativo falharam"} | |
| def _try_imagen(self, prompt: str, aspect_ratio: str) -> Optional[Dict[str, Any]]: | |
| """Tenta gerar imagem via Imagen 3 (predict API).""" | |
| try: | |
| available_models = [] | |
| try: | |
| available_models = [m.name.replace("models/", "") for m in self.client.models.list()] | |
| except Exception: | |
| pass | |
| preferred = os.getenv("GEMINI_IMAGE_MODEL", "").split(",") if os.getenv("GEMINI_IMAGE_MODEL") else [] | |
| models_to_try = preferred + self.IMAGEN_MODELS | |
| models_to_try = [m.strip() for m in models_to_try if m.strip() in available_models] | |
| if not models_to_try: | |
| logger.info("⏭️ [GOOGLE] Nenhum modelo Imagen disponível no plano atual") | |
| return None | |
| logger.info(f"🎨 [GOOGLE] Tentando Imagen: {models_to_try}") | |
| for model_id in models_to_try: | |
| for method_name in ["generate_image", "generate_images"]: | |
| if not hasattr(self.client.models, method_name): | |
| continue | |
| try: | |
| method = getattr(self.client.models, method_name) | |
| config_class = types.GenerateImageConfig if method_name == "generate_image" else types.GenerateImagesConfig | |
| img_response = method( | |
| model=model_id, | |
| prompt=prompt, | |
| config=config_class( | |
| number_of_images=1, | |
| aspect_ratio=aspect_ratio, | |
| ) | |
| ) | |
| if img_response and img_response.generated_images: | |
| img = img_response.generated_images[0] | |
| data = None | |
| if hasattr(img, 'image') and hasattr(img.image, 'data'): | |
| data = img.image.data | |
| elif hasattr(img, 'image') and hasattr(img.image, 'image_bytes'): | |
| data = img.image.image_bytes | |
| elif hasattr(img, 'image_bytes'): | |
| data = img.image_bytes | |
| if data: | |
| import base64 as b64 | |
| img_b64 = b64.b64encode(data).decode('utf-8') if isinstance(data, bytes) else b64.b64encode(bytes(data)).decode('utf-8') | |
| logger.success(f"✅ [GOOGLE] Imagem gerada via {model_id}") | |
| return { | |
| "success": True, | |
| "image_data": img_b64, | |
| "mime_type": "image/png", | |
| "model": f"google-{model_id}", | |
| "prompt": prompt | |
| } | |
| except Exception as inner_e: | |
| err_str = str(inner_e).lower() | |
| if "paid plan" in err_str or "upgrade" in err_str: | |
| logger.info(f"⏭️ [GOOGLE] {model_id} requer plano pago, pulando") | |
| break | |
| logger.warning(f"⚠️ [GOOGLE] {model_id} falhou: {inner_e}") | |
| continue | |
| except Exception as e: | |
| logger.warning(f"⚠️ [GOOGLE] Erro Imagen: {e}") | |
| return None | |
| def _try_gemini_native(self, prompt: str, aspect_ratio: str) -> Optional[Dict[str, Any]]: | |
| """ | |
| Tenta Gemini 2.0 Flash com geração nativa de imagem. | |
| Gemini Flash 2.0 suporta output de imagem no free tier. | |
| """ | |
| # FIX 2026-08-28: Apenas 3.5-flash-lite é válido (Google deprecou 2.x). | |
| gemini_models = [ | |
| "gemini-2.5-flash", | |
| ] | |
| for gemini_model in gemini_models: | |
| try: | |
| logger.info(f"🔄 [GOOGLE] Tentando Gemini nativo ({gemini_model})...") | |
| response = self.client.models.generate_content( | |
| model=gemini_model, | |
| contents=[ | |
| types.Content( | |
| role="user", | |
| parts=[types.Part.from_text(text=f"Generate an image in {aspect_ratio} aspect ratio. {prompt}")] | |
| ) | |
| ], | |
| config=types.GenerateContentConfig( | |
| response_modalities=["image"], | |
| temperature=0.5, | |
| ) | |
| ) | |
| if response and response.candidates: | |
| for candidate in response.candidates: | |
| for part in candidate.content.parts: | |
| if hasattr(part, 'inline_data') and part.inline_data: | |
| data = part.inline_data.data | |
| mime = part.inline_data.mime_type or "image/png" | |
| img_b64 = base64.b64encode(data).decode('utf-8') if isinstance(data, bytes) else data | |
| logger.success(f"✅ [GOOGLE] Imagem gerada via {gemini_model}") | |
| return { | |
| "success": True, | |
| "image_data": img_b64, | |
| "mime_type": mime, | |
| "model": f"google-{gemini_model}", | |
| "prompt": prompt | |
| } | |
| except Exception as e: | |
| err_str = str(e).lower() | |
| if "not found" in err_str or "not supported" in err_str: | |
| logger.info(f"⏭️ [GOOGLE] {gemini_model} não disponível, pulando") | |
| continue | |
| if "modalities" in err_str or "response_modalities" in err_str: | |
| logger.info(f"⏭️ [GOOGLE] {gemini_model} não suporta imagem nativa, pulando") | |
| continue | |
| logger.warning(f"⚠️ [GOOGLE] {gemini_model} falhou: {e}") | |
| continue | |
| return None | |
| _instance = None | |
| def get_google_image_gen(): | |
| global _instance | |
| if _instance is None: | |
| _instance = GoogleImageGenerator() | |
| return _instance | |