Nicolas Pierson commited on
Commit
dd4ac24
·
unverified ·
1 Parent(s): 249e4ff
Files changed (1) hide show
  1. src/pages/1_Historical_Prices.py +107 -24
src/pages/1_Historical_Prices.py CHANGED
@@ -16,14 +16,19 @@ AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY")
16
  ROOT_DIR = "./data/"
17
  MISSING_VALUE_PLACEHOLDER = -1
18
 
 
19
  # --- Asynchronous Data Loading Functions ---
20
  async def async_load_file_s3(object_key: str) -> pd.DataFrame:
21
  if not AWS_S3_BUCKET or not AWS_ACCESS_KEY_ID or not AWS_SECRET_ACCESS_KEY:
22
- raise ValueError("AWS credentials or bucket name not set in environment variables.")
 
 
23
 
24
  session = get_session()
25
  async with session.create_client(
26
- "s3", aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY
 
 
27
  ) as s3_client:
28
  response = await s3_client.get_object(Bucket=AWS_S3_BUCKET, Key=object_key)
29
  status = response.get("ResponseMetadata", {}).get("HTTPStatusCode")
@@ -34,54 +39,80 @@ async def async_load_file_s3(object_key: str) -> pd.DataFrame:
34
  return pd.read_csv(io.StringIO(content.decode("utf-8")))
35
  raise ValueError(f"Unsuccessful S3 get_object response. Status - {status}")
36
 
 
37
  async def async_load_geojson_from_s3(object_key: str) -> dict:
38
  local_file_path = f"{ROOT_DIR}{object_key}"
39
  if os.path.exists(local_file_path):
40
  with open(local_file_path, "r") as f:
41
  return json.load(f)
42
 
 
43
  # Internal async function to gather all data loading tasks
44
  async def _load_all_data_async_internal():
45
- departements_df_task = async_load_file_s3("processed/housing/dataset_departements_housing_prices.csv")
46
- departements_geojson_task = async_load_geojson_from_s3("processed/referentiel/departements.geojson")
47
- communes_df_task = async_load_file_s3("processed/housing/dataset_housing_prices.csv")
48
- communes_geojson_task = async_load_geojson_from_s3("processed/referentiel/communes.geojson")
 
 
 
 
 
 
 
 
49
 
50
  return await asyncio.gather(
51
  departements_df_task,
52
  departements_geojson_task,
53
  communes_df_task,
54
- communes_geojson_task
55
  )
56
 
 
57
  @st.cache_resource
58
  def load_all_data_sync_wrapper():
59
  # This synchronous wrapper runs the async data loading
60
  return asyncio.run(_load_all_data_async_internal())
61
 
 
62
  # --- Helper for Color Scale ---
63
  def _generate_custom_colorscale(min_val, max_val):
64
  custom_colorscale = [[0.0, "lightgrey"]]
65
  reversed_rdylgn_colors = pcolors.diverging.RdYlGn[::-1]
66
 
67
- normalized_min_actual = (min_val - MISSING_VALUE_PLACEHOLDER) / (max_val - MISSING_VALUE_PLACEHOLDER)
68
- normalized_max_actual = (max_val - MISSING_VALUE_PLACEHOLDER) / (max_val - MISSING_VALUE_PLACEHOLDER)
 
 
 
 
69
 
70
  num_steps = len(reversed_rdylgn_colors)
71
  for i, color in enumerate(reversed_rdylgn_colors):
72
- normalized_point = normalized_min_actual + (normalized_max_actual - normalized_min_actual) * (i / (num_steps - 1))
 
 
73
  if normalized_point > 0.0:
74
  custom_colorscale.append([normalized_point, color])
75
  return sorted(custom_colorscale, key=lambda x: x[0])
76
 
 
77
  # --- Plotly Figure Generation Functions ---
78
  @st.cache_data
79
  def display_choropleth_map(df: pd.DataFrame, geojson_data: dict):
80
- df_agg = df[df["prixm2moyen"] > 0].groupby(["code_departement", "annee"])["prixm2moyen"].mean().reset_index()
 
 
 
 
 
81
  min_actual_prixm2moyen = df_agg["prixm2moyen"].min()
82
  max_actual_prixm2moyen = df_agg["prixm2moyen"].max()
83
 
84
- custom_colorscale = _generate_custom_colorscale(min_actual_prixm2moyen, max_actual_prixm2moyen)
 
 
85
 
86
  fig = px.choropleth_map(
87
  df_agg,
@@ -113,20 +144,27 @@ def display_choropleth_map(df: pd.DataFrame, geojson_data: dict):
113
  st.warning("No animation updatemenus found.")
114
  return fig
115
 
 
116
  @st.cache_data
117
  def display_choropleth_map_for_department(
118
- df: pd.DataFrame, department_code: str, geojson_data: dict,
119
- min_global_prixm2moyen: float, max_global_prixm2moyen: float
 
 
 
120
  ):
121
  df_filtered = df[df["code_departement"] == department_code].copy()
122
 
123
  filtered_features = [
124
- feature for feature in geojson_data["features"]
 
125
  if feature["properties"]["code"].startswith(department_code)
126
  ]
127
  filtered_geojson = {"type": "FeatureCollection", "features": filtered_features}
128
 
129
- custom_colorscale = _generate_custom_colorscale(min_global_prixm2moyen, max_global_prixm2moyen)
 
 
130
 
131
  center_lat, center_lon, zoom_level = 46.603354, 1.888334, 6
132
  if filtered_features:
@@ -137,9 +175,12 @@ def display_choropleth_map_for_department(
137
  center_lat, center_lon = department_centroid.y, department_centroid.x
138
  minx, miny, maxx, maxy = dissolved_department.total_bounds
139
  width, height = maxx - minx, maxy - miny
140
- if width < 0.2 and height < 0.2: zoom_level = 10
141
- elif width < 0.5 and height < 0.5: zoom_level = 9
142
- else: zoom_level = 8
 
 
 
143
 
144
  fig = px.choropleth_map(
145
  df_filtered,
@@ -171,19 +212,29 @@ def display_choropleth_map_for_department(
171
  st.warning("No animation updatemenus found.")
172
  return fig
173
 
 
174
  # --- Streamlit App Layout ---
175
  st.set_page_config(page_title="Oasis", page_icon=":house:", layout="wide")
176
 
177
  st.header("Historical Price - France")
178
  st.subheader("An overview of real estate prices in France from 2015 to 2024")
179
 
180
- st.write("This map shows the average price per square meter in French departments over the years, with a focus on climatic events.")
 
 
181
 
182
  with st.spinner("Loading data and preparing maps..."):
183
  # Call the synchronous wrapper function
184
- dataset_departements_housing_prices, departements_geojson, dataset_housing_prices, communes_geojson = load_all_data_sync_wrapper()
185
-
186
- min_global_commune_prixm2moyen = dataset_housing_prices[dataset_housing_prices["prixm2moyen"] > 0]["prixm2moyen"].min()
 
 
 
 
 
 
 
187
  max_global_commune_prixm2moyen = dataset_housing_prices["prixm2moyen"].max()
188
 
189
  fig_france = display_choropleth_map(
@@ -192,4 +243,36 @@ fig_france = display_choropleth_map(
192
  )
193
  st.plotly_chart(fig_france, use_container_width=True)
194
  st.write("Hover over the map to see detailed information for each department and year.")
195
- st.write("Missing values are represented in light grey.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  ROOT_DIR = "./data/"
17
  MISSING_VALUE_PLACEHOLDER = -1
18
 
19
+
20
  # --- Asynchronous Data Loading Functions ---
21
  async def async_load_file_s3(object_key: str) -> pd.DataFrame:
22
  if not AWS_S3_BUCKET or not AWS_ACCESS_KEY_ID or not AWS_SECRET_ACCESS_KEY:
23
+ raise ValueError(
24
+ "AWS credentials or bucket name not set in environment variables."
25
+ )
26
 
27
  session = get_session()
28
  async with session.create_client(
29
+ "s3",
30
+ aws_access_key_id=AWS_ACCESS_KEY_ID,
31
+ aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
32
  ) as s3_client:
33
  response = await s3_client.get_object(Bucket=AWS_S3_BUCKET, Key=object_key)
34
  status = response.get("ResponseMetadata", {}).get("HTTPStatusCode")
 
39
  return pd.read_csv(io.StringIO(content.decode("utf-8")))
40
  raise ValueError(f"Unsuccessful S3 get_object response. Status - {status}")
41
 
42
+
43
  async def async_load_geojson_from_s3(object_key: str) -> dict:
44
  local_file_path = f"{ROOT_DIR}{object_key}"
45
  if os.path.exists(local_file_path):
46
  with open(local_file_path, "r") as f:
47
  return json.load(f)
48
 
49
+
50
  # Internal async function to gather all data loading tasks
51
  async def _load_all_data_async_internal():
52
+ departements_df_task = async_load_file_s3(
53
+ "processed/housing/dataset_departements_housing_prices.csv"
54
+ )
55
+ departements_geojson_task = async_load_geojson_from_s3(
56
+ "processed/referentiel/departements.geojson"
57
+ )
58
+ communes_df_task = async_load_file_s3(
59
+ "processed/housing/dataset_housing_prices.csv"
60
+ )
61
+ communes_geojson_task = async_load_geojson_from_s3(
62
+ "processed/referentiel/communes.geojson"
63
+ )
64
 
65
  return await asyncio.gather(
66
  departements_df_task,
67
  departements_geojson_task,
68
  communes_df_task,
69
+ communes_geojson_task,
70
  )
71
 
72
+
73
  @st.cache_resource
74
  def load_all_data_sync_wrapper():
75
  # This synchronous wrapper runs the async data loading
76
  return asyncio.run(_load_all_data_async_internal())
77
 
78
+
79
  # --- Helper for Color Scale ---
80
  def _generate_custom_colorscale(min_val, max_val):
81
  custom_colorscale = [[0.0, "lightgrey"]]
82
  reversed_rdylgn_colors = pcolors.diverging.RdYlGn[::-1]
83
 
84
+ normalized_min_actual = (min_val - MISSING_VALUE_PLACEHOLDER) / (
85
+ max_val - MISSING_VALUE_PLACEHOLDER
86
+ )
87
+ normalized_max_actual = (max_val - MISSING_VALUE_PLACEHOLDER) / (
88
+ max_val - MISSING_VALUE_PLACEHOLDER
89
+ )
90
 
91
  num_steps = len(reversed_rdylgn_colors)
92
  for i, color in enumerate(reversed_rdylgn_colors):
93
+ normalized_point = normalized_min_actual + (
94
+ normalized_max_actual - normalized_min_actual
95
+ ) * (i / (num_steps - 1))
96
  if normalized_point > 0.0:
97
  custom_colorscale.append([normalized_point, color])
98
  return sorted(custom_colorscale, key=lambda x: x[0])
99
 
100
+
101
  # --- Plotly Figure Generation Functions ---
102
  @st.cache_data
103
  def display_choropleth_map(df: pd.DataFrame, geojson_data: dict):
104
+ df_agg = (
105
+ df[df["prixm2moyen"] > 0]
106
+ .groupby(["code_departement", "annee"])["prixm2moyen"]
107
+ .mean()
108
+ .reset_index()
109
+ )
110
  min_actual_prixm2moyen = df_agg["prixm2moyen"].min()
111
  max_actual_prixm2moyen = df_agg["prixm2moyen"].max()
112
 
113
+ custom_colorscale = _generate_custom_colorscale(
114
+ min_actual_prixm2moyen, max_actual_prixm2moyen
115
+ )
116
 
117
  fig = px.choropleth_map(
118
  df_agg,
 
144
  st.warning("No animation updatemenus found.")
145
  return fig
146
 
147
+
148
  @st.cache_data
149
  def display_choropleth_map_for_department(
150
+ df: pd.DataFrame,
151
+ department_code: str,
152
+ geojson_data: dict,
153
+ min_global_prixm2moyen: float,
154
+ max_global_prixm2moyen: float,
155
  ):
156
  df_filtered = df[df["code_departement"] == department_code].copy()
157
 
158
  filtered_features = [
159
+ feature
160
+ for feature in geojson_data["features"]
161
  if feature["properties"]["code"].startswith(department_code)
162
  ]
163
  filtered_geojson = {"type": "FeatureCollection", "features": filtered_features}
164
 
165
+ custom_colorscale = _generate_custom_colorscale(
166
+ min_global_prixm2moyen, max_global_prixm2moyen
167
+ )
168
 
169
  center_lat, center_lon, zoom_level = 46.603354, 1.888334, 6
170
  if filtered_features:
 
175
  center_lat, center_lon = department_centroid.y, department_centroid.x
176
  minx, miny, maxx, maxy = dissolved_department.total_bounds
177
  width, height = maxx - minx, maxy - miny
178
+ if width < 0.2 and height < 0.2:
179
+ zoom_level = 10
180
+ elif width < 0.5 and height < 0.5:
181
+ zoom_level = 9
182
+ else:
183
+ zoom_level = 8
184
 
185
  fig = px.choropleth_map(
186
  df_filtered,
 
212
  st.warning("No animation updatemenus found.")
213
  return fig
214
 
215
+
216
  # --- Streamlit App Layout ---
217
  st.set_page_config(page_title="Oasis", page_icon=":house:", layout="wide")
218
 
219
  st.header("Historical Price - France")
220
  st.subheader("An overview of real estate prices in France from 2015 to 2024")
221
 
222
+ st.write(
223
+ "This map shows the average price per square meter in French departments over the years, with a focus on climatic events."
224
+ )
225
 
226
  with st.spinner("Loading data and preparing maps..."):
227
  # Call the synchronous wrapper function
228
+ (
229
+ dataset_departements_housing_prices,
230
+ departements_geojson,
231
+ dataset_housing_prices,
232
+ communes_geojson,
233
+ ) = load_all_data_sync_wrapper()
234
+
235
+ min_global_commune_prixm2moyen = dataset_housing_prices[
236
+ dataset_housing_prices["prixm2moyen"] > 0
237
+ ]["prixm2moyen"].min()
238
  max_global_commune_prixm2moyen = dataset_housing_prices["prixm2moyen"].max()
239
 
240
  fig_france = display_choropleth_map(
 
243
  )
244
  st.plotly_chart(fig_france, use_container_width=True)
245
  st.write("Hover over the map to see detailed information for each department and year.")
246
+ st.write(
247
+ "Missing values are represented in light grey, while actual data is shown in a gradient from red (high prices) to green (low prices)."
248
+ )
249
+ st.write(
250
+ "Note: The color scale is customized to highlight missing values in light grey, while the actual data is represented using a reversed RdYlGn color scale, where red indicates higher prices and green indicates lower prices."
251
+ )
252
+
253
+ st.subheader("Select a Department to View Commune Prices")
254
+ selected_departement = st.selectbox(
255
+ "Select a Department",
256
+ options=dataset_housing_prices["code_departement"].unique(),
257
+ )
258
+
259
+ fig_department = display_choropleth_map_for_department(
260
+ dataset_housing_prices,
261
+ selected_departement,
262
+ communes_geojson,
263
+ min_global_commune_prixm2moyen,
264
+ max_global_commune_prixm2moyen,
265
+ )
266
+
267
+ st.subheader("Average Price per Square Meter in French Communes (2015-2024)")
268
+ st.plotly_chart(fig_department, use_container_width=True)
269
+ st.write("Hover over the map to see detailed information for each commune and year.")
270
+ st.write(
271
+ "Missing values are represented in light grey, while actual data is shown in a gradient from red (high prices) to green (low prices)."
272
+ )
273
+ st.write(
274
+ "Note: The color scale is customized to highlight missing values in light grey, while the actual data is represented using a reversed RdYlGn color scale, where red indicates higher prices and green indicates lower prices."
275
+ )
276
+ st.write(
277
+ "The map is animated by year, allowing you to see how the average price per square meter changes over time."
278
+ )