from fastapi import FastAPI, File, UploadFile, HTTPException, Depends, Request, Form 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 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/grai4", "04_004.h5", token=model_key) # PSD classes for the model output (softmax) PSD_CLASSES = ['Cl', 'fSi', 'mSi', 'cSi', 'fSa', 'mSa', 'cSa', 'fGr', 'mGr', 'cGr', 'Co'] # ============================================================================= # AUTH SETUP # ============================================================================= DATA_DIR = os.getenv("DATA_DIR", "/tmp/grai_data") DB_PATH = os.getenv("API_KEYS_DB_PATH", os.path.join(DATA_DIR, "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", os.path.join(DATA_DIR, "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)" ) # Per-user usage counter (optimized for billing queries) conn.execute( """ CREATE TABLE IF NOT EXISTS user_usage_counts ( api_key_hash TEXT PRIMARY KEY, owner TEXT, total_calls INTEGER NOT NULL DEFAULT 0, successful_calls INTEGER NOT NULL DEFAULT 0, last_call_at REAL, first_call_at REAL ); """ ) conn.execute( "CREATE INDEX IF NOT EXISTS idx_uuc_owner ON user_usage_counts(owner)" ) 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 {}) ) ) # Increment per-user counter (upsert) conn.execute( """ INSERT INTO user_usage_counts (api_key_hash, owner, total_calls, successful_calls, last_call_at, first_call_at) VALUES (?, ?, 1, ?, ?, ?) ON CONFLICT(api_key_hash) DO UPDATE SET total_calls = total_calls + 1, successful_calls = successful_calls + ?, last_call_at = ? """, ( api_key_hash, owner, 1 if success else 0, start_time, start_time, 1 if success else 0, start_time, ) ) 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() # ============================================================================= # BUCKET SYNC (PERSISTENT STORAGE) # ============================================================================= # # Usage data persists across Space restarts by syncing a private HF Bucket. # The bucket is NEVER mounted — it's accessed via the HF Hub API using a # secret token. This means the bucket stays private even on a public Space. # # Environment variables: # HF_BUCKET_NAME - e.g. "soranz84/grai-usage" (no mount needed) # HF_TOKEN - a write-capable token (set in Space Secrets) # # On startup we download the SQLite DBs from the bucket. # Every N requests we upload them back (with locking so we don't corrupt). # ============================================================================= import threading import json BUCKET_NAME = os.getenv("HF_BUCKET_NAME", "") # e.g. "soranz84/grai-usage" BUCKET_TOKEN = os.getenv("BUCKET_TOKEN", "") _sync_counter = 0 _sync_lock = threading.Lock() _SYNC_EVERY_N = 10 # sync to bucket every N successful API calls def _bucket_api(): """Return an HfApi instance with write access to the bucket.""" from huggingface_hub import HfApi return HfApi(token=BUCKET_TOKEN) if BUCKET_TOKEN else None def _bucket_startup_sync(): """On startup: download usage_tracking.db and auth.db from the bucket.""" if not BUCKET_NAME: print("No HF_BUCKET_NAME set — bucket sync disabled, using ephemeral storage.") return api = _bucket_api() if not api: print("No BUCKET_TOKEN set — bucket sync disabled. Set BUCKET_TOKEN secret in Space Settings.") return import tempfile for db_file in ["usage_tracking.db", "auth.db"]: try: local_path = os.path.join(DATA_DIR, db_file) api.download_bucket_files( BUCKET_NAME, files=[(db_file, local_path)], token=BUCKET_TOKEN, ) print(f"Restored {db_file} from bucket") except Exception as e: # File may not exist yet on first run — that's fine print(f"Could not restore {db_file} from bucket: {e}") # The local DB (freshly created by init_db/init_usage_db) will be # uploaded on the next sync cycle. def _bucket_sync_to_remote(): """Upload the SQLite DBs to the private bucket.""" if not BUCKET_NAME or not BUCKET_TOKEN: return api = _bucket_api() if not api: return from huggingface_hub import batch_bucket_files files_to_upload = [] for db_file in ["usage_tracking.db", "auth.db"]: local_path = os.path.join(DATA_DIR, db_file) if os.path.exists(local_path): files_to_upload.append((local_path, db_file)) if files_to_upload: try: batch_bucket_files( BUCKET_NAME, add=files_to_upload, token=BUCKET_TOKEN, ) print(f"Synced {len(files_to_upload)} file(s) to bucket {BUCKET_NAME}") except Exception as e: print(f"Bucket sync failed: {e}") def _maybe_sync_to_bucket(): """Called after each API request. Syncs to bucket every _SYNC_EVERY_N calls.""" global _sync_counter with _sync_lock: _sync_counter += 1 if _sync_counter >= _SYNC_EVERY_N: _sync_counter = 0 _bucket_sync_to_remote() def bucket_sync_on_shutdown(): """On shutdown: final sync to bucket.""" _bucket_sync_to_remote() # ============================================================================= # 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) # Edge Wasserstein Distance (EWD) loss used by grai4 model @tf.function def edge_wasserstein_distance(y_true, y_pred): """Edge Wasserstein Distance (1-Wasserstein) for probability distributions.""" cdf_true = tf.cumsum(y_true, axis=-1) cdf_pred = tf.cumsum(y_pred, axis=-1) cdf_diff = tf.abs(cdf_true - cdf_pred) ewd = tf.reduce_sum(cdf_diff, axis=-1) return tf.reduce_mean(ewd) # 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, 'edge_wasserstein_distance': edge_wasserstein_distance }) # ============================================================================= # FASTAPI APP # ============================================================================= app = FastAPI( title="grai Soil Analysis API", description="API for soil particle size distribution analysis from images (grai4 model with 11 PSD classes)", version="4.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(): # Ensure local data directory exists os.makedirs(DATA_DIR, exist_ok=True) init_db() seed_api_keys_from_env() init_usage_db() # Initialize usage tracking # Load persisted data from private bucket (if configured) _bucket_startup_sync() # 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, edge_wasserstein_distance") 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 PSDClasses(BaseModel): """Particle size distribution percentages for each class (softmax output)""" Cl: float # Clay (<0.002 mm) fSi: float # Fine silt (0.002-0.006 mm) mSi: float # Medium silt (0.006-0.020 mm) cSi: float # Coarse silt (0.020-0.063 mm) fSa: float # Fine sand (0.063-0.200 mm) mSa: float # Medium sand (0.200-0.630 mm) cSa: float # Coarse sand (0.630-2.0 mm) fGr: float # Fine gravel (2.0-6.3 mm) mGr: float # Medium gravel (6.3-20 mm) cGr: float # Coarse gravel (20-63 mm) Co: float # Cobbles (>63 mm) class SoilFractions(BaseModel): """Aggregate soil fractions derived from PSD classes""" clay: float # = Cl silt: float # = fSi + mSi + cSi sand: float # = fSa + mSa + cSa gravel: float # = fGr + mGr + cGr cobbles: float # = Co class AnalysisResponse(BaseModel): status: str psd: PSDClasses fractions: SoilFractions supported_device: bool image_dimensions: Dict[str, int] usage_id: str # Track which usage record this response corresponds to ppm_source: Optional[str] = None # "auto", "csv:", or "manual:" 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, ppm_override: Optional[float] = None) -> tuple: """ Process the image according to device specifications and return predictions Args: image: PIL Image to process ppm_override: If provided, use this PPM value directly instead of auto-detection. When None, uses CSV lookup with 70° angle fallback (auto behavior). """ 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) ppm_source = "auto" if ppm_override is not None: # Use user-provided PPM value directly ppm = ppm_override phone_name = None supported_device = True ppm_source = f"manual:{ppm_override}" else: # Auto mode: check CSV, fall back to 70° angle of view if camera is not None: ppm, phone_name = find_ppm_and_phone_csv("ppm.csv", camera, width, height) # handle unknown phone camera (assume 70° angle of view) if ppm is None: ppm = max(width,height)/294.087 supported_device = False ppm_source = "auto:70deg_fallback" else: ppm_source = f"csv:{phone_name or camera or 'unknown'}" # 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, ppm_source def calculate_psd_and_fractions(predictions: np.ndarray) -> Dict[str, Any]: """ Calculate PSD class percentages and aggregate fractions from model predictions. The model outputs a softmax distribution over PSD_CLASSES: ['Cl', 'fSi', 'mSi', 'cSi', 'fSa', 'mSa', 'cSa', 'fGr', 'mGr', 'cGr', 'Co'] Returns a dict with: - "psd": dict mapping each class name to its percentage (0-100) - "fractions": dict with aggregate fractions (clay, silt, sand, gravel, cobbles) """ # predictions shape: (1, 11) or (11,) pred = predictions[0] if predictions.ndim > 1 else predictions # Build PSD percentages (convert from 0-1 to 0-100) psd = {} for i, cls in enumerate(PSD_CLASSES): psd[cls] = round(float(pred[i]) * 100, 1) # Compute aggregate fractions fractions = { "clay": round(psd["Cl"], 1), "silt": round(psd["fSi"] + psd["mSi"] + psd["cSi"], 1), "sand": round(psd["fSa"] + psd["mSa"] + psd["cSa"], 1), "gravel": round(psd["fGr"] + psd["mGr"] + psd["cGr"], 1), "cobbles": round(psd["Co"], 1) } return { "psd": psd, "fractions": fractions } # ============================================================================= # HTML LANDING PAGE # ============================================================================= HTML_CONTENT = """ grai Soil Analysis API v4.0

