Spaces:
Sleeping
Sleeping
Update app/core/hf_client.py
Browse files1 unmodified line23456569789121314151617101112131415161718192021222021232425242526272829303132333435363738394041424344454647484950512627282930313233343536373839404155565758596061626364656667686970717273747542434445464748495078511 unmodified line# app/core/hf_client.py# Hugging Face dataset erişimi (günlük ve geçmiş için)# =====================================================
import osimport pandas as pdimport numpy as npfrom datetime import datetime, timedeltafrom datetime import datetimefrom huggingface_hub import hf_hub_downloadfrom app.core.config import settings
def _clean_df(df: pd.DataFrame, day: str) -> pd.DataFrame: """NaN/inf temizliği + zaman formatlama + source_day etiketi.""" if df is None or df.empty: return pd.DataFrame(columns=["source_day"])from app.core.cache import get_cache, set_cache
def _load_csv(path: str) -> pd.DataFrame: local = hf_hub_download( repo_id=settings.HF_DATASET_REPO, filename=path, repo_type="dataset", token=settings.HF_TOKEN, force_download=True, ) df = pd.read_csv(local, encoding="utf-8-sig") df = df.replace([np.inf, -np.inf], np.nan).fillna(0) if "time" in df.columns: df["time"] = pd.to_datetime(df["time"], errors="coerce", utc=True).dt.strftime("%Y-%m-%d %H:%M:%S") df["source_day"] = day df["time"] = pd.to_datetime(df["time"], errors="coerce", utc=True) return df
def _try_download(day: str) -> pd.DataFrame: """Belirtilen günün predictions_latest.csv dosyasını indirir.""" path = f"data/{day}/predictions_latest.csv" try: print(f"📥 Dosya indiriliyor: {path}") local = hf_hub_download( repo_id=settings.HF_DATASET_REPO, filename=path, repo_type="dataset", token=settings.HF_TOKEN, force_download=True, ) df = pd.read_csv(local, encoding="utf-8-sig") df = _clean_df(df, day) print(f"✅ {day} yüklendi ({len(df)} satır)") return df except Exception as e: print(f"⚠️ {day} indirilemedi: {e}") return pd.DataFrame(columns=["source_day"])
def load_today() -> pd.DataFrame: """Sadece bugünün verisini getirir.""" today = datetime.utcnow().strftime("%Y-%m-%d") df = _try_download(today) if df.empty: raise RuntimeError(f"❌ Bugün ({today}) için veri bulunamadı.")def load_predict() -> pd.DataFrame: cached = get_cache() if cached and "predict" in cached: return cached["predict"] df = _load_csv(settings.PATH_PREDICT) set_cache({"predict": df}) return df
def load_latest() -> pd.DataFrame: cached = get_cache() if cached and "latest" in cached: return cached["latest"] df = _load_csv(settings.PATH_LATEST) set_cache({"latest": df}) return df
def load_history(days_back: int = 7) -> pd.DataFrame: """Son N güne ait verileri birleştirir (bugün dahil).""" frames = [] for i in range(days_back): day = (datetime.utcnow() - timedelta(days=i)).strftime("%Y-%m-%d") df = _try_download(day) if not df.empty: frames.append(df)
if not frames: raise RuntimeError("❌ Geçmişte hiçbir predictions_latest.csv bulunamadı.")
merged = pd.concat(frames, ignore_index=True).replace([np.inf, -np.inf], np.nan).fillna(0)
if "time" in merged.columns: merged["time"] = pd.to_datetime(merged["time"], errors="coerce", utc=True).dt.strftime("%Y-%m-%d %H:%M:%S")
merged = merged.sort_values("source_day", ascending=False) print(f"📊 Birleştirilen toplam: {len(merged)} satır ({len(frames)} gün)") return merged
def load_dataset() -> pd.DataFrame: cached = get_cache() if cached and "dataset" in cached: return cached["dataset"] df = _load_csv(settings.PATH_DATASET) set_cache({"dataset": df}) return df
def get_latest_timestamp() -> str: """Son veri güncelleme zamanını ISO formatında döndürür.""" return datetime.utcnow().replace(microsecond=0).isoformat() + "Z"app/core/hf_client.py+33-61