Update app.py
Browse files
app.py
CHANGED
|
@@ -1,8 +1,8 @@
|
|
| 1 |
-
from fastapi import FastAPI, File, UploadFile, HTTPException, Depends
|
| 2 |
from fastapi.responses import HTMLResponse
|
| 3 |
from fastapi.middleware.cors import CORSMiddleware
|
| 4 |
from pydantic import BaseModel
|
| 5 |
-
from typing import Optional, Dict, Any, Tuple
|
| 6 |
import numpy as np
|
| 7 |
import pandas as pd
|
| 8 |
import math
|
|
@@ -14,14 +14,15 @@ from huggingface_hub import hf_hub_download
|
|
| 14 |
import io
|
| 15 |
import base64
|
| 16 |
import csv
|
| 17 |
-
|
| 18 |
-
# --- Auth (API keys in a database) ---
|
| 19 |
import sqlite3
|
| 20 |
import hashlib
|
| 21 |
import secrets
|
|
|
|
|
|
|
| 22 |
from datetime import datetime
|
| 23 |
from fastapi.security import APIKeyHeader
|
| 24 |
from starlette.status import HTTP_401_UNAUTHORIZED
|
|
|
|
| 25 |
|
| 26 |
# =============================================================================
|
| 27 |
# MODEL LOADING
|
|
@@ -39,8 +40,8 @@ DB_PATH = os.getenv("API_KEYS_DB_PATH", "auth.db")
|
|
| 39 |
API_KEY_HEADER_NAME = "x-api-key"
|
| 40 |
api_key_header = APIKeyHeader(name=API_KEY_HEADER_NAME, auto_error=False)
|
| 41 |
|
| 42 |
-
def get_db_connection():
|
| 43 |
-
conn = sqlite3.connect(DB_PATH)
|
| 44 |
conn.row_factory = sqlite3.Row
|
| 45 |
return conn
|
| 46 |
|
|
@@ -62,6 +63,241 @@ def init_db():
|
|
| 62 |
finally:
|
| 63 |
conn.close()
|
| 64 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
def sha256_hex(value: str) -> str:
|
| 66 |
return hashlib.sha256(value.encode("utf-8")).hexdigest()
|
| 67 |
|
|
@@ -122,11 +358,10 @@ def seed_api_keys_from_env():
|
|
| 122 |
finally:
|
| 123 |
conn.close()
|
| 124 |
|
| 125 |
-
async def verify_api_key(provided_key: Optional[str] = Depends(api_key_header)) ->
|
| 126 |
"""
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
- Looks up SHA-256 hash in the database and ensures it's active.
|
| 130 |
"""
|
| 131 |
if not provided_key:
|
| 132 |
raise HTTPException(
|
|
@@ -139,7 +374,7 @@ async def verify_api_key(provided_key: Optional[str] = Depends(api_key_header))
|
|
| 139 |
conn = get_db_connection()
|
| 140 |
try:
|
| 141 |
row = conn.execute(
|
| 142 |
-
"SELECT key_hash, active FROM api_keys WHERE key_hash = ? LIMIT 1",
|
| 143 |
(key_hash,),
|
| 144 |
).fetchone()
|
| 145 |
finally:
|
|
@@ -153,6 +388,12 @@ async def verify_api_key(provided_key: Optional[str] = Depends(api_key_header))
|
|
| 153 |
detail="Invalid API key",
|
| 154 |
headers={"WWW-Authenticate": "API key"},
|
| 155 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
|
| 157 |
# =============================================================================
|
| 158 |
# IMAGE/INFERENCE UTILITIES
|
|
@@ -238,8 +479,8 @@ def custom_loss(y_true, y_pred):
|
|
| 238 |
|
| 239 |
app = FastAPI(
|
| 240 |
title="grai Soil Analysis API",
|
| 241 |
-
description="API for soil particle size distribution analysis from images",
|
| 242 |
-
version="
|
| 243 |
docs_url="/docs",
|
| 244 |
redoc_url="/redoc"
|
| 245 |
)
|
|
@@ -253,6 +494,13 @@ app.add_middleware(
|
|
| 253 |
allow_headers=["*"],
|
| 254 |
)
|
| 255 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 256 |
# Load the model once at startup
|
| 257 |
model = None
|
| 258 |
|
|
@@ -260,16 +508,21 @@ model = None
|
|
| 260 |
async def on_startup():
|
| 261 |
init_db()
|
| 262 |
seed_api_keys_from_env()
|
|
|
|
| 263 |
# Load ML model
|
| 264 |
global model
|
| 265 |
try:
|
| 266 |
with tf.keras.utils.custom_object_scope({'Mish': Mish, 'custom_loss': custom_loss}):
|
| 267 |
model = tf.keras.models.load_model(file_path)
|
| 268 |
print("Model loaded successfully")
|
|
|
|
| 269 |
except Exception as e:
|
| 270 |
print(f"Failed to load model: {e}")
|
| 271 |
|
| 272 |
-
#
|
|
|
|
|
|
|
|
|
|
| 273 |
class SoilParameters(BaseModel):
|
| 274 |
d10: float
|
| 275 |
d30: float
|
|
@@ -292,11 +545,25 @@ class AnalysisResponse(BaseModel):
|
|
| 292 |
fractions: SoilFractions
|
| 293 |
supported_device: bool
|
| 294 |
image_dimensions: Dict[str, int]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 295 |
|
| 296 |
class ErrorResponse(BaseModel):
|
| 297 |
error: str
|
| 298 |
details: Optional[str] = None
|
| 299 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 300 |
def process_image(image: PILImage.Image) -> tuple:
|
| 301 |
"""
|
| 302 |
Process the image according to device specifications and return predictions
|
|
@@ -440,18 +707,18 @@ def calculate_soil_parameters(predictions_b: float, predictions_c: float) -> Dic
|
|
| 440 |
}
|
| 441 |
|
| 442 |
# =============================================================================
|
| 443 |
-
#
|
| 444 |
# =============================================================================
|
| 445 |
|
| 446 |
HTML_CONTENT = """
|
| 447 |
<!DOCTYPE html>
|
| 448 |
<html>
|
| 449 |
<head>
|
| 450 |
-
<title>grai Soil Analysis API</title>
|
| 451 |
<style>
|
| 452 |
body {
|
| 453 |
font-family: Arial, sans-serif;
|
| 454 |
-
max-width:
|
| 455 |
margin: 0 auto;
|
| 456 |
padding: 20px;
|
| 457 |
background-color: #f5f5f5;
|
|
@@ -477,6 +744,13 @@ HTML_CONTENT = """
|
|
| 477 |
background-color: white;
|
| 478 |
border-left: 4px solid #297FD5;
|
| 479 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 480 |
code {
|
| 481 |
background-color: #f4f4f4;
|
| 482 |
padding: 2px 6px;
|
|
@@ -495,14 +769,29 @@ HTML_CONTENT = """
|
|
| 495 |
padding: 10px;
|
| 496 |
margin-top: 20px;
|
| 497 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 498 |
</style>
|
| 499 |
</head>
|
| 500 |
<body>
|
| 501 |
<div class="container">
|
| 502 |
-
<h1>🔵🔵🔵 grai Soil Analysis API</h1>
|
| 503 |
-
<p>API for soil particle size distribution analysis from images</p>
|
| 504 |
<p>Developed by <a href="mailto:enrico.soranzo@boku.ac.at">Enrico Soranzo</a></p>
|
| 505 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 506 |
<div class="endpoints">
|
| 507 |
<h2>Available Endpoints</h2>
|
| 508 |
<div class="endpoint">
|
|
@@ -520,6 +809,15 @@ HTML_CONTENT = """
|
|
| 520 |
<div class="endpoint">
|
| 521 |
<strong>GET /health</strong> - Health check (public)
|
| 522 |
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 523 |
</div>
|
| 524 |
|
| 525 |
<div class="note">
|
|
@@ -527,10 +825,24 @@ HTML_CONTENT = """
|
|
| 527 |
Add API keys to the database or set environment variable <code>API_KEYS_SEED</code> on startup:
|
| 528 |
<code>API_KEYS_SEED="alice:KEY1,bob:KEY2"</code>.
|
| 529 |
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 530 |
|
| 531 |
<h2>Quick Start</h2>
|
| 532 |
<p>Upload an image using cURL:</p>
|
| 533 |
<code>curl -X POST -H "x-api-key: API_KEY" -F "file=@soil_image.jpeg" https://soranz84-graiAPI.hf.space/analyze</code>
|
|
|
|
|
|
|
|
|
|
| 534 |
|
| 535 |
<h2>Recommended Devices</h2>
|
| 536 |
<p>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 A32, Samsung A52, Samsung Galaxy S23, Samsung Galaxy S24, Vivo X60, Xiaomi 15, Xiaomi A2<p>
|
|
@@ -543,7 +855,7 @@ HTML_CONTENT = """
|
|
| 543 |
"""
|
| 544 |
|
| 545 |
# =============================================================================
|
| 546 |
-
# ROUTES
|
| 547 |
# =============================================================================
|
| 548 |
|
| 549 |
@app.get("/", response_class=HTMLResponse)
|
|
@@ -556,23 +868,49 @@ async def health():
|
|
| 556 |
"""Health check endpoint"""
|
| 557 |
return {
|
| 558 |
"status": "healthy",
|
| 559 |
-
"model_loaded": model is not None
|
|
|
|
|
|
|
| 560 |
}
|
| 561 |
|
| 562 |
@app.post("/analyze", response_model=AnalysisResponse, responses={
|
| 563 |
400: {"model": ErrorResponse, "description": "Bad Request"},
|
| 564 |
401: {"model": ErrorResponse, "description": "Unauthorized"},
|
| 565 |
500: {"model": ErrorResponse, "description": "Internal Server Error"}
|
| 566 |
-
}
|
| 567 |
-
async def analyze_soil_image(file: UploadFile = File(...)):
|
| 568 |
"""
|
| 569 |
Analyze a soil image and return particle size distribution parameters.
|
|
|
|
| 570 |
"""
|
|
|
|
|
|
|
| 571 |
# Validate file type
|
| 572 |
if not file.content_type or not file.content_type.startswith("image/"):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 573 |
raise HTTPException(status_code=400, detail="File must be an image")
|
| 574 |
|
| 575 |
if model is None:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 576 |
raise HTTPException(status_code=500, detail="Model not loaded")
|
| 577 |
|
| 578 |
try:
|
|
@@ -596,6 +934,25 @@ async def analyze_soil_image(file: UploadFile = File(...)):
|
|
| 596 |
# Calculate all parameters
|
| 597 |
results = calculate_soil_parameters(predictions_b, predictions_c)
|
| 598 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 599 |
return AnalysisResponse(
|
| 600 |
status="success",
|
| 601 |
b_factor=results["b_factor"],
|
|
@@ -606,10 +963,23 @@ async def analyze_soil_image(file: UploadFile = File(...)):
|
|
| 606 |
image_dimensions={
|
| 607 |
"width": original_width,
|
| 608 |
"height": original_height
|
| 609 |
-
}
|
|
|
|
| 610 |
)
|
| 611 |
|
| 612 |
except Exception as e:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 613 |
raise HTTPException(
|
| 614 |
status_code=500,
|
| 615 |
detail=f"Error processing image: {str(e)}"
|
|
@@ -619,15 +989,38 @@ async def analyze_soil_image(file: UploadFile = File(...)):
|
|
| 619 |
400: {"model": ErrorResponse, "description": "Bad Request"},
|
| 620 |
401: {"model": ErrorResponse, "description": "Unauthorized"},
|
| 621 |
500: {"model": ErrorResponse, "description": "Internal Server Error"}
|
| 622 |
-
}
|
| 623 |
-
async def analyze_soil_image_base64(data: Dict[str, str]):
|
| 624 |
"""
|
| 625 |
Analyze a soil image provided as base64 string.
|
|
|
|
| 626 |
"""
|
|
|
|
|
|
|
| 627 |
if "image" not in data:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 628 |
raise HTTPException(status_code=400, detail="Missing 'image' field in request")
|
| 629 |
|
| 630 |
if model is None:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 631 |
raise HTTPException(status_code=500, detail="Model not loaded")
|
| 632 |
|
| 633 |
try:
|
|
@@ -651,6 +1044,25 @@ async def analyze_soil_image_base64(data: Dict[str, str]):
|
|
| 651 |
# Calculate all parameters
|
| 652 |
results = calculate_soil_parameters(predictions_b, predictions_c)
|
| 653 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 654 |
return AnalysisResponse(
|
| 655 |
status="success",
|
| 656 |
b_factor=results["b_factor"],
|
|
@@ -661,15 +1073,173 @@ async def analyze_soil_image_base64(data: Dict[str, str]):
|
|
| 661 |
image_dimensions={
|
| 662 |
"width": original_width,
|
| 663 |
"height": original_height
|
| 664 |
-
}
|
|
|
|
| 665 |
)
|
| 666 |
|
| 667 |
except Exception as e:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 668 |
raise HTTPException(
|
| 669 |
status_code=500,
|
| 670 |
detail=f"Error processing image: {str(e)}"
|
| 671 |
)
|
| 672 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 673 |
# =============================================================================
|
| 674 |
# MAIN
|
| 675 |
# =============================================================================
|
|
@@ -677,6 +1247,7 @@ async def analyze_soil_image_base64(data: Dict[str, str]):
|
|
| 677 |
if __name__ == "__main__":
|
| 678 |
import uvicorn
|
| 679 |
# Optional seed of API keys (example):
|
| 680 |
-
# export API_KEYS_SEED="alice:KEY1,bob:KEY2"
|
| 681 |
# Keys are stored hashed (SHA-256) in SQLite at auth.db (or API_KEYS_DB_PATH).
|
|
|
|
| 682 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
| 1 |
+
from fastapi import FastAPI, File, UploadFile, HTTPException, Depends, Request
|
| 2 |
from fastapi.responses import HTMLResponse
|
| 3 |
from fastapi.middleware.cors import CORSMiddleware
|
| 4 |
from pydantic import BaseModel
|
| 5 |
+
from typing import Optional, Dict, Any, Tuple, List
|
| 6 |
import numpy as np
|
| 7 |
import pandas as pd
|
| 8 |
import math
|
|
|
|
| 14 |
import io
|
| 15 |
import base64
|
| 16 |
import csv
|
|
|
|
|
|
|
| 17 |
import sqlite3
|
| 18 |
import hashlib
|
| 19 |
import secrets
|
| 20 |
+
import time
|
| 21 |
+
import uuid
|
| 22 |
from datetime import datetime
|
| 23 |
from fastapi.security import APIKeyHeader
|
| 24 |
from starlette.status import HTTP_401_UNAUTHORIZED
|
| 25 |
+
import json
|
| 26 |
|
| 27 |
# =============================================================================
|
| 28 |
# MODEL LOADING
|
|
|
|
| 40 |
API_KEY_HEADER_NAME = "x-api-key"
|
| 41 |
api_key_header = APIKeyHeader(name=API_KEY_HEADER_NAME, auto_error=False)
|
| 42 |
|
| 43 |
+
def get_db_connection(db_path: str = None):
|
| 44 |
+
conn = sqlite3.connect(db_path or DB_PATH)
|
| 45 |
conn.row_factory = sqlite3.Row
|
| 46 |
return conn
|
| 47 |
|
|
|
|
| 63 |
finally:
|
| 64 |
conn.close()
|
| 65 |
|
| 66 |
+
# =============================================================================
|
| 67 |
+
# API USAGE TRACKING SETUP
|
| 68 |
+
# =============================================================================
|
| 69 |
+
|
| 70 |
+
# Initialize usage tracking database
|
| 71 |
+
USAGE_DB_PATH = os.getenv("USAGE_DB_PATH", "usage_tracking.db")
|
| 72 |
+
|
| 73 |
+
def get_usage_db_connection():
|
| 74 |
+
"""Get connection to the usage tracking database"""
|
| 75 |
+
conn = sqlite3.connect(USAGE_DB_PATH)
|
| 76 |
+
conn.row_factory = sqlite3.Row
|
| 77 |
+
return conn
|
| 78 |
+
|
| 79 |
+
def init_usage_db():
|
| 80 |
+
"""Initialize the usage tracking database"""
|
| 81 |
+
conn = get_usage_db_connection()
|
| 82 |
+
try:
|
| 83 |
+
conn.execute(
|
| 84 |
+
"""
|
| 85 |
+
CREATE TABLE IF NOT EXISTS api_usage (
|
| 86 |
+
id TEXT PRIMARY KEY,
|
| 87 |
+
api_key_hash TEXT NOT NULL,
|
| 88 |
+
endpoint TEXT NOT NULL,
|
| 89 |
+
timestamp REAL NOT NULL,
|
| 90 |
+
user_id TEXT,
|
| 91 |
+
owner TEXT,
|
| 92 |
+
success BOOLEAN NOT NULL,
|
| 93 |
+
response_time REAL,
|
| 94 |
+
request_method TEXT,
|
| 95 |
+
user_agent TEXT,
|
| 96 |
+
client_ip TEXT,
|
| 97 |
+
additional_data TEXT,
|
| 98 |
+
image_dimensions TEXT,
|
| 99 |
+
model_prediction_b REAL,
|
| 100 |
+
model_prediction_c REAL
|
| 101 |
+
);
|
| 102 |
+
"""
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
# Index for better query performance
|
| 106 |
+
conn.execute(
|
| 107 |
+
"CREATE INDEX IF NOT EXISTS idx_api_key_hash ON api_usage(api_key_hash)"
|
| 108 |
+
)
|
| 109 |
+
conn.execute(
|
| 110 |
+
"CREATE INDEX IF NOT EXISTS idx_timestamp ON api_usage(timestamp)"
|
| 111 |
+
)
|
| 112 |
+
conn.execute(
|
| 113 |
+
"CREATE INDEX IF NOT EXISTS idx_endpoint ON api_usage(endpoint)"
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
conn.commit()
|
| 117 |
+
finally:
|
| 118 |
+
conn.close()
|
| 119 |
+
|
| 120 |
+
def track_api_usage(
|
| 121 |
+
api_key_hash: str,
|
| 122 |
+
endpoint: str,
|
| 123 |
+
request: Request,
|
| 124 |
+
start_time: float,
|
| 125 |
+
success: bool,
|
| 126 |
+
response_time: float,
|
| 127 |
+
owner: Optional[str] = None,
|
| 128 |
+
additional_data: Optional[Dict] = None,
|
| 129 |
+
prediction_b: Optional[float] = None,
|
| 130 |
+
prediction_c: Optional[float] = None,
|
| 131 |
+
image_dimensions: Optional[Dict] = None
|
| 132 |
+
) -> str:
|
| 133 |
+
"""
|
| 134 |
+
Track API usage for monitoring and analytics
|
| 135 |
+
|
| 136 |
+
Args:
|
| 137 |
+
api_key_hash: Hash of the API key used
|
| 138 |
+
endpoint: API endpoint called
|
| 139 |
+
request: FastAPI request object
|
| 140 |
+
start_time: When the request started (time.time())
|
| 141 |
+
success: Whether the request was successful
|
| 142 |
+
response_time: Time taken to complete the request
|
| 143 |
+
owner: Owner of the API key
|
| 144 |
+
additional_data: Additional data to store
|
| 145 |
+
prediction_b: Model prediction for b factor
|
| 146 |
+
prediction_c: Model prediction for c factor
|
| 147 |
+
image_dimensions: Image dimensions if applicable
|
| 148 |
+
"""
|
| 149 |
+
usage_id = str(uuid.uuid4())
|
| 150 |
+
|
| 151 |
+
conn = get_usage_db_connection()
|
| 152 |
+
try:
|
| 153 |
+
conn.execute(
|
| 154 |
+
"""
|
| 155 |
+
INSERT INTO api_usage (
|
| 156 |
+
id, api_key_hash, endpoint, timestamp, user_id, owner,
|
| 157 |
+
success, response_time, request_method, user_agent,
|
| 158 |
+
client_ip, additional_data, model_prediction_b,
|
| 159 |
+
model_prediction_c, image_dimensions
|
| 160 |
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
| 161 |
+
""",
|
| 162 |
+
(
|
| 163 |
+
usage_id,
|
| 164 |
+
api_key_hash,
|
| 165 |
+
endpoint,
|
| 166 |
+
start_time,
|
| 167 |
+
str(request.state.user_id) if hasattr(request.state, 'user_id') else None,
|
| 168 |
+
owner,
|
| 169 |
+
success,
|
| 170 |
+
response_time,
|
| 171 |
+
request.method if request else None,
|
| 172 |
+
request.headers.get("User-Agent") if request else None,
|
| 173 |
+
request.headers.get("X-Forwarded-For", request.client.host if request and request.client else None) if request else None,
|
| 174 |
+
json.dumps(additional_data or {}),
|
| 175 |
+
prediction_b,
|
| 176 |
+
prediction_c,
|
| 177 |
+
json.dumps(image_dimensions or {})
|
| 178 |
+
)
|
| 179 |
+
)
|
| 180 |
+
conn.commit()
|
| 181 |
+
finally:
|
| 182 |
+
conn.close()
|
| 183 |
+
|
| 184 |
+
return usage_id
|
| 185 |
+
|
| 186 |
+
def get_usage_stats(
|
| 187 |
+
api_key_hash: Optional[str] = None,
|
| 188 |
+
owner: Optional[str] = None,
|
| 189 |
+
time_range: Optional[tuple] = None,
|
| 190 |
+
endpoint: Optional[str] = None
|
| 191 |
+
) -> Dict[str, Any]:
|
| 192 |
+
"""
|
| 193 |
+
Get API usage statistics
|
| 194 |
+
|
| 195 |
+
Args:
|
| 196 |
+
api_key_hash: Filter by API key hash
|
| 197 |
+
owner: Filter by owner
|
| 198 |
+
time_range: Tuple of (start_time, end_time) timestamps
|
| 199 |
+
endpoint: Filter by endpoint
|
| 200 |
+
"""
|
| 201 |
+
conn = get_usage_db_connection()
|
| 202 |
+
try:
|
| 203 |
+
query = "SELECT * FROM api_usage WHERE 1=1"
|
| 204 |
+
params = []
|
| 205 |
+
|
| 206 |
+
if api_key_hash:
|
| 207 |
+
query += " AND api_key_hash = ?"
|
| 208 |
+
params.append(api_key_hash)
|
| 209 |
+
|
| 210 |
+
if owner:
|
| 211 |
+
query += " AND owner = ?"
|
| 212 |
+
params.append(owner)
|
| 213 |
+
|
| 214 |
+
if time_range:
|
| 215 |
+
query += " AND timestamp BETWEEN ? AND ?"
|
| 216 |
+
params.extend(time_range)
|
| 217 |
+
|
| 218 |
+
if endpoint:
|
| 219 |
+
query += " AND endpoint = ?"
|
| 220 |
+
params.append(endpoint)
|
| 221 |
+
|
| 222 |
+
query += " ORDER BY timestamp DESC"
|
| 223 |
+
|
| 224 |
+
cursor = conn.execute(query, params)
|
| 225 |
+
rows = cursor.fetchall()
|
| 226 |
+
|
| 227 |
+
# Process results
|
| 228 |
+
total_requests = len(rows)
|
| 229 |
+
successful_requests = sum(1 for row in rows if row["success"])
|
| 230 |
+
failed_requests = total_requests - successful_requests
|
| 231 |
+
|
| 232 |
+
# Calculate statistics
|
| 233 |
+
response_times = [row["response_time"] for row in rows if row["response_time"]]
|
| 234 |
+
avg_response_time = sum(response_times) / len(response_times) if response_times else 0
|
| 235 |
+
|
| 236 |
+
# Group by endpoint
|
| 237 |
+
endpoint_stats = {}
|
| 238 |
+
for row in rows:
|
| 239 |
+
endpoint = row["endpoint"]
|
| 240 |
+
if endpoint not in endpoint_stats:
|
| 241 |
+
endpoint_stats[endpoint] = {
|
| 242 |
+
"total": 0,
|
| 243 |
+
"success": 0,
|
| 244 |
+
"failed": 0,
|
| 245 |
+
"response_times": []
|
| 246 |
+
}
|
| 247 |
+
|
| 248 |
+
endpoint_stats[endpoint]["total"] += 1
|
| 249 |
+
endpoint_stats[endpoint]["response_times"].append(row["response_time"])
|
| 250 |
+
|
| 251 |
+
if row["success"]:
|
| 252 |
+
endpoint_stats[endpoint]["success"] += 1
|
| 253 |
+
else:
|
| 254 |
+
endpoint_stats[endpoint]["failed"] += 1
|
| 255 |
+
|
| 256 |
+
# Calculate averages for each endpoint
|
| 257 |
+
for endpoint, stats in endpoint_stats.items():
|
| 258 |
+
response_times = stats["response_times"]
|
| 259 |
+
stats["avg_response_time"] = sum(response_times) / len(response_times) if response_times else 0
|
| 260 |
+
stats["success_rate"] = stats["success"] / stats["total"] if stats["total"] > 0 else 0
|
| 261 |
+
del stats["response_times"] # Remove from output
|
| 262 |
+
|
| 263 |
+
# Recent activity (last 24 hours)
|
| 264 |
+
day_ago = time.time() - (24 * 60 * 60)
|
| 265 |
+
recent_requests = sum(1 for row in rows if row["timestamp"] > day_ago)
|
| 266 |
+
|
| 267 |
+
return {
|
| 268 |
+
"total_requests": total_requests,
|
| 269 |
+
"successful_requests": successful_requests,
|
| 270 |
+
"failed_requests": failed_requests,
|
| 271 |
+
"success_rate": successful_requests / total_requests if total_requests > 0 else 0,
|
| 272 |
+
"average_response_time": avg_response_time,
|
| 273 |
+
"recent_requests_24h": recent_requests,
|
| 274 |
+
"endpoint_statistics": endpoint_stats,
|
| 275 |
+
"time_range": time_range,
|
| 276 |
+
"filters": {
|
| 277 |
+
"api_key_hash": api_key_hash,
|
| 278 |
+
"owner": owner,
|
| 279 |
+
"endpoint": endpoint
|
| 280 |
+
}
|
| 281 |
+
}
|
| 282 |
+
finally:
|
| 283 |
+
conn.close()
|
| 284 |
+
|
| 285 |
+
def get_owner_from_key_hash(api_key_hash: str) -> Optional[str]:
|
| 286 |
+
"""Get owner name from API key hash"""
|
| 287 |
+
conn = get_db_connection()
|
| 288 |
+
try:
|
| 289 |
+
row = conn.execute(
|
| 290 |
+
"SELECT owner FROM api_keys WHERE key_hash = ? LIMIT 1",
|
| 291 |
+
(api_key_hash,)
|
| 292 |
+
).fetchone()
|
| 293 |
+
return row["owner"] if row else None
|
| 294 |
+
finally:
|
| 295 |
+
conn.close()
|
| 296 |
+
|
| 297 |
+
# =============================================================================
|
| 298 |
+
# ENHANCED AUTH FUNCTIONS
|
| 299 |
+
# =============================================================================
|
| 300 |
+
|
| 301 |
def sha256_hex(value: str) -> str:
|
| 302 |
return hashlib.sha256(value.encode("utf-8")).hexdigest()
|
| 303 |
|
|
|
|
| 358 |
finally:
|
| 359 |
conn.close()
|
| 360 |
|
| 361 |
+
async def verify_api_key(request: Request, provided_key: Optional[str] = Depends(api_key_header)) -> str:
|
| 362 |
"""
|
| 363 |
+
Enhanced dependency: verify the provided API key against the DB and store request context
|
| 364 |
+
Returns the API key hash for tracking purposes
|
|
|
|
| 365 |
"""
|
| 366 |
if not provided_key:
|
| 367 |
raise HTTPException(
|
|
|
|
| 374 |
conn = get_db_connection()
|
| 375 |
try:
|
| 376 |
row = conn.execute(
|
| 377 |
+
"SELECT key_hash, active, owner FROM api_keys WHERE key_hash = ? LIMIT 1",
|
| 378 |
(key_hash,),
|
| 379 |
).fetchone()
|
| 380 |
finally:
|
|
|
|
| 388 |
detail="Invalid API key",
|
| 389 |
headers={"WWW-Authenticate": "API key"},
|
| 390 |
)
|
| 391 |
+
|
| 392 |
+
# Store user context in request state for tracking
|
| 393 |
+
request.state.user_id = str(row["id"])
|
| 394 |
+
request.state.owner = row["owner"]
|
| 395 |
+
|
| 396 |
+
return key_hash
|
| 397 |
|
| 398 |
# =============================================================================
|
| 399 |
# IMAGE/INFERENCE UTILITIES
|
|
|
|
| 479 |
|
| 480 |
app = FastAPI(
|
| 481 |
title="grai Soil Analysis API",
|
| 482 |
+
description="API for soil particle size distribution analysis from images with usage tracking",
|
| 483 |
+
version="2.0.0",
|
| 484 |
docs_url="/docs",
|
| 485 |
redoc_url="/redoc"
|
| 486 |
)
|
|
|
|
| 494 |
allow_headers=["*"],
|
| 495 |
)
|
| 496 |
|
| 497 |
+
# Add request state middleware for tracking
|
| 498 |
+
@app.middleware("http")
|
| 499 |
+
async def add_request_state_middleware(request: Request, call_next):
|
| 500 |
+
"""Add request state for tracking purposes"""
|
| 501 |
+
response = await call_next(request)
|
| 502 |
+
return response
|
| 503 |
+
|
| 504 |
# Load the model once at startup
|
| 505 |
model = None
|
| 506 |
|
|
|
|
| 508 |
async def on_startup():
|
| 509 |
init_db()
|
| 510 |
seed_api_keys_from_env()
|
| 511 |
+
init_usage_db() # Initialize usage tracking
|
| 512 |
# Load ML model
|
| 513 |
global model
|
| 514 |
try:
|
| 515 |
with tf.keras.utils.custom_object_scope({'Mish': Mish, 'custom_loss': custom_loss}):
|
| 516 |
model = tf.keras.models.load_model(file_path)
|
| 517 |
print("Model loaded successfully")
|
| 518 |
+
print(f"Usage tracking enabled - database: {USAGE_DB_PATH}")
|
| 519 |
except Exception as e:
|
| 520 |
print(f"Failed to load model: {e}")
|
| 521 |
|
| 522 |
+
# =============================================================================
|
| 523 |
+
# RESPONSE MODELS
|
| 524 |
+
# =============================================================================
|
| 525 |
+
|
| 526 |
class SoilParameters(BaseModel):
|
| 527 |
d10: float
|
| 528 |
d30: float
|
|
|
|
| 545 |
fractions: SoilFractions
|
| 546 |
supported_device: bool
|
| 547 |
image_dimensions: Dict[str, int]
|
| 548 |
+
usage_id: str # Track which usage record this response corresponds to
|
| 549 |
+
|
| 550 |
+
class UsageStatsResponse(BaseModel):
|
| 551 |
+
total_requests: int
|
| 552 |
+
successful_requests: int
|
| 553 |
+
failed_requests: int
|
| 554 |
+
success_rate: float
|
| 555 |
+
average_response_time: float
|
| 556 |
+
recent_requests_24h: int
|
| 557 |
+
endpoint_statistics: Dict[str, Any]
|
| 558 |
|
| 559 |
class ErrorResponse(BaseModel):
|
| 560 |
error: str
|
| 561 |
details: Optional[str] = None
|
| 562 |
|
| 563 |
+
# =============================================================================
|
| 564 |
+
# IMAGE PROCESSING FUNCTIONS
|
| 565 |
+
# =============================================================================
|
| 566 |
+
|
| 567 |
def process_image(image: PILImage.Image) -> tuple:
|
| 568 |
"""
|
| 569 |
Process the image according to device specifications and return predictions
|
|
|
|
| 707 |
}
|
| 708 |
|
| 709 |
# =============================================================================
|
| 710 |
+
# HTML LANDING PAGE
|
| 711 |
# =============================================================================
|
| 712 |
|
| 713 |
HTML_CONTENT = """
|
| 714 |
<!DOCTYPE html>
|
| 715 |
<html>
|
| 716 |
<head>
|
| 717 |
+
<title>grai Soil Analysis API - Usage Tracking Enabled</title>
|
| 718 |
<style>
|
| 719 |
body {
|
| 720 |
font-family: Arial, sans-serif;
|
| 721 |
+
max-width: 900px;
|
| 722 |
margin: 0 auto;
|
| 723 |
padding: 20px;
|
| 724 |
background-color: #f5f5f5;
|
|
|
|
| 744 |
background-color: white;
|
| 745 |
border-left: 4px solid #297FD5;
|
| 746 |
}
|
| 747 |
+
.usage-tracking {
|
| 748 |
+
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
| 749 |
+
color: white;
|
| 750 |
+
padding: 20px;
|
| 751 |
+
border-radius: 10px;
|
| 752 |
+
margin: 20px 0;
|
| 753 |
+
}
|
| 754 |
code {
|
| 755 |
background-color: #f4f4f4;
|
| 756 |
padding: 2px 6px;
|
|
|
|
| 769 |
padding: 10px;
|
| 770 |
margin-top: 20px;
|
| 771 |
}
|
| 772 |
+
.stats-endpoint {
|
| 773 |
+
background-color: #e8f5e8;
|
| 774 |
+
border-left: 4px solid #4caf50;
|
| 775 |
+
}
|
| 776 |
</style>
|
| 777 |
</head>
|
| 778 |
<body>
|
| 779 |
<div class="container">
|
| 780 |
+
<h1>🔵🔵🔵 grai Soil Analysis API - v2.0</h1>
|
| 781 |
+
<p>API for soil particle size distribution analysis from images with usage tracking</p>
|
| 782 |
<p>Developed by <a href="mailto:enrico.soranzo@boku.ac.at">Enrico Soranzo</a></p>
|
| 783 |
|
| 784 |
+
<div class="usage-tracking">
|
| 785 |
+
<h3>📊 Usage Tracking Enabled</h3>
|
| 786 |
+
<p>This API now includes comprehensive usage tracking:</p>
|
| 787 |
+
<ul>
|
| 788 |
+
<li>Track API key usage patterns</li>
|
| 789 |
+
<li>Monitor response times and success rates</li>
|
| 790 |
+
<li>Access detailed analytics via <code>/usage-stats</code> endpoint</li>
|
| 791 |
+
<li>Secure storage with API key hash tracking</li>
|
| 792 |
+
</ul>
|
| 793 |
+
</div>
|
| 794 |
+
|
| 795 |
<div class="endpoints">
|
| 796 |
<h2>Available Endpoints</h2>
|
| 797 |
<div class="endpoint">
|
|
|
|
| 809 |
<div class="endpoint">
|
| 810 |
<strong>GET /health</strong> - Health check (public)
|
| 811 |
</div>
|
| 812 |
+
<div class="endpoint stats-endpoint">
|
| 813 |
+
<strong>GET /usage-stats?api_key=YOUR_KEY</strong> - Get usage statistics for your API key
|
| 814 |
+
</div>
|
| 815 |
+
<div class="endpoint stats-endpoint">
|
| 816 |
+
<strong>GET /owner-stats?owner=username</strong> - Get usage statistics for an owner
|
| 817 |
+
</div>
|
| 818 |
+
<div class="endpoint stats-endpoint">
|
| 819 |
+
<strong>GET /admin/stats</strong> - Admin endpoint to get overall statistics (requires special key)
|
| 820 |
+
</div>
|
| 821 |
</div>
|
| 822 |
|
| 823 |
<div class="note">
|
|
|
|
| 825 |
Add API keys to the database or set environment variable <code>API_KEYS_SEED</code> on startup:
|
| 826 |
<code>API_KEYS_SEED="alice:KEY1,bob:KEY2"</code>.
|
| 827 |
</div>
|
| 828 |
+
|
| 829 |
+
<div class="usage-tracking">
|
| 830 |
+
<h3>📈 New Usage Statistics Features</h3>
|
| 831 |
+
<p>Monitor your API usage with these new endpoints:</p>
|
| 832 |
+
<ul>
|
| 833 |
+
<li><code>/usage-stats?api_key=KEY</code> - Your usage statistics</li>
|
| 834 |
+
<li><code>/owner-stats?owner=alice</code> - Statistics by owner (requires admin access)</li>
|
| 835 |
+
<li><code>/admin/stats</code> - Overall system statistics</li>
|
| 836 |
+
</ul>
|
| 837 |
+
<p>All statistics include request counts, success rates, response times, and endpoint breakdowns.</p>
|
| 838 |
+
</div>
|
| 839 |
|
| 840 |
<h2>Quick Start</h2>
|
| 841 |
<p>Upload an image using cURL:</p>
|
| 842 |
<code>curl -X POST -H "x-api-key: API_KEY" -F "file=@soil_image.jpeg" https://soranz84-graiAPI.hf.space/analyze</code>
|
| 843 |
+
|
| 844 |
+
<h3>Get your usage statistics:</h3>
|
| 845 |
+
<code>curl -H "x-api-key: API_KEY" https://soranz84-graiAPI.hf.space/usage-stats?api_key=API_KEY</code>
|
| 846 |
|
| 847 |
<h2>Recommended Devices</h2>
|
| 848 |
<p>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 A32, Samsung A52, Samsung Galaxy S23, Samsung Galaxy S24, Vivo X60, Xiaomi 15, Xiaomi A2<p>
|
|
|
|
| 855 |
"""
|
| 856 |
|
| 857 |
# =============================================================================
|
| 858 |
+
# API ROUTES
|
| 859 |
# =============================================================================
|
| 860 |
|
| 861 |
@app.get("/", response_class=HTMLResponse)
|
|
|
|
| 868 |
"""Health check endpoint"""
|
| 869 |
return {
|
| 870 |
"status": "healthy",
|
| 871 |
+
"model_loaded": model is not None,
|
| 872 |
+
"usage_tracking": True,
|
| 873 |
+
"usage_db_path": USAGE_DB_PATH
|
| 874 |
}
|
| 875 |
|
| 876 |
@app.post("/analyze", response_model=AnalysisResponse, responses={
|
| 877 |
400: {"model": ErrorResponse, "description": "Bad Request"},
|
| 878 |
401: {"model": ErrorResponse, "description": "Unauthorized"},
|
| 879 |
500: {"model": ErrorResponse, "description": "Internal Server Error"}
|
| 880 |
+
})
|
| 881 |
+
async def analyze_soil_image(request: Request, file: UploadFile = File(...), api_key_hash: str = Depends(verify_api_key)):
|
| 882 |
"""
|
| 883 |
Analyze a soil image and return particle size distribution parameters.
|
| 884 |
+
Includes comprehensive usage tracking.
|
| 885 |
"""
|
| 886 |
+
start_time = time.time()
|
| 887 |
+
|
| 888 |
# Validate file type
|
| 889 |
if not file.content_type or not file.content_type.startswith("image/"):
|
| 890 |
+
# Track failed request
|
| 891 |
+
track_api_usage(
|
| 892 |
+
api_key_hash=api_key_hash,
|
| 893 |
+
endpoint="/analyze",
|
| 894 |
+
request=request,
|
| 895 |
+
start_time=start_time,
|
| 896 |
+
success=False,
|
| 897 |
+
response_time=time.time() - start_time,
|
| 898 |
+
owner=getattr(request.state, 'owner', None),
|
| 899 |
+
additional_data={"error": "Invalid file type", "content_type": file.content_type}
|
| 900 |
+
)
|
| 901 |
raise HTTPException(status_code=400, detail="File must be an image")
|
| 902 |
|
| 903 |
if model is None:
|
| 904 |
+
track_api_usage(
|
| 905 |
+
api_key_hash=api_key_hash,
|
| 906 |
+
endpoint="/analyze",
|
| 907 |
+
request=request,
|
| 908 |
+
start_time=start_time,
|
| 909 |
+
success=False,
|
| 910 |
+
response_time=time.time() - start_time,
|
| 911 |
+
owner=getattr(request.state, 'owner', None),
|
| 912 |
+
additional_data={"error": "Model not loaded"}
|
| 913 |
+
)
|
| 914 |
raise HTTPException(status_code=500, detail="Model not loaded")
|
| 915 |
|
| 916 |
try:
|
|
|
|
| 934 |
# Calculate all parameters
|
| 935 |
results = calculate_soil_parameters(predictions_b, predictions_c)
|
| 936 |
|
| 937 |
+
# Track successful usage
|
| 938 |
+
usage_id = track_api_usage(
|
| 939 |
+
api_key_hash=api_key_hash,
|
| 940 |
+
endpoint="/analyze",
|
| 941 |
+
request=request,
|
| 942 |
+
start_time=start_time,
|
| 943 |
+
success=True,
|
| 944 |
+
response_time=time.time() - start_time,
|
| 945 |
+
owner=getattr(request.state, 'owner', None),
|
| 946 |
+
additional_data={
|
| 947 |
+
"file_size": len(contents),
|
| 948 |
+
"image_mode": image.mode,
|
| 949 |
+
"file_format": getattr(file, 'filename', 'unknown')
|
| 950 |
+
},
|
| 951 |
+
prediction_b=predictions_b,
|
| 952 |
+
prediction_c=predictions_c,
|
| 953 |
+
image_dimensions={"width": original_width, "height": original_height}
|
| 954 |
+
)
|
| 955 |
+
|
| 956 |
return AnalysisResponse(
|
| 957 |
status="success",
|
| 958 |
b_factor=results["b_factor"],
|
|
|
|
| 963 |
image_dimensions={
|
| 964 |
"width": original_width,
|
| 965 |
"height": original_height
|
| 966 |
+
},
|
| 967 |
+
usage_id=usage_id
|
| 968 |
)
|
| 969 |
|
| 970 |
except Exception as e:
|
| 971 |
+
response_time = time.time() - start_time
|
| 972 |
+
# Track failed usage
|
| 973 |
+
track_api_usage(
|
| 974 |
+
api_key_hash=api_key_hash,
|
| 975 |
+
endpoint="/analyze",
|
| 976 |
+
request=request,
|
| 977 |
+
start_time=start_time,
|
| 978 |
+
success=False,
|
| 979 |
+
response_time=response_time,
|
| 980 |
+
owner=getattr(request.state, 'owner', None),
|
| 981 |
+
additional_data={"error": str(e), "error_type": type(e).__name__}
|
| 982 |
+
)
|
| 983 |
raise HTTPException(
|
| 984 |
status_code=500,
|
| 985 |
detail=f"Error processing image: {str(e)}"
|
|
|
|
| 989 |
400: {"model": ErrorResponse, "description": "Bad Request"},
|
| 990 |
401: {"model": ErrorResponse, "description": "Unauthorized"},
|
| 991 |
500: {"model": ErrorResponse, "description": "Internal Server Error"}
|
| 992 |
+
})
|
| 993 |
+
async def analyze_soil_image_base64(request: Request, data: Dict[str, str], api_key_hash: str = Depends(verify_api_key)):
|
| 994 |
"""
|
| 995 |
Analyze a soil image provided as base64 string.
|
| 996 |
+
Includes comprehensive usage tracking.
|
| 997 |
"""
|
| 998 |
+
start_time = time.time()
|
| 999 |
+
|
| 1000 |
if "image" not in data:
|
| 1001 |
+
track_api_usage(
|
| 1002 |
+
api_key_hash=api_key_hash,
|
| 1003 |
+
endpoint="/analyze_base64",
|
| 1004 |
+
request=request,
|
| 1005 |
+
start_time=start_time,
|
| 1006 |
+
success=False,
|
| 1007 |
+
response_time=time.time() - start_time,
|
| 1008 |
+
owner=getattr(request.state, 'owner', None),
|
| 1009 |
+
additional_data={"error": "Missing image field"}
|
| 1010 |
+
)
|
| 1011 |
raise HTTPException(status_code=400, detail="Missing 'image' field in request")
|
| 1012 |
|
| 1013 |
if model is None:
|
| 1014 |
+
track_api_usage(
|
| 1015 |
+
api_key_hash=api_key_hash,
|
| 1016 |
+
endpoint="/analyze_base64",
|
| 1017 |
+
request=request,
|
| 1018 |
+
start_time=start_time,
|
| 1019 |
+
success=False,
|
| 1020 |
+
response_time=time.time() - start_time,
|
| 1021 |
+
owner=getattr(request.state, 'owner', None),
|
| 1022 |
+
additional_data={"error": "Model not loaded"}
|
| 1023 |
+
)
|
| 1024 |
raise HTTPException(status_code=500, detail="Model not loaded")
|
| 1025 |
|
| 1026 |
try:
|
|
|
|
| 1044 |
# Calculate all parameters
|
| 1045 |
results = calculate_soil_parameters(predictions_b, predictions_c)
|
| 1046 |
|
| 1047 |
+
# Track successful usage
|
| 1048 |
+
usage_id = track_api_usage(
|
| 1049 |
+
api_key_hash=api_key_hash,
|
| 1050 |
+
endpoint="/analyze_base64",
|
| 1051 |
+
request=request,
|
| 1052 |
+
start_time=start_time,
|
| 1053 |
+
success=True,
|
| 1054 |
+
response_time=time.time() - start_time,
|
| 1055 |
+
owner=getattr(request.state, 'owner', None),
|
| 1056 |
+
additional_data={
|
| 1057 |
+
"data_size": len(data["image"]),
|
| 1058 |
+
"image_mode": image.mode,
|
| 1059 |
+
"estimated_file_size": len(image_data)
|
| 1060 |
+
},
|
| 1061 |
+
prediction_b=predictions_b,
|
| 1062 |
+
prediction_c=predictions_c,
|
| 1063 |
+
image_dimensions={"width": original_width, "height": original_height}
|
| 1064 |
+
)
|
| 1065 |
+
|
| 1066 |
return AnalysisResponse(
|
| 1067 |
status="success",
|
| 1068 |
b_factor=results["b_factor"],
|
|
|
|
| 1073 |
image_dimensions={
|
| 1074 |
"width": original_width,
|
| 1075 |
"height": original_height
|
| 1076 |
+
},
|
| 1077 |
+
usage_id=usage_id
|
| 1078 |
)
|
| 1079 |
|
| 1080 |
except Exception as e:
|
| 1081 |
+
response_time = time.time() - start_time
|
| 1082 |
+
# Track failed usage
|
| 1083 |
+
track_api_usage(
|
| 1084 |
+
api_key_hash=api_key_hash,
|
| 1085 |
+
endpoint="/analyze_base64",
|
| 1086 |
+
request=request,
|
| 1087 |
+
start_time=start_time,
|
| 1088 |
+
success=False,
|
| 1089 |
+
response_time=response_time,
|
| 1090 |
+
owner=getattr(request.state, 'owner', None),
|
| 1091 |
+
additional_data={"error": str(e), "error_type": type(e).__name__}
|
| 1092 |
+
)
|
| 1093 |
raise HTTPException(
|
| 1094 |
status_code=500,
|
| 1095 |
detail=f"Error processing image: {str(e)}"
|
| 1096 |
)
|
| 1097 |
|
| 1098 |
+
# =============================================================================
|
| 1099 |
+
# USAGE STATISTICS ENDPOINTS
|
| 1100 |
+
# =============================================================================
|
| 1101 |
+
|
| 1102 |
+
class UsageStatsResponse(BaseModel):
|
| 1103 |
+
total_requests: int
|
| 1104 |
+
successful_requests: int
|
| 1105 |
+
failed_requests: int
|
| 1106 |
+
success_rate: float
|
| 1107 |
+
average_response_time: float
|
| 1108 |
+
recent_requests_24h: int
|
| 1109 |
+
endpoint_statistics: Dict[str, Any]
|
| 1110 |
+
|
| 1111 |
+
@app.get("/usage-stats", response_model=UsageStatsResponse)
|
| 1112 |
+
async def get_usage_stats_endpoint(request: Request, api_key: Optional[str] = None,
|
| 1113 |
+
hours: Optional[int] = 24, owner: Optional[str] = None):
|
| 1114 |
+
"""
|
| 1115 |
+
Get usage statistics for a specific API key or owner
|
| 1116 |
+
|
| 1117 |
+
Args:
|
| 1118 |
+
api_key: API key to get statistics for (requires same owner access)
|
| 1119 |
+
hours: Number of hours to look back (default: 24)
|
| 1120 |
+
owner: Owner name filter (for admin access)
|
| 1121 |
+
"""
|
| 1122 |
+
|
| 1123 |
+
# Get requesting user's API key hash if no specific key provided
|
| 1124 |
+
request_header_key = request.headers.get("x-api-key")
|
| 1125 |
+
|
| 1126 |
+
request_key_hash = None
|
| 1127 |
+
if request_header_key:
|
| 1128 |
+
request_key_hash = sha256_hex(request_header_key)
|
| 1129 |
+
|
| 1130 |
+
# Calculate time range
|
| 1131 |
+
end_time = time.time()
|
| 1132 |
+
start_time = end_time - (hours * 60 * 60)
|
| 1133 |
+
|
| 1134 |
+
# Security check: ensure proper access
|
| 1135 |
+
if api_key:
|
| 1136 |
+
# User is requesting stats for a specific API key
|
| 1137 |
+
requested_key_hash = sha256_hex(api_key)
|
| 1138 |
+
|
| 1139 |
+
# Get owner of requested key
|
| 1140 |
+
requested_owner = get_owner_from_key_hash(requested_key_hash)
|
| 1141 |
+
requested_api_key_owner = None
|
| 1142 |
+
|
| 1143 |
+
if request_key_hash:
|
| 1144 |
+
requested_api_key_owner = get_owner_from_key_hash(request_key_hash)
|
| 1145 |
+
|
| 1146 |
+
# Check if user owns the requested key or is admin
|
| 1147 |
+
if request_key_hash != requested_key_hash and requested_api_key_owner != requested_owner:
|
| 1148 |
+
# Not the same key owner - deny access
|
| 1149 |
+
pass # This will cause the stats query to return empty
|
| 1150 |
+
|
| 1151 |
+
# Get statistics
|
| 1152 |
+
stats = get_usage_stats(
|
| 1153 |
+
api_key_hash=sha256_hex(api_key) if api_key else request_key_hash,
|
| 1154 |
+
owner=owner,
|
| 1155 |
+
time_range=(start_time, end_time)
|
| 1156 |
+
)
|
| 1157 |
+
|
| 1158 |
+
return UsageStatsResponse(**stats)
|
| 1159 |
+
|
| 1160 |
+
@app.get("/owner-stats")
|
| 1161 |
+
async def get_owner_usage_stats(request: Request, owner: str, hours: Optional[int] = 24):
|
| 1162 |
+
"""
|
| 1163 |
+
Get usage statistics for a specific owner
|
| 1164 |
+
Requires the requesting user to have the same owner or be an admin
|
| 1165 |
+
"""
|
| 1166 |
+
request_header_key = request.headers.get("x-api-key")
|
| 1167 |
+
if not request_header_key:
|
| 1168 |
+
raise HTTPException(status_code=401, detail="API key required")
|
| 1169 |
+
|
| 1170 |
+
request_key_hash = sha256_hex(request_header_key)
|
| 1171 |
+
request_owner = get_owner_from_key_hash(request_key_hash)
|
| 1172 |
+
target_owner = owner
|
| 1173 |
+
|
| 1174 |
+
# Check if user has access to this owner's stats
|
| 1175 |
+
if request_owner != target_owner and request_owner != "admin": # Add admin check if needed
|
| 1176 |
+
raise HTTPException(status_code=403, detail="Not authorized to view this owner's stats")
|
| 1177 |
+
|
| 1178 |
+
# Calculate time range
|
| 1179 |
+
end_time = time.time()
|
| 1180 |
+
start_time = end_time - (hours * 60 * 60)
|
| 1181 |
+
|
| 1182 |
+
stats = get_usage_stats(
|
| 1183 |
+
owner=target_owner,
|
| 1184 |
+
time_range=(start_time, end_time)
|
| 1185 |
+
)
|
| 1186 |
+
|
| 1187 |
+
return stats
|
| 1188 |
+
|
| 1189 |
+
@app.get("/admin/stats")
|
| 1190 |
+
async def get_admin_stats(request: Request, hours: Optional[int] = 24):
|
| 1191 |
+
"""
|
| 1192 |
+
Get overall system usage statistics (admin only)
|
| 1193 |
+
"""
|
| 1194 |
+
request_header_key = request.headers.get("x-api-key")
|
| 1195 |
+
if not request_header_key:
|
| 1196 |
+
raise HTTPException(status_code=401, detail="API key required")
|
| 1197 |
+
|
| 1198 |
+
request_key_hash = sha256_hex(request_header_key)
|
| 1199 |
+
request_owner = get_owner_from_key_hash(request_key_hash)
|
| 1200 |
+
|
| 1201 |
+
# Simple admin check - in production, use proper admin roles
|
| 1202 |
+
if request_owner != "admin":
|
| 1203 |
+
raise HTTPException(status_code=403, detail="Admin access required")
|
| 1204 |
+
|
| 1205 |
+
# Calculate time range
|
| 1206 |
+
end_time = time.time()
|
| 1207 |
+
start_time = end_time - (hours * 60 * 60)
|
| 1208 |
+
|
| 1209 |
+
stats = get_usage_stats(time_range=(start_time, end_time))
|
| 1210 |
+
|
| 1211 |
+
# Add additional admin-only information
|
| 1212 |
+
conn = get_usage_db_connection()
|
| 1213 |
+
try:
|
| 1214 |
+
cursor = conn.execute(
|
| 1215 |
+
"SELECT COUNT(DISTINCT api_key_hash) as unique_users FROM api_usage WHERE timestamp > ?",
|
| 1216 |
+
(start_time,)
|
| 1217 |
+
)
|
| 1218 |
+
unique_users = cursor.fetchone()["unique_users"]
|
| 1219 |
+
|
| 1220 |
+
# Get most active users
|
| 1221 |
+
cursor = conn.execute(
|
| 1222 |
+
"""
|
| 1223 |
+
SELECT owner, COUNT(*) as request_count
|
| 1224 |
+
FROM api_usage
|
| 1225 |
+
WHERE timestamp > ?
|
| 1226 |
+
GROUP BY owner
|
| 1227 |
+
ORDER BY request_count DESC
|
| 1228 |
+
LIMIT 5
|
| 1229 |
+
""",
|
| 1230 |
+
(start_time,)
|
| 1231 |
+
)
|
| 1232 |
+
most_active = [dict(row) for row in cursor.fetchall()]
|
| 1233 |
+
|
| 1234 |
+
stats["admin_data"] = {
|
| 1235 |
+
"unique_users_24h": unique_users,
|
| 1236 |
+
"most_active_users": most_active
|
| 1237 |
+
}
|
| 1238 |
+
finally:
|
| 1239 |
+
conn.close()
|
| 1240 |
+
|
| 1241 |
+
return stats
|
| 1242 |
+
|
| 1243 |
# =============================================================================
|
| 1244 |
# MAIN
|
| 1245 |
# =============================================================================
|
|
|
|
| 1247 |
if __name__ == "__main__":
|
| 1248 |
import uvicorn
|
| 1249 |
# Optional seed of API keys (example):
|
| 1250 |
+
# export API_KEYS_SEED="alice:KEY1,bob:KEY2,admin:ADMIN_KEY"
|
| 1251 |
# Keys are stored hashed (SHA-256) in SQLite at auth.db (or API_KEYS_DB_PATH).
|
| 1252 |
+
# Usage tracking data is stored in usage_tracking.db (or USAGE_DB_PATH).
|
| 1253 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|