Spaces:
Configuration error
Configuration error
File size: 7,193 Bytes
03e7fda | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 | """
data_loader.py
--------------
Loads renovation project data from SQLite DB (primary) or CSV fallback.
Returns clean DataFrames with parsed dates and correct dtypes.
"""
import os
import pandas as pd
import numpy as np
from datetime import datetime
from sqlalchemy import create_engine
DATA_DIR = os.path.join(os.path.dirname(__file__), "data")
DB_PATH = os.path.join(DATA_DIR, "data.db")
DATE_COLS = {
"projects": ["planned_start", "planned_end", "actual_start", "actual_end"],
"activities": ["planned_start_date", "planned_end_date", "actual_start_date",
"actual_end_date", "forecasted_start_date", "forecasted_end_date"],
"daily_updates": ["date"],
"issues": ["date_raised"],
"resources": ["start_date", "end_date"],
}
REFERENCE_DATE = datetime(2024, 6, 1) # "today" for in-progress activities
class DataLoader:
"""Loads and caches all project data."""
def __init__(self, db_path: str = None, use_csv: bool = False):
self.db_path = db_path or DB_PATH
self.use_csv = use_csv
self._cache = {}
self._engine = None
def _get_engine(self):
if self._engine is None:
self._engine = create_engine(f"sqlite:///{self.db_path}")
return self._engine
def _load_table(self, table_name: str) -> pd.DataFrame:
if table_name in self._cache:
return self._cache[table_name]
df = None
# Try DB first
if not self.use_csv and os.path.exists(self.db_path):
try:
engine = self._get_engine()
df = pd.read_sql_table(table_name, engine)
except Exception:
df = None
# Fallback to CSV
if df is None:
csv_map = {
"projects": "projects.csv",
"activities": "activities.csv",
"daily_updates": "daily_updates.csv",
"issues": "issues.csv",
"boq": "boq.csv",
"resources": "resources.csv",
}
fname = csv_map.get(table_name)
if fname:
fpath = os.path.join(DATA_DIR, fname)
if os.path.exists(fpath):
df = pd.read_csv(fpath)
if df is None:
df = pd.DataFrame()
return df
# Parse dates
for col in DATE_COLS.get(table_name, []):
if col in df.columns:
df[col] = pd.to_datetime(df[col], errors="coerce")
# Normalize column names for projects table
if table_name == "projects":
rename = {
"planned_start": "planned_start_date",
"planned_end": "planned_end_date",
"actual_start": "actual_start_date",
"actual_end": "actual_end_date",
}
df = df.rename(columns={k: v for k, v in rename.items() if k in df.columns and v not in df.columns})
self._cache[table_name] = df
return df
# ββ Public accessors ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@property
def projects(self) -> pd.DataFrame:
return self._load_table("projects")
@property
def activities(self) -> pd.DataFrame:
return self._load_table("activities")
@property
def daily_updates(self) -> pd.DataFrame:
return self._load_table("daily_updates")
@property
def issues(self) -> pd.DataFrame:
return self._load_table("issues")
@property
def boq(self) -> pd.DataFrame:
return self._load_table("boq")
@property
def resources(self) -> pd.DataFrame:
return self._load_table("resources")
# ββ Filtered views ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def get_historical_activities(self) -> pd.DataFrame:
"""Completed activities β used for training ML models."""
acts = self.activities
if acts.empty:
return acts
return acts[acts["status"] == "completed"].copy()
def get_active_activities(self, project_id: str = None) -> pd.DataFrame:
"""In-progress and not-started activities for a project (or all)."""
acts = self.activities
if acts.empty:
return acts
mask = acts["status"].isin(["in_progress", "not_started"])
if project_id:
mask &= acts["project_id"] == project_id
return acts[mask].copy()
def get_inprogress_projects(self) -> pd.DataFrame:
projs = self.projects
if projs.empty:
return projs
return projs[projs["status"] == "in_progress"].copy()
def get_project_activities(self, project_id: str) -> pd.DataFrame:
acts = self.activities
return acts[acts["project_id"] == project_id].copy()
def get_activity_updates(self, activity_id: str) -> pd.DataFrame:
upd = self.daily_updates
return upd[upd["activity_id"] == activity_id].sort_values("date").copy()
def get_activity_issues(self, activity_id: str = None, project_id: str = None) -> pd.DataFrame:
iss = self.issues
if activity_id:
iss = iss[iss["activity_id"] == activity_id]
if project_id:
iss = iss[iss["project_id"] == project_id]
return iss.copy()
def get_project_boq(self, project_id: str) -> pd.DataFrame:
b = self.boq
return b[b["project_id"] == project_id].copy()
def get_activity_boq(self, activity_id: str) -> pd.DataFrame:
b = self.boq
return b[b["activity_id"] == activity_id].copy()
def get_all_data(self) -> dict:
return {
"projects": self.projects,
"activities": self.activities,
"daily_updates": self.daily_updates,
"issues": self.issues,
"boq": self.boq,
"resources": self.resources,
}
def reference_date(self) -> datetime:
"""The 'today' reference for in-progress predictions."""
return REFERENCE_DATE
def clear_cache(self):
self._cache = {}
# Singleton for convenience
_loader = None
def get_loader(db_path: str = None, use_csv: bool = False) -> DataLoader:
global _loader
if _loader is None:
_loader = DataLoader(db_path=db_path, use_csv=use_csv)
return _loader
if __name__ == "__main__":
dl = DataLoader()
print("Projects:", len(dl.projects))
print("Activities:", len(dl.activities))
print("Daily Updates:", len(dl.daily_updates))
print("Issues:", len(dl.issues))
print("BOQ:", len(dl.boq))
hist = dl.get_historical_activities()
print(f"Historical (completed) activities: {len(hist)}")
active = dl.get_active_activities()
print(f"Active activities: {len(active)}")
|