Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from flask import Flask, request, jsonify
|
2 |
+
from PIL import Image
|
3 |
+
import torch
|
4 |
+
from torchvision import transforms, models
|
5 |
+
|
6 |
+
# Initialize Flask app
|
7 |
+
app = Flask(__name__)
|
8 |
+
|
9 |
+
# Load the trained model
|
10 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
11 |
+
|
12 |
+
# Define the model architecture
|
13 |
+
model = models.resnet152()
|
14 |
+
model.fc = torch.nn.Linear(model.fc.in_features, 26) # Adjust for the number of classes
|
15 |
+
model.load_state_dict(torch.load("model.pth", map_location=device))
|
16 |
+
model = model.to(device)
|
17 |
+
model.eval()
|
18 |
+
|
19 |
+
# Define preprocessing for the input image
|
20 |
+
preprocess = transforms.Compose([
|
21 |
+
transforms.Resize((224, 224)),
|
22 |
+
transforms.ToTensor(),
|
23 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
|
24 |
+
])
|
25 |
+
|
26 |
+
# Class labels (replace with your dataset's classes)
|
27 |
+
CLASS_LABELS = [
|
28 |
+
"bluebell", "buttercup", "colts_foot", "corn_poppy", "cowslip",
|
29 |
+
"crocus", "daffodil", "daisy", "dandelion", "foxglove",
|
30 |
+
"fritillary", "geranium", "hibiscus", "iris", "lily_valley",
|
31 |
+
"pansy", "petunia", "rose", "snowdrop", "sunflower",
|
32 |
+
"tigerlily", "tulip", "wallflower", "water_lily", "wild_tulip",
|
33 |
+
"windflower"
|
34 |
+
]
|
35 |
+
|
36 |
+
@app.route("/predict", methods=["POST"])
|
37 |
+
def predict():
|
38 |
+
if "file" not in request.files:
|
39 |
+
return jsonify({"error": "No file uploaded"}), 400
|
40 |
+
|
41 |
+
file = request.files["file"]
|
42 |
+
|
43 |
+
try:
|
44 |
+
# Load and preprocess the image
|
45 |
+
image = Image.open(file.stream).convert("RGB")
|
46 |
+
input_tensor = preprocess(image).unsqueeze(0).to(device)
|
47 |
+
|
48 |
+
# Perform inference
|
49 |
+
with torch.no_grad():
|
50 |
+
outputs = model(input_tensor)
|
51 |
+
_, predicted_class = torch.max(outputs, 1)
|
52 |
+
|
53 |
+
predicted_label = CLASS_LABELS[predicted_class.item()]
|
54 |
+
return jsonify({"predicted_class": predicted_label})
|
55 |
+
|
56 |
+
except Exception as e:
|
57 |
+
return jsonify({"error": f"Error during prediction: {str(e)}"}), 500
|
58 |
+
|
59 |
+
# Run the app (Hugging Face Spaces requires `app.run()` here)
|
60 |
+
if __name__ == "__main__":
|
61 |
+
app.run(host="0.0.0.0", port=8080)
|