gibhug's picture
Update app.py
74b5743 verified
Raw History Blame Contribute Delete
1.54 kB
from flask import Flask, request, jsonify
from PIL import Image, ImageOps
import numpy as np
import tensorflow as tf
import os
import io
app = Flask(__name__)
# Load model and labels
model = tf.saved_model.load("model")
with open("labels.txt", "r") as f:
labels = [line.strip() for line in f]
@app.route("/", methods=["GET"])
def home():
return jsonify({"message": "Flask API is live on Hugging Face Space"})
@app.route("/predict", methods=["POST"])
def predict():
if "file" not in request.files:
return jsonify({"error": "No file uploaded"}), 400
file = request.files["file"]
try:
# image = Image.open(io.BytesIO(file.read())).resize((224, 224))
# image = np.array(image).astype(np.float32) / 255.0
# image = np.expand_dims(image, axis=0)
image = Image.open(io.BytesIO(file.read())).resize((224, 224)).convert("RGB")
image = np.array(image).astype(np.float32) / 255.0
image = np.expand_dims(image, axis=0)
predictions = model(image)
predicted_index = int(np.argmax(predictions))
predicted_label = labels[predicted_index]
confidence = float(np.max(predictions))
return jsonify({
"label": predicted_label,
"confidence": round(confidence, 4)
})
except Exception as e:
return jsonify({"error": str(e)}), 500
if __name__ == '__main__':
port = int(os.getenv("PORT", 7860))
app.run(host='0.0.0.0', port=port, debug=True)
#app.run(host='0.0.0.0', port=port)