File size: 2,271 Bytes
4474009
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b6ace6a
 
 
 
 
4474009
 
 
b6ace6a
 
 
 
 
 
 
4474009
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b6ace6a
 
4474009
 
 
b6ace6a
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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)