Spaces:
Sleeping
Sleeping
batch insert
Browse filesFiles changed (7)
- .gitignore-4
- Dockerfile+3-14
- app.py+175-69
- crontabDeleted-4
- last_push_date.txtDeleted-1
- start_with_cron.shDeleted-25
- upload_hf_dataset.pyDeleted-108
33 unmodified lines3435363738394033 unmodified lines# λ‘κ·Έ*.log# μ λ‘λ λ°μ΄ν°uploads/training_data/33 unmodified lines34353633 unmodified lines# λ‘κ·Έ*.log
5 unmodified lines67891011123 unmodified lines161718192021222324252627282930313233343536375 unmodified lines# μμ€ν ν¨ν€μ§ μ λ°μ΄νΈ λ° νμν ν¨ν€μ§ μ€μΉRUN apt-get update && apt-get install -y \build-essential \cron \&& rm -rf /var/lib/apt/lists/*# requirements λ³΅μ¬ λ° μ€μΉ3 unmodified lines# μ ν리μΌμ΄μ μ½λ 볡μ¬COPY . .# cron μ€μ νμΌ λ³΅μ¬COPY crontab /etc/cron.d/batch-push-cron# cron κΆν μ€μ RUN chmod 0644 /etc/cron.d/batch-push-cronRUN crontab /etc/cron.d/batch-push-cron# λ‘κ·Έ λλ ν 리 μμ±RUN mkdir -p /var/log# Hugging Face Spaceλ ν¬νΈ 7860μ μ¬μ©ν©λλ€EXPOSE 7860# μμ μ€ν¬λ¦½νΈ λ³΅μ¬ λ° μ€νCOPY start_with_cron.sh /start_with_cron.shRUN chmod +x /start_with_cron.shCMD ["/start_with_cron.sh"]5 unmodified lines678910113 unmodified lines1516171819202122232425265 unmodified lines# μμ€ν ν¨ν€μ§ μ λ°μ΄νΈ λ° νμν ν¨ν€μ§ μ€μΉRUN apt-get update && apt-get install -y \build-essential \&& rm -rf /var/lib/apt/lists/*# requirements λ³΅μ¬ λ° μ€μΉ3 unmodified lines# μ ν리μΌμ΄μ μ½λ 볡μ¬COPY . .# λ‘κ·Έ λλ ν 리 μμ±RUN mkdir -p /app/logs# Hugging Face Spaceλ ν¬νΈ 7860μ μ¬μ©ν©λλ€EXPOSE 7860# FastAPI μλ² μ§μ μ€ν (APScheduler ν¬ν¨)CMD ["python", "start.py"]
2 unmodified lines345678946 unmodified lines56575859606112 unmodified lines7475767778798065 unmodified lines1461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362 unmodified linesfrom typing import List, Optionalfrom fastapi import FastAPI, HTTPException, Requestfrom pydantic import BaseModel, Field, ConfigDictfrom typing import Listimport oracledbfrom dotenv import load_dotenvimport json46 unmodified linesuser_emb: Optional[List[float]] = Field(default=None, description="length=12")model_version: Optional[str] = None# ----- μ νΈ -----def clob_json(obj) -> str:12 unmodified lines"health_db": "/health/db (DB μ°κ²° 체ν¬)","docs": "/docs","upload_state": "/upload_state","upload_dataset": "/upload_dataset","user_dataset": "/user_dataset/{user_id}"}}65 unmodified linesexcept Exception as e:raise HTTPException(500, f"upload_state failed: {e}")@app.post("/upload_dataset")async def upload_to_dataset(request: Request):"""λ‘컬 νμΌμ μ¬μ©μλ³ λ°μ΄ν° μ μ₯"""try:data = await request.json()user_id = data.get("user_id")if not user_id:raise HTTPException(status_code=400, detail="user_idκ° νμν©λλ€")# λ°μ΄ν°μ νμμ€ν¬ν μΆκ°data["timestamp"] = datetime.now().isoformat()# λ‘컬 λ°μ΄ν° λλ ν 리 μμ±data_dir = "user_data"os.makedirs(data_dir, exist_ok=True)# μ¬μ©μλ³ JSON νμΌ κ²½λ‘user_file = os.path.join(data_dir, f"{user_id}.json")# κΈ°μ‘΄ λ°μ΄ν° λ‘λexisting_data = []if os.path.exists(user_file):try:with open(user_file, 'r', encoding='utf-8') as f:existing_data = json.load(f)print(f"π κΈ°μ‘΄ λ°μ΄ν° λ‘λ: {user_id} ({len(existing_data)}κ° λ μ½λ)")except:existing_data = []# μ λ°μ΄ν° μΆκ°existing_data.append(data)# νμΌ μ μ₯with open(user_file, 'w', encoding='utf-8') as f:json.dump(existing_data, f, ensure_ascii=False, indent=2)print(f"β λ‘컬 νμΌ μ μ₯ μλ£: {user_id} ({len(existing_data)}κ° λ μ½λ)")return {"user_id": user_id,"rows": len(existing_data),"status": "success","filename": f"{user_id}.json","file_path": user_file,"message": f"Data saved to local file: {user_file}"}except Exception as e:print(f"β λ‘컬 μ μ₯ μ€ν¨: {e}")raise HTTPException(status_code=500, detail=f"λ‘컬 μ μ₯ μ€ν¨: {str(e)}")@app.get("/user_dataset/{user_id}")async def read_user_dataset(user_id: str):"""λ‘컬 νμΌμμ μ¬μ©μ λ°μ΄ν° μ‘°ν"""try:# μ¬μ©μλ³ JSON νμΌ κ²½λ‘data_dir = "user_data"user_file = os.path.join(data_dir, f"{user_id}.json")if not os.path.exists(user_file):return {"user_id": user_id,"count": 0,"recent_data": [],"source": "local_file","message": "No data found"}# λ°μ΄ν° λ‘λwith open(user_file, 'r', encoding='utf-8') as f:data = json.load(f)# μ΅κ·Ό 5κ° λ μ½λ λ°νrecent_data = data[-5:] if len(data) > 5 else datareturn {"user_id": user_id,"count": len(data),"recent_data": recent_data,"filename": f"{user_id}.json","source": "local_file"}except Exception as e:print(f"β λ‘컬 μ‘°ν μ€ν¨: {e}")raise HTTPException(status_code=500, detail=f"λ‘컬 μ‘°ν μ€ν¨: {str(e)}")2 unmodified lines34567846 unmodified lines55565758596061626364656667686970717273747576777812 unmodified lines9192939495969765 unmodified lines1631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413422 unmodified linesfrom typing import List, Optionalfrom fastapi import FastAPI, HTTPException, Requestfrom pydantic import BaseModel, Field, ConfigDictimport oracledbfrom dotenv import load_dotenvimport json46 unmodified linesuser_emb: Optional[List[float]] = Field(default=None, description="length=12")model_version: Optional[str] = None# λ°°μΉ λ°μ΄ν°μ© μ€ν€λ§class BatchDataItem(BaseModel):user_id: strsession_id: strmeasure_date: strrms: floatfreq: floatfatigue: floatmode: strwindow_count: intwindows: List[dict] = Field(default_factory=list)measurement_count: intclass BatchUploadPayload(BaseModel):batch_data: List[BatchDataItem]batch_size: intbatch_date: str# ----- μ νΈ -----def clob_json(obj) -> str:12 unmodified lines"health_db": "/health/db (DB μ°κ²° 체ν¬)","docs": "/docs","upload_state": "/upload_state","upload_batch_dataset": "/upload_batch_dataset (λ°°μΉ λ°μ΄ν°)","user_dataset": "/user_dataset/{user_id}"}}65 unmodified linesexcept Exception as e:raise HTTPException(500, f"upload_state failed: {e}")@app.on_event("startup")async def startup_event():"""μλ² μμ μ μ΄κΈ°ν"""print("π MuscleCare API μλ² μμ μ€...")# λ‘κ·Έ λλ ν 리 μμ± (λ‘컬/λ°°ν¬ νκ²½ ꡬλΆ)log_dir = "/app/logs" if os.path.exists("/app") else "./logs"os.makedirs(log_dir, exist_ok=True)print(f"π λ‘κ·Έ λλ ν 리 μμ±: {log_dir}")# Oracle DB μ΄κΈ°νtry:db_initialized = init_db_from_env()if db_initialized:print("β Oracle DB μ°κ²° μλ£")else:print("β οΈ Oracle DB μ°κ²° μ€ν¨ - DB κ΄λ ¨ κΈ°λ₯μ΄ λΉνμ±νλ©λλ€")except Exception as e:print(f"β Oracle DB μ΄κΈ°ν μ€λ₯: {e}")print("β μλ² μμ μλ£")@app.on_event("shutdown")async def shutdown_event():"""μλ² μ’ λ£ μ μ 리"""print("π μλ² μ’ λ£ μ€...")try:db_manager = get_db_manager()db_manager.close()print("β Oracle DB μ°κ²° μ’ λ£ μλ£")except Exception as e:print(f"β μ’ λ£ μ²λ¦¬ μ€λ₯: {e}")@app.get("/user_dataset/{user_id}")async def read_user_dataset(user_id: str):"""Hugging Face Hubμμ μ¬μ©μ λ°μ΄ν° μ‘°ν"""try:# Hugging Face νκ²½λ³μ νμΈhf_repo_id = os.getenv("HF_DATA_REPO_ID")hf_token = os.getenv("HF_DATA_TOKEN")if not hf_repo_id or not hf_token:raise HTTPException(status_code=500, detail="Hugging Face μ€μ μ΄ νμν©λλ€ (HF_DATA_REPO_ID, HF_DATA_TOKEN)")# Hugging Face Hubμμ μ¬μ©μ λ°μ΄ν° λ‘λtry:dataset = load_dataset(hf_repo_id, split=user_id, token=hf_token)data = dataset.to_pandas().to_dict(orient="records")# μ΅κ·Ό 5κ° λ μ½λ λ°νrecent_data = data[-5:] if len(data) > 5 else datareturn {"user_id": user_id,"count": len(data),"recent_data": recent_data,"filename": f"{user_id}.parquet","source": "huggingface_hub","repo_id": hf_repo_id}except Exception as e:# λ°μ΄ν°κ° μλ κ²½μ°return {"user_id": user_id,"count": 0,"recent_data": [],"source": "huggingface_hub","repo_id": hf_repo_id,"message": "No data found"}except HTTPException:raiseexcept Exception as e:print(f"β Hugging Face Hub μ‘°ν μ€ν¨: {e}")raise HTTPException(status_code=500, detail=f"Hugging Face Hub μ‘°ν μ€ν¨: {str(e)}")@app.post("/upload_batch_dataset")async def upload_batch_dataset(payload: BatchUploadPayload):"""λ°°μΉ λ¨μλ‘ μ¬μ©μ λ°μ΄ν°λ₯Ό Hugging Face Hubλ‘ νΈμ"""try:# Hugging Face νκ²½λ³μ νμΈhf_repo_id = os.getenv("HF_DATA_REPO_ID")hf_token = os.getenv("HF_DATA_TOKEN")if not hf_repo_id or not hf_token:raise HTTPException(status_code=500, detail="Hugging Face μ€μ μ΄ νμν©λλ€ (HF_DATA_REPO_ID, HF_DATA_TOKEN)")# μ¬μ©μλ³λ‘ λ°μ΄ν° κ·Έλ£Ήνuser_data_groups = {}for item in payload.batch_data:user_id = item.user_idif user_id not in user_data_groups:user_data_groups[user_id] = []# λ°μ΄ν° λ³νrecord = {"session_id": item.session_id,"measure_date": item.measure_date,"rms": item.rms,"freq": item.freq,"fatigue": item.fatigue,"mode": item.mode,"window_count": item.window_count,"windows": item.windows,"measurement_count": item.measurement_count,"batch_date": payload.batch_date,"batch_size": payload.batch_size,"timestamp": datetime.now().isoformat()}user_data_groups[user_id].append(record)results = {}# νμ¬ repoμ μλ λͺ¨λ split λΆλ¬μ€κΈ°try:existing = load_dataset(hf_repo_id, token=hf_token)all_splits = list(existing.keys())print(f"π κΈ°μ‘΄ splits: {all_splits}")except Exception:existing = DatasetDict()print("π κΈ°μ‘΄ repo μμ β μλ‘ μμ±")# νμ¬ μ¬μ©μλ§ μ λ°μ΄νΈfor user_id, records in user_data_groups.items():try:df = pd.DataFrame(records)new_dataset = Dataset.from_pandas(df)if user_id in existing:# κΈ°μ‘΄ λ°μ΄ν°νλ μκ³Ό λ³ν©old_df = existing[user_id].to_pandas()merged = pd.concat([old_df, df], ignore_index=True)existing[user_id] = Dataset.from_pandas(merged)print(f"π {user_id}: κΈ°μ‘΄ λ°μ΄ν°μ λ³ν© ({len(old_df)} + {len(df)} = {len(merged)}κ° λ μ½λ)")else:existing[user_id] = new_datasetprint(f"π {user_id}: μ κ· λ°μ΄ν° μΆκ° ({len(df)}κ° λ μ½λ)")results[user_id] = {"status": "success","new_rows": len(records),"filename": f"{user_id}.parquet"}except Exception as e:print(f"β {user_id} μ²λ¦¬ μ€ν¨: {e}")results[user_id] = {"status": "failed","error": str(e)}# λͺ¨λ split ν΅μ§Έλ‘ λ€μ pushtry:existing.push_to_hub(hf_repo_id, token=hf_token, private=True)print(f"β μ 체 DatasetDict νΈμ μλ£: {len(existing)}κ° μ¬μ©μ")except Exception as e:print(f"β μ 체 νΈμ μ€ν¨: {e}")raise HTTPException(status_code=500, detail=f"μ 체 νΈμ μ€ν¨: {str(e)}")return {"batch_date": payload.batch_date,"batch_size": payload.batch_size,"processed_users": len(user_data_groups),"results": results,"repo_id": hf_repo_id,"message": f"Batch upload completed for {len(user_data_groups)} users"}except HTTPException:raiseexcept Exception as e:print(f"β λ°°μΉ νΈμ μ€ν¨: {e}")raise HTTPException(status_code=500, detail=f"λ°°μΉ νΈμ μ€ν¨: {str(e)}")
1234# λ§€μΌ μμ μ λ°°μΉ νΈμ μ€ν0 0 * * * cd /app && python upload_hF_dataset.py >> /var/log/batch_push.log 2>&1
# λΉ μ€ νμ (cron μꡬμ¬ν)12025-10-2312345678910111213141516171819202122232425#!/bin/bash
# λ‘κ·Έ λλ ν 리 μμ±mkdir -p /var/log
# cron μλΉμ€ μμservice cron start
# cron μν νμΈecho "π
Cron μλΉμ€ μμλ¨"crontab -l
# FastAPI μλ² μμ (λ°±κ·ΈλΌμ΄λ)echo "π FastAPI μλ² μμ..."python start.py &
# μλ²κ° μμλ λκΉμ§ λκΈ°sleep 5
# μλ² μμ μλ£echo "β
FastAPI μλ² μμ μλ£"
# λ‘κ·Έ λͺ¨λν°λ§ (μ νμ¬ν)echo "π λ°°μΉ νΈμ λ‘κ·Έ λͺ¨λν°λ§ μμ..."tail -f /var/log/batch_push.log &123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108from datasets import Dataset, DatasetDictfrom datetime import datetime, dateimport pandas as pd, glob, json, os, shutilfrom dotenv import load_dotenv
load_dotenv()
HF_DATA_REPO_ID = os.getenv("HF_DATA_REPO_ID")HF_DATA_TOKEN = os.getenv("HF_DATA_TOKEN")CACHE_DIR = "./user_data"BACKUP_DIR = "./backup"LAST_PUSH_FILE = "./last_push_date.txt"
def now_str(): return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
def get_last_push_date(): """λ§μ§λ§ νΈμ λ μ§ λ°ν""" if os.path.exists(LAST_PUSH_FILE): with open(LAST_PUSH_FILE, "r") as f: return f.read().strip() return None
def update_last_push_date(): """λ§μ§λ§ νΈμ λ μ§ κΈ°λ‘""" with open(LAST_PUSH_FILE, "w") as f: f.write(str(date.today()))
def should_push_today(): """μ€λ νΈμ μ¬λΆ νμΈ""" last_push = get_last_push_date() today = str(date.today()) return last_push != today
def batch_push_to_huggingface(): """ν루 1ν Hugging Face Dataset μ
λ‘λ""" # νμ νκ²½λ³μ νμΈ if not HF_DATA_REPO_ID or not HF_DATA_TOKEN: print(f"β {now_str()} - νκ²½λ³μ HF_DATA_REPO_ID λλ HF_DATA_TOKENμ΄ μ€μ λμ§ μμμ΅λλ€.") return
# νΈμ μ¬λΆ μ²΄ν¬ if not should_push_today(): print(f"π
{now_str()} - μ΄λ―Έ μ€λ νΈμ μλ£λ¨. μ’
λ£.") return
files = glob.glob(os.path.join(CACHE_DIR, "*.json")) if not files: print(f"π {now_str()} - μΊμλ νμΌμ΄ μμ΅λλ€. μ’
λ£.") return
print(f"π {now_str()} - λ°°μΉ νΈμ μμ ({len(files)}κ° νμΌ)")
user_splits = {} for path in files: user_id = os.path.basename(path).split(".")[0] try: with open(path, "r", encoding="utf-8") as f: records = json.load(f) if not records: print(f"β οΈ {user_id}: λΉμ΄μλ νμΌ, 건λλ") continue
df = pd.DataFrame(records) user_splits[user_id] = Dataset.from_pandas(df) print(f"π {user_id}: {len(records)}κ° λ μ½λ λ³ν μλ£")
except Exception as e: print(f"β {user_id}: νμΌ λ‘λ μ€ν¨ β {e}") continue
if not user_splits: print(f"β {now_str()} - μ²λ¦¬ν λ°μ΄ν°κ° μμ΅λλ€. μ’
λ£.") return
# λ°±μ
λλ ν 리 μμ± os.makedirs(BACKUP_DIR, exist_ok=True) backup_path = os.path.join(BACKUP_DIR, date.today().isoformat()) shutil.copytree(CACHE_DIR, backup_path, dirs_exist_ok=True) print(f"ποΈ {now_str()} - λ°μ΄ν° λ°±μ
μλ£ β {backup_path}")
try: dataset_dict = DatasetDict(user_splits) dataset_dict.push_to_hub(HF_DATA_REPO_ID, token=HF_DATA_TOKEN, private=True) print(f"β
{now_str()} - Hugging Face Hub νΈμ μ±κ³΅ ({len(user_splits)}λͺ
) β {HF_DATA_REPO_ID}")
# νΈμ μ±κ³΅ μ μΊμ μ 리 shutil.rmtree(CACHE_DIR, ignore_errors=True) print(f"ποΈ {now_str()} - user_data λλ ν 리 μμ μλ£")
update_last_push_date() print(f"π
{now_str()} - λ§μ§λ§ νΈμ λ μ§ μ
λ°μ΄νΈ μλ£")
except Exception as e: print(f"β {now_str()} - νΈμ μ€ν¨: {e}") print(f"β οΈ {now_str()} - μΊμ μ μ§ (λ°μ΄ν° μ μ€ λ°©μ§)") # μ€ν¨ μ μΊμ μ μ§ return
def main(): """CLI/cron μ§μ
μ """ try: batch_push_to_huggingface() except Exception as e: print(f"π₯ {now_str()} - μκΈ°μΉ λͺ»ν μ€λ₯ λ°μ: {e}")
if __name__ == "__main__": main().gitignore-4
Dockerfile+3-14
app.py+175-69
crontabDeleted-4
last_push_date.txtDeleted-1
start_with_cron.shDeleted-25
upload_hf_dataset.pyDeleted-108