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