import pandas as pd from flask import Flask, request, jsonify from flask_cors import CORS from sklearn.preprocessing import LabelEncoder from xgboost import XGBClassifier import joblib app = Flask(__name__) CORS(app) # Load the model and label encoder model = joblib.load('crop_model.pkl') label_encoder = joblib.load('label_encoder.pkl') # Define preprocessing function def preprocess_input(form_data): """Ensure input data matches the model's requirements.""" required_columns = ['N', 'P', 'K', 'temperature', 'humidity', 'ph', 'rainfall'] input_data = pd.DataFrame([form_data], columns=required_columns) return input_data # Define prediction function def predict(input_data): """Predict the crop label for given input data.""" predictions = model.predict(input_data) decoded_predictions = label_encoder.inverse_transform(predictions) return decoded_predictions[0] @app.route('/', methods=['GET']) def health_check(): """Health check endpoint.""" return jsonify({'status': 'healthy', 'message': 'CropSmartAI API is running'}) @app.route('/predict', methods=['POST']) def get_prediction(): """Receive input data, preprocess, and return crop prediction.""" if not request.json: return jsonify({'error': 'No input data provided'}), 400 required_fields = ['N', 'P', 'K', 'temperature', 'humidity', 'ph', 'rainfall'] if not all(field in request.json for field in required_fields): return jsonify({'error': 'Missing required fields'}), 400 try: print("here") # Get the input JSON data from the request form_data = request.json print(form_data) # Preprocess the input data preprocessed_data = preprocess_input(form_data) # Get the prediction from the model predicted_label = predict(preprocessed_data) print(predicted_label) # Return the prediction as a JSON response return jsonify({'crop': predicted_label}) except Exception as e: response = jsonify({'error': f'Prediction error: {str(e)}'}) return response, 500 if __name__ == '__main__': # Update to use port 7860 to match Hugging Face Spaces requirements app.run(host='0.0.0.0', port=7860, debug=False)