Rajkhanke007 commited on
Commit
8ba7382
·
verified ·
1 Parent(s): 788caba

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +241 -241
app.py CHANGED
@@ -1,241 +1,241 @@
1
- from flask import Flask, render_template, request
2
- import folium
3
- from folium.plugins import HeatMapWithTime, FeatureGroupSubGroup, HeatMap
4
- import pandas as pd
5
- import os
6
-
7
- app = Flask(__name__)
8
-
9
- # Load the dataset
10
- df = pd.read_csv('final_crop_historic_data_pkjk.csv')
11
- df.columns = ['State', 'District', 'Crop_Year', 'Season', 'Crop', 'Area', 'Production', 'Latitude', 'Longitude']
12
-
13
-
14
- @app.route('/')
15
- def home():
16
- return render_template('index.html', map_html="", selected_map="Home")
17
-
18
-
19
- @app.route('/prodction_analysis', methods=['GET', 'POST'])
20
- def production_analysis():
21
- crop_options = df['Crop'].unique().tolist()
22
- selected_crop = request.form.get('crop_type') if request.method == 'POST' else None
23
-
24
- if not selected_crop:
25
- return render_template('index.html', map_html="", selected_map="Production Analysis",
26
- crop_options=crop_options, selected_crop=None)
27
-
28
- crop_data = df[df['Crop'] == selected_crop]
29
-
30
- if crop_data.empty:
31
- return render_template('index.html', map_html="", selected_map="No Data Available",
32
- crop_options=crop_options, selected_crop=selected_crop)
33
-
34
- time_index = crop_data['Crop_Year'].unique()
35
- heatmap_data = [
36
- [[row['Latitude'], row['Longitude']] for _, row in crop_data[crop_data['Crop_Year'] == year].iterrows()]
37
- for year in time_index
38
- ]
39
-
40
- m = folium.Map(location=[20.5937, 78.9629], zoom_start=5)
41
- heatmap = HeatMapWithTime(
42
- heatmap_data,
43
- index=[str(year) for year in time_index],
44
- auto_play=True,
45
- max_opacity=0.6
46
- )
47
- heatmap.add_to(m)
48
-
49
- map_html = m._repr_html_()
50
- return render_template('index.html', map_html=map_html, selected_map="Production Heatmap Analysis",
51
- crop_options=crop_options, selected_crop=selected_crop)
52
-
53
-
54
- @app.route('/heatmap_analysis')
55
- def heatmap_analysis():
56
- global df # Declare df as global
57
- m = folium.Map(location=[20.5937, 78.9629], zoom_start=5)
58
- fg = folium.FeatureGroup(name="Crops")
59
- m.add_child(fg)
60
- df_sampled = df.sample(frac=0.005, random_state=42) # Use a different variable for sampled df
61
- for crop in df_sampled['Crop'].unique():
62
- subgroup = FeatureGroupSubGroup(fg, crop)
63
- m.add_child(subgroup)
64
- crop_data = df_sampled[df_sampled['Crop'] == crop]
65
-
66
- heatmap_data = [[row['Latitude'], row['Longitude']] for _, row in crop_data.iterrows()]
67
- HeatMap(heatmap_data).add_to(subgroup)
68
-
69
- folium.LayerControl(collapsed=False).add_to(m)
70
-
71
- map_html = m._repr_html_()
72
- return render_template('index.html', map_html=map_html, selected_map="Crop Heatmap Analysis")
73
-
74
-
75
- @app.route('/season_analysis')
76
- def season_analysis():
77
- global df # Declare df as global
78
-
79
- # Initialize the map centered over India with an appropriate zoom level
80
- m = folium.Map(location=[20.5937, 78.9629], zoom_start=5)
81
-
82
- # Sample a fraction of the dataframe for performance
83
- df_sampled = df.sample(frac=0.005, random_state=42)
84
-
85
- # Create a dictionary to store top 5 crops for each location
86
- top_crops = {}
87
-
88
- # Collect the top crops for each unique location (Latitude, Longitude)
89
- for _, row in df_sampled.iterrows():
90
- lat_lon = (row['Latitude'], row['Longitude'])
91
- crop = row['Crop']
92
- production = row['Production']
93
-
94
- if lat_lon not in top_crops:
95
- top_crops[lat_lon] = {'Season': row['Season'], 'Crops': {}, 'Area': row['Area']}
96
-
97
- if crop not in top_crops[lat_lon]['Crops']:
98
- top_crops[lat_lon]['Crops'][crop] = 0
99
- top_crops[lat_lon]['Crops'][crop] += production
100
-
101
- # Limit to top 5 crops for each location
102
- for location, data in top_crops.items():
103
- top_crops[location]['Crops'] = sorted(data['Crops'].items(), key=lambda x: x[1], reverse=True)[:5]
104
-
105
- # Add scatter points for each unique location with a different color for each season
106
- season_colors = {
107
- 'Kharif': 'orange',
108
- 'Rabi': 'green',
109
- 'Winter': 'blue',
110
- 'Autumn':'pink',
111
- 'Rabi':'brown',
112
- 'Summer':'yellow',
113
- 'Whole Year':'Red'
114
- }
115
-
116
- for (latitude, longitude), data in top_crops.items():
117
- season = data['Season']
118
- top_crop_list = data['Crops']
119
- area = data['Area']
120
-
121
- # Create a string for the top crops
122
- top_crops_str = "<br>".join([f"{crop[0]}: {crop[1]}" for crop in top_crop_list])
123
-
124
- # Add a scatter point to the map for each location
125
- folium.CircleMarker(
126
- location=[latitude, longitude],
127
- radius=7, # Fixed radius for scatter points
128
- color=season_colors.get(season, 'gray'), # Use season color or gray if not found
129
- fill=True,
130
- fill_color=season_colors.get(season, 'gray'),
131
- fill_opacity=0.7,
132
- tooltip=(f"Latitude: {latitude}<br>"
133
- f"Longitude: {longitude}<br>"
134
- f"Season: {season}<br>"
135
- f"Area: {area}<br>"
136
- f"Top 5 Crops:<br>{top_crops_str}")
137
- ).add_to(m)
138
-
139
- # Convert the map to HTML format for rendering
140
- map_html = m._repr_html_()
141
-
142
- # Render the map in the template
143
- return render_template('index.html', map_html=map_html, selected_map="Season Analysis")
144
-
145
-
146
- @app.route('/crop_analysis')
147
- def crop_analysis():
148
- global df # Declare df as global
149
- df_sampled = df.sample(frac=0.005, random_state=42) # Use a different variable for sampled df
150
- m = folium.Map(location=[20.5937, 78.9629], zoom_start=5)
151
-
152
- for district in df_sampled['District'].unique():
153
- district_data = df_sampled[df_sampled['District'] == district]
154
- top_crops = district_data.groupby('Crop')['Production'].sum().nlargest(5).index.tolist()
155
- lat, lon = district_data.iloc[0]['Latitude'], district_data.iloc[0]['Longitude']
156
-
157
- folium.Marker(
158
- location=[lat, lon],
159
- popup=f"<b>District:</b> {district}<br><b>Top 5 Crops:</b> {', '.join(top_crops)}",
160
- icon=folium.Icon(icon='arrow-up', color='green')
161
- ).add_to(m)
162
-
163
- map_html = m._repr_html_()
164
- return render_template('index.html', map_html=map_html, selected_map="District Crop Analysis")
165
-
166
-
167
- @app.route('/combined_analysis')
168
- def combined_analysis():
169
- global df # Declare df as global
170
-
171
- # Sample a fraction of the dataframe for performance
172
- df_sampled = df.sample(frac=0.005, random_state=42)
173
-
174
- # Create the map centered over India with an appropriate zoom level
175
- m = folium.Map(location=[20.5937, 78.9629], zoom_start=5)
176
-
177
- # Prepare heatmap data for area
178
- area_heat_data = [
179
- [row['Latitude'], row['Longitude'], row['Area']]
180
- for _, row in df_sampled.iterrows()
181
- ]
182
-
183
- # Add the heatmap for area (blue to red: low to high)
184
- HeatMap(
185
- data=area_heat_data,
186
- min_opacity=0.3,
187
- max_opacity=0.8,
188
- radius=15,
189
- blur=10,
190
- gradient={0.0: 'blue', 0.5: 'lightblue', 1.0: 'red'}
191
- ).add_to(m)
192
-
193
- # Prepare heatmap data for production
194
- production_heat_data = [
195
- [row['Latitude'], row['Longitude'], row['Production']]
196
- for _, row in df_sampled.iterrows()
197
- ]
198
-
199
- # Add the heatmap for production (green to red: low to high production)
200
- HeatMap(
201
- data=production_heat_data,
202
- min_opacity=0.3,
203
- max_opacity=0.8,
204
- radius=15,
205
- blur=10,
206
- gradient={0.0: 'green', 0.5: 'yellow', 1.0: 'red'}
207
- ).add_to(m)
208
-
209
- # Scatter plot for different seasons with distinct colors
210
- season_colors = {
211
- 'Kharif': 'purple',
212
- 'Rabi': 'orange',
213
- 'Rabi': 'cyan',
214
- 'Winter':'Yellow',
215
- 'Summer':'Green',
216
- 'Whole Year':'Red'
217
- }
218
-
219
- for _, row in df_sampled.iterrows():
220
- season = row['Season']
221
- color = season_colors.get(season, 'gray') # Default to gray if the season is not recognized
222
- folium.CircleMarker(
223
- location=[row['Latitude'], row['Longitude']],
224
- radius=5,
225
- color=color,
226
- fill=True,
227
- fill_opacity=0.7,
228
- tooltip=(f"District: {row['District']}<br>"
229
- f"Season: {row['Season']}<br>"
230
- f"Area: {row['Area']}<br>"
231
- f"Production: {row['Production']}")
232
- ).add_to(m)
233
-
234
- # Convert the map to HTML format
235
- map_html = m._repr_html_()
236
-
237
- # Render the map in the template
238
- return render_template('index.html', map_html=map_html, selected_map="Combined Area & Production Heatmaps")
239
-
240
- if __name__ == '__main__':
241
- app.run(debug=True)
 
