Spaces:
Configuration error
Configuration error
royajaygit commited on
Commit ·
4d071cd
1
Parent(s): fdc2547
Initial commit - Snake AI API
Browse files- api/main.py +45 -38
- api/model_service.py +96 -108
- requirements.txt +9 -11
- start.sh +8 -0
api/main.py
CHANGED
|
@@ -4,76 +4,83 @@ import io
|
|
| 4 |
import base64
|
| 5 |
from fastapi import FastAPI, UploadFile, File, Form
|
| 6 |
from fastapi.responses import JSONResponse
|
| 7 |
-
from fastapi.middleware.cors import CORSMiddleware
|
| 8 |
from PIL import Image
|
| 9 |
|
| 10 |
-
#
|
| 11 |
-
from .model_service import predict_snake, generate_image_from_text
|
| 12 |
|
| 13 |
-
# Initialize
|
| 14 |
app = FastAPI(title="Snake AI Detection API")
|
| 15 |
|
| 16 |
-
# ==========================================
|
| 17 |
-
#
|
| 18 |
-
# ====================================================================
|
| 19 |
-
# Define the allowed origins (replace the placeholder with your Next.js domain)
|
| 20 |
origins = [
|
| 21 |
-
"http://localhost:3000",
|
| 22 |
-
"http://localhost:8080",
|
| 23 |
"http://localhost",
|
| 24 |
-
"https://your-production-frontend-domain.com"
|
| 25 |
]
|
| 26 |
|
| 27 |
app.add_middleware(
|
| 28 |
CORSMiddleware,
|
| 29 |
-
allow_origins=origins,
|
| 30 |
-
allow_credentials=True,
|
| 31 |
-
allow_methods=["*"],
|
| 32 |
-
allow_headers=["*"]
|
| 33 |
)
|
| 34 |
-
# ====================================================================
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
# ====================================================================
|
| 38 |
-
# Endpoint 1: Image Upload and Prediction
|
| 39 |
-
# ====================================================================
|
| 40 |
|
|
|
|
| 41 |
@app.post("/predict-image")
|
| 42 |
async def predict_image_endpoint(file: UploadFile = File(...)):
|
| 43 |
-
"""
|
|
|
|
|
|
|
| 44 |
try:
|
| 45 |
image_data = await file.read()
|
| 46 |
-
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
| 48 |
prediction_result = predict_snake(image)
|
| 49 |
-
|
| 50 |
return JSONResponse(content=prediction_result)
|
| 51 |
-
|
| 52 |
except Exception as e:
|
| 53 |
print(f"Prediction Error: {e}")
|
| 54 |
-
return JSONResponse(
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
# ====================================================================
|
| 59 |
|
|
|
|
| 60 |
@app.post("/generate-and-predict")
|
| 61 |
async def generate_and_predict_endpoint(description: str = Form(...)):
|
| 62 |
-
"""
|
|
|
|
|
|
|
|
|
|
| 63 |
try:
|
|
|
|
| 64 |
image_bytes, gen_image_pil = generate_image_from_text(description)
|
|
|
|
|
|
|
| 65 |
prediction_result = predict_snake(gen_image_pil)
|
| 66 |
-
|
| 67 |
-
# Encode
|
| 68 |
base64_image = base64.b64encode(image_bytes).decode('utf-8')
|
| 69 |
-
|
| 70 |
response_data = {
|
| 71 |
"generated_image_base64": base64_image,
|
| 72 |
"prediction": prediction_result
|
| 73 |
}
|
| 74 |
-
|
| 75 |
return JSONResponse(content=response_data)
|
| 76 |
-
|
| 77 |
except Exception as e:
|
| 78 |
print(f"Generation/Prediction Error: {e}")
|
| 79 |
-
return JSONResponse(
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
import base64
|
| 5 |
from fastapi import FastAPI, UploadFile, File, Form
|
| 6 |
from fastapi.responses import JSONResponse
|
| 7 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 8 |
from PIL import Image
|
| 9 |
|
| 10 |
+
# Import optimized service
|
| 11 |
+
from .model_service import predict_snake, generate_image_from_text
|
| 12 |
|
| 13 |
+
# Initialize FastAPI
|
| 14 |
app = FastAPI(title="Snake AI Detection API")
|
| 15 |
|
| 16 |
+
# ===================== 1. CORS MIDDLEWARE =====================
|
| 17 |
+
# Allowed origins (update with your frontend domain)
|
|
|
|
|
|
|
| 18 |
origins = [
|
| 19 |
+
"http://localhost:3000",
|
| 20 |
+
"http://localhost:8080",
|
| 21 |
"http://localhost",
|
| 22 |
+
"https://your-production-frontend-domain.com"
|
| 23 |
]
|
| 24 |
|
| 25 |
app.add_middleware(
|
| 26 |
CORSMiddleware,
|
| 27 |
+
allow_origins=origins,
|
| 28 |
+
allow_credentials=True,
|
| 29 |
+
allow_methods=["*"],
|
| 30 |
+
allow_headers=["*"]
|
| 31 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
+
# ===================== 2. IMAGE UPLOAD & PREDICTION =====================
|
| 34 |
@app.post("/predict-image")
|
| 35 |
async def predict_image_endpoint(file: UploadFile = File(...)):
|
| 36 |
+
"""
|
| 37 |
+
Accepts an image file upload and returns snake prediction metadata.
|
| 38 |
+
"""
|
| 39 |
try:
|
| 40 |
image_data = await file.read()
|
| 41 |
+
|
| 42 |
+
# Load image safely in RGB
|
| 43 |
+
image = Image.open(io.BytesIO(image_data)).convert("RGB")
|
| 44 |
+
|
| 45 |
+
# Run prediction (uses global ONNX session)
|
| 46 |
prediction_result = predict_snake(image)
|
| 47 |
+
|
| 48 |
return JSONResponse(content=prediction_result)
|
| 49 |
+
|
| 50 |
except Exception as e:
|
| 51 |
print(f"Prediction Error: {e}")
|
| 52 |
+
return JSONResponse(
|
| 53 |
+
content={"error": "An error occurred during image prediction.", "detail": str(e)},
|
| 54 |
+
status_code=500
|
| 55 |
+
)
|
|
|
|
| 56 |
|
| 57 |
+
# ===================== 3. TEXT-TO-IMAGE & PREDICTION =====================
|
| 58 |
@app.post("/generate-and-predict")
|
| 59 |
async def generate_and_predict_endpoint(description: str = Form(...)):
|
| 60 |
+
"""
|
| 61 |
+
Generates an image from text description, runs snake prediction, and returns
|
| 62 |
+
both the Base64 image and prediction metadata.
|
| 63 |
+
"""
|
| 64 |
try:
|
| 65 |
+
# Generate image using Gemini API
|
| 66 |
image_bytes, gen_image_pil = generate_image_from_text(description)
|
| 67 |
+
|
| 68 |
+
# Run snake prediction on generated image
|
| 69 |
prediction_result = predict_snake(gen_image_pil)
|
| 70 |
+
|
| 71 |
+
# Encode generated image to Base64 for frontend display
|
| 72 |
base64_image = base64.b64encode(image_bytes).decode('utf-8')
|
| 73 |
+
|
| 74 |
response_data = {
|
| 75 |
"generated_image_base64": base64_image,
|
| 76 |
"prediction": prediction_result
|
| 77 |
}
|
| 78 |
+
|
| 79 |
return JSONResponse(content=response_data)
|
| 80 |
+
|
| 81 |
except Exception as e:
|
| 82 |
print(f"Generation/Prediction Error: {e}")
|
| 83 |
+
return JSONResponse(
|
| 84 |
+
content={"error": "An error occurred during image generation or prediction.", "detail": str(e)},
|
| 85 |
+
status_code=500
|
| 86 |
+
)
|
api/model_service.py
CHANGED
|
@@ -2,142 +2,130 @@
|
|
| 2 |
|
| 3 |
import os
|
| 4 |
import io
|
| 5 |
-
|
| 6 |
import numpy as np
|
| 7 |
-
import
|
| 8 |
from PIL import Image
|
| 9 |
-
import
|
| 10 |
-
from torchvision import transforms
|
| 11 |
from scipy.special import softmax
|
| 12 |
-
|
| 13 |
-
from pathlib import Path # CRITICAL for production-ready file path handling
|
| 14 |
|
| 15 |
-
# ===================== 1. GLOBAL INITIALIZATION
|
| 16 |
|
| 17 |
-
#
|
| 18 |
BASE_DIR = Path(__file__).resolve().parent
|
| 19 |
|
| 20 |
-
#
|
| 21 |
ONNX_MODEL_PATH = BASE_DIR / "ViT_PreProcessing-ops11-preprocessing-int-dynam_graph.onnx"
|
| 22 |
METADATA_PATH = BASE_DIR / "train_metadata.csv"
|
| 23 |
VENOM_DATA_PATH = BASE_DIR / "venomstatus_with_antivenom.csv"
|
| 24 |
-
|
| 25 |
-
COUNTRY_DATA_PATH = BASE_DIR / "min-train_metadata.csv"
|
| 26 |
|
|
|
|
| 27 |
try:
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
#
|
| 47 |
-
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
|
| 48 |
-
|
| 49 |
if not GEMINI_API_KEY:
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
genai_client = genai.Client(api_key=GEMINI_API_KEY)
|
| 53 |
|
|
|
|
| 54 |
|
| 55 |
# ===================== 2. IMAGE PREPROCESSING =====================
|
| 56 |
|
| 57 |
def preprocess_image(image: Image.Image) -> np.ndarray:
|
| 58 |
"""
|
| 59 |
-
|
| 60 |
-
|
| 61 |
"""
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
image = transform(image)
|
| 69 |
-
|
| 70 |
-
# Add a batch dimension (1, C, H, W) and convert to float32 NumPy array
|
| 71 |
-
input_tensor = np.expand_dims(image.numpy(), axis=0).astype(np.float32)
|
| 72 |
-
return input_tensor
|
| 73 |
-
|
| 74 |
|
| 75 |
# ===================== 3. PREDICTION FUNCTION =====================
|
| 76 |
|
| 77 |
def predict_snake(image: Image.Image) -> dict:
|
| 78 |
"""
|
| 79 |
-
|
| 80 |
-
(venom status, antidote, country).
|
| 81 |
"""
|
| 82 |
if not session:
|
| 83 |
-
return {
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
"
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
|
| 123 |
# ===================== 4. IMAGE GENERATION FUNCTION =====================
|
| 124 |
|
| 125 |
def generate_image_from_text(prompt: str) -> tuple[bytes, Image.Image]:
|
| 126 |
"""
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
Returns:
|
| 130 |
-
A tuple: (raw JPEG bytes of the generated image, PIL Image object)
|
| 131 |
"""
|
| 132 |
-
|
| 133 |
-
if not GEMINI_API_KEY:
|
| 134 |
-
# Raise a specific error if the endpoint relies on the key
|
| 135 |
raise ConnectionError("Gemini API key not configured. Cannot generate image.")
|
| 136 |
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
# Call the image generation model
|
| 141 |
result = genai_client.models.generate_images(
|
| 142 |
model='imagen-3.0-generate-002',
|
| 143 |
prompt=full_prompt,
|
|
@@ -147,14 +135,14 @@ def generate_image_from_text(prompt: str) -> tuple[bytes, Image.Image]:
|
|
| 147 |
aspect_ratio="1:1"
|
| 148 |
)
|
| 149 |
)
|
| 150 |
-
|
| 151 |
if not result.generated_images:
|
| 152 |
raise RuntimeError("Gemini API returned no image.")
|
| 153 |
|
| 154 |
-
# Decode bytes
|
| 155 |
image_bytes = result.generated_images[0].image.image_bytes
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
|
|
|
|
|
| 2 |
|
| 3 |
import os
|
| 4 |
import io
|
| 5 |
+
from pathlib import Path
|
| 6 |
import numpy as np
|
| 7 |
+
import pandas as pd
|
| 8 |
from PIL import Image
|
| 9 |
+
import onnxruntime as ort
|
|
|
|
| 10 |
from scipy.special import softmax
|
| 11 |
+
from google.generativeai import Client as GeminiClient
|
|
|
|
| 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 (CPU only for Render)
|
| 25 |
try:
|
| 26 |
+
session = ort.InferenceSession(str(ONNX_MODEL_PATH), providers=["CPUExecutionProvider"])
|
| 27 |
+
except FileNotFoundError:
|
| 28 |
+
raise SystemExit(f"ONNX model not found at {ONNX_MODEL_PATH}. Deployment cannot proceed.")
|
| 29 |
+
|
| 30 |
+
# Load CSV metadata safely
|
| 31 |
+
def load_csv(path):
|
| 32 |
+
try:
|
| 33 |
+
return pd.read_csv(path)
|
| 34 |
+
except FileNotFoundError:
|
| 35 |
+
raise SystemExit(f"Required CSV not found: {path}")
|
| 36 |
+
|
| 37 |
+
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 |
+
# Gemini API Client
|
| 45 |
+
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
|
|
|
|
| 46 |
if not GEMINI_API_KEY:
|
| 47 |
+
print("WARNING: GEMINI_API_KEY not found. Image generation will fail.")
|
|
|
|
|
|
|
| 48 |
|
| 49 |
+
genai_client = GeminiClient(api_key=GEMINI_API_KEY) if GEMINI_API_KEY else None
|
| 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 |
# ===================== 3. PREDICTION FUNCTION =====================
|
| 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.",
|
| 73 |
+
"species_name": "Unknown",
|
| 74 |
+
"venom_status": -1,
|
| 75 |
+
"antivenom_name": "N/A",
|
| 76 |
+
"manufacturer": "N/A",
|
| 77 |
+
"confidence": 0.0,
|
| 78 |
+
"countries": "N/A"
|
| 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 |
+
# Construct result
|
| 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'),
|
| 108 |
+
"manufacturer": species_row.get('manufacturer', 'N/A'),
|
| 109 |
+
"confidence": round(confidence, 4),
|
| 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 |
# ===================== 4. IMAGE GENERATION FUNCTION =====================
|
| 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 = genai_client.models.generate_images(
|
| 130 |
model='imagen-3.0-generate-002',
|
| 131 |
prompt=full_prompt,
|
|
|
|
| 135 |
aspect_ratio="1:1"
|
| 136 |
)
|
| 137 |
)
|
| 138 |
+
|
| 139 |
if not result.generated_images:
|
| 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 |
+
# Optional: resize to 224x224 to match model input
|
| 146 |
+
gen_image_pil = gen_image_pil.resize((224, 224))
|
| 147 |
+
|
| 148 |
+
return image_bytes, gen_image_pil
|
requirements.txt
CHANGED
|
@@ -1,11 +1,9 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
torchvision
|
| 11 |
-
google-genai
|
|
|
|
| 1 |
+
fastapi==0.111.0
|
| 2 |
+
uvicorn[standard]==0.23.2
|
| 3 |
+
onnxruntime==1.15.1
|
| 4 |
+
Pillow==10.1.0
|
| 5 |
+
pandas==2.1.1
|
| 6 |
+
numpy==1.26.5
|
| 7 |
+
scipy==1.11.1
|
| 8 |
+
google-genai==0.1.5
|
| 9 |
+
python-multipart==0.0.6
|
|
|
|
|
|
start.sh
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# =============================
|
| 3 |
+
# start.sh for Snake AI API
|
| 4 |
+
# =============================
|
| 5 |
+
# Run FastAPI with Gunicorn using 1 worker to avoid OOM
|
| 6 |
+
# Bind to Render's $PORT environment variable
|
| 7 |
+
|
| 8 |
+
exec gunicorn -w 1 -k uvicorn.workers.UvicornWorker api.main:app --bind 0.0.0.0:$PORT
|