Spaces:
Sleeping
Sleeping
Update app/core/hf_client.py
Browse files8 unmodified lines910111213144 unmodified lines192021222324252627282930313233343536373839404142435 unmodified lines4950515253545556575859606162636465666768698 unmodified linesfrom huggingface_hub import hf_hub_downloadfrom app.core.config import settingsdef _try_download(filename: str):"""Belirtilen dosyayı Hugging Face'ten indirir."""return hf_hub_download(4 unmodified linesforce_download=True,)def _available_days(days_back: int = 30):"""Son N günün tarihlerini üretir (YYYY-MM-DD formatında)."""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üne göre predictions_latest.csv dosyasını indirir."""candidates = [datetime.utcnow().strftime("%Y-%m-%d")] + _available_days(7)for day in candidates:try:path = f"data/{day}/predictions_latest.csv"local = _try_download(path)df = pd.read_csv(local)df["source_day"] = dayreturn 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 verisini indirir."""try:5 unmodified linesexcept Exception as e:raise RuntimeError(f"❌ {day} tarihli dataset indirilemedi: {e}")def load_all_history(days_back: int = 30):"""Son N günün tüm predictions verilerini 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"8 unmodified lines9101112131415161718194 unmodified lines2425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970715 unmodified lines77787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301318 unmodified linesfrom huggingface_hub import hf_hub_downloadfrom app.core.config import settings# =====================================================# Yardımcı Fonksiyonlar# =====================================================def _try_download(filename: str):"""Belirtilen dosyayı Hugging Face'ten indirir."""return hf_hub_download(4 unmodified linesforce_download=True,)def _available_days(days_back: int = 30):"""Son N günün tarihlerini üretir (YYYY-MM-DD formatında)."""today = datetime.utcnow().date()return [(today - timedelta(days=i)).strftime("%Y-%m-%d") for i in range(days_back)]# =====================================================# Ana Veri Çekme Fonksiyonları# =====================================================def download_latest_csv():"""Son 7 güne göre predictions_latest.csv dosyasını indirir.Öncelik: bugünün klasörü → geçmiş 7 gün."""today_str = datetime.utcnow().strftime("%Y-%m-%d")candidates = [today_str] + _available_days(7)for day in candidates:try:path = f"data/{day}/predictions_latest.csv"local = _try_download(path)df = pd.read_csv(local)df["source_day"] = day# Eğer "processing_day" kolonu varsa, sadece bugünün kayıtlarını filtreleif "processing_day" in df.columns:df = df[df["processing_day"] == today_str]# Eğer hiç kayıt kalmazsa, sonraki güne geçif len(df) == 0:continueprint(f"✅ {day} gününe ait veri 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 verisini indirir."""try:5 unmodified linesexcept Exception as e:raise RuntimeError(f"❌ {day} tarihli dataset indirilemedi: {e}")def load_all_history(days_back: int = 30, only_today: bool = False):"""Son N günün tüm predictions verilerini birleştirir.Eğer only_today=True ise sadece bugünün verileri döner."""frames = []today_str = datetime.utcnow().strftime("%Y-%m-%d")for day in _available_days(days_back):try:df = load_day_csv(day)# Eğer only_today istenmişse sadece bugüne ait kayıtları alif only_today and "processing_day" in df.columns:df = df[df["processing_day"] == today_str]if len(df):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 merged# =====================================================# Meta Bilgiler# =====================================================def get_latest_timestamp():"""Son veri güncelleme zamanını ISO formatında döndürür."""try:today = datetime.utcnow().strftime("%Y-%m-%d")path = f"data/{today}/predictions_latest.csv"local = _try_download(path)ts = datetime.utcfromtimestamp(os.path.getmtime(local))return ts.replace(microsecond=0).isoformat() + "Z"except Exception:# Eğer bugünkü yoksa dünün zamanını denetry:yesterday = (datetime.utcnow() - timedelta(days=1)).strftime("%Y-%m-%d")path = f"data/{yesterday}/predictions_latest.csv"local = _try_download(path)ts = datetime.utcfromtimestamp(os.path.getmtime(local))return ts.replace(microsecond=0).isoformat() + "Z"except Exception:return "1970-01-01T00:00:00Z"
app/core/hf_client.py+69-7