Spaces:
Sleeping
Sleeping
Yousef Awad commited on
Upload src/wqf7009_aqi/dataset.py with huggingface_hub
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133from __future__ import annotations
import randomfrom pathlib import Path
import pandas as pd
from tqdm import tqdm
from wqf7009_aqi.features import build_training_frame
from wqf7009_aqi.openaq_archive import ( download_object, extract_location_catalog, list_day_objects, list_location_ids, read_measurements_csv_gz,)
def _daily_pm25_from_measurements(df: pd.DataFrame) -> pd.DataFrame:
df = df.copy()
if "parameter" not in df.columns:
return pd.DataFrame()
df = df[df["parameter"].astype(str).str.lower().eq("pm25")]
if df.empty:
return pd.DataFrame()
df["datetime"] = pd.to_datetime(df["datetime"], errors="coerce", utc=True)
df = df.dropna(subset=["datetime", "value", "location_id"])
df["date"] = df["datetime"].dt.date
out = (
df.groupby(["location_id", "location", "lat", "lon", "date"], as_index=False)["value"]
.mean()
.rename(columns={"value": "pm25"})
)
return out
def build_dataset(
*,
out_path: Path,
year: int,
months: list[int],
max_locations: int,
max_days_per_location: int,
seed: int,
cache_dir: Path,
scan_location_ids: int,
) -> None:
out_path.parent.mkdir(parents=True, exist_ok=True)
cache_dir.mkdir(parents=True, exist_ok=True)
rng = random.Random(seed)
cache_ids = Path("data/cache/openaq_location_ids.json")
location_ids = list_location_ids(max_ids=scan_location_ids, cache_path=cache_ids)
rng.shuffle(location_ids)
# Select locations that actually have data for the requested year/months.
selected: list[int] = []
for loc_id in tqdm(location_ids, desc="Selecting locations"):
has_any = False
for m in months:
if list_day_objects(location_id=loc_id, year=year, month=m, max_days=1):
has_any = True
break
if has_any:
selected.append(loc_id)
if len(selected) >= max_locations:
break
location_ids = selected
pm25_rows: list[pd.DataFrame] = []
catalogs: list[pd.DataFrame] = []
for loc_id in tqdm(location_ids, desc="Downloading locations"):
objects: list = []
for m in months:
objects.extend(list_day_objects(location_id=loc_id, year=year, month=m, max_days=max_days_per_location))
if not objects:
continue
rng.shuffle(objects)
objects = objects[:max_days_per_location]
loc_measurements: list[pd.DataFrame] = []
for obj in objects:
try:
local_path = cache_dir / Path(obj.key)
local_path.parent.mkdir(parents=True, exist_ok=True)
if local_path.exists():
blob = local_path.read_bytes()
else:
blob = download_object(obj.key)
local_path.write_bytes(blob)
except Exception:
continue
try:
meas = read_measurements_csv_gz(blob)
except Exception:
continue
loc_measurements.append(meas)
if not loc_measurements:
continue
cat = extract_location_catalog(loc_measurements)
catalogs.append(cat)
daily_frames = [_daily_pm25_from_measurements(m) for m in loc_measurements]
daily_frames = [d for d in daily_frames if not d.empty]
if not daily_frames:
continue
loc_daily = pd.concat(daily_frames, ignore_index=True)
pm25_rows.append(loc_daily)
if not pm25_rows:
raise RuntimeError("No PM2.5 data collected. Try different year/months or increase max_locations.")
pm25_daily = pd.concat(pm25_rows, ignore_index=True).drop_duplicates(subset=["location_id", "date"])
location_catalog = (
pd.concat(catalogs, ignore_index=True).drop_duplicates(subset=["location_id"])
if catalogs
else pm25_daily[["location_id", "location", "lat", "lon"]].drop_duplicates(subset=["location_id"])
)
if "country" not in location_catalog.columns:
location_catalog["country"] = "UNKNOWN"
location_catalog["country"] = location_catalog["country"].fillna("UNKNOWN")
df = build_training_frame(pm25_daily=pm25_daily) df.to_parquet(out_path, index=False)
# Save a location catalog for the app/training artifacts
catalog_out = out_path.parent / "location_catalog.parquet"
location_catalog.to_parquet(catalog_out, index=False)src/wqf7009_aqi/dataset.pyAdded+133