fschwartzer commited on
Commit
6c40417
1 Parent(s): bf69bd0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +13 -63
app.py CHANGED
@@ -6,12 +6,6 @@ from geopy.distance import geodesic
6
  import googlemaps
7
  from geopy.exc import GeocoderTimedOut
8
 
9
- # Function to calculate distance in meters between two coordinates
10
- def calculate_distance(lat1, lon1, lat2, lon2):
11
- coords_1 = (lat1, lon1)
12
- coords_2 = (lat2, lon2)
13
- return geodesic(coords_1, coords_2).meters
14
-
15
  # Function to apply KNN and return V_oferta values
16
  def knn_predict(df, target_column, features_columns, k=5):
17
  # Separate features and target variable
@@ -61,7 +55,6 @@ st.markdown(
61
  data = pd.read_excel('ven_fim_PEDÓ_nov_23.xlsx')
62
 
63
  # Initialize variables to avoid NameError
64
- selected_coords = 'Direcionada'
65
  radius_visible = True
66
  custom_address_initial = 'Centro, Lajeado - RS, Brazil' # Initial custom address
67
  custom_lat = data['latitude'].median()
@@ -69,15 +62,8 @@ custom_lon = data['longitude'].median()
69
  radius_in_meters = 1500
70
  filtered_data = data # Initialize with the entire dataset
71
 
72
- # Find the maximum distance between coordinates
73
- max_distance = 0
74
- for index, row in data.iterrows():
75
- distance = calculate_distance(row['latitude'], row['longitude'], data['latitude'].mean(), data['longitude'].mean())
76
- if distance > max_distance:
77
- max_distance = distance
78
-
79
  # Calculate a zoom level based on the maximum distance
80
- zoom_level = round(17 - np.log10(max_distance))
81
 
82
  # Set font to 'Quicksand' for title_html
83
  title_html = """
@@ -129,8 +115,6 @@ evo_html = """
129
 
130
  # Create a sidebar for controls
131
  with st.sidebar:
132
- #st.title('avalia.se')
133
-
134
  st.sidebar.markdown(title_html, unsafe_allow_html=True)
135
 
136
  # Add a dropdown for filtering "Tipo"
@@ -138,18 +122,8 @@ with st.sidebar:
138
 
139
  data_tipo = data[data['Tipo'] == selected_tipo]
140
 
141
- selected_coords = st.selectbox('Selecione o tipo de pesquisa', ['Ampla', 'Direcionada'])
142
-
143
- if selected_coords == 'Direcionada':
144
- custom_address = st.text_input('Informe o endereço', custom_address_initial)
145
- radius_visible = True # Show radius slider for custom coordinates
146
- # No need to initialize max_distance_all here
147
- else:
148
- custom_address = "Lajeado, Rio Grande do Sul, Brazil" # Default address
149
- radius_visible = False # Hide radius slider for random coordinates
150
- max_distance_all = 0 # Initialize max_distance_all here
151
-
152
- max_distance_all = 0 # Initialize max_distance_all here
153
 
154
  # Geocode the custom address using the Google Maps API
155
  gmaps = googlemaps.Client(key='AIzaSyDoJ6C7NE2CHqFcaHTnhreOfgJeTk4uSH0') # Replace with your API key
@@ -161,19 +135,7 @@ with st.sidebar:
161
  st.error("Erro: Não foi possível geocodificar o endereço fornecido. Por favor, verifique e tente novamente.")
162
 
163
  # Slider for setting the zoom level
164
- if selected_coords == 'Direcionada':
165
- zoom_level = st.slider('Nível de zoom', min_value=1, max_value=15, value=zoom_level)
166
- else:
167
- for index, row in data_tipo.iterrows():
168
- distance_all = calculate_distance(row['latitude'], row['longitude'], data_tipo['latitude'].mean(), data_tipo['longitude'].mean())
169
- if distance_all > max_distance_all:
170
- max_distance_all = distance_all
171
-
172
- # Calculate a zoom level based on the maximum distance of the entire dataset
173
- zoom_level_all = round(15 - np.log10(max_distance_all))
174
-
175
- # Slider for setting the zoom level based on the entire dataset
176
- zoom_level = st.slider('Nível de zoom', min_value=1, max_value=15, value=zoom_level_all)
177
 
178
  # Conditionally render the radius slider
179
  if radius_visible:
@@ -228,10 +190,8 @@ with st.sidebar:
228
  st.sidebar.markdown(evo_html, unsafe_allow_html=True)
229
 
230
 
231
- # Filter data based on the radius
232
- if selected_coords == 'Direcionada':
233
- filtered_data = data_tipo[data_tipo.apply(lambda x: calculate_distance(x['latitude'], x['longitude'], custom_lat, custom_lon), axis=1) <= radius_in_meters]
234
- filtered_data = filtered_data.dropna() # Drop rows with NaN values
235
 
236
  # Add a custom CSS class to the map container
237
  st.markdown(f"""<style>
@@ -244,26 +204,16 @@ st.markdown(f"""<style>
244
  # Determine which area feature to use for prediction
245
  filtered_data['area_feature'] = np.where(filtered_data['Apriv'] != 0, filtered_data['Apriv'], filtered_data['Atotal'])
246
 
247
- # Check if KNN should be applied
248
- if selected_coords == 'Direcionada' and radius_visible:
249
- # Apply KNN and get predicted V_oferta values
250
- predicted_V_oferta = knn_predict(filtered_data, 'V_oferta', ['latitude', 'longitude', 'area_feature']) # Update with your features
251
- # Add predicted V_oferta values to filtered_data
252
- filtered_data['Predicted_V_oferta'] = predicted_V_oferta
253
 
254
  # Display the map and filtered_data
255
  with st.container():
256
- if selected_coords == 'Direcionada':
257
- st.write("Filtered Data:", filtered_data) # Debug: Print filtered_data
258
- st.write("Zoom Level:", zoom_level) # Debug: Print zoom_level
259
- st.write("Custom Coordinates:", custom_lat, custom_lon) # Debug: Print custom coordinates
260
- st.map(filtered_data, zoom=zoom_level, use_container_width=True)
261
- elif selected_coords == 'Ampla':
262
- st.write("Complete Data:", data) # Debug: Print complete data
263
- st.write("Zoom Level:", zoom_level) # Debug: Print zoom_level
264
- st.map(data, zoom=zoom_level, use_container_width=True)
265
-
266
-
267
  # Display the predicted V_oferta values if applicable
268
  if 'Predicted_V_oferta' in filtered_data.columns:
269
  st.write("Valores (R$/m²) previstos com algoritmo KNN:")
 
6
  import googlemaps
7
  from geopy.exc import GeocoderTimedOut
8
 
 
 
 
 
 
 
9
  # Function to apply KNN and return V_oferta values
10
  def knn_predict(df, target_column, features_columns, k=5):
11
  # Separate features and target variable
 
55
  data = pd.read_excel('ven_fim_PEDÓ_nov_23.xlsx')
56
 
57
  # Initialize variables to avoid NameError
 
58
  radius_visible = True
59
  custom_address_initial = 'Centro, Lajeado - RS, Brazil' # Initial custom address
60
  custom_lat = data['latitude'].median()
 
62
  radius_in_meters = 1500
63
  filtered_data = data # Initialize with the entire dataset
64
 
 
 
 
 
 
 
 
65
  # Calculate a zoom level based on the maximum distance
66
+ zoom_level = 14
67
 
68
  # Set font to 'Quicksand' for title_html
69
  title_html = """
 
115
 
116
  # Create a sidebar for controls
117
  with st.sidebar:
 
 
118
  st.sidebar.markdown(title_html, unsafe_allow_html=True)
119
 
120
  # Add a dropdown for filtering "Tipo"
 
122
 
123
  data_tipo = data[data['Tipo'] == selected_tipo]
124
 
125
+ custom_address = st.text_input('Informe o endereço', custom_address_initial)
126
+ radius_visible = True # Show radius slider for custom coordinates
 
 
 
 
 
 
 
 
 
 
127
 
128
  # Geocode the custom address using the Google Maps API
129
  gmaps = googlemaps.Client(key='AIzaSyDoJ6C7NE2CHqFcaHTnhreOfgJeTk4uSH0') # Replace with your API key
 
135
  st.error("Erro: Não foi possível geocodificar o endereço fornecido. Por favor, verifique e tente novamente.")
136
 
137
  # Slider for setting the zoom level
138
+ zoom_level = st.slider('Nível de zoom', min_value=1, max_value=15, value=zoom_level)
 
 
 
 
 
 
 
 
 
 
 
 
139
 
140
  # Conditionally render the radius slider
141
  if radius_visible:
 
190
  st.sidebar.markdown(evo_html, unsafe_allow_html=True)
191
 
192
 
193
+ filtered_data = data_tipo[data_tipo.apply(lambda x: calculate_distance(x['latitude'], x['longitude'], custom_lat, custom_lon), axis=1) <= radius_in_meters]
194
+ filtered_data = filtered_data.dropna() # Drop rows with NaN values
 
 
195
 
196
  # Add a custom CSS class to the map container
197
  st.markdown(f"""<style>
 
204
  # Determine which area feature to use for prediction
205
  filtered_data['area_feature'] = np.where(filtered_data['Apriv'] != 0, filtered_data['Apriv'], filtered_data['Atotal'])
206
 
207
+ # Apply KNN and get predicted V_oferta values
208
+ predicted_V_oferta = knn_predict(filtered_data, 'V_oferta', ['latitude', 'longitude', 'area_feature']) # Update with your features
209
+ # Add predicted V_oferta values to filtered_data
210
+ filtered_data['Predicted_V_oferta'] = predicted_V_oferta
 
 
211
 
212
  # Display the map and filtered_data
213
  with st.container():
214
+ st.map(filtered_data, zoom=zoom_level, use_container_width=True)
215
+ st.write("Dados:", filtered_data) # Debug: Print filtered_data
216
+
 
 
 
 
 
 
 
 
217
  # Display the predicted V_oferta values if applicable
218
  if 'Predicted_V_oferta' in filtered_data.columns:
219
  st.write("Valores (R$/m²) previstos com algoritmo KNN:")