Update src/streamlit_app.py
Browse files- src/streamlit_app.py +49 -20
src/streamlit_app.py
CHANGED
|
@@ -27,32 +27,56 @@ st.markdown(
|
|
| 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 |
-
"""
|
|
|
|
|
|
|
| 32 |
try:
|
| 33 |
-
#
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
df.columns = [c.lower().replace(" ", "_") for c in df.columns]
|
| 38 |
-
|
| 39 |
except FileNotFoundError:
|
| 40 |
-
st.error("
|
| 41 |
return pd.DataFrame()
|
| 42 |
except Exception as e:
|
| 43 |
-
st.error(f"
|
| 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")
|
| 49 |
-
|
| 50 |
df = df.dropna(subset=["date"])
|
|
|
|
| 51 |
df["Date_Only"] = df["date"].dt.floor("d")
|
| 52 |
-
df["Hour"]
|
| 53 |
-
df["weekday"]
|
| 54 |
-
|
| 55 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
if "district" in df.columns:
|
| 57 |
df["District_Str"] = (
|
| 58 |
pd.to_numeric(df["district"], errors="coerce")
|
|
@@ -61,17 +85,22 @@ def load_crime_data():
|
|
| 61 |
df["District"] = df["District_Str"]
|
| 62 |
else:
|
| 63 |
df["District_Str"] = df["District"] = "-1"
|
| 64 |
-
|
| 65 |
if "community_area" not in df.columns:
|
| 66 |
df["community_area"] = None
|
| 67 |
-
|
| 68 |
def get_period(h):
|
| 69 |
-
if
|
| 70 |
-
|
| 71 |
-
elif
|
| 72 |
-
|
| 73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
df["Period"] = df["Hour"].apply(get_period)
|
|
|
|
| 75 |
return df
|
| 76 |
|
| 77 |
@st.cache_data(show_spinner="Loading socioeconomic data...")
|
|
|
|
| 27 |
# Data loading (Now using local CSV for extreme speedup)
|
| 28 |
# ---------------------------------------------------------------------------
|
| 29 |
@st.cache_data(show_spinner="Loading local Chicago crime data...")
|
| 30 |
+
@st.cache_data(show_spinner="Loading local Chicago crime data...")
|
| 31 |
def load_crime_data():
|
| 32 |
+
"""Robust loading for Hugging Face Spaces (handles path issues)."""
|
| 33 |
+
import os
|
| 34 |
+
|
| 35 |
try:
|
| 36 |
+
# ✅ 获取当前脚本所在目录(关键!!)
|
| 37 |
+
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 38 |
+
|
| 39 |
+
# ✅ 构造绝对路径
|
| 40 |
+
file_path = os.path.join(BASE_DIR, "Crimes_-_2026_20260417.csv")
|
| 41 |
+
|
| 42 |
+
# ✅ Debug信息(第一次部署时非常重要)
|
| 43 |
+
st.write("📂 Current working dir:", os.getcwd())
|
| 44 |
+
st.write("📂 BASE_DIR:", BASE_DIR)
|
| 45 |
+
st.write("📄 Files in BASE_DIR:", os.listdir(BASE_DIR))
|
| 46 |
+
st.write("📄 Trying to read:", file_path)
|
| 47 |
+
|
| 48 |
+
# ✅ 读取 CSV
|
| 49 |
+
df = pd.read_csv(file_path)
|
| 50 |
+
|
| 51 |
+
# 标准化列名
|
| 52 |
df.columns = [c.lower().replace(" ", "_") for c in df.columns]
|
| 53 |
+
|
| 54 |
except FileNotFoundError:
|
| 55 |
+
st.error("❌ CSV file not found. Check filename and path.")
|
| 56 |
return pd.DataFrame()
|
| 57 |
except Exception as e:
|
| 58 |
+
st.error(f"❌ Failed to read CSV: {e}")
|
| 59 |
return pd.DataFrame()
|
| 60 |
|
| 61 |
+
# -------------------------
|
| 62 |
+
# 后处理(你原来的逻辑)
|
| 63 |
+
# -------------------------
|
| 64 |
df["date"] = pd.to_datetime(df["date"], errors="coerce")
|
| 65 |
+
|
| 66 |
for col in ["latitude", "longitude"]:
|
| 67 |
df[col] = pd.to_numeric(df.get(col, pd.Series(dtype=float)), errors="coerce")
|
| 68 |
+
|
| 69 |
df = df.dropna(subset=["date"])
|
| 70 |
+
|
| 71 |
df["Date_Only"] = df["date"].dt.floor("d")
|
| 72 |
+
df["Hour"] = df["date"].dt.hour
|
| 73 |
+
df["weekday"] = df["date"].dt.day_name().str[:3]
|
| 74 |
+
|
| 75 |
+
df["Primary Type"] = (
|
| 76 |
+
df["primary_type"].str.upper()
|
| 77 |
+
if "primary_type" in df.columns else "UNKNOWN"
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
if "district" in df.columns:
|
| 81 |
df["District_Str"] = (
|
| 82 |
pd.to_numeric(df["district"], errors="coerce")
|
|
|
|
| 85 |
df["District"] = df["District_Str"]
|
| 86 |
else:
|
| 87 |
df["District_Str"] = df["District"] = "-1"
|
| 88 |
+
|
| 89 |
if "community_area" not in df.columns:
|
| 90 |
df["community_area"] = None
|
| 91 |
+
|
| 92 |
def get_period(h):
|
| 93 |
+
if 6 < h <= 12:
|
| 94 |
+
return "Morning (6am-12pm)"
|
| 95 |
+
elif 12 < h <= 18:
|
| 96 |
+
return "Afternoon (12pm-6pm)"
|
| 97 |
+
elif 18 < h <= 24:
|
| 98 |
+
return "Evening (6pm-12am)"
|
| 99 |
+
else:
|
| 100 |
+
return "Late Night (12am-6am)"
|
| 101 |
+
|
| 102 |
df["Period"] = df["Hour"].apply(get_period)
|
| 103 |
+
|
| 104 |
return df
|
| 105 |
|
| 106 |
@st.cache_data(show_spinner="Loading socioeconomic data...")
|