from fastapi import FastAPI, File, UploadFile, HTTPException, Depends, Request from fastapi.responses import HTMLResponse from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel from typing import Optional, Dict, Any, Tuple, List import numpy as np import pandas as pd import math import os import tensorflow as tf from PIL import Image as PILImage from PIL import ExifTags from huggingface_hub import hf_hub_download import io import base64 import csv import sqlite3 import hashlib import secrets import time import uuid from datetime import datetime from fastapi.security import APIKeyHeader from starlette.status import HTTP_401_UNAUTHORIZED import json # ============================================================================= # MODEL LOADING # ============================================================================= # model token model_key = os.getenv("hf_token") file_path = hf_hub_download("soranz84/grai3", "grai_3_076.h5", token=model_key) # ============================================================================= # AUTH SETUP # ============================================================================= DB_PATH = os.getenv("API_KEYS_DB_PATH", "auth.db") API_KEY_HEADER_NAME = "x-api-key" api_key_header = APIKeyHeader(name=API_KEY_HEADER_NAME, auto_error=False) def get_db_connection(db_path: str = None): conn = sqlite3.connect(db_path or DB_PATH) conn.row_factory = sqlite3.Row return conn def init_db(): conn = get_db_connection() try: conn.execute( """ CREATE TABLE IF NOT EXISTS api_keys ( id INTEGER PRIMARY KEY AUTOINCREMENT, owner TEXT NOT NULL, key_hash TEXT NOT NULL UNIQUE, active INTEGER NOT NULL DEFAULT 1, created_at TEXT NOT NULL ); """ ) conn.commit() finally: conn.close() # ============================================================================= # API USAGE TRACKING SETUP # ============================================================================= # Initialize usage tracking database USAGE_DB_PATH = os.getenv("USAGE_DB_PATH", "usage_tracking.db") def get_usage_db_connection(): """Get connection to the usage tracking database""" conn = sqlite3.connect(USAGE_DB_PATH) conn.row_factory = sqlite3.Row return conn def init_usage_db(): """Initialize the usage tracking database""" conn = get_usage_db_connection() try: conn.execute( """ CREATE TABLE IF NOT EXISTS api_usage ( id TEXT PRIMARY KEY, api_key_hash TEXT NOT NULL, endpoint TEXT NOT NULL, timestamp REAL NOT NULL, user_id TEXT, owner TEXT, success BOOLEAN NOT NULL, response_time REAL, request_method TEXT, user_agent TEXT, client_ip TEXT, additional_data TEXT, image_dimensions TEXT, model_prediction_b REAL, model_prediction_c REAL ); """ ) # Index for better query performance conn.execute( "CREATE INDEX IF NOT EXISTS idx_api_key_hash ON api_usage(api_key_hash)" ) conn.execute( "CREATE INDEX IF NOT EXISTS idx_timestamp ON api_usage(timestamp)" ) conn.execute( "CREATE INDEX IF NOT EXISTS idx_endpoint ON api_usage(endpoint)" ) conn.commit() finally: conn.close() def track_api_usage( api_key_hash: str, endpoint: str, request: Request, start_time: float, success: bool, response_time: float, owner: Optional[str] = None, additional_data: Optional[Dict] = None, prediction_b: Optional[float] = None, prediction_c: Optional[float] = None, image_dimensions: Optional[Dict] = None ) -> str: """ Track API usage for monitoring and analytics Args: api_key_hash: Hash of the API key used endpoint: API endpoint called request: FastAPI request object start_time: When the request started (time.time()) success: Whether the request was successful response_time: Time taken to complete the request owner: Owner of the API key additional_data: Additional data to store prediction_b: Model prediction for b factor prediction_c: Model prediction for c factor image_dimensions: Image dimensions if applicable """ usage_id = str(uuid.uuid4()) conn = get_usage_db_connection() try: conn.execute( """ INSERT INTO api_usage ( id, api_key_hash, endpoint, timestamp, user_id, owner, success, response_time, request_method, user_agent, client_ip, additional_data, model_prediction_b, model_prediction_c, image_dimensions ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, ( usage_id, api_key_hash, endpoint, start_time, str(request.state.user_id) if hasattr(request.state, 'user_id') else None, owner, success, response_time, request.method if request else None, request.headers.get("User-Agent") if request else None, request.headers.get("X-Forwarded-For", request.client.host if request and request.client else None) if request else None, json.dumps(additional_data or {}), prediction_b, prediction_c, json.dumps(image_dimensions or {}) ) ) conn.commit() finally: conn.close() return usage_id def get_usage_stats( api_key_hash: Optional[str] = None, owner: Optional[str] = None, time_range: Optional[tuple] = None, endpoint: Optional[str] = None ) -> Dict[str, Any]: """ Get API usage statistics Args: api_key_hash: Filter by API key hash owner: Filter by owner time_range: Tuple of (start_time, end_time) timestamps endpoint: Filter by endpoint """ conn = get_usage_db_connection() try: query = "SELECT * FROM api_usage WHERE 1=1" params = [] if api_key_hash: query += " AND api_key_hash = ?" params.append(api_key_hash) if owner: query += " AND owner = ?" params.append(owner) if time_range: query += " AND timestamp BETWEEN ? AND ?" params.extend(time_range) if endpoint: query += " AND endpoint = ?" params.append(endpoint) query += " ORDER BY timestamp DESC" cursor = conn.execute(query, params) rows = cursor.fetchall() # Process results total_requests = len(rows) successful_requests = sum(1 for row in rows if row["success"]) failed_requests = total_requests - successful_requests # Calculate statistics response_times = [row["response_time"] for row in rows if row["response_time"]] avg_response_time = sum(response_times) / len(response_times) if response_times else 0 # Group by endpoint endpoint_stats = {} for row in rows: endpoint = row["endpoint"] if endpoint not in endpoint_stats: endpoint_stats[endpoint] = { "total": 0, "success": 0, "failed": 0, "response_times": [] } endpoint_stats[endpoint]["total"] += 1 endpoint_stats[endpoint]["response_times"].append(row["response_time"]) if row["success"]: endpoint_stats[endpoint]["success"] += 1 else: endpoint_stats[endpoint]["failed"] += 1 # Calculate averages for each endpoint for endpoint, stats in endpoint_stats.items(): response_times = stats["response_times"] stats["avg_response_time"] = sum(response_times) / len(response_times) if response_times else 0 stats["success_rate"] = stats["success"] / stats["total"] if stats["total"] > 0 else 0 del stats["response_times"] # Remove from output # Recent activity (last 24 hours) day_ago = time.time() - (24 * 60 * 60) recent_requests = sum(1 for row in rows if row["timestamp"] > day_ago) return { "total_requests": total_requests, "successful_requests": successful_requests, "failed_requests": failed_requests, "success_rate": successful_requests / total_requests if total_requests > 0 else 0, "average_response_time": avg_response_time, "recent_requests_24h": recent_requests, "endpoint_statistics": endpoint_stats, "time_range": time_range, "filters": { "api_key_hash": api_key_hash, "owner": owner, "endpoint": endpoint } } finally: conn.close() def get_owner_from_key_hash(api_key_hash: str) -> Optional[str]: """Get owner name from API key hash""" conn = get_db_connection() try: row = conn.execute( "SELECT owner FROM api_keys WHERE key_hash = ? LIMIT 1", (api_key_hash,) ).fetchone() return row["owner"] if row else None finally: conn.close() # ============================================================================= # ENHANCED AUTH FUNCTIONS # ============================================================================= def sha256_hex(value: str) -> str: return hashlib.sha256(value.encode("utf-8")).hexdigest() def seed_api_keys_from_env(): """ Seed API keys from env var API_KEYS_SEED. Accepts entries separated by commas, newlines, semicolons, or spaces. Each entry must be 'owner:raw_key'. Example: alice:MY_SUPER_KEY_1 bob:ANOTHER_KEY_2 """ seed = os.getenv("API_KEYS_SEED", "") if not seed: return normalized = seed.replace("\r", "\n") for sep in ["\n", ";", " "]: normalized = normalized.replace(sep, ",") entries = [e.strip() for e in normalized.split(",") if e.strip()] if not entries: return conn = get_db_connection() try: conn.execute( """ CREATE TABLE IF NOT EXISTS api_keys ( id INTEGER PRIMARY KEY AUTOINCREMENT, owner TEXT NOT NULL, key_hash TEXT NOT NULL UNIQUE, active INTEGER NOT NULL DEFAULT 1, created_at TEXT NOT NULL ); """ ) from datetime import datetime count = 0 for entry in entries: if ":" not in entry: continue owner, key = entry.split(":", 1) owner = owner.strip() key = key.strip() if not owner or not key: continue key_hash = sha256_hex(key) conn.execute( """ INSERT OR IGNORE INTO api_keys (owner, key_hash, active, created_at) VALUES (?, ?, 1, ?) """, (owner, key_hash, datetime.utcnow().isoformat(timespec="seconds")), ) count += 1 conn.commit() print(f"Seeded {count} API key entries from API_KEYS_SEED") finally: conn.close() async def verify_api_key(request: Request, provided_key: Optional[str] = Depends(api_key_header)) -> str: """ Enhanced dependency: verify the provided API key against the DB and store request context Returns the API key hash for tracking purposes """ if not provided_key: raise HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail="Missing API key", headers={"WWW-Authenticate": "API key"}, ) key_hash = sha256_hex(provided_key) conn = get_db_connection() try: row = conn.execute( "SELECT id, key_hash, active, owner FROM api_keys WHERE key_hash = ? LIMIT 1", (key_hash,), ).fetchone() finally: conn.close() if not row or int(row["active"]) != 1: # Use constant-time compare for parity (even though we already filtered by DB) if not row or not secrets.compare_digest(row["key_hash"], key_hash): raise HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail="Invalid API key", headers={"WWW-Authenticate": "API key"}, ) # Store user context in request state for tracking request.state.user_id = str(row["id"]) request.state.owner = row["owner"] return key_hash # ============================================================================= # IMAGE/INFERENCE UTILITIES # ============================================================================= # clean the camera string def clean_exif_string(val): if val is None: return None # Decode bytes using a few likely encodings if isinstance(val, bytes): for enc in ("utf-8", "utf-16", "utf-16le", "latin-1"): try: val = val.decode(enc) break except Exception: pass else: val = val.decode("latin-1", errors="ignore") # Remove null padding and non-printables val = val.replace("\x00", "") val = "".join(ch for ch in val if ch.isprintable()) return val.strip() # find ppm and phone name def find_ppm_and_phone_csv( path: str, camera: str, w: int, h: int, phone: Optional[str] = None ) -> Tuple[Optional[float], Optional[str]]: cam = camera.strip().lower() w, h = int(w), int(h) phone_norm = phone.strip().lower() if phone else None with open(path, newline="", encoding="utf-8") as f: reader = csv.DictReader(f) for row in reader: cam_row = (row.get("camera", "")).strip().lower() if cam_row != cam: continue if phone_norm: if (row.get("phone", "")).strip().lower() != phone_norm: continue try: rw = int(str(row.get("width", "")).strip()) rh = int(str(row.get("height", "")).strip()) ppm = float(str(row.get("ppm", "")).strip()) except ValueError: continue # Orientation-independent comparison if (rw == w and rh == h) or (rw == h and rh == w): phone_name = (row.get("phone", "")).strip() or None return ppm, phone_name return None, None # Define the Mish activation function (essential for the model) class Mish(tf.keras.layers.Layer): def __init__(self, **kwargs): super(Mish, self).__init__(**kwargs) def call(self, inputs): return inputs * tf.math.tanh(tf.math.softplus(inputs)) # Register the custom object for TensorFlow to recognize it when loading the model tf.keras.utils.get_custom_objects().update({'Mish': Mish}) # Define a custom loss function def custom_loss(y_true, y_pred): weights = np.array([0.7, 0.3]) squared_diff = tf.square(y_true - y_pred) weighted_squared_diff = squared_diff * weights return tf.reduce_mean(weighted_squared_diff, axis=-1) # Custom functions for TensorFlow version compatibility def mse_metric(y_true, y_pred): """Mean Squared Error metric for older Keras compatibility""" return tf.keras.metrics.mean_squared_error(y_true, y_pred) def mae_metric(y_true, y_pred): """Mean Absolute Error metric for older Keras compatibility""" return tf.keras.metrics.mean_absolute_error(y_true, y_pred) # Custom DepthwiseConv2D for compatibility with different TF versions class CompatibleDepthwiseConv2D(tf.keras.layers.DepthwiseConv2D): """Custom DepthwiseConv2D that handles the 'groups' parameter for different TF versions""" def __init__(self, **kwargs): # Remove 'groups' parameter if it exists, as it's not supported in newer TF kwargs.pop('groups', None) super().__init__(**kwargs) def call(self, inputs): # Call the parent method without the problematic 'groups' parameter return super().call(inputs) # Register custom objects for model loading tf.keras.utils.get_custom_objects().update({ 'Mish': Mish, 'custom_loss': custom_loss, 'DepthwiseConv2D': CompatibleDepthwiseConv2D, 'mse': mse_metric, 'mae': mae_metric, 'mean_squared_error': mse_metric, 'mean_absolute_error': mae_metric, 'binary_crossentropy': tf.keras.losses.binary_crossentropy, 'categorical_crossentropy': tf.keras.losses.categorical_crossentropy }) # ============================================================================= # FASTAPI APP # ============================================================================= app = FastAPI( title="grai Soil Analysis API", description="API for soil particle size distribution analysis from images with usage tracking", version="2.0.0", docs_url="/docs", redoc_url="/redoc" ) # Configure CORS app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Add request state middleware for tracking @app.middleware("http") async def add_request_state_middleware(request: Request, call_next): """Add request state for tracking purposes""" response = await call_next(request) return response # Load the model once at startup model = None @app.on_event("startup") async def on_startup(): init_db() seed_api_keys_from_env() init_usage_db() # Initialize usage tracking # Load ML model global model try: # Load model with comprehensive TensorFlow version compatibility fix with tf.keras.utils.custom_object_scope(tf.keras.utils.get_custom_objects()): model = tf.keras.models.load_model(file_path) print("Model loaded successfully") print(f"Usage tracking enabled - database: {USAGE_DB_PATH}") except Exception as e: print(f"Failed to load model: {e}") print("This is likely a TensorFlow version compatibility issue.") print("Tried to register: Mish, custom_loss, DepthwiseConv2D, mse, mae, mse, mae") print("The API will still work but image analysis will be disabled.") # If model loading still fails, set model to None to prevent crashes model = None # ============================================================================= # RESPONSE MODELS # ============================================================================= class SoilParameters(BaseModel): d10: float d30: float d60: float Cu: float # coefficient of uniformity Cc: float # coefficient of curvature class SoilFractions(BaseModel): clay: float # percentage silt: float # percentage sand: float # percentage gravel: float # percentage boulder: float # percentage class AnalysisResponse(BaseModel): status: str b_factor: float c_factor: float parameters: SoilParameters fractions: SoilFractions supported_device: bool image_dimensions: Dict[str, int] usage_id: str # Track which usage record this response corresponds to class UsageStatsResponse(BaseModel): total_requests: int successful_requests: int failed_requests: int success_rate: float average_response_time: float recent_requests_24h: int endpoint_statistics: Dict[str, Any] class ErrorResponse(BaseModel): error: str details: Optional[str] = None # ============================================================================= # IMAGE PROCESSING FUNCTIONS # ============================================================================= def process_image(image: PILImage.Image) -> tuple: """ Process the image according to device specifications and return predictions """ width, height = image.size scale = 1 supported_device = True # read metadata width, height = image.size camera = None # Pillow >= 6 supports img.getexif(); older versions use _getexif() raw_exif = None try: raw_exif = image.getexif() except Exception: raw_exif = getattr(image, "_getexif", lambda: None)() if raw_exif: exif = {} for tag_id, value in raw_exif.items(): tag = ExifTags.TAGS.get(tag_id, tag_id) exif[tag] = value camera = exif.get("Model") # camera model (tag 272) camera = clean_exif_string(camera) # find ppm and phone name: ppm, phone_name = (None, None) if camera is not None: ppm, phone_name = find_ppm_and_phone_csv("ppm.csv", camera, width, height) # handle unkwnon phone camera if ppm is None: # Form to confirm guessed ppm ppm = max(width,height)/294.087 # resize image to 4.6 PPM scale = 4.6 / ppm # Calculate new dimensions new_width = int(width * scale) new_height = int(height * scale) # Resize the image resized_image = image.resize((new_width, new_height), PILImage.Resampling.LANCZOS) # Crop to 400x400 width_crop = 400 height_crop = 400 if resized_image.size != (width_crop, height_crop): width, height = resized_image.width, resized_image.height left = (width - width_crop) // 2 upper = (height - height_crop) // 2 right = left + width_crop lower = upper + height_crop cropped_image = resized_image.crop((left, upper, right, lower)) else: cropped_image = resized_image # Split channels red_channel, green_channel, blue_channel = cropped_image.split() # Import channels and normalize red_array = np.array(red_channel) green_array = np.array(green_channel) blue_array = np.array(blue_channel) # Convert to dataframe red_df = pd.DataFrame(red_array) green_df = pd.DataFrame(green_array) blue_df = pd.DataFrame(blue_array) # Convert to list red_list = red_df.values.tolist() green_list = green_df.values.tolist() blue_list = blue_df.values.tolist() # Create input X = [] X.append([red_list, green_list, blue_list]) # Scale for mobilenet/efficientnet preprocessing X0 = np.array(X) X = tf.keras.applications.efficientnet_v2.preprocess_input(X0) # Transpose data X = tf.transpose(X, perm=[0, 2, 3, 1]) return X, supported_device def calculate_soil_parameters(predictions_b: float, predictions_c: float) -> Dict[str, Any]: """ Calculate soil parameters from model predictions """ # Transform predictions b = math.exp(predictions_b) c = float(predictions_c) # Characteristic diameters d10 = b * ((-math.log(0.9)) ** (1/c)) d30 = b * ((-math.log(0.7)) ** (1/c)) d60 = b * ((-math.log(0.4)) ** (1/c)) # Coefficients Cu = d60 / d10 # coefficient of uniformity Cc = (d30 ** 2) / (d10 * d60) # coefficient of curvature # Diameter boundaries dCl = 0.002 # max. clay fraction diameter dSi = 0.063 # max silt fraction diameter dSa = 2 # max sand fraction diameter dGr = 63 # max gravel fraction diameter # Calculate fractions Cl = 1 - math.exp(-(dCl/b)**c) # clay fraction Si = 1 - math.exp(-(dSi/b)**c) - Cl Sa = 1 - math.exp(-(dSa/b)**c) - Si - Cl Gr = 1 - math.exp(-(dGr/b)**c) - Sa - Si - Cl Bo = 1 - Gr - Sa - Si - Cl return { "b_factor": round(b, 3), "c_factor": round(c, 3), "parameters": { "d10": round(d10, 3), "d30": round(d30, 3), "d60": round(d60, 3), "Cu": round(Cu, 3), "Cc": round(Cc, 3) }, "fractions": { "clay": round(Cl * 100, 1), "silt": round(Si * 100, 1), "sand": round(Sa * 100, 1), "gravel": round(Gr * 100, 1), "boulder": round(Bo * 100, 1) } } # ============================================================================= # HTML LANDING PAGE # ============================================================================= HTML_CONTENT = """
API for soil particle size distribution analysis from images with usage tracking
Developed by Enrico Soranzo
This API now includes comprehensive usage tracking:
/usage-stats endpointx-api-key: YOUR_KEY.
Add API keys to the database or set environment variable API_KEYS_SEED on startup:
API_KEYS_SEED="alice:KEY1,bob:KEY2".
Monitor your API usage with these new endpoints:
/usage-stats?api_key=KEY - Your usage statistics/owner-stats?owner=alice - Statistics by owner (requires admin access)/admin/stats - Overall system statisticsAll statistics include request counts, success rates, response times, and endpoint breakdowns.
Upload an image using cURL:
curl -X POST -H "x-api-key: API_KEY" -F "file=@soil_image.jpeg" https://soranz84-graiAPI.hf.space/analyze
curl -H "x-api-key: API_KEY" https://soranz84-graiAPI.hf.space/usage-stats?api_key=API_KEY
HUAWEI_p9_Lite_20177, iPad Pro, iPhone 13 mini, iPhone 14, iPhone 14 Pro, iPhone 15 Pro, iPhone 16, iPhone 16 Pro, Motorola Edge, Motorola Edge 60 fusion, Motorola G7+, Motorola G30, Samsung Galaxy A17, Samsung Galaxy A32, Samsung A52, Samsung Galaxy S23, Samsung Galaxy S24, Vivo X60, Xiaomi 15, Xiaomi A2
grai is device-agnostic. An angle of view of 70° is assumed for uncalibrated devices. You can write to enrico@deepsoil.at to update the list of calibrated devices.