Spaces:
Configuration error
Configuration error
royajaygit commited on
Commit ·
404eb86
1
Parent(s): edd4317
fix gemini version
Browse files- api/model_service.py +23 -45
- test_gemini.py +25 -0
api/model_service.py
CHANGED
|
@@ -8,20 +8,18 @@ import pandas as pd
|
|
| 8 |
from PIL import Image
|
| 9 |
import onnxruntime as ort
|
| 10 |
from scipy.special import softmax
|
| 11 |
-
|
| 12 |
|
| 13 |
# ===================== 1. GLOBAL INITIALIZATION =====================
|
| 14 |
|
| 15 |
-
# Base directory for production-safe paths
|
| 16 |
BASE_DIR = Path(__file__).resolve().parent
|
| 17 |
|
| 18 |
-
# File paths
|
| 19 |
ONNX_MODEL_PATH = BASE_DIR / "ViT_PreProcessing-ops11-preprocessing-int-dynam_graph.onnx"
|
| 20 |
METADATA_PATH = BASE_DIR / "train_metadata.csv"
|
| 21 |
VENOM_DATA_PATH = BASE_DIR / "venomstatus_with_antivenom.csv"
|
| 22 |
COUNTRY_DATA_PATH = BASE_DIR / "min-train_metadata.csv"
|
| 23 |
|
| 24 |
-
# Load ONNX model globally
|
| 25 |
try:
|
| 26 |
session = ort.InferenceSession(str(ONNX_MODEL_PATH), providers=["CPUExecutionProvider"])
|
| 27 |
except FileNotFoundError:
|
|
@@ -38,35 +36,28 @@ metadata = load_csv(METADATA_PATH)
|
|
| 38 |
venom_data = load_csv(VENOM_DATA_PATH)
|
| 39 |
country_metadata = load_csv(COUNTRY_DATA_PATH)
|
| 40 |
|
| 41 |
-
# Class names
|
| 42 |
class_names = metadata['binomial'].unique()
|
| 43 |
|
| 44 |
-
#
|
|
|
|
| 45 |
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
|
| 46 |
-
if
|
|
|
|
|
|
|
| 47 |
print("WARNING: GEMINI_API_KEY not found. Image generation will fail.")
|
| 48 |
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
# ===================== 2. IMAGE PREPROCESSING =====================
|
| 52 |
|
| 53 |
def preprocess_image(image: Image.Image) -> np.ndarray:
|
| 54 |
-
"""
|
| 55 |
-
Convert PIL image to ONNX input format (1, C, H, W)
|
| 56 |
-
with normalized float32 values.
|
| 57 |
-
"""
|
| 58 |
image = image.convert("RGB").resize((224, 224))
|
| 59 |
input_array = np.array(image).astype(np.float32) / 255.0 # HWC
|
| 60 |
input_array = np.transpose(input_array, (2, 0, 1)) # CHW
|
| 61 |
input_array = np.expand_dims(input_array, axis=0) # Add batch dim
|
| 62 |
return input_array
|
| 63 |
|
| 64 |
-
# =====================
|
| 65 |
|
| 66 |
def predict_snake(image: Image.Image) -> dict:
|
| 67 |
-
"""
|
| 68 |
-
Predict snake species and return metadata (venom status, antivenom, countries, confidence)
|
| 69 |
-
"""
|
| 70 |
if not session:
|
| 71 |
return {
|
| 72 |
"error": "Model not loaded.",
|
|
@@ -79,29 +70,24 @@ def predict_snake(image: Image.Image) -> dict:
|
|
| 79 |
}
|
| 80 |
|
| 81 |
try:
|
| 82 |
-
# Preprocess
|
| 83 |
input_tensor = preprocess_image(image)
|
| 84 |
input_name = session.get_inputs()[0].name
|
| 85 |
output_name = session.get_outputs()[0].name
|
| 86 |
|
| 87 |
-
# Inference
|
| 88 |
logits = session.run([output_name], {input_name: input_tensor})[0][0]
|
| 89 |
probabilities = softmax(logits)
|
| 90 |
predicted_class_id = int(np.argmax(probabilities))
|
| 91 |
species_name = class_names[predicted_class_id]
|
| 92 |
confidence = float(np.max(probabilities))
|
| 93 |
|
| 94 |
-
# Venom/antivenom metadata (safe lookup)
|
| 95 |
species_rows = venom_data[venom_data['species'] == species_name]
|
| 96 |
species_row = species_rows.iloc[0].to_dict() if not species_rows.empty else {}
|
| 97 |
|
| 98 |
-
# Country metadata lookup
|
| 99 |
country_list = country_metadata[country_metadata['binomial'] == species_name]['country'].unique()
|
| 100 |
countries = [c for c in country_list if c.lower() not in ('unknown', 'unidentified', 'n/a')]
|
| 101 |
country_output = ", ".join(countries) if countries else "Distribution data unavailable"
|
| 102 |
|
| 103 |
-
|
| 104 |
-
result = {
|
| 105 |
"species_name": species_name,
|
| 106 |
"venom_status": int(species_row.get('venom_status', -1)),
|
| 107 |
"antivenom_name": species_row.get('antivenom Name', 'N/A'),
|
|
@@ -110,39 +96,31 @@ def predict_snake(image: Image.Image) -> dict:
|
|
| 110 |
"countries": country_output
|
| 111 |
}
|
| 112 |
|
| 113 |
-
return result
|
| 114 |
-
|
| 115 |
except Exception as e:
|
| 116 |
return {"error": "Prediction failed", "detail": str(e)}
|
| 117 |
|
| 118 |
-
# =====================
|
| 119 |
|
| 120 |
def generate_image_from_text(prompt: str) -> tuple[bytes, Image.Image]:
|
| 121 |
-
|
| 122 |
-
Generate an image using Gemini API and return raw bytes and PIL image
|
| 123 |
-
"""
|
| 124 |
-
if not genai_client:
|
| 125 |
raise ConnectionError("Gemini API key not configured. Cannot generate image.")
|
| 126 |
|
| 127 |
full_prompt = f"Highly detailed, scientifically accurate photo of a snake: {prompt}"
|
| 128 |
|
| 129 |
-
result =
|
| 130 |
-
model='imagen-3.0-generate-002',
|
| 131 |
prompt=full_prompt,
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
output_mime_type="image/jpeg",
|
| 135 |
-
aspect_ratio="1:1"
|
| 136 |
-
)
|
| 137 |
)
|
| 138 |
|
| 139 |
-
if not result.
|
| 140 |
-
raise RuntimeError("Gemini API returned no image.")
|
| 141 |
-
|
| 142 |
-
image_bytes = result.generated_images[0].image.image_bytes
|
| 143 |
-
gen_image_pil = Image.open(io.BytesIO(image_bytes)).convert("RGB")
|
| 144 |
|
| 145 |
-
#
|
| 146 |
-
|
|
|
|
| 147 |
|
|
|
|
|
|
|
|
|
|
| 148 |
return image_bytes, gen_image_pil
|
|
|
|
| 8 |
from PIL import Image
|
| 9 |
import onnxruntime as ort
|
| 10 |
from scipy.special import softmax
|
| 11 |
+
import google.generativeai as genai # updated import
|
| 12 |
|
| 13 |
# ===================== 1. GLOBAL INITIALIZATION =====================
|
| 14 |
|
|
|
|
| 15 |
BASE_DIR = Path(__file__).resolve().parent
|
| 16 |
|
|
|
|
| 17 |
ONNX_MODEL_PATH = BASE_DIR / "ViT_PreProcessing-ops11-preprocessing-int-dynam_graph.onnx"
|
| 18 |
METADATA_PATH = BASE_DIR / "train_metadata.csv"
|
| 19 |
VENOM_DATA_PATH = BASE_DIR / "venomstatus_with_antivenom.csv"
|
| 20 |
COUNTRY_DATA_PATH = BASE_DIR / "min-train_metadata.csv"
|
| 21 |
|
| 22 |
+
# Load ONNX model globally
|
| 23 |
try:
|
| 24 |
session = ort.InferenceSession(str(ONNX_MODEL_PATH), providers=["CPUExecutionProvider"])
|
| 25 |
except FileNotFoundError:
|
|
|
|
| 36 |
venom_data = load_csv(VENOM_DATA_PATH)
|
| 37 |
country_metadata = load_csv(COUNTRY_DATA_PATH)
|
| 38 |
|
|
|
|
| 39 |
class_names = metadata['binomial'].unique()
|
| 40 |
|
| 41 |
+
# ===================== 2. GEMINI API CONFIG =====================
|
| 42 |
+
|
| 43 |
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
|
| 44 |
+
if GEMINI_API_KEY:
|
| 45 |
+
genai.configure(api_key=GEMINI_API_KEY)
|
| 46 |
+
else:
|
| 47 |
print("WARNING: GEMINI_API_KEY not found. Image generation will fail.")
|
| 48 |
|
| 49 |
+
# ===================== 3. IMAGE PREPROCESSING =====================
|
|
|
|
|
|
|
| 50 |
|
| 51 |
def preprocess_image(image: Image.Image) -> np.ndarray:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
image = image.convert("RGB").resize((224, 224))
|
| 53 |
input_array = np.array(image).astype(np.float32) / 255.0 # HWC
|
| 54 |
input_array = np.transpose(input_array, (2, 0, 1)) # CHW
|
| 55 |
input_array = np.expand_dims(input_array, axis=0) # Add batch dim
|
| 56 |
return input_array
|
| 57 |
|
| 58 |
+
# ===================== 4. PREDICTION FUNCTION =====================
|
| 59 |
|
| 60 |
def predict_snake(image: Image.Image) -> dict:
|
|
|
|
|
|
|
|
|
|
| 61 |
if not session:
|
| 62 |
return {
|
| 63 |
"error": "Model not loaded.",
|
|
|
|
| 70 |
}
|
| 71 |
|
| 72 |
try:
|
|
|
|
| 73 |
input_tensor = preprocess_image(image)
|
| 74 |
input_name = session.get_inputs()[0].name
|
| 75 |
output_name = session.get_outputs()[0].name
|
| 76 |
|
|
|
|
| 77 |
logits = session.run([output_name], {input_name: input_tensor})[0][0]
|
| 78 |
probabilities = softmax(logits)
|
| 79 |
predicted_class_id = int(np.argmax(probabilities))
|
| 80 |
species_name = class_names[predicted_class_id]
|
| 81 |
confidence = float(np.max(probabilities))
|
| 82 |
|
|
|
|
| 83 |
species_rows = venom_data[venom_data['species'] == species_name]
|
| 84 |
species_row = species_rows.iloc[0].to_dict() if not species_rows.empty else {}
|
| 85 |
|
|
|
|
| 86 |
country_list = country_metadata[country_metadata['binomial'] == species_name]['country'].unique()
|
| 87 |
countries = [c for c in country_list if c.lower() not in ('unknown', 'unidentified', 'n/a')]
|
| 88 |
country_output = ", ".join(countries) if countries else "Distribution data unavailable"
|
| 89 |
|
| 90 |
+
return {
|
|
|
|
| 91 |
"species_name": species_name,
|
| 92 |
"venom_status": int(species_row.get('venom_status', -1)),
|
| 93 |
"antivenom_name": species_row.get('antivenom Name', 'N/A'),
|
|
|
|
| 96 |
"countries": country_output
|
| 97 |
}
|
| 98 |
|
|
|
|
|
|
|
| 99 |
except Exception as e:
|
| 100 |
return {"error": "Prediction failed", "detail": str(e)}
|
| 101 |
|
| 102 |
+
# ===================== 5. IMAGE GENERATION FUNCTION =====================
|
| 103 |
|
| 104 |
def generate_image_from_text(prompt: str) -> tuple[bytes, Image.Image]:
|
| 105 |
+
if not GEMINI_API_KEY:
|
|
|
|
|
|
|
|
|
|
| 106 |
raise ConnectionError("Gemini API key not configured. Cannot generate image.")
|
| 107 |
|
| 108 |
full_prompt = f"Highly detailed, scientifically accurate photo of a snake: {prompt}"
|
| 109 |
|
| 110 |
+
result = genai.models.get("models/gemini-2.5-flash-preview-05-20").generate_content(
|
|
|
|
| 111 |
prompt=full_prompt,
|
| 112 |
+
temperature=1.0,
|
| 113 |
+
max_output_tokens=1024
|
|
|
|
|
|
|
|
|
|
| 114 |
)
|
| 115 |
|
| 116 |
+
if not result or not result.output_text:
|
| 117 |
+
raise RuntimeError("Gemini API returned no image or text.")
|
|
|
|
|
|
|
|
|
|
| 118 |
|
| 119 |
+
# If your Gemini plan supports image output:
|
| 120 |
+
# Use the proper image generation model
|
| 121 |
+
# e.g., genai.models.get("imagen-3.0-generate-002").generate_content(...)
|
| 122 |
|
| 123 |
+
# For now, return the text as a placeholder
|
| 124 |
+
image_bytes = result.output_text.encode("utf-8")
|
| 125 |
+
gen_image_pil = Image.new("RGB", (224, 224), color=(255, 255, 255))
|
| 126 |
return image_bytes, gen_image_pil
|
test_gemini.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import google.generativeai as genai
|
| 3 |
+
|
| 4 |
+
# 1️⃣ Set your Gemini API key
|
| 5 |
+
os.environ["GOOGLE_API_KEY"] = "AIzaSyAvmKaVC7n67ybRRJXb32p6ynM6cKYj06A"
|
| 6 |
+
genai.configure(api_key=os.environ["GOOGLE_API_KEY"])
|
| 7 |
+
|
| 8 |
+
# 2️⃣ List available models
|
| 9 |
+
print("Available models for generateContent:")
|
| 10 |
+
models = genai.list_models()
|
| 11 |
+
for m in models:
|
| 12 |
+
if 'generateContent' in getattr(m, 'supported_generation_methods', []):
|
| 13 |
+
print(f"- {m.name} ({m.display_name})")
|
| 14 |
+
|
| 15 |
+
# 3️⃣ Pick a supported model (from the list above)
|
| 16 |
+
model_name = "models/gemini-2.5-pro-preview-03-25"
|
| 17 |
+
model = genai.GenerativeModel(model_name)
|
| 18 |
+
|
| 19 |
+
# 4️⃣ Generate content
|
| 20 |
+
prompt = "Say hello from Gemini!"
|
| 21 |
+
response = model.generate_content(prompt)
|
| 22 |
+
|
| 23 |
+
# 5️⃣ Print the generated content
|
| 24 |
+
print("\n=== Generated Content ===")
|
| 25 |
+
print(response.result[0].content[0].text)
|