🔵🔵🔵 grai Soil Analysis API - v4.0

API for soil particle size distribution analysis from images with usage tracking

Powered by graiv4 model — outputs 11 PSD classes (softmax) for fine-grained particle size distribution

Developed by Enrico Soranzo

📊 Usage Tracking Enabled

This API now includes comprehensive usage tracking:

  • Track API key usage patterns
  • Monitor response times and success rates
  • Access detailed analytics via /usage-stats endpoint
  • Secure storage with API key hash tracking

Available Endpoints

GET / - This page (public)
POST /analyze - Analyze soil image (multipart/form-data) [requires x-api-key]
   Optional form field: ppm — auto (default) or numeric value (e.g. 15.0)
POST /analyze_base64 - Analyze base64 encoded image [requires x-api-key]
   Optional data field: ppm — auto (default) or numeric value
GET /health - Health check (public)
GET /usage-stats?api_key=YOUR_KEY - Get usage statistics for your API key
GET /owner-stats?owner=username - Get usage statistics for an owner
GET /admin/stats - Admin endpoint to get overall statistics (requires special key)
GET /my-usage - Get your usage count for billing (requires x-api-key)
GET /admin/all-usage - Get usage counts for ALL users (admin only)
Authentication: Protected endpoints require the header x-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".

📈 New Usage Statistics Features

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 statistics
  • /my-usage - Your personal call count (for billing)
  • /admin/all-usage - All users' call counts (admin only)

