Spaces:
Sleeping
Sleeping
Update app/core/hf_client.py
Browse files1234567891011121314151617181920212 unmodified lines24252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172733 unmodified lines7778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131# =====================================================# app/core/hf_client.py# Hugging Face Dataset erişimi ve CSV işleme# =====================================================import osimport pandas as pdfrom datetime import datetime, timedeltafrom 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(repo_id=settings.HF_DATASET_REPO,filename=filename,2 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:path = f"data/{day}/predictions_latest.csv"local = _try_download(path)3 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"12345678910111213142 unmodified lines171819202122232425262728293031323334353637383940414243444546473 unmodified lines515253545556575859606162636465666768697071# =====================================================# app/core/hf_client.py — Günlük klasör uyumlu 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."""return hf_hub_download(repo_id=settings.HF_DATASET_REPO,filename=filename,2 unmodified linesforce_download=True,)def _available_days(days_back: int = 7):"""Bugün ve geçmiş 7 günü (string) olarak 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.İlk bulunan dosyayı indirir ve DataFrame döner."""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."""try:path = f"data/{day}/predictions_latest.csv"local = _try_download(path)3 unmodified linesexcept Exception as e:raise RuntimeError(f"❌ {day} tarihli dataset indirilemedi: {e}")def load_all_history(days_back: int = 30):"""Son 30 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"
app/core/hf_client.py+16-76