Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,529 +1,232 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
|
| 2 |
-
|
| 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 |
-
|
| 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
|
| 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
|
| 146 |
-
b_factor: float
|
| 147 |
-
c_factor: float
|
| 148 |
-
parameters: SoilParameters
|
| 149 |
-
fractions: SoilFractions
|
| 150 |
-
supported_device: bool
|
| 151 |
-
image_dimensions: Dict[str, int]
|
| 152 |
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
"""
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 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 |
-
#
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
#
|
| 203 |
-
|
| 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 |
-
|
| 238 |
-
X = []
|
| 239 |
-
X.append([red_list, green_list, blue_list])
|
| 240 |
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 244 |
|
| 245 |
-
|
| 246 |
-
X = tf.transpose(X, perm=[0, 2, 3, 1])
|
| 247 |
|
| 248 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 249 |
|
| 250 |
-
|
|
|
|
|
|
|
| 251 |
"""
|
| 252 |
-
|
|
|
|
|
|
|
| 253 |
"""
|
| 254 |
-
#
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 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 |
-
"
|
| 282 |
-
"
|
| 283 |
-
"
|
| 284 |
-
|
| 285 |
-
|
| 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 |
-
|
| 300 |
-
|
| 301 |
-
|
| 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 |
-
"
|
| 397 |
-
"
|
|
|
|
|
|
|
| 398 |
}
|
| 399 |
|
| 400 |
-
|
| 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 |
-
|
| 465 |
-
|
| 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 |
-
|
| 473 |
-
|
|
|
|
|
|
|
| 474 |
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
- Calculated soil parameters
|
| 478 |
-
- Soil fractions percentages
|
| 479 |
-
"""
|
| 480 |
|
| 481 |
-
if
|
| 482 |
-
|
| 483 |
|
| 484 |
-
|
| 485 |
-
|
|
|
|
| 486 |
|
| 487 |
try:
|
| 488 |
-
#
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 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
|
| 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 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
|
|
|
|
|
|
|
|
|
| 526 |
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
grai3 API with API Key Protection
|
| 3 |
+
=================================
|
| 4 |
+
Instructions:
|
| 5 |
+
1. Replace "YOUR_MODEL_CODE_HERE" with your actual model prediction
|
| 6 |
+
2. Add your API keys in the VALID_API_KEYS dictionary below
|
| 7 |
+
3. Add keys for free trial users and paying customers
|
| 8 |
+
"""
|
| 9 |
|
| 10 |
+
import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
import os
|
| 12 |
+
from PIL import Image
|
|
|
|
|
|
|
|
|
|
| 13 |
import io
|
| 14 |
+
import json
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
+
# ============= CONFIGURATION =============
|
| 17 |
+
# ADD YOUR API KEYS HERE
|
| 18 |
+
# Format: "key_name": {"uses": 0, "max_uses": 100, "plan": "plan_name"}
|
| 19 |
|
| 20 |
+
VALID_API_KEYS = {
|
| 21 |
+
# FREE TRIAL KEYS (1 use each)
|
| 22 |
+
# Users get these for free from your website
|
| 23 |
+
"free_001": {"uses": 0, "max_uses": 1, "plan": "free", "name": "Free Trial"},
|
| 24 |
+
"free_002": {"uses": 0, "max_uses": 1, "plan": "free", "name": "Free Trial"},
|
| 25 |
+
"free_003": {"uses": 0, "max_uses": 1, "plan": "free", "name": "Free Trial"},
|
| 26 |
+
"free_004": {"uses": 0, "max_uses": 1, "plan": "free", "name": "Free Trial"},
|
| 27 |
+
"free_005": {"uses": 0, "max_uses": 1, "plan": "free", "name": "Free Trial"},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
+
# PREMIUM KEYS (add customer keys here)
|
| 30 |
+
# Example: "customer_john": {"uses": 0, "max_uses": 100, "plan": "premium", "name": "John Smith"},
|
| 31 |
+
|
| 32 |
+
# DATA PARTNERSHIP KEYS
|
| 33 |
+
# Example: "data_partner_xyz": {"uses": 0, "max_uses": 500, "plan": "data_partner", "name": "XYZ Lab"},
|
| 34 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
+
# ============= HELPER FUNCTIONS =============
|
|
|
|
|
|
|
| 37 |
|
| 38 |
+
def validate_api_key(api_key):
|
| 39 |
+
"""Validate API key and return (is_valid, message, plan, name)"""
|
| 40 |
+
if not api_key:
|
| 41 |
+
return False, "โ No API key. Add ?api_key=YOUR_KEY to URL or enter below.", None, None
|
| 42 |
+
|
| 43 |
+
if api_key not in VALID_API_KEYS:
|
| 44 |
+
return False, "โ Invalid API key. Contact enrico@deepsoil.at to get access.", None, None
|
| 45 |
+
|
| 46 |
+
key_data = VALID_API_KEYS[api_key]
|
| 47 |
+
|
| 48 |
+
if key_data["uses"] >= key_data["max_uses"]:
|
| 49 |
+
return False, f"โ Limit reached ({key_data['max_uses']} uses). Contact us to upgrade.", None, None
|
| 50 |
+
|
| 51 |
+
# Increment usage
|
| 52 |
+
VALID_API_KEYS[api_key]["uses"] += 1
|
| 53 |
|
| 54 |
+
return True, f"โ Valid ({key_data['plan']})", key_data["plan"], key_data.get("name", "Unknown")
|
|
|
|
| 55 |
|
| 56 |
+
def get_api_key_from_request(req):
|
| 57 |
+
"""Extract API key from request"""
|
| 58 |
+
# Try query parameter: ?api_key=xxx
|
| 59 |
+
api_key = req.query_params.get("api_key", None)
|
| 60 |
+
|
| 61 |
+
# Try header: X-API-Key
|
| 62 |
+
if not api_key:
|
| 63 |
+
api_key = req.headers.get("X-API-Key", None)
|
| 64 |
+
|
| 65 |
+
return api_key
|
| 66 |
|
| 67 |
+
# ============= YOUR MODEL - REPLACE THIS =============
|
| 68 |
+
# REPLACE THIS FUNCTION WITH YOUR ACTUAL MODEL CODE
|
| 69 |
+
def run_model(image):
|
| 70 |
"""
|
| 71 |
+
YOUR ACTUAL MODEL PREDICTION CODE GOES HERE
|
| 72 |
+
|
| 73 |
+
This is a placeholder - replace with your real model inference
|
| 74 |
"""
|
| 75 |
+
# Your model code here, e.g.:
|
| 76 |
+
# model = load_model()
|
| 77 |
+
# result = model.predict(image)
|
| 78 |
+
# return result
|
| 79 |
+
|
| 80 |
+
# Placeholder return:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
return {
|
| 82 |
+
"d10": 0.023,
|
| 83 |
+
"d30": 0.085,
|
| 84 |
+
"d60": 0.250,
|
| 85 |
+
"Cu": 10.87,
|
| 86 |
+
"Cc": 1.24
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
}
|
| 88 |
|
| 89 |
+
def get_fractions_from_parameters(params):
|
| 90 |
+
"""Convert parameters to fractions (placeholder)"""
|
| 91 |
+
# Your actual conversion logic here
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
return {
|
| 93 |
+
"clay": 5.2,
|
| 94 |
+
"silt": 22.8,
|
| 95 |
+
"sand": 58.5,
|
| 96 |
+
"gravel": 13.5
|
| 97 |
}
|
| 98 |
|
| 99 |
+
# ============= MAIN PREDICTION FUNCTION =============
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
|
| 101 |
+
def predict(image, api_key_input, req: gr.Request):
|
| 102 |
+
"""Main prediction function with API key validation"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
|
| 104 |
+
# Get API key from request or input field
|
| 105 |
+
api_key = get_api_key_from_request(req)
|
| 106 |
+
if not api_key and api_key_input:
|
| 107 |
+
api_key = api_key_input
|
| 108 |
|
| 109 |
+
# Validate API key
|
| 110 |
+
is_valid, message, plan, name = validate_api_key(api_key)
|
|
|
|
|
|
|
|
|
|
| 111 |
|
| 112 |
+
if not is_valid:
|
| 113 |
+
return {"error": message}
|
| 114 |
|
| 115 |
+
# Run the model
|
| 116 |
+
if image is None:
|
| 117 |
+
return {"error": "โ Please upload an image"}
|
| 118 |
|
| 119 |
try:
|
| 120 |
+
# Your model prediction
|
| 121 |
+
parameters = run_model(image)
|
| 122 |
+
fractions = get_fractions_from_parameters(parameters)
|
| 123 |
+
|
| 124 |
+
result = {
|
| 125 |
+
"status": "success",
|
| 126 |
+
"plan": plan,
|
| 127 |
+
"remaining_uses": VALID_API_KEYS[api_key]["max_uses"] - VALID_API_KEYS[api_key]["uses"],
|
| 128 |
+
"parameters": parameters,
|
| 129 |
+
"fractions": fractions
|
| 130 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
|
| 132 |
+
return result
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
|
| 134 |
except Exception as e:
|
| 135 |
+
return {"error": f"โ Prediction error: {str(e)}"}
|
| 136 |
+
|
| 137 |
+
# ============= GRADIO UI =============
|
| 138 |
+
|
| 139 |
+
css = """
|
| 140 |
+
.gradio-container {max-width: 1200px !important;}
|
| 141 |
+
"""
|
| 142 |
|
| 143 |
+
with gr.Blocks(css=css, title="grai3 - AI Soil Analysis") as demo:
|
| 144 |
+
gr.Markdown("""
|
| 145 |
+
# ๐ฑ grai3: AI-Powered Soil Analysis
|
| 146 |
+
|
| 147 |
+
**Revolutionize your soil analysis with AI**
|
| 148 |
+
|
| 149 |
+
---
|
| 150 |
+
|
| 151 |
+
### ๐ API Access Required
|
| 152 |
+
|
| 153 |
+
**Option 1:** Add `?api_key=YOUR_KEY` to the URL
|
| 154 |
+
|
| 155 |
+
**Option 2:** Enter your API key below
|
| 156 |
+
|
| 157 |
+
**Get a key:** Contact enrico@deepsoil.at
|
| 158 |
+
|
| 159 |
+
---
|
| 160 |
+
""")
|
| 161 |
+
|
| 162 |
+
with gr.Row():
|
| 163 |
+
with gr.Column(scale=1):
|
| 164 |
+
gr.Markdown("### ๐ Input")
|
| 165 |
+
|
| 166 |
+
# API Key input
|
| 167 |
+
api_key_input = gr.Textbox(
|
| 168 |
+
label="API Key",
|
| 169 |
+
placeholder="Enter your API key",
|
| 170 |
+
info="Required for analysis"
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
# Image input
|
| 174 |
+
image_input = gr.Image(
|
| 175 |
+
type="pil",
|
| 176 |
+
label="Soil Sample Image",
|
| 177 |
+
height=400
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
# Submit button
|
| 181 |
+
submit_btn = gr.Button("๐ฌ Analyze Soil Sample", variant="primary", size="lg")
|
| 182 |
+
|
| 183 |
+
with gr.Column(scale=1):
|
| 184 |
+
gr.Markdown("### ๐ Results")
|
| 185 |
+
output = gr.JSON(label="Analysis Results")
|
| 186 |
+
|
| 187 |
+
# Connect button
|
| 188 |
+
submit_btn.click(
|
| 189 |
+
fn=predict,
|
| 190 |
+
inputs=[image_input, api_key_input],
|
| 191 |
+
outputs=output
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
# API documentation
|
| 195 |
+
gr.Markdown("""
|
| 196 |
+
---
|
| 197 |
+
|
| 198 |
+
### ๐ง API Usage
|
| 199 |
+
|
| 200 |
+
**cURL:**
|
| 201 |
+
```bash
|
| 202 |
+
curl -X POST "https://soranz84-grai3api.hf.space/analyze?api_key=YOUR_KEY" \\
|
| 203 |
+
-F "file=@soil_image.jpg"
|
| 204 |
+
```
|
| 205 |
+
|
| 206 |
+
**Python:**
|
| 207 |
+
```python
|
| 208 |
+
import requests
|
| 209 |
+
|
| 210 |
+
url = "https://soranz84-grai3api.hf.space/analyze"
|
| 211 |
+
files = {"file": open("soil.jpg", "rb")}
|
| 212 |
+
data = {"api_key": "YOUR_KEY"}
|
| 213 |
+
|
| 214 |
+
response = requests.post(url, files=files, data=data)
|
| 215 |
+
print(response.json())
|
| 216 |
+
```
|
| 217 |
+
|
| 218 |
+
**JavaScript:**
|
| 219 |
+
```javascript
|
| 220 |
+
const formData = new FormData();
|
| 221 |
+
formData.append('file', fileInput.files[0]);
|
| 222 |
+
formData.append('api_key', 'YOUR_KEY');
|
| 223 |
+
|
| 224 |
+
fetch('https://soranz84-grai3api.hf.space/analyze', {
|
| 225 |
+
method: 'POST',
|
| 226 |
+
body: formData
|
| 227 |
+
}).then(r => r.json()).then(console.log);
|
| 228 |
+
```
|
| 229 |
+
""")
|
| 230 |
+
|
| 231 |
+
# Launch
|
| 232 |
+
demo.queue().launch()
|