Update app.py
Browse files
app.py
CHANGED
|
@@ -1,135 +1,145 @@
|
|
| 1 |
-
|
| 2 |
-
import
|
| 3 |
-
import
|
| 4 |
-
import
|
| 5 |
-
import
|
|
|
|
| 6 |
import numpy as np
|
| 7 |
import pandas as pd
|
|
|
|
|
|
|
| 8 |
import tensorflow as tf
|
| 9 |
-
from typing import Optional, Dict, Any, Tuple
|
| 10 |
from PIL import Image as PILImage
|
| 11 |
from PIL import ExifTags
|
| 12 |
from huggingface_hub import hf_hub_download
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
-
|
| 15 |
-
from fastapi.responses import JSONResponse
|
| 16 |
-
from fastapi.middleware.cors import CORSMiddleware
|
| 17 |
-
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
| 18 |
-
from pydantic import BaseModel
|
| 19 |
-
|
| 20 |
-
# --- 1. AUTHENTIFIZIERUNG ---
|
| 21 |
-
security = HTTPBearer()
|
| 22 |
-
|
| 23 |
-
def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)):
|
| 24 |
-
expected_token = os.environ.get("P1")
|
| 25 |
-
if not expected_token:
|
| 26 |
-
raise HTTPException(status_code=500, detail="Security Secret 'P1' not set in Space Settings.")
|
| 27 |
-
if credentials.credentials != expected_token:
|
| 28 |
-
raise HTTPException(status_code=403, detail="Invalid API Token.")
|
| 29 |
-
return credentials.credentials
|
| 30 |
-
|
| 31 |
-
# --- 2. MODELL-SETUP & CUSTOM LAYERS ---
|
| 32 |
-
class Mish(tf.keras.layers.Layer):
|
| 33 |
-
def __init__(self, **kwargs):
|
| 34 |
-
super(Mish, self).__init__(**kwargs)
|
| 35 |
-
def call(self, inputs):
|
| 36 |
-
return inputs * tf.math.tanh(tf.math.softplus(inputs))
|
| 37 |
-
|
| 38 |
-
def custom_loss(y_true, y_pred):
|
| 39 |
-
weights = np.array([0.7, 0.3])
|
| 40 |
-
squared_diff = tf.square(y_true - y_pred)
|
| 41 |
-
weighted_squared_diff = squared_diff * weights
|
| 42 |
-
return tf.reduce_mean(weighted_squared_diff, axis=-1)
|
| 43 |
-
|
| 44 |
-
tf.keras.utils.get_custom_objects().update({'Mish': Mish, 'custom_loss': custom_loss})
|
| 45 |
-
|
| 46 |
-
# Modell laden
|
| 47 |
model_key = os.getenv("hf_token")
|
| 48 |
-
file_path = hf_hub_download(
|
| 49 |
-
|
| 50 |
|
| 51 |
-
#
|
| 52 |
def clean_exif_string(val):
|
| 53 |
-
if val is None:
|
|
|
|
|
|
|
|
|
|
| 54 |
if isinstance(val, bytes):
|
| 55 |
for enc in ("utf-8", "utf-16", "utf-16le", "latin-1"):
|
| 56 |
try:
|
| 57 |
val = val.decode(enc)
|
| 58 |
break
|
| 59 |
-
except
|
| 60 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
val = val.replace("\x00", "")
|
| 62 |
-
|
|
|
|
| 63 |
|
| 64 |
-
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
cam = camera.strip().lower()
|
| 67 |
w, h = int(w), int(h)
|
| 68 |
phone_norm = phone.strip().lower() if phone else None
|
|
|
|
| 69 |
with open(path, newline="", encoding="utf-8") as f:
|
| 70 |
reader = csv.DictReader(f)
|
| 71 |
for row in reader:
|
| 72 |
-
|
| 73 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
try:
|
| 75 |
-
rw
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
return None, None
|
| 81 |
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
except: raw_exif = getattr(image, "_getexif", lambda: None)()
|
| 87 |
-
|
| 88 |
-
camera = None
|
| 89 |
-
if raw_exif:
|
| 90 |
-
exif = {ExifTags.TAGS.get(t, t): v for t, v in raw_exif.items()}
|
| 91 |
-
camera = clean_exif_string(exif.get("Model"))
|
| 92 |
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
ppm = max(width, height) / 294.087
|
| 96 |
-
|
| 97 |
-
scale = 4.6 / ppm
|
| 98 |
-
resized = image.resize((int(width * scale), int(height * scale)), PILImage.Resampling.LANCZOS)
|
| 99 |
-
|
| 100 |
-
# Center Crop 400x400
|
| 101 |
-
tw, th = 400, 400
|
| 102 |
-
cw, ch = resized.size
|
| 103 |
-
left, top = (cw - tw) // 2, (ch - th) // 2
|
| 104 |
-
cropped = resized.crop((left, top, left + tw, top + th))
|
| 105 |
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
X = np.expand_dims(img_array, axis=0)
|
| 109 |
-
X = tf.keras.applications.efficientnet_v2.preprocess_input(X)
|
| 110 |
-
return X
|
| 111 |
|
| 112 |
-
#
|
| 113 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
|
|
|
| 115 |
app.add_middleware(
|
| 116 |
CORSMiddleware,
|
| 117 |
allow_origins=["*"],
|
|
|
|
| 118 |
allow_methods=["*"],
|
| 119 |
allow_headers=["*"],
|
| 120 |
)
|
| 121 |
|
|
|
|
|
|
|
|
|
|
| 122 |
@app.on_event("startup")
|
| 123 |
-
async def
|
| 124 |
global model
|
| 125 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
|
| 127 |
-
#
|
| 128 |
class SoilParameters(BaseModel):
|
| 129 |
-
d10: float
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
|
| 131 |
class SoilFractions(BaseModel):
|
| 132 |
-
clay: float
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
|
| 134 |
class AnalysisResponse(BaseModel):
|
| 135 |
status: str
|
|
@@ -137,44 +147,383 @@ class AnalysisResponse(BaseModel):
|
|
| 137 |
c_factor: float
|
| 138 |
parameters: SoilParameters
|
| 139 |
fractions: SoilFractions
|
|
|
|
| 140 |
image_dimensions: Dict[str, int]
|
| 141 |
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
|
|
|
| 149 |
|
| 150 |
-
|
| 151 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
|
| 153 |
-
#
|
| 154 |
-
|
| 155 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
return {
|
| 170 |
-
"status": "
|
| 171 |
-
"
|
| 172 |
-
"c_factor": c_val,
|
| 173 |
-
"parameters": {"d10": d10, "d30": d30, "d60": d60, "Cu": d60/d10, "Cc": (d30**2)/(d10*d60)},
|
| 174 |
-
"fractions": {"clay": max(0,cl), "silt": max(0,si), "sand": max(0,sa), "gravel": max(0,gr), "boulder": max(0,bo)},
|
| 175 |
-
"image_dimensions": {"width": orig_w, "height": orig_h}
|
| 176 |
}
|
| 177 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
if __name__ == "__main__":
|
| 179 |
import uvicorn
|
| 180 |
-
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
| 1 |
+
|
| 2 |
+
from fastapi import FastAPI, File, UploadFile, HTTPException
|
| 3 |
+
from fastapi.responses import JSONResponse, HTMLResponse
|
| 4 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 5 |
+
from pydantic import BaseModel
|
| 6 |
+
from typing import Optional, Dict, Any, Tuple
|
| 7 |
import numpy as np
|
| 8 |
import pandas as pd
|
| 9 |
+
import math
|
| 10 |
+
import os
|
| 11 |
import tensorflow as tf
|
|
|
|
| 12 |
from PIL import Image as PILImage
|
| 13 |
from PIL import ExifTags
|
| 14 |
from huggingface_hub import hf_hub_download
|
| 15 |
+
import io
|
| 16 |
+
import base64
|
| 17 |
+
import csv
|
| 18 |
|
| 19 |
+
# model token
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
model_key = os.getenv("hf_token")
|
| 21 |
+
file_path = hf_hub_download("soranz84/grai3", "grai_3_076.h5",
|
| 22 |
+
token=model_key)
|
| 23 |
|
| 24 |
+
# clean the camera string
|
| 25 |
def clean_exif_string(val):
|
| 26 |
+
if val is None:
|
| 27 |
+
return None
|
| 28 |
+
|
| 29 |
+
# Decode bytes using a few likely encodings
|
| 30 |
if isinstance(val, bytes):
|
| 31 |
for enc in ("utf-8", "utf-16", "utf-16le", "latin-1"):
|
| 32 |
try:
|
| 33 |
val = val.decode(enc)
|
| 34 |
break
|
| 35 |
+
except Exception:
|
| 36 |
+
pass
|
| 37 |
+
else:
|
| 38 |
+
val = val.decode("latin-1", errors="ignore")
|
| 39 |
+
|
| 40 |
+
# Remove null padding and non-printables
|
| 41 |
val = val.replace("\x00", "")
|
| 42 |
+
val = "".join(ch for ch in val if ch.isprintable())
|
| 43 |
+
return val.strip()
|
| 44 |
|
| 45 |
+
# find ppm and phone name
|
| 46 |
+
def find_ppm_and_phone_csv(
|
| 47 |
+
path: str,
|
| 48 |
+
camera: str,
|
| 49 |
+
w: int,
|
| 50 |
+
h: int,
|
| 51 |
+
phone: Optional[str] = None
|
| 52 |
+
) -> Tuple[Optional[float], Optional[str]]:
|
| 53 |
cam = camera.strip().lower()
|
| 54 |
w, h = int(w), int(h)
|
| 55 |
phone_norm = phone.strip().lower() if phone else None
|
| 56 |
+
|
| 57 |
with open(path, newline="", encoding="utf-8") as f:
|
| 58 |
reader = csv.DictReader(f)
|
| 59 |
for row in reader:
|
| 60 |
+
cam_row = (row.get("camera", "")).strip().lower()
|
| 61 |
+
if cam_row != cam:
|
| 62 |
+
continue
|
| 63 |
+
if phone_norm:
|
| 64 |
+
if (row.get("phone", "")).strip().lower() != phone_norm:
|
| 65 |
+
continue
|
| 66 |
try:
|
| 67 |
+
rw = int(str(row.get("width", "")).strip())
|
| 68 |
+
rh = int(str(row.get("height", "")).strip())
|
| 69 |
+
ppm = float(str(row.get("ppm", "")).strip())
|
| 70 |
+
except ValueError:
|
| 71 |
+
continue
|
| 72 |
+
|
| 73 |
+
# Orientation-independent comparison
|
| 74 |
+
if (rw == w and rh == h) or (rw == h and rh == w):
|
| 75 |
+
phone_name = (row.get("phone", "")).strip() or None
|
| 76 |
+
return ppm, phone_name
|
| 77 |
+
|
| 78 |
return None, None
|
| 79 |
|
| 80 |
+
# Define the Mish activation function (essential for the model)
|
| 81 |
+
class Mish(tf.keras.layers.Layer):
|
| 82 |
+
def __init__(self, **kwargs):
|
| 83 |
+
super(Mish, self).__init__(**kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
|
| 85 |
+
def call(self, inputs):
|
| 86 |
+
return inputs * tf.math.tanh(tf.math.softplus(inputs))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
|
| 88 |
+
# Register the custom object for TensorFlow to recognize it when loading the model
|
| 89 |
+
tf.keras.utils.get_custom_objects().update({'Mish': Mish})
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
+
# Define a custom loss function
|
| 92 |
+
def custom_loss(y_true, y_pred):
|
| 93 |
+
weights = np.array([0.7, 0.3])
|
| 94 |
+
squared_diff = tf.square(y_true - y_pred)
|
| 95 |
+
weighted_squared_diff = squared_diff * weights
|
| 96 |
+
return tf.reduce_mean(weighted_squared_diff, axis=-1)
|
| 97 |
+
|
| 98 |
+
# Initialize FastAPI app
|
| 99 |
+
app = FastAPI(
|
| 100 |
+
title="grai3 Soil Analysis API",
|
| 101 |
+
description="API for soil particle size distribution analysis from images",
|
| 102 |
+
version="1.0.0",
|
| 103 |
+
docs_url="/docs",
|
| 104 |
+
redoc_url="/redoc"
|
| 105 |
+
)
|
| 106 |
|
| 107 |
+
# Configure CORS
|
| 108 |
app.add_middleware(
|
| 109 |
CORSMiddleware,
|
| 110 |
allow_origins=["*"],
|
| 111 |
+
allow_credentials=True,
|
| 112 |
allow_methods=["*"],
|
| 113 |
allow_headers=["*"],
|
| 114 |
)
|
| 115 |
|
| 116 |
+
# Load the model once at startup
|
| 117 |
+
model = None
|
| 118 |
+
|
| 119 |
@app.on_event("startup")
|
| 120 |
+
async def load_model():
|
| 121 |
global model
|
| 122 |
+
try:
|
| 123 |
+
with tf.keras.utils.custom_object_scope({'Mish': Mish, 'custom_loss': custom_loss}):
|
| 124 |
+
model = tf.keras.models.load_model(file_path)
|
| 125 |
+
print("Model loaded successfully")
|
| 126 |
+
except Exception as e:
|
| 127 |
+
print(f"Failed to load model: {e}")
|
| 128 |
|
| 129 |
+
# Response models
|
| 130 |
class SoilParameters(BaseModel):
|
| 131 |
+
d10: float
|
| 132 |
+
d30: float
|
| 133 |
+
d60: float
|
| 134 |
+
Cu: float # coefficient of uniformity
|
| 135 |
+
Cc: float # coefficient of curvature
|
| 136 |
|
| 137 |
class SoilFractions(BaseModel):
|
| 138 |
+
clay: float # percentage
|
| 139 |
+
silt: float # percentage
|
| 140 |
+
sand: float # percentage
|
| 141 |
+
gravel: float # percentage
|
| 142 |
+
boulder: float # percentage
|
| 143 |
|
| 144 |
class AnalysisResponse(BaseModel):
|
| 145 |
status: str
|
|
|
|
| 147 |
c_factor: float
|
| 148 |
parameters: SoilParameters
|
| 149 |
fractions: SoilFractions
|
| 150 |
+
supported_device: bool
|
| 151 |
image_dimensions: Dict[str, int]
|
| 152 |
|
| 153 |
+
class ErrorResponse(BaseModel):
|
| 154 |
+
error: str
|
| 155 |
+
details: Optional[str] = None
|
| 156 |
+
|
| 157 |
+
def process_image(image: PILImage.Image) -> tuple:
|
| 158 |
+
"""
|
| 159 |
+
Process the image according to device specifications and return predictions
|
| 160 |
+
"""
|
| 161 |
+
width, height = image.size
|
| 162 |
+
scale = 1
|
| 163 |
+
supported_device = True
|
| 164 |
+
|
| 165 |
+
# read metadata
|
| 166 |
+
width, height = image.size
|
| 167 |
+
|
| 168 |
+
camera = None
|
| 169 |
+
|
| 170 |
+
# Pillow >= 6 supports img.getexif(); older versions use _getexif()
|
| 171 |
+
raw_exif = None
|
| 172 |
+
try:
|
| 173 |
+
raw_exif = image.getexif()
|
| 174 |
+
except Exception:
|
| 175 |
+
raw_exif = getattr(image, "_getexif", lambda: None)()
|
| 176 |
+
|
| 177 |
+
if raw_exif:
|
| 178 |
+
exif = {}
|
| 179 |
+
for tag_id, value in raw_exif.items():
|
| 180 |
+
tag = ExifTags.TAGS.get(tag_id, tag_id)
|
| 181 |
+
exif[tag] = value
|
| 182 |
+
camera = exif.get("Model") # camera model (tag 272)
|
| 183 |
+
camera = clean_exif_string(camera)
|
| 184 |
+
|
| 185 |
+
# find ppm and phone name:
|
| 186 |
+
ppm, phone_name = (None, None)
|
| 187 |
+
if camera is not None:
|
| 188 |
+
ppm, phone_name = find_ppm_and_phone_csv("ppm.csv", camera, width, height)
|
| 189 |
+
|
| 190 |
+
# handle unkwnon phone camera
|
| 191 |
+
if ppm is None:
|
| 192 |
+
# Form to confirm guessed ppm
|
| 193 |
+
ppm = max(width,height)/294.087
|
| 194 |
+
|
| 195 |
+
# resize image to 4.6 PPM
|
| 196 |
+
scale = 4.6 / ppm
|
| 197 |
+
|
| 198 |
+
# Calculate new dimensions
|
| 199 |
+
new_width = int(width * scale)
|
| 200 |
+
new_height = int(height * scale)
|
| 201 |
+
|
| 202 |
+
# Resize the image
|
| 203 |
+
resized_image = image.resize((new_width, new_height), PILImage.Resampling.LANCZOS)
|
| 204 |
+
|
| 205 |
+
# Crop to 400x400
|
| 206 |
+
width_crop = 400
|
| 207 |
+
height_crop = 400
|
| 208 |
+
|
| 209 |
+
if resized_image.size != (width_crop, height_crop):
|
| 210 |
+
width, height = resized_image.width, resized_image.height
|
| 211 |
+
left = (width - width_crop) // 2
|
| 212 |
+
upper = (height - height_crop) // 2
|
| 213 |
+
right = left + width_crop
|
| 214 |
+
lower = upper + height_crop
|
| 215 |
+
cropped_image = resized_image.crop((left, upper, right, lower))
|
| 216 |
+
else:
|
| 217 |
+
cropped_image = resized_image
|
| 218 |
+
|
| 219 |
+
# Split channels
|
| 220 |
+
red_channel, green_channel, blue_channel = cropped_image.split()
|
| 221 |
+
|
| 222 |
+
# Import channels and normalize
|
| 223 |
+
red_array = np.array(red_channel)
|
| 224 |
+
green_array = np.array(green_channel)
|
| 225 |
+
blue_array = np.array(blue_channel)
|
| 226 |
|
| 227 |
+
# Convert to dataframe
|
| 228 |
+
red_df = pd.DataFrame(red_array)
|
| 229 |
+
green_df = pd.DataFrame(green_array)
|
| 230 |
+
blue_df = pd.DataFrame(blue_array)
|
| 231 |
|
| 232 |
+
# Convert to list
|
| 233 |
+
red_list = red_df.values.tolist()
|
| 234 |
+
green_list = green_df.values.tolist()
|
| 235 |
+
blue_list = blue_df.values.tolist()
|
| 236 |
+
|
| 237 |
+
# Create input
|
| 238 |
+
X = []
|
| 239 |
+
X.append([red_list, green_list, blue_list])
|
| 240 |
+
|
| 241 |
+
# Scale for mobilenet
|
| 242 |
+
X0 = np.array(X)
|
| 243 |
+
X = tf.keras.applications.efficientnet_v2.preprocess_input(X0)
|
| 244 |
|
| 245 |
+
# Transpose data
|
| 246 |
+
X = tf.transpose(X, perm=[0, 2, 3, 1])
|
| 247 |
+
|
| 248 |
+
return X, supported_device
|
| 249 |
+
|
| 250 |
+
def calculate_soil_parameters(predictions_b: float, predictions_c: float) -> Dict[str, Any]:
|
| 251 |
+
"""
|
| 252 |
+
Calculate soil parameters from model predictions
|
| 253 |
+
"""
|
| 254 |
+
# Transform predictions
|
| 255 |
+
b = math.exp(predictions_b)
|
| 256 |
+
c = float(predictions_c)
|
| 257 |
+
|
| 258 |
+
# Characteristic diameters
|
| 259 |
+
d10 = b * ((-math.log(0.9)) ** (1/c))
|
| 260 |
+
d30 = b * ((-math.log(0.7)) ** (1/c))
|
| 261 |
+
d60 = b * ((-math.log(0.4)) ** (1/c))
|
| 262 |
+
|
| 263 |
+
# Coefficients
|
| 264 |
+
Cu = d60 / d10 # coefficient of uniformity
|
| 265 |
+
Cc = (d30 ** 2) / (d10 * d60) # coefficient of curvature
|
| 266 |
+
|
| 267 |
+
# Diameter boundaries
|
| 268 |
+
dCl = 0.002 # max. clay fraction diameter
|
| 269 |
+
dSi = 0.063 # max silt fraction diameter
|
| 270 |
+
dSa = 2 # max sand fraction diameter
|
| 271 |
+
dGr = 63 # max gravel fraction diameter
|
| 272 |
+
|
| 273 |
+
# Calculate fractions
|
| 274 |
+
Cl = 1 - math.exp(-(dCl/b)**c) # clay fraction
|
| 275 |
+
Si = 1 - math.exp(-(dSi/b)**c) - Cl
|
| 276 |
+
Sa = 1 - math.exp(-(dSa/b)**c) - Si - Cl
|
| 277 |
+
Gr = 1 - math.exp(-(dGr/b)**c) - Sa - Si - Cl
|
| 278 |
+
Bo = 1 - Gr - Sa - Si - Cl
|
| 279 |
+
|
| 280 |
+
return {
|
| 281 |
+
"b_factor": round(b, 3),
|
| 282 |
+
"c_factor": round(c, 3),
|
| 283 |
+
"parameters": {
|
| 284 |
+
"d10": round(d10, 3),
|
| 285 |
+
"d30": round(d30, 3),
|
| 286 |
+
"d60": round(d60, 3),
|
| 287 |
+
"Cu": round(Cu, 3),
|
| 288 |
+
"Cc": round(Cc, 3)
|
| 289 |
+
},
|
| 290 |
+
"fractions": {
|
| 291 |
+
"clay": round(Cl * 100, 1),
|
| 292 |
+
"silt": round(Si * 100, 1),
|
| 293 |
+
"sand": round(Sa * 100, 1),
|
| 294 |
+
"gravel": round(Gr * 100, 1),
|
| 295 |
+
"boulder": round(Bo * 100, 1)
|
| 296 |
+
}
|
| 297 |
+
}
|
| 298 |
|
| 299 |
+
# HTML landing page
|
| 300 |
+
HTML_CONTENT = """
|
| 301 |
+
<!DOCTYPE html>
|
| 302 |
+
<html>
|
| 303 |
+
<head>
|
| 304 |
+
<title>grai3 Soil Analysis API</title>
|
| 305 |
+
<style>
|
| 306 |
+
body {
|
| 307 |
+
font-family: Arial, sans-serif;
|
| 308 |
+
max-width: 800px;
|
| 309 |
+
margin: 0 auto;
|
| 310 |
+
padding: 20px;
|
| 311 |
+
background-color: #f5f5f5;
|
| 312 |
+
}
|
| 313 |
+
.container {
|
| 314 |
+
background-color: white;
|
| 315 |
+
padding: 30px;
|
| 316 |
+
border-radius: 10px;
|
| 317 |
+
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
|
| 318 |
+
}
|
| 319 |
+
h1 {
|
| 320 |
+
color: #2F4F4F;
|
| 321 |
+
}
|
| 322 |
+
.endpoints {
|
| 323 |
+
background-color: #f0f0f0;
|
| 324 |
+
padding: 15px;
|
| 325 |
+
border-radius: 5px;
|
| 326 |
+
margin: 20px 0;
|
| 327 |
+
}
|
| 328 |
+
.endpoint {
|
| 329 |
+
margin: 10px 0;
|
| 330 |
+
padding: 10px;
|
| 331 |
+
background-color: white;
|
| 332 |
+
border-left: 4px solid #297FD5;
|
| 333 |
+
}
|
| 334 |
+
code {
|
| 335 |
+
background-color: #f4f4f4;
|
| 336 |
+
padding: 2px 6px;
|
| 337 |
+
border-radius: 3px;
|
| 338 |
+
}
|
| 339 |
+
a {
|
| 340 |
+
color: #297FD5;
|
| 341 |
+
text-decoration: none;
|
| 342 |
+
}
|
| 343 |
+
a:hover {
|
| 344 |
+
text-decoration: underline;
|
| 345 |
+
}
|
| 346 |
+
</style>
|
| 347 |
+
</head>
|
| 348 |
+
<body>
|
| 349 |
+
<div class="container">
|
| 350 |
+
<h1>🔵🔵🔵 grai3 Soil Analysis API</h1>
|
| 351 |
+
<p>API for soil particle size distribution analysis from images</p>
|
| 352 |
+
<p>Developed by <a href="mailto:enrico.soranzo@boku.ac.at">Enrico Soranzo</a></p>
|
| 353 |
+
|
| 354 |
+
<div class="endpoints">
|
| 355 |
+
<h2>Available Endpoints</h2>
|
| 356 |
+
<div class="endpoint">
|
| 357 |
+
<strong>GET /</strong> - This page
|
| 358 |
+
</div>
|
| 359 |
+
<div class="endpoint">
|
| 360 |
+
<strong>POST /analyze</strong> - Analyze soil image (multipart/form-data)
|
| 361 |
+
</div>
|
| 362 |
+
<div class="endpoint">
|
| 363 |
+
<strong>POST /analyze_base64</strong> - Analyze base64 encoded image
|
| 364 |
+
</div>
|
| 365 |
+
<div class="endpoint">
|
| 366 |
+
<strong>GET /docs</strong> - <a href="/docs">Interactive API Documentation</a>
|
| 367 |
+
</div>
|
| 368 |
+
<div class="endpoint">
|
| 369 |
+
<strong>GET /health</strong> - Health check
|
| 370 |
+
</div>
|
| 371 |
+
</div>
|
| 372 |
+
|
| 373 |
+
<h2>Quick Start</h2>
|
| 374 |
+
<p>Upload an image using cURL:</p>
|
| 375 |
+
<code>curl -X POST -F "file=@soil_image.jpg" https://soranz84-grai3api.hf.space/analyze</code>
|
| 376 |
+
|
| 377 |
+
<h2>Recommended Devices</h2>
|
| 378 |
+
<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>
|
| 379 |
|
| 380 |
+
<h2>Other Devices</h2>
|
| 381 |
+
<p>grai3 is device-agnostic. An angle of view of 70° is assumed for uncalibrated devices. You can write to <a href="mailto:enrico.soranzo@boku.ac.at">enrico.soranzo@boku.ac.at</a> to update the list of calibrated devices.</p>
|
| 382 |
+
</div>
|
| 383 |
+
</body>
|
| 384 |
+
</html>
|
| 385 |
+
"""
|
| 386 |
|
| 387 |
+
@app.get("/", response_class=HTMLResponse)
|
| 388 |
+
async def root():
|
| 389 |
+
"""Landing page with API information"""
|
| 390 |
+
return HTML_CONTENT
|
| 391 |
+
|
| 392 |
+
@app.get("/health")
|
| 393 |
+
async def health():
|
| 394 |
+
"""Health check endpoint"""
|
| 395 |
return {
|
| 396 |
+
"status": "healthy",
|
| 397 |
+
"model_loaded": model is not None
|
|
|
|
|
|
|
|
|
|
|
|
|
| 398 |
}
|
| 399 |
|
| 400 |
+
@app.post("/analyze", response_model=AnalysisResponse, responses={
|
| 401 |
+
400: {"model": ErrorResponse, "description": "Bad Request"},
|
| 402 |
+
500: {"model": ErrorResponse, "description": "Internal Server Error"}
|
| 403 |
+
})
|
| 404 |
+
async def analyze_soil_image(file: UploadFile = File(...)):
|
| 405 |
+
"""
|
| 406 |
+
Analyze a soil image and return particle size distribution parameters.
|
| 407 |
+
|
| 408 |
+
Parameters:
|
| 409 |
+
- file: Image file (JPG, PNG, or JPEG)
|
| 410 |
+
|
| 411 |
+
Returns:
|
| 412 |
+
- B and C factors from the model
|
| 413 |
+
- Calculated soil parameters (d10, d30, d60, Cu, Cc)
|
| 414 |
+
- Soil fractions percentages (clay, silt, sand, gravel, boulder)
|
| 415 |
+
"""
|
| 416 |
+
|
| 417 |
+
# Validate file type
|
| 418 |
+
if not file.content_type or not file.content_type.startswith("image/"):
|
| 419 |
+
raise HTTPException(status_code=400, detail="File must be an image")
|
| 420 |
+
|
| 421 |
+
if model is None:
|
| 422 |
+
raise HTTPException(status_code=500, detail="Model not loaded")
|
| 423 |
+
|
| 424 |
+
try:
|
| 425 |
+
# Read image file
|
| 426 |
+
contents = await file.read()
|
| 427 |
+
image = PILImage.open(io.BytesIO(contents))
|
| 428 |
+
|
| 429 |
+
# Get original dimensions
|
| 430 |
+
original_width, original_height = image.size
|
| 431 |
+
|
| 432 |
+
# Process image
|
| 433 |
+
X, supported_device = process_image(image)
|
| 434 |
+
|
| 435 |
+
# Make prediction
|
| 436 |
+
predictions = model.predict(X, verbose=0)
|
| 437 |
+
|
| 438 |
+
# Extract predictions
|
| 439 |
+
predictions_b = predictions[0][0]
|
| 440 |
+
predictions_c = predictions[0][1]
|
| 441 |
+
|
| 442 |
+
# Calculate all parameters
|
| 443 |
+
results = calculate_soil_parameters(predictions_b, predictions_c)
|
| 444 |
+
|
| 445 |
+
return AnalysisResponse(
|
| 446 |
+
status="success",
|
| 447 |
+
b_factor=results["b_factor"],
|
| 448 |
+
c_factor=results["c_factor"],
|
| 449 |
+
parameters=SoilParameters(**results["parameters"]),
|
| 450 |
+
fractions=SoilFractions(**results["fractions"]),
|
| 451 |
+
supported_device=supported_device,
|
| 452 |
+
image_dimensions={
|
| 453 |
+
"width": original_width,
|
| 454 |
+
"height": original_height
|
| 455 |
+
}
|
| 456 |
+
)
|
| 457 |
+
|
| 458 |
+
except Exception as e:
|
| 459 |
+
raise HTTPException(
|
| 460 |
+
status_code=500,
|
| 461 |
+
detail=f"Error processing image: {str(e)}"
|
| 462 |
+
)
|
| 463 |
+
|
| 464 |
+
@app.post("/analyze_base64", response_model=AnalysisResponse, responses={
|
| 465 |
+
400: {"model": ErrorResponse, "description": "Bad Request"},
|
| 466 |
+
500: {"model": ErrorResponse, "description": "Internal Server Error"}
|
| 467 |
+
})
|
| 468 |
+
async def analyze_soil_image_base64(data: Dict[str, str]):
|
| 469 |
+
"""
|
| 470 |
+
Analyze a soil image provided as base64 string.
|
| 471 |
+
|
| 472 |
+
Parameters:
|
| 473 |
+
- data: JSON with 'image' field containing base64 encoded image
|
| 474 |
+
|
| 475 |
+
Returns:
|
| 476 |
+
- B and C factors from the model
|
| 477 |
+
- Calculated soil parameters
|
| 478 |
+
- Soil fractions percentages
|
| 479 |
+
"""
|
| 480 |
+
|
| 481 |
+
if "image" not in data:
|
| 482 |
+
raise HTTPException(status_code=400, detail="Missing 'image' field in request")
|
| 483 |
+
|
| 484 |
+
if model is None:
|
| 485 |
+
raise HTTPException(status_code=500, detail="Model not loaded")
|
| 486 |
+
|
| 487 |
+
try:
|
| 488 |
+
# Decode base64 image
|
| 489 |
+
image_data = base64.b64decode(data["image"])
|
| 490 |
+
image = PILImage.open(io.BytesIO(image_data))
|
| 491 |
+
|
| 492 |
+
# Get original dimensions
|
| 493 |
+
original_width, original_height = image.size
|
| 494 |
+
|
| 495 |
+
# Process image
|
| 496 |
+
X, supported_device = process_image(image)
|
| 497 |
+
|
| 498 |
+
# Make prediction
|
| 499 |
+
predictions = model.predict(X, verbose=0)
|
| 500 |
+
|
| 501 |
+
# Extract predictions
|
| 502 |
+
predictions_b = predictions[0][0]
|
| 503 |
+
predictions_c = predictions[0][1]
|
| 504 |
+
|
| 505 |
+
# Calculate all parameters
|
| 506 |
+
results = calculate_soil_parameters(predictions_b, predictions_c)
|
| 507 |
+
|
| 508 |
+
return AnalysisResponse(
|
| 509 |
+
status="success",
|
| 510 |
+
b_factor=results["b_factor"],
|
| 511 |
+
c_factor=results["c_factor"],
|
| 512 |
+
parameters=SoilParameters(**results["parameters"]),
|
| 513 |
+
fractions=SoilFractions(**results["fractions"]),
|
| 514 |
+
supported_device=supported_device,
|
| 515 |
+
image_dimensions={
|
| 516 |
+
"width": original_width,
|
| 517 |
+
"height": original_height
|
| 518 |
+
}
|
| 519 |
+
)
|
| 520 |
+
|
| 521 |
+
except Exception as e:
|
| 522 |
+
raise HTTPException(
|
| 523 |
+
status_code=500,
|
| 524 |
+
detail=f"Error processing image: {str(e)}"
|
| 525 |
+
)
|
| 526 |
+
|
| 527 |
if __name__ == "__main__":
|
| 528 |
import uvicorn
|
| 529 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|