This commit is contained in:
Daniel Bedeleanu
2026-04-14 22:54:19 +03:00
parent 1ea5e90bc4
commit 6c57b1b0c2
69 changed files with 1020 additions and 554 deletions

View File

@@ -1,42 +1,50 @@
import os
import json
import io
import logging
from PIL import Image
from google import genai
from google.genai import types
log = logging.getLogger("ainventory")
def get_best_models():
# Using the exact models discovered via diagnostic
return ["gemini-2.0-flash", "gemini-2.5-flash"]
# Priority list based on aliases and future-gen models found in user logs
return [
"gemini-flash-latest", # Points to the best stable Flash version
"gemini-3.1-flash-lite-preview", # Cutting edge 3.1 Lite
"gemini-flash-lite-latest", # Best Lite alias
"gemini-pro-latest" # Pro fallback alias
]
def extract(image_bytes: bytes, prompt: str):
api_key = os.environ.get("GEMINI_API_KEY")
if not api_key:
print("CRITICAL: GEMINI_API_KEY is MISSING in environment!")
log.error("CRITICAL: GEMINI_API_KEY is MISSING in environment!")
return None
# Log partial key for safety debug
key_hint = f"{api_key[:4]}...{api_key[-4:]}" if len(api_key) > 8 else "too short"
print(f"🔑 Using API Key: {key_hint}")
log.info(f"🔑 Using API Key: {key_hint}")
try:
# Initialize the NEW SDK Client forcing stable v1 API
client = genai.Client(api_key=api_key, http_options={'api_version': 'v1'})
# Switching to v1beta which is required for many experimental/new models
client = genai.Client(api_key=api_key, http_options={'api_version': 'v1beta'})
# DEBUG: List allowed models for this key
print("🔍 Checking available models for your key...")
log.debug("🔍 Checking available models for your key...")
try:
for m in client.models.list():
print(f" - Found: {m.name}")
log.debug(f" - Found: {m.name}")
except Exception as list_e:
print(f" ⚠️ Could not list models: {list_e}")
log.warning(f" ⚠️ Could not list models: {list_e}")
models_to_try = get_best_models()
# Try models in order
for model_name in models_to_try:
try:
print(f"🚀 AI Launching (v2 SDK): {model_name}...")
log.info(f"🚀 AI Launching (v2 SDK): {model_name}...")
# In the new SDK, we pass a list of parts (text string and image bytes)
response = client.models.generate_content(
@@ -48,10 +56,12 @@ def extract(image_bytes: bytes, prompt: str):
)
if not response or not response.text:
log.warning(f"⚠️ Gemini {model_name} returned NO text.")
continue
text = response.text.strip()
print(f"✅ AI Response Received ({len(text)} bytes)")
log.info(f"✅ AI Response Received ({len(text)} bytes)")
log.debug(f"FULL RESPONSE:\n{text}")
# Extract JSON block
if "```json" in text:
@@ -62,10 +72,10 @@ def extract(image_bytes: bytes, prompt: str):
return json.loads(text)
except Exception as e:
print(f"❌ Gemini {model_name} failed: {e}")
log.error(f"❌ Gemini {model_name} failed: {e}")
continue
except Exception as outer_e:
print(f"❌ Gemini Client Init failed: {outer_e}")
log.error(f"❌ Gemini Client Init failed: {outer_e}")
return None