munnae commited on
Commit
e580512
·
verified ·
1 Parent(s): 6dbe984

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -0
app.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, jsonify
2
+ from transformers import pipeline
3
+ from PIL import Image
4
+ import io
5
+
6
+ app = Flask(__name__)
7
+
8
+ # Load model at startup
9
+ print("Loading model...")
10
+ classifier = pipeline("image-classification", model="Xenova/mobilenet_v2_1.0_224")
11
+ print("Model loaded successfully!")
12
+
13
+ @app.route('/')
14
+ def home():
15
+ return "Food Image Classifier API is running!"
16
+
17
+ @app.route('/classify', methods=['POST'])
18
+ def classify_image():
19
+ if 'file' not in request.files:
20
+ return jsonify({"error": "No file provided"}), 400
21
+
22
+ file = request.files['file']
23
+
24
+ try:
25
+ # Convert file to PIL image
26
+ image = Image.open(io.BytesIO(file.read()))
27
+
28
+ # Run classification
29
+ results = classifier(image)
30
+
31
+ # Get top result
32
+ if results:
33
+ prediction = {
34
+ "label": results[0]['label'],
35
+ "confidence": results[0]['score']
36
+ }
37
+ return jsonify(prediction)
38
+ else:
39
+ return jsonify({"error": "No results returned"}), 500
40
+
41
+ except Exception as e:
42
+ return jsonify({"error": str(e)}), 500
43
+
44
+ if __name__ == '__main__':
45
+ app.run(host="0.0.0.0", port=7860, debug=True)