Spaces:
Sleeping
Sleeping
Update app/core/hf_client.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475# =====================================================# app/core/hf_client.py — Güvenli sürüm# =====================================================import osimport pandas as pdfrom datetime import datetime, timedeltafrom huggingface_hub import hf_hub_downloadfrom app.core.config import settingsdef _try_download(filename: str):"""Hugging Face’ten dosya indirir (varsa)."""try:return hf_hub_download(repo_id=settings.HF_DATASET_REPO,filename=filename,repo_type="dataset",token=settings.HF_TOKEN,force_download=True,)except Exception as e:print(f"⚠️ Dosya indirilemedi: {filename} ({e})")raisedef _available_days(days_back: int = 7):"""Bugün + geçmiş N günü döndürür."""today = datetime.utcnow().date()return [(today - timedelta(days=i)).strftime("%Y-%m-%d") for i in range(days_back)]def download_latest_csv():"""Son 7 gün içinde predictions_latest.csv dosyasını bulur."""days = _available_days(7)for day in days:path = f"data/{day}/predictions_latest.csv"try:local = _try_download(path)df = pd.read_csv(local)df["source_day"] = dayprint(f"✅ {path} bulundu ({len(df)} satır).")return dfexcept Exception:continueraise RuntimeError("❌ Son 7 gün içinde predictions_latest.csv bulunamadı.")def load_day_csv(day: str):"""Belirli bir günün predictions_latest.csv dosyasını indirir."""if not day:raise ValueError("Gün parametresi boş olamaz.")try:path = f"data/{day}/predictions_latest.csv"local = _try_download(path)df = pd.read_csv(local)df["source_day"] = dayprint(f"📅 {day} yüklendi ({len(df)} satır)")return dfexcept Exception as e:raise RuntimeError(f"❌ {day} tarihli dataset indirilemedi: {e}")def load_all_history(days_back: int = 30):"""Son N günün predictions_latest.csv dosyalarını birleştirir."""frames = []for day in _available_days(days_back):try:df = load_day_csv(day)frames.append(df)except Exception:continueif not frames:raise RuntimeError("❌ Geçmişte hiç CSV bulunamadı.")merged = pd.concat(frames, ignore_index=True)merged.sort_values("source_day", inplace=True)return mergeddef get_latest_timestamp():"""Son veri güncelleme zamanını ISO formatında döndürür."""return datetime.utcnow().replace(microsecond=0).isoformat() + "Z"12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273# =====================================================# app/core/hf_client.py# Her gün için sadece predictions_latest.csv'yi indirir# =====================================================import osimport pandas as pdfrom datetime import datetime, timedeltafrom huggingface_hub import hf_hub_downloadfrom app.core.config import settingsdef _try_download(day: str):"""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)df["source_day"] = dayprint(f"✅ {path} yüklendi ({len(df)} satır)")return dfexcept Exception as e:print(f"⚠️ {path} indirilemedi: {e}")raisedef download_latest_csv():"""Sadece bugünün klasöründen predictions_latest.csv dosyasını indirir."""today = datetime.utcnow().strftime("%Y-%m-%d")try:return _try_download(today)except Exception:raise RuntimeError(f"❌ {today} klasöründe predictions_latest.csv bulunamadı.")def load_day_csv(day: str):"""Belirtilen günün predictions_latest.csv dosyasını indirir."""if not day:raise ValueError("Gün parametresi boş olamaz.")return _try_download(day)def load_all_history(days_back: int = 7):"""Son N günün her birinde varsa predictions_latest.csv dosyasını indirip birleştirir.Yani sadece günlük predictions_latest.csv dosyaları birleştirilir."""frames = []for i in range(days_back):day = (datetime.utcnow() - timedelta(days=i)).strftime("%Y-%m-%d")try:df = _try_download(day)frames.append(df)except Exception:continueif not frames:raise RuntimeError("❌ Geçmişte hiçbir predictions_latest.csv bulunamadı.")merged = pd.concat(frames, ignore_index=True)merged.sort_values("source_day", inplace=True)print(f"📊 Birleştirilen toplam: {len(merged)} satır ({len(frames)} gün)")return mergeddef get_latest_timestamp():"""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+36-38