Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from flask import Flask, request, jsonify
|
2 |
+
from fastai.vision.all import *
|
3 |
+
from huggingface_hub import from_pretrained_fastai
|
4 |
+
from PIL import Image
|
5 |
+
import io
|
6 |
+
|
7 |
+
app = Flask(__name__)
|
8 |
+
|
9 |
+
def classify_image(image_file):
|
10 |
+
# Load the trained model from Huggingface
|
11 |
+
learn = from_pretrained_fastai("devdatanalytics/commonbean")
|
12 |
+
|
13 |
+
# Open the image file
|
14 |
+
img = Image.open(image_file)
|
15 |
+
|
16 |
+
# Perform any necessary preprocessing on the image
|
17 |
+
# For example, resizing or normalization
|
18 |
+
img = img.resize((224, 224)) # Resize the image to match the model's input size
|
19 |
+
|
20 |
+
# Convert the image to a BytesIO object
|
21 |
+
img_bytes = io.BytesIO()
|
22 |
+
img.save(img_bytes, format='PNG')
|
23 |
+
img_bytes.seek(0)
|
24 |
+
|
25 |
+
# Perform the classification
|
26 |
+
pred_class, pred_idx, probs = learn.predict(img_bytes)
|
27 |
+
|
28 |
+
# Return the classification results
|
29 |
+
return f"Predicted Class: {pred_class}, Probability: {probs[pred_idx]:.2f}"
|
30 |
+
|
31 |
+
@app.route('/classify', methods=['POST'])
|
32 |
+
def classify():
|
33 |
+
if 'image' not in request.files:
|
34 |
+
return "No image file found", 400
|
35 |
+
|
36 |
+
image_file = request.files['image']
|
37 |
+
|
38 |
+
# Perform image classification
|
39 |
+
classification_results = classify_image(image_file)
|
40 |
+
|
41 |
+
return jsonify(classification_results)
|
42 |
+
|
43 |
+
if __name__ == '__main__':
|
44 |
+
app.run()
|