All statistics include request counts, success rates, response times, and endpoint breakdowns.

Quick Start

Upload an image using cURL:

curl -X POST -H "x-api-key: API_KEY" -F "file=@soil_image.jpeg" https://soranz84-test.hf.space/analyze

Custom PPM (pixel density) override:

curl -X POST -H "x-api-key: API_KEY" -F "file=@soil_image.jpeg" -F "ppm=15.0" https://soranz84-test.hf.space/analyze

Use ppm=auto (default) for automatic detection from EXIF/CSV with 70° angle fallback, or provide a numeric value to set the pixel density (pixels per mm) directly.

Get your usage statistics:

curl -H "x-api-key: API_KEY" https://soranz84-test.hf.space/my-usage

Recommended Devices

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

Other Devices

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.

""" # ============================================================================= # API ROUTES # ============================================================================= @app.get("/", response_class=HTMLResponse) async def root(): """Landing page with API information""" return HTML_CONTENT @app.get("/health") async def health(): """Health check endpoint""" return { "status": "healthy", "model_loaded": model is not None, "model_version": "graiv4-04_004", "psd_classes": PSD_CLASSES, "usage_tracking": True, "usage_db_path": USAGE_DB_PATH } @app.post("/analyze", response_model=AnalysisResponse, responses={ 400: {"model": ErrorResponse, "description": "Bad Request"}, 401: {"model": ErrorResponse, "description": "Unauthorized"}, 500: {"model": ErrorResponse, "description": "Internal Server Error"} }) async def analyze_soil_image(request: Request, file: UploadFile = File(...), ppm: Optional[str] = Form("auto"), api_key_hash: str = Depends(verify_api_key)): """ Analyze a soil image and return particle size distribution (PSD) for 11 classes. The model outputs a softmax distribution over these PSD classes: Cl, fSi, mSi, cSi, fSa, mSa, cSa, fGr, mGr, cGr, Co Aggregate fractions (clay, silt, sand, gravel, cobbles) are also returned. Args: file: Image file to analyze ppm: Pixel density (pixels per mm). Use "auto" (default) for automatic detection from EXIF/CSV lookup with 70° angle fallback, or provide a numeric value (e.g. "15.0") to use a specific PPM for scaling. """ start_time = time.time() # Parse ppm parameter ppm_override = None if ppm is not None and ppm.strip().lower() != "auto": try: ppm_override = float(ppm.strip()) except ValueError: raise HTTPException(status_code=400, detail=f"Invalid ppm value: '{ppm}'. Must be 'auto' or a numeric value.") # Validate file type if not file.content_type or not file.content_type.startswith("image/"): # Track failed request track_api_usage( api_key_hash=api_key_hash, endpoint="/analyze", request=request, start_time=start_time, success=False, response_time=time.time() - start_time, owner=getattr(request.state, 'owner', None), additional_data={"error": "Invalid file type", "content_type": file.content_type} ) raise HTTPException(status_code=400, detail="File must be an image") if model is None: track_api_usage( api_key_hash=api_key_hash, endpoint="/analyze", request=request, start_time=start_time, success=False, response_time=time.time() - start_time, owner=getattr(request.state, 'owner', None), additional_data={"error": "Model not loaded"} ) raise HTTPException(status_code=500, detail="Model not loaded") try: # Read image file contents = await file.read() image = PILImage.open(io.BytesIO(contents)) # Get original dimensions original_width, original_height = image.size # Process image X, supported_device, ppm_source = process_image(image, ppm_override=ppm_override) # Make prediction predictions = model.predict(X, verbose=0) # Calculate PSD classes and aggregate fractions results = calculate_psd_and_fractions(predictions) # Track successful usage usage_id = track_api_usage( api_key_hash=api_key_hash, endpoint="/analyze", request=request, start_time=start_time, success=True, response_time=time.time() - start_time, owner=getattr(request.state, 'owner', None), additional_data={ "file_size": len(contents), "image_mode": image.mode, "file_format": getattr(file, 'filename', 'unknown'), "ppm_source": ppm_source, "psd": results["psd"] }, image_dimensions={"width": original_width, "height": original_height} ) return AnalysisResponse( status="success", psd=PSDClasses(**results["psd"]), fractions=SoilFractions(**results["fractions"]), supported_device=supported_device, image_dimensions={ "width": original_width, "height": original_height }, usage_id=usage_id, ppm_source=ppm_source ) except Exception as e: response_time = time.time() - start_time # Track failed usage track_api_usage( api_key_hash=api_key_hash, endpoint="/analyze", request=request, start_time=start_time, success=False, response_time=response_time, owner=getattr(request.state, 'owner', None), additional_data={"error": str(e), "error_type": type(e).__name__} ) raise HTTPException( status_code=500, detail=f"Error processing image: {str(e)}" ) @app.post("/analyze_base64", response_model=AnalysisResponse, responses={ 400: {"model": ErrorResponse, "description": "Bad Request"}, 401: {"model": ErrorResponse, "description": "Unauthorized"}, 500: {"model": ErrorResponse, "description": "Internal Server Error"} }) async def analyze_soil_image_base64(request: Request, data: Dict[str, str], api_key_hash: str = Depends(verify_api_key)): """ Analyze a soil image provided as base64 string. The model outputs a softmax distribution over 11 PSD classes: Cl, fSi, mSi, cSi, fSa, mSa, cSa, fGr, mGr, cGr, Co Aggregate fractions (clay, silt, sand, gravel, cobbles) are also returned. The data dict can optionally include a 'ppm' field: - "auto" (default if omitted): automatic detection from EXIF/CSV with 70° angle fallback - A numeric string (e.g. "15.0"): use this PPM value directly for scaling """ start_time = time.time() if "image" not in data: track_api_usage( api_key_hash=api_key_hash, endpoint="/analyze_base64", request=request, start_time=start_time, success=False, response_time=time.time() - start_time, owner=getattr(request.state, 'owner', None), additional_data={"error": "Missing image field"} ) raise HTTPException(status_code=400, detail="Missing 'image' field in request") # Parse ppm parameter from data dict ppm_override = None ppm_value = data.get("ppm", "auto") if ppm_value is not None and ppm_value.strip().lower() != "auto": try: ppm_override = float(ppm_value.strip()) except ValueError: track_api_usage( api_key_hash=api_key_hash, endpoint="/analyze_base64", request=request, start_time=start_time, success=False, response_time=time.time() - start_time, owner=getattr(request.state, 'owner', None), additional_data={"error": "Invalid ppm value"} ) raise HTTPException(status_code=400, detail=f"Invalid ppm value: '{ppm_value}'. Must be 'auto' or a numeric value.") if model is None: track_api_usage( api_key_hash=api_key_hash, endpoint="/analyze_base64", request=request, start_time=start_time, success=False, response_time=time.time() - start_time, owner=getattr(request.state, 'owner', None), additional_data={"error": "Model not loaded"} ) raise HTTPException(status_code=500, detail="Model not loaded") try: # Decode base64 image image_data = base64.b64decode(data["image"]) image = PILImage.open(io.BytesIO(image_data)) # Get original dimensions original_width, original_height = image.size # Process image X, supported_device, ppm_source = process_image(image, ppm_override=ppm_override) # Make prediction predictions = model.predict(X, verbose=0) # Calculate PSD classes and aggregate fractions results = calculate_psd_and_fractions(predictions) # Track successful usage usage_id = track_api_usage( api_key_hash=api_key_hash, endpoint="/analyze_base64", request=request, start_time=start_time, success=True, response_time=time.time() - start_time, owner=getattr(request.state, 'owner', None), additional_data={ "data_size": len(data["image"]), "image_mode": image.mode, "estimated_file_size": len(image_data), "ppm_source": ppm_source, "psd": results["psd"] }, image_dimensions={"width": original_width, "height": original_height} ) return AnalysisResponse( status="success", psd=PSDClasses(**results["psd"]), fractions=SoilFractions(**results["fractions"]), supported_device=supported_device, image_dimensions={ "width": original_width, "height": original_height }, usage_id=usage_id, ppm_source=ppm_source ) except Exception as e: response_time = time.time() - start_time # Track failed usage track_api_usage( api_key_hash=api_key_hash, endpoint="/analyze_base64", request=request, start_time=start_time, success=False, response_time=response_time, owner=getattr(request.state, 'owner', None), additional_data={"error": str(e), "error_type": type(e).__name__} ) raise HTTPException( status_code=500, detail=f"Error processing image: {str(e)}" ) # ============================================================================= # USAGE STATISTICS ENDPOINTS # ============================================================================= 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] @app.get("/usage-stats", response_model=UsageStatsResponse) async def get_usage_stats_endpoint(request: Request, api_key: Optional[str] = None, hours: Optional[int] = 24, owner: Optional[str] = None): """ Get usage statistics for a specific API key or owner Args: api_key: API key to get statistics for (requires same owner access) hours: Number of hours to look back (default: 24) owner: Owner name filter (for admin access) """ # Get requesting user's API key hash if no specific key provided request_header_key = request.headers.get("x-api-key") request_key_hash = None if request_header_key: request_key_hash = sha256_hex(request_header_key) # Calculate time range end_time = time.time() start_time = end_time - (hours * 60 * 60) # Security check: ensure proper access if api_key: # User is requesting stats for a specific API key requested_key_hash = sha256_hex(api_key) # Get owner of requested key requested_owner = get_owner_from_key_hash(requested_key_hash) requested_api_key_owner = None if request_key_hash: requested_api_key_owner = get_owner_from_key_hash(request_key_hash) # Check if user owns the requested key or is admin if request_key_hash != requested_key_hash and requested_api_key_owner != requested_owner: # Not the same key owner - deny access pass # This will cause the stats query to return empty # Get statistics stats = get_usage_stats( api_key_hash=sha256_hex(api_key) if api_key else request_key_hash, owner=owner, time_range=(start_time, end_time) ) return UsageStatsResponse(**stats) @app.get("/owner-stats") async def get_owner_usage_stats(request: Request, owner: str, hours: Optional[int] = 24): """ Get usage statistics for a specific owner Requires the requesting user to have the same owner or be an admin """ request_header_key = request.headers.get("x-api-key") if not request_header_key: raise HTTPException(status_code=401, detail="API key required") request_key_hash = sha256_hex(request_header_key) request_owner = get_owner_from_key_hash(request_key_hash) target_owner = owner # Check if user has access to this owner's stats if request_owner != target_owner and request_owner != "admin": # Add admin check if needed raise HTTPException(status_code=403, detail="Not authorized to view this owner's stats") # Calculate time range end_time = time.time() start_time = end_time - (hours * 60 * 60) stats = get_usage_stats( owner=target_owner, time_range=(start_time, end_time) ) return stats @app.get("/admin/stats") async def get_admin_stats(request: Request, hours: Optional[int] = 24): """ Get overall system usage statistics (admin only) """ request_header_key = request.headers.get("x-api-key") if not request_header_key: raise HTTPException(status_code=401, detail="API key required") request_key_hash = sha256_hex(request_header_key) request_owner = get_owner_from_key_hash(request_key_hash) # Simple admin check - in production, use proper admin roles if request_owner != "admin": raise HTTPException(status_code=403, detail="Admin access required") # Calculate time range end_time = time.time() start_time = end_time - (hours * 60 * 60) stats = get_usage_stats(time_range=(start_time, end_time)) # Add additional admin-only information conn = get_usage_db_connection() try: cursor = conn.execute( "SELECT COUNT(DISTINCT api_key_hash) as unique_users FROM api_usage WHERE timestamp > ?", (start_time,) ) unique_users = cursor.fetchone()["unique_users"] # Get most active users cursor = conn.execute( """ SELECT owner, COUNT(*) as request_count FROM api_usage WHERE timestamp > ? GROUP BY owner ORDER BY request_count DESC LIMIT 5 """, (start_time,) ) most_active = [dict(row) for row in cursor.fetchall()] stats["admin_data"] = { "unique_users_24h": unique_users, "most_active_users": most_active } finally: conn.close() return stats # ============================================================================= # BILLING / USAGE COUNT ENDPOINTS # ============================================================================= @app.get("/my-usage") async def get_my_usage(request: Request, api_key_hash: str = Depends(verify_api_key)): """ Get usage count for the authenticated user (billing endpoint). Returns total and successful call counts from the persistent counter. """ conn = get_usage_db_connection() try: row = conn.execute( """ SELECT total_calls, successful_calls, last_call_at, first_call_at, owner FROM user_usage_counts WHERE api_key_hash = ? """, (api_key_hash,), ).fetchone() if not row: return { "api_key_hash": api_key_hash, "total_calls": 0, "successful_calls": 0, "last_call_at": None, "first_call_at": None, "owner": getattr(request.state, "owner", None), } return { "api_key_hash": api_key_hash, "owner": row["owner"], "total_calls": row["total_calls"], "successful_calls": row["successful_calls"], "last_call_at": row["last_call_at"], "first_call_at": row["first_call_at"], } finally: conn.close() @app.get("/admin/all-usage") async def get_all_usage(request: Request, api_key_hash: str = Depends(verify_api_key)): """ Get usage counts for ALL users (admin/billing endpoint). Only accessible by the 'admin' owner. """ owner = getattr(request.state, "owner", None) if owner != "admin": raise HTTPException(status_code=403, detail="Admin access required") conn = get_usage_db_connection() try: cursor = conn.execute( """ SELECT api_key_hash, owner, total_calls, successful_calls, last_call_at, first_call_at FROM user_usage_counts ORDER BY total_calls DESC """ ) users = [dict(row) for row in cursor.fetchall()] return { "total_users": len(users), "total_calls_all_users": sum(u["total_calls"] for u in users), "users": users, } finally: conn.close() @app.on_event("shutdown") async def on_shutdown(): """Final sync to bucket before shutdown.""" bucket_sync_on_shutdown() # ============================================================================= # MAIN # ============================================================================= if __name__ == "__main__": import uvicorn # Optional seed of API keys (example): # export API_KEYS_SEED="alice:KEY1,bob:KEY2,admin:ADMIN_KEY" # Keys are stored hashed (SHA-256) in SQLite at auth.db (or API_KEYS_DB_PATH). # Usage tracking data is stored in usage_tracking.db (or USAGE_DB_PATH). uvicorn.run(app, host="0.0.0.0", port=7860)