grai2API / app.py
soranz84's picture
Update app.py
3e408b2 verified
Raw History Blame Contribute Delete
14.3 kB
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
import numpy as np
import pandas as pd
import math
import os
import tensorflow as tf
from PIL import Image as PILImage
from huggingface_hub import hf_hub_download
import io
import base64
# model token
model_key = os.getenv("hf_token")
file_path = hf_hub_download("soranz84/grai2", "Model_047.h5",
token=model_key)
# 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="GRAI2 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
# Device-specific scaling
# Motorola Edge
if width == 1800 and height == 4000:
scale = 720/1800
elif width == 4000 and height == 1800:
scale = 720/1800
# Samsung A52
elif width == 6936 or width == 9248:
scale = 1600/9248
# iPhone 14
elif width == 3024 or width == 4032:
scale = 552/1673
# iPhone 16
elif width == 4284 or width == 5712:
scale = 368/1562
# Samsung A32 5G Aspect ratio 4:3
elif width == 6000 or width == 8000:
scale = 1334/7487
# Samsung A32 5G Aspect ratio 16:9
elif (width == 4000 and height == 2250) or (width == 2250 and height == 4000):
scale = 1334/3744
# Samsung Galaxy S23
elif (width == 4000 and height == 3000) or (width == 3000 and height == 4000):
scale = 1380/3746
else:
supported_device = False
# Default scaling for unsupported devices
scale = 1
# 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.mobilenet.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 = 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>GRAI2 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 #4CAF50;
}
code {
background-color: #f4f4f4;
padding: 2px 6px;
border-radius: 3px;
}
a {
color: #4CAF50;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<div class="container">
<h1>🌱 GRAI2 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-grai2api.hf.space/analyze</code>
<h2>Recommended Devices</h2>
<ul>
<li>Motorola Edge (1800x4000)</li>
<li>Samsung A52 (6936x9248)</li>
<li>iPhone 14 (3024x4032)</li>
</ul>
<h2>Other Supported Devices</h2>
<li>iPhone 16 (4284x5712)</li>
<li>Samsung A32 G5 (4000x2250)</li>
<li>Samsung Galaxy S23 (4000x3000)</li>
</ul>
</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)