1
+ from flask import Flask, render_template, request
2
+ import folium
3
+ from folium.plugins import HeatMapWithTime, FeatureGroupSubGroup, HeatMap
4
+ import pandas as pd
5
+ import os
6
+
7
+ app = Flask(__name__)
8
+
9
+ # Load the dataset
10
+ df = pd.read_csv('final_crop_historic_data_pkjk.csv')
11
+ df.columns = ['State', 'District', 'Crop_Year', 'Season', 'Crop', 'Area', 'Production', 'Latitude', 'Longitude']
12
+
13
+
14
+ @app.route('/')
15
+ def home():
16
+ return render_template('index.html', map_html="", selected_map="Home")
17
+
18
+
19
+ @app.route('/prodction_analysis', methods=['GET', 'POST'])
20
+ def production_analysis():
21
+ crop_options = df['Crop'].unique().tolist()
22
+ selected_crop = request.form.get('crop_type') if request.method == 'POST' else None
23
+
24
+ if not selected_crop:
25
+ return render_template('index.html', map_html="", selected_map="Production Analysis",
26
+ crop_options=crop_options, selected_crop=None)
27
+
28
+ crop_data = df[df['Crop'] == selected_crop]
29
+
30
+ if crop_data.empty:
31
+ return render_template('index.html', map_html="", selected_map="No Data Available",
32
+ crop_options=crop_options, selected_crop=selected_crop)
33
+
34
+ time_index = crop_data['Crop_Year'].unique()
35
+ heatmap_data = [
36
+ [[row['Latitude'], row['Longitude']] for _, row in crop_data[crop_data['Crop_Year'] == year].iterrows()]
37
+ for year in time_index
38
+ ]
39
+
40
+ m = folium.Map(location=[20.5937, 78.9629], zoom_start=5)
41
+ heatmap = HeatMapWithTime(
42
+ heatmap_data,
43
+ index=[str(year) for year in time_index],
44
+ auto_play=True,
45
+ max_opacity=0.6
46
+ )
47
+ heatmap.add_to(m)
48
+
49
+ map_html = m._repr_html_()
50
+ return render_template('index.html', map_html=map_html, selected_map="Production Heatmap Analysis",
51
+ crop_options=crop_options, selected_crop=selected_crop)
52
+
53
+
54
+ @app.route('/heatmap_analysis')
55
+ def heatmap_analysis():
56
+ global df # Declare df as global
57
+ m = folium.Map(location=[20.5937, 78.9629], zoom_start=5)
58
+ fg = folium.FeatureGroup(name="Crops")
59
+ m.add_child(fg)
60
+ df_sampled = df.sample(frac=0.005, random_state=42) # Use a different variable for sampled df
61
+ for crop in df_sampled['Crop'].unique():
62
+ subgroup = FeatureGroupSubGroup(fg, crop)
63
+ m.add_child(subgroup)
64
+ crop_data = df_sampled[df_sampled['Crop'] == crop]
65
+
66
+ heatmap_data = [[row['Latitude'], row['Longitude']] for _, row in crop_data.iterrows()]
67
+ HeatMap(heatmap_data).add_to(subgroup)
68
+
69
+ folium.LayerControl(collapsed=False).add_to(m)
70
+
71
+ map_html = m._repr_html_()
72
+ return render_template('index.html', map_html=map_html, selected_map="Crop Heatmap Analysis")
73
+
74
+
75
+ @app.route('/season_analysis')
76
+ def season_analysis():
77
+ global df # Declare df as global
78
+
79
+ # Initialize the map centered over India with an appropriate zoom level
80
+ m = folium.Map(location=[20.5937, 78.9629], zoom_start=5)
81
+
82
+ # Sample a fraction of the dataframe for performance
83
+ df_sampled = df.sample(frac=0.005, random_state=42)
84
+
85
+ # Create a dictionary to store top 5 crops for each location
86
+ top_crops = {}
87
+
88
+ # Collect the top crops for each unique location (Latitude, Longitude)
89
+ for _, row in df_sampled.iterrows():
90
+ lat_lon = (row['Latitude'], row['Longitude'])
91
+ crop = row['Crop']
92
+ production = row['Production']
93
+
94
+ if lat_lon not in top_crops:
95
+ top_crops[lat_lon] = {'Season': row['Season'], 'Crops': {}, 'Area': row['Area']}
96
+
97
+ if crop not in top_crops[lat_lon]['Crops']:
98
+ top_crops[lat_lon]['Crops'][crop] = 0
99
+ top_crops[lat_lon]['Crops'][crop] += production
100
+
101
+ # Limit to top 5 crops for each location
102
+ for location, data in top_crops.items():
103
+ top_crops[location]['Crops'] = sorted(data['Crops'].items(), key=lambda x: x[1], reverse=True)[:5]
104
+
105
+ # Add scatter points for each unique location with a different color for each season
106
+ season_colors = {
107
+ 'Kharif': 'orange',
108
+ 'Rabi': 'green',
109
+ 'Winter': 'blue',
110
+ 'Autumn':'pink',
111
+ 'Rabi':'brown',
112
+ 'Summer':'yellow',
113
+ 'Whole Year':'Red'
114
+ }
115
+
116
+ for (latitude, longitude), data in top_crops.items():
117
+ season = data['Season']
118
+ top_crop_list = data['Crops']
119
+ area = data['Area']
120
+
121
+ # Create a string for the top crops
122
+ top_crops_str = "<br>".join([f"{crop[0]}: {crop[1]}" for crop in top_crop_list])
123
+
124
+ # Add a scatter point to the map for each location
125
+ folium.CircleMarker(
126
+ location=[latitude, longitude],
127
+ radius=7, # Fixed radius for scatter points
128
+ color=season_colors.get(season, 'gray'), # Use season color or gray if not found
129
+ fill=True,
130
+ fill_color=season_colors.get(season, 'gray'),
131
+ fill_opacity=0.7,
132
+ tooltip=(f"Latitude: {latitude}<br>"
133
+ f"Longitude: {longitude}<br>"
134
+ f"Season: {season}<br>"
135
+ f"Area: {area}<br>"
136
+ f"Top 5 Crops:<br>{top_crops_str}")
137
+ ).add_to(m)
138
+
139
+ # Convert the map to HTML format for rendering
140
+ map_html = m._repr_html_()
141
+
142
+ # Render the map in the template
143
+ return render_template('index.html', map_html=map_html, selected_map="Season Analysis")
144
+
145
+
146
+ @app.route('/crop_analysis')
147
+ def crop_analysis():
148
+ global df # Declare df as global
149
+ df_sampled = df.sample(frac=0.005, random_state=42) # Use a different variable for sampled df
150
+ m = folium.Map(location=[20.5937, 78.9629], zoom_start=5)
151
+
152
+ for district in df_sampled['District'].unique():
153
+ district_data = df_sampled[df_sampled['District'] == district]
154
+ top_crops = district_data.groupby('Crop')['Production'].sum().nlargest(5).index.tolist()
155
+ lat, lon = district_data.iloc[0]['Latitude'], district_data.iloc[0]['Longitude']
156
+
157
+ folium.Marker(
158
+ location=[lat, lon],
159
+ popup=f"<b>District:</b> {district}<br><b>Top 5 Crops:</b> {', '.join(top_crops)}",
160
+ icon=folium.Icon(icon='arrow-up', color='green')
161
+ ).add_to(m)
162
+
163
+ map_html = m._repr_html_()
164
+ return render_template('index.html', map_html=map_html, selected_map="District Crop Analysis")
165
+
166
+
167
+ @app.route('/combined_analysis')
168
+ def combined_analysis():
169
+ global df # Declare df as global
170
+
171
+ # Sample a fraction of the dataframe for performance
172
+ df_sampled = df.sample(frac=0.005, random_state=42)
173
+
174
+ # Create the map centered over India with an appropriate zoom level
175
+ m = folium.Map(location=[20.5937, 78.9629], zoom_start=5)
176
+
177
+ # Prepare heatmap data for area
178
+ area_heat_data = [
179
+ [row['Latitude'], row['Longitude'], row['Area']]
180
+ for _, row in df_sampled.iterrows()
181
+ ]
182
+
183
+ # Add the heatmap for area (blue to red: low to high)
184
+ HeatMap(
185
+ data=area_heat_data,
186
+ min_opacity=0.3,
187
+ max_opacity=0.8,
188
+ radius=15,
189
+ blur=10,
190
+ gradient={0.0: 'blue', 0.5: 'lightblue', 1.0: 'red'}
191
+ ).add_to(m)
192
+
193
+ # Prepare heatmap data for production
194
+ production_heat_data = [
195
+ [row['Latitude'], row['Longitude'], row['Production']]
196
+ for _, row in df_sampled.iterrows()
197
+ ]
198
+
199
+ # Add the heatmap for production (green to red: low to high production)
200
+ HeatMap(
201
+ data=production_heat_data,
202
+ min_opacity=0.3,
203
+ max_opacity=0.8,
204
+ radius=15,
205
+ blur=10,
206
+ gradient={0.0: 'green', 0.5: 'yellow', 1.0: 'red'}
207
+ ).add_to(m)
208
+
209
+ # Scatter plot for different seasons with distinct colors
210
+ season_colors = {
211
+ 'Kharif': 'purple',
212
+ 'Rabi': 'orange',
213
+ 'Rabi': 'cyan',
214
+ 'Winter':'Yellow',
215
+ 'Summer':'Green',
216
+ 'Whole Year':'Red'
217
+ }
218
+
219
+ for _, row in df_sampled.iterrows():
220
+ season = row['Season']
221
+ color = season_colors.get(season, 'gray') # Default to gray if the season is not recognized
222
+ folium.CircleMarker(
223
+ location=[row['Latitude'], row['Longitude']],
224
+ radius=5,
225
+ color=color,
226
+ fill=True,
227
+ fill_opacity=0.7,
228
+ tooltip=(f"District: {row['District']}<br>"
229
+ f"Season: {row['Season']}<br>"
230
+ f"Area: {row['Area']}<br>"
231
+ f"Production: {row['Production']}")
232
+ ).add_to(m)
233
+
234
+ # Convert the map to HTML format
235
+ map_html = m._repr_html_()
236
+
237
+ # Render the map in the template
238
+ return render_template('index.html', map_html=map_html, selected_map="Combined Area & Production Heatmaps")
239
+
240
+ if __name__ == '__main__':
241
+ app.run(port=7860,host='0.0.0.0')