Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,173 +1,30 @@
|
|
| 1 |
-
import
|
| 2 |
-
import base64
|
| 3 |
-
import io
|
| 4 |
-
from pathlib import Path
|
| 5 |
-
|
| 6 |
-
# Fastai imports
|
| 7 |
from fastai.vision.all import *
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
from
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
except FileNotFoundError as e:
|
| 30 |
-
print(f"Error: {e}")
|
| 31 |
-
print("Please make sure 'model.pkl' is in the same directory as app.py.")
|
| 32 |
-
raise SystemExit(f"CRITICAL ERROR: Model file not found at {MODEL_PATH}. Application cannot start.")
|
| 33 |
-
except Exception as e:
|
| 34 |
-
print(f"CRITICAL ERROR: An unexpected error occurred loading the model: {e}")
|
| 35 |
-
raise SystemExit(f"CRITICAL ERROR: Failed to load model. Application cannot start. Error: {e}")
|
| 36 |
-
|
| 37 |
-
# --- FastHTML App Setup ---
|
| 38 |
-
app = FastHTML()
|
| 39 |
-
rt = app.route # Shortcut for the route decorator
|
| 40 |
-
|
| 41 |
-
# --- Helper Function for Prediction ---
|
| 42 |
-
def predict_image(img_bytes: bytes):
|
| 43 |
-
"""Takes image bytes, predicts using the fastai model."""
|
| 44 |
-
if not img_bytes:
|
| 45 |
-
return "Error: Image data is empty", 0.0
|
| 46 |
-
try:
|
| 47 |
-
# Create PILImage from bytes
|
| 48 |
-
img = PILImage.create(img_bytes)
|
| 49 |
-
# Get prediction from the learner
|
| 50 |
-
pred_class, pred_idx, probs = learn.predict(img)
|
| 51 |
-
# Get the confidence score for the predicted class
|
| 52 |
-
confidence = probs[pred_idx].item()
|
| 53 |
-
return pred_class, confidence
|
| 54 |
-
except Exception as e:
|
| 55 |
-
print(f"Error during prediction: {e}")
|
| 56 |
-
return f"Prediction Error: Could not process image ({e})", 0.0
|
| 57 |
-
|
| 58 |
-
# --- Define Routes ---
|
| 59 |
-
@rt("/")
|
| 60 |
-
async def get(request):
|
| 61 |
-
"""Serves the main page with the upload form."""
|
| 62 |
-
return Titled("Fastai Image Classifier",
|
| 63 |
-
Main(
|
| 64 |
-
H1("Upload an Image for Classification"),
|
| 65 |
-
# --- Form for uploading the image ---
|
| 66 |
-
Form(
|
| 67 |
-
# Positional argument: Div that contains the file input
|
| 68 |
-
Div(
|
| 69 |
-
FileInput(name="file", id="fileInput", cls="form-control", required=True, accept="image/*"),
|
| 70 |
-
cls="mb-3"
|
| 71 |
-
),
|
| 72 |
-
# Positional argument: Submit button
|
| 73 |
-
Button("Classify Image", type="submit", cls="btn btn-primary"),
|
| 74 |
-
# Keyword arguments: Form attributes
|
| 75 |
-
hx_post="/predict",
|
| 76 |
-
hx_target="#results",
|
| 77 |
-
hx_swap="innerHTML",
|
| 78 |
-
hx_encoding="multipart/form-data",
|
| 79 |
-
hx_indicator="#loading-spinner",
|
| 80 |
-
id="upload-form"
|
| 81 |
-
),
|
| 82 |
-
# --- Loading Indicator ---
|
| 83 |
-
Div(
|
| 84 |
-
Span("Loading...", cls="visually-hidden"),
|
| 85 |
-
id="loading-spinner", cls="htmx-indicator spinner-border mt-3",
|
| 86 |
-
role="status", style="display: none;"
|
| 87 |
-
),
|
| 88 |
-
# --- Results Area ---
|
| 89 |
-
Div(
|
| 90 |
-
id="results", cls="mt-4"
|
| 91 |
-
),
|
| 92 |
-
cls="container mt-4"
|
| 93 |
-
)
|
| 94 |
-
)
|
| 95 |
-
|
| 96 |
-
@rt("/predict", methods=["POST"])
|
| 97 |
-
async def post(request, file: Upload):
|
| 98 |
-
"""Handles image upload, performs prediction, and returns results as an HTML fragment."""
|
| 99 |
-
if not file or not file.filename:
|
| 100 |
-
return Div(
|
| 101 |
-
P("No file uploaded. Please select an image file.", cls="alert alert-warning mt-3"),
|
| 102 |
-
id="results"
|
| 103 |
-
)
|
| 104 |
-
|
| 105 |
-
allowed_extensions = {'.png', '.jpg', '.jpeg', '.gif', '.bmp', '.webp'}
|
| 106 |
-
file_ext = Path(file.filename).suffix.lower()
|
| 107 |
-
if file_ext not in allowed_extensions:
|
| 108 |
-
return Div(
|
| 109 |
-
P(f"Invalid file type: '{file_ext}'. Please upload an image ({', '.join(allowed_extensions)}).", cls="alert alert-danger mt-3"),
|
| 110 |
-
id="results"
|
| 111 |
-
)
|
| 112 |
-
|
| 113 |
-
print(f"Received file: {file.filename}, Content-Type: {file.content_type}, Size: {file.size}")
|
| 114 |
-
|
| 115 |
-
try:
|
| 116 |
-
img_bytes = await file.read() # Read the file content asynchronously
|
| 117 |
-
if not img_bytes:
|
| 118 |
-
return Div(
|
| 119 |
-
P("Uploaded file appears to be empty.", cls="alert alert-warning mt-3"),
|
| 120 |
-
id="results"
|
| 121 |
-
)
|
| 122 |
-
except Exception as e:
|
| 123 |
-
print(f"Error reading uploaded file: {e}")
|
| 124 |
-
return Div(
|
| 125 |
-
P(f"Error reading uploaded file: {e}", cls="alert alert-danger mt-3"),
|
| 126 |
-
id="results"
|
| 127 |
-
)
|
| 128 |
-
|
| 129 |
-
# --- Perform Prediction ---
|
| 130 |
-
prediction, confidence = predict_image(img_bytes)
|
| 131 |
-
|
| 132 |
-
# Encode image to base64 for preview (only if prediction was successful)
|
| 133 |
-
img_src = None
|
| 134 |
-
if "Error" not in str(prediction):
|
| 135 |
-
try:
|
| 136 |
-
img_base64 = base64.b64encode(img_bytes).decode('utf-8')
|
| 137 |
-
content_type = file.content_type if (file.content_type and file.content_type.startswith('image/')) else 'image/jpeg'
|
| 138 |
-
img_src = f"data:{content_type};base64,{img_base64}"
|
| 139 |
-
except Exception as e:
|
| 140 |
-
print(f"Error encoding image to base64: {e}")
|
| 141 |
-
|
| 142 |
-
result_cls = "alert alert-danger" if "Error" in str(prediction) else "alert alert-success"
|
| 143 |
-
|
| 144 |
-
return Div(
|
| 145 |
-
# Display image preview if available
|
| 146 |
-
(Img(src=img_src, alt="Uploaded Image Preview",
|
| 147 |
-
style="max-width: 300px; max-height: 300px; margin-top: 15px; margin-bottom: 10px; display: block; border: 1px solid #ddd;")
|
| 148 |
-
if img_src else P("Preview not available.")),
|
| 149 |
-
# Display prediction results or error message
|
| 150 |
-
Div(
|
| 151 |
-
P(Strong("Prediction: "), f"{prediction}"),
|
| 152 |
-
(P(Strong("Confidence: "), f"{confidence:.4f}") if "Error" not in str(prediction) else None),
|
| 153 |
-
cls=f"{result_cls} mt-3",
|
| 154 |
-
role="alert"
|
| 155 |
-
),
|
| 156 |
-
id="results",
|
| 157 |
-
hx_swap_oob="true"
|
| 158 |
-
)
|
| 159 |
-
|
| 160 |
-
# --- Add CSS/JS Headers ---
|
| 161 |
-
app.sheets.append(
|
| 162 |
-
Link(href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css", rel="stylesheet",
|
| 163 |
-
integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN", crossorigin="anonymous")
|
| 164 |
-
)
|
| 165 |
-
app.hdrs.append(
|
| 166 |
-
Script(src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js",
|
| 167 |
-
integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL", crossorigin="anonymous")
|
| 168 |
)
|
| 169 |
|
| 170 |
-
#
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
from fastai.vision.all import *
|
| 3 |
+
import skimage
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
learn = load_learner('model.pkl')
|
| 7 |
+
#from huggingface_hub import from_pretrained_fastai
|
| 8 |
+
#learn = from_pretrained_fastai("devdatanalytics/commonbean")
|
| 9 |
+
|
| 10 |
+
labels = learn.dls.vocab
|
| 11 |
+
def predict(img):
|
| 12 |
+
img = PILImage.create(img)
|
| 13 |
+
pred,pred_idx,probs = learn.predict(img)
|
| 14 |
+
return {labels[i]: float(probs[i]) for i in range(len(labels))}
|
| 15 |
+
|
| 16 |
+
#title = "Common beans diseases classfier"
|
| 17 |
+
#description = "An app for Common beans diseases Classisfication"
|
| 18 |
+
#article="<p style='text-align: center'>The app identifies and classifies common beans diseases: Anthracnose and Bean rust.</p>"
|
| 19 |
+
# Create the Gradio interface
|
| 20 |
+
interface = gr.Interface(
|
| 21 |
+
fn=predict,
|
| 22 |
+
inputs=gr.Image(),
|
| 23 |
+
outputs=gr.Label(num_top_classes=3)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
)
|
| 25 |
|
| 26 |
+
# Enable the queue to handle POST requests
|
| 27 |
+
interface.queue(api_open=True)
|
| 28 |
+
|
| 29 |
+
# Launch the interface
|
| 30 |
+
interface.launch()
|