XinyiC11 commited on
Commit
5a79afa
·
verified ·
1 Parent(s): ac58e5c

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +17 -31
src/streamlit_app.py CHANGED
@@ -24,39 +24,25 @@ st.markdown(
24
  )
25
 
26
  # ---------------------------------------------------------------------------
27
- # Data loading
28
  # ---------------------------------------------------------------------------
29
- @st.cache_data(show_spinner="Loading Chicago crime data (full dataset)...")
30
  def load_crime_data():
31
- """Fetch ALL 2026 records in batches. Bar/line/heatmap use the full df;
32
- only geo rendering on maps uses sampling."""
33
- all_chunks = []
34
- limit = 50000
35
- offset = 0
36
- while True:
37
- url = (
38
- "https://data.cityofchicago.org/resource/ijzp-q8t2.json"
39
- "?$where=year=2026"
40
- f"&$limit={limit}"
41
- f"&$offset={offset}"
42
- "&$order=date%20DESC"
43
- )
44
- try:
45
- chunk = pd.read_json(url)
46
- except Exception as e:
47
- st.error(f"Failed to load crime data at offset {offset}: {e}")
48
- break
49
- if chunk.empty:
50
- break
51
- all_chunks.append(chunk)
52
- if len(chunk) < limit:
53
- break
54
- offset += limit
55
-
56
- if not all_chunks:
57
  return pd.DataFrame()
58
-
59
- df = pd.concat(all_chunks, ignore_index=True)
 
 
60
  df["date"] = pd.to_datetime(df["date"], errors="coerce")
61
  for col in ["latitude", "longitude"]:
62
  df[col] = pd.to_numeric(df.get(col, pd.Series(dtype=float)), errors="coerce")
@@ -351,7 +337,7 @@ with col3:
351
  .properties(width=360, height=440, title="Chicago Poverty Rate by Community Area")
352
  )
353
 
354
- # --- FIX: Pre-aggregate data for geographic binning in Pandas ---
355
  # 舍入到 2 位小数创建了与 maxbins=50 相似的地理网格
356
  df_geo_binned = df_geo.copy()
357
  df_geo_binned['lat_bin'] = df_geo_binned['latitude'].round(2)
 
24
  )
25
 
26
  # ---------------------------------------------------------------------------
27
+ # Data loading (Now using local CSV for extreme speedup)
28
  # ---------------------------------------------------------------------------
29
+ @st.cache_data(show_spinner="Loading local Chicago crime data...")
30
  def load_crime_data():
31
+ """Read directly from the local CSV file instead of slow API pagination."""
32
+ try:
33
+ # 直接读取本地上传的 CSV 文件
34
+ df = pd.read_csv("Crimes_-_2026_20260417.csv")
35
+
36
+ # 将原本诸如 "Primary Type" 的表头标准化为 "primary_type" 以适配后续代码
37
+ df.columns = [c.lower().replace(" ", "_") for c in df.columns]
38
+
39
+ except FileNotFoundError:
40
+ st.error("找不到文件 'Crimes_-_2026_20260417.csv'。请确保它与此脚本位于同一目录下。")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  return pd.DataFrame()
42
+ except Exception as e:
43
+ st.error(f"读取本地数据失败: {e}")
44
+ return pd.DataFrame()
45
+
46
  df["date"] = pd.to_datetime(df["date"], errors="coerce")
47
  for col in ["latitude", "longitude"]:
48
  df[col] = pd.to_numeric(df.get(col, pd.Series(dtype=float)), errors="coerce")
 
337
  .properties(width=360, height=440, title="Chicago Poverty Rate by Community Area")
338
  )
339
 
340
+ # --- Pre-aggregate data for geographic binning in Pandas ---
341
  # 舍入到 2 位小数创建了与 maxbins=50 相似的地理网格
342
  df_geo_binned = df_geo.copy()
343
  df_geo_binned['lat_bin'] = df_geo_binned['latitude'].round(2)