-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
128 lines (109 loc) · 4.19 KB
/
app.py
File metadata and controls
128 lines (109 loc) · 4.19 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
from flask import Flask, render_template, request, jsonify, flash
from model import CropYieldPredictor, validate_input
import os
import traceback
app = Flask(__name__, static_folder='static', static_url_path='/static')
app.secret_key = 'your-secret-key-here' # Change this in production
# Global model instance
predictor = None
def initialize_app():
"""Initialize the Flask app with the trained model"""
global predictor
try:
predictor = CropYieldPredictor()
predictor.load_model('crop_yield_model.pkl')
print(" Model loaded successfully!")
return True
except Exception as e:
print(f" Failed to load model: {str(e)}")
print("Please run 'python train_model.py' first to train the model.")
return False
@app.route('/')
def home():
"""Home page with input form"""
return render_template('index.html')
@app.route('/predict', methods=['POST'])
def predict():
"""Handle prediction requests"""
try:
if predictor is None or not predictor.is_trained:
return jsonify({
'success': False,
'error': 'Model not loaded. Please contact administrator.'
})
# Get form data
input_data = {
'State': request.form.get('state', '').strip(),
'Crop_Year': request.form.get('crop_year', ''),
'Crop': request.form.get('crop', '').strip(),
'Season': request.form.get('season', '').strip(),
'Area': request.form.get('area', ''),
'Annual_Rainfall': request.form.get('rainfall', ''),
'Fertilizer': request.form.get('fertilizer', ''),
'Pesticide': request.form.get('pesticide', '')
}
# Convert numeric fields
numeric_fields = ['Crop_Year', 'Area', 'Annual_Rainfall', 'Fertilizer', 'Pesticide']
for field in numeric_fields:
try:
input_data[field] = float(input_data[field]) if input_data[field] else 0.0
except (ValueError, TypeError):
return jsonify({
'success': False,
'error': f'Invalid value for {field}. Please enter a valid number.'
})
# Validate input
if not validate_input(input_data):
return jsonify({
'success': False,
'error': 'Please fill in all required fields with valid values.'
})
# Make prediction
prediction = predictor.predict_yield(input_data)
# Get feature importance for this prediction
feature_importance = predictor.get_feature_importance()
return jsonify({
'success': True,
'prediction': round(prediction, 2),
'input_data': input_data,
'feature_importance': feature_importance
})
except Exception as e:
print(f"Prediction error: {str(e)}")
traceback.print_exc()
return jsonify({
'success': False,
'error': f'Prediction failed: {str(e)}'
})
@app.route('/results')
def results():
"""Display prediction results"""
return render_template('results.html')
@app.route('/api/model-info')
def model_info():
"""Get model information"""
if predictor is None or not predictor.is_trained:
return jsonify({'error': 'Model not loaded'})
try:
feature_importance = predictor.get_feature_importance()
return jsonify({
'feature_importance': feature_importance,
'feature_columns': predictor.feature_columns
})
except Exception as e:
return jsonify({'error': str(e)})
@app.errorhandler(404)
def not_found(error):
return render_template('index.html'), 404
@app.errorhandler(500)
def internal_error(error):
return jsonify({'error': 'Internal server error'}), 500
if __name__ == '__main__':
print(" Starting MyFarm Application...")
if initialize_app():
print(" Flask app is running!")
print(" Open your browser and go to: http://localhost:5000")
app.run(debug=True, host='0.0.0.0', port=5000)
else:
print(" Failed to start application. Model not available.")
print("Please run: python train_model.py")