from flask import Flask, request, jsonify from tensorflow.keras.models import load_model from tensorflow.keras.preprocessing.image import load_img, img_to_array import numpy as np import io import os import requests from flask_cors import CORS app = Flask(_name_) CORS(app) # Hugging Face .h5 model URL MODEL_URL = "https://huggingface.co/vishwak1/plant/resolve/main/model.h5" MODEL_PATH = "model.h5" # Download the model if it doesn't exist if not os.path.exists(MODEL_PATH): print("Downloading model from Hugging Face...") response = requests.get(MODEL_URL) with open(MODEL_PATH, 'wb') as f: f.write(response.content) print("Model downloaded successfully.") # Load the trained model model = load_model(MODEL_PATH) @app.route('/predict', methods=['POST']) def predict(): if 'file' not in request.files: return jsonify({'error': 'No file part'}), 400 file = request.files['file'] if file.filename == '': return jsonify({'error': 'No selected file'}), 400 try: image_bytes = file.read() image = load_img(io.BytesIO(image_bytes), target_size=(225, 225)) # Match model input size x = img_to_array(image) x = x.astype('float32') / 255.0 x = np.expand_dims(x, axis=0) predictions = model.predict(x) predicted_class = int(np.argmax(predictions, axis=1)[0]) return jsonify({'predicted_class': predicted_class}) except Exception as e: return jsonify({'error': str(e)}), 500 if _name_ == '_main_': app.run(debug=True)