Spaces:
Running
Running
File size: 8,761 Bytes
2b83ee8 ece3e89 2b83ee8 ece3e89 2b83ee8 ece3e89 2b83ee8 ece3e89 2b83ee8 ece3e89 2b83ee8 ece3e89 2b83ee8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 | """FastAPI μ±: μλ νμ΅ λ° Hugging Face μ
λ‘λ νΈλ¦¬κ±°"""
from __future__ import annotations
import json
import os
import threading
import time
from pathlib import Path
from typing import Any, Dict, Optional
import schedule
from fastapi import FastAPI, HTTPException
from fastapi.responses import FileResponse
from huggingface_hub import HfApi, hf_hub_download
try:
from huggingface_hub.utils import HfHubHTTPError
except ImportError: # pragma: no cover
HfHubHTTPError = Exception # type: ignore
from pydantic import BaseModel
from train_scheduler import TrainingScheduler
app = FastAPI(
title="MuscleCare Train Scheduler API",
description="μλμΌλ‘ λͺ¨λΈ νμ΅ λ° Hugging Face μ
λ‘λλ₯Ό νΈλ¦¬κ±°ν©λλ€.",
)
_scheduler = TrainingScheduler()
class TrainResponse(BaseModel):
status: str
new_data_count: int
model_path: Optional[str] = None
hub_url: Optional[str] = None
model_version: Optional[int] = None
message: str
@app.on_event("startup")
def startup_training() -> None:
"""μλ² μμ μ μλμΌλ‘ λͺ¨λΈ νμ΅μ μ€νν©λλ€."""
try:
print("π μλ² μμ: μλ λͺ¨λΈ νμ΅μ μμν©λλ€...")
result = _scheduler.run_scheduled_training()
if result["status"] == "trained":
print(f"β
μλ² μμ μ νμ΅ μλ£: {result['new_data_count']}κ° λ°μ΄ν°λ‘ νμ΅λ¨")
else:
print(f"βΉοΈ μλ² μμ μ νμ΅ κ±΄λλ: {result.get('message', 'μλ‘μ΄ λ°μ΄ν° μμ')}")
except Exception as exc:
print(f"β οΈ μλ² μμ μ νμ΅ μ€ν¨: {exc}")
# κΈ°μ‘΄ μ€μΌμ€λ§ μ€μ
schedule.clear()
schedule.every().sunday.at("00:00").do(_scheduler.run_scheduled_training)
def _run_schedule() -> None:
while True:
schedule.run_pending()
time.sleep(60)
threading.Thread(target=_run_schedule, daemon=True).start()
@app.head("/health")
async def health_head():
return None # HEADλ λ°λκ° νμ μμΌλ―λ‘ None λ°ν
@app.get("/health")
def health_check() -> dict:
return {"status": "ok"}
@app.get("/")
def root() -> dict:
return {
"message": "MuscleCare Train Scheduler APIκ° μ€ν μ€μ
λλ€.",
"endpoints": {
"health": "/health",
"trigger": "/trigger",
},
"docs": "/docs",
}
def _upload_to_hub(model_path: str) -> Optional[str]:
token = os.getenv("HF_E2E_MODEL_TOKEN")
repo_id = os.getenv("HF_E2E_MODEL_REPO_ID")
if not token or not repo_id:
raise HTTPException(
status_code=400,
detail="νκ²½ λ³μ HF_E2E_MODEL_TOKEN / HF_E2E_MODEL_REPO_IDκ° μ€μ λμ΄ μμ§ μμ΅λλ€.",
)
path = Path(model_path)
if not path.exists():
raise HTTPException(status_code=404, detail=f"λͺ¨λΈ νμΌμ μ°Ύμ μ μμ΅λλ€: {model_path}")
api = HfApi(token=token)
api.create_repo(repo_id=repo_id, repo_type="model", private=False, exist_ok=True)
api.upload_file(
path_or_fileobj=path,
path_in_repo=path.name,
repo_id=repo_id,
repo_type="model",
commit_message="Manual scheduler trigger upload",
)
return f"https://huggingface.co/{repo_id}"
# TODO: include version info in response body
@app.get("/model")
@app.get("/model/{version:int}")
def download_model(
version: Optional[int] = None,
filename: Optional[str] = None
) -> FileResponse:
repo_id = os.getenv("HF_E2E_MODEL_REPO_ID")
token = os.getenv("HF_E2E_MODEL_TOKEN")
default_filename = os.getenv("HF_E2E_MODEL_FILE", "cnn_gru_fatigue.tflite")
if not repo_id:
raise HTTPException(
status_code=400,
detail="νκ²½ λ³μ HF_E2E_MODEL_REPO_IDκ° μ€μ λμ΄ μμ§ μμ΅λλ€."
)
current_state = _scheduler.load_training_state()
current_version = int(current_state.get("model_version", 0) or 0)
try:
if not version:
target_filename = filename or default_filename
local_path = hf_hub_download(
repo_id=repo_id,
filename=target_filename,
repo_type="model",
token=token,
local_dir="./model_cache",
local_dir_use_symlinks=False,
)
actual_version = current_version
else:
if version > current_version:
raise HTTPException(
status_code=404,
detail=f"νμ¬ λͺ¨λΈ λ²μ μ {current_version}μ
λλ€. λ²μ {version}μ μ‘΄μ¬νμ§ μμ΅λλ€."
)
manifest_path = hf_hub_download(
repo_id=repo_id,
filename="model_versions.json",
repo_type="model",
token=token,
local_dir="./model_cache",
local_dir_use_symlinks=False,
)
with open(manifest_path, "r", encoding="utf-8") as f:
manifest = json.load(f)
version_entry = next(
(entry for entry in manifest if entry.get("version") == version),
None
)
if version_entry is None:
raise HTTPException(
status_code=404,
detail=f"λ²μ {version}μ ν΄λΉνλ λͺ¨λΈμ μ°Ύμ μ μμ΅λλ€."
)
target_filename = filename or version_entry.get("filename")
target_revision = version_entry.get("commit")
if not target_filename or not target_revision:
raise HTTPException(
status_code=500,
detail=f"λ²μ {version} λ©νλ°μ΄ν°κ° μ¬λ°λ₯΄μ§ μμ΅λλ€."
)
local_path = hf_hub_download(
repo_id=repo_id,
filename=target_filename,
repo_type="model",
token=token,
local_dir="./model_cache",
local_dir_use_symlinks=False,
revision=target_revision,
)
actual_version = version
except Exception as exc:
status = getattr(getattr(exc, "response", None), "status_code", None)
if status == 404:
raise HTTPException(
status_code=404,
detail="νκΉ
νμ΄μ€μμ μ§μ ν λͺ¨λΈ νμΌμ μ°Ύμ μ μμ΅λλ€."
) from exc
raise HTTPException(
status_code=500,
detail=f"Hugging Face Hub λ€μ΄λ‘λ μ€ν¨: {exc}"
) from exc
response = FileResponse(
path=local_path,
filename=Path(target_filename).name,
media_type="application/octet-stream"
)
response.headers["X-Model-Version"] = str(actual_version)
response.headers["X-Model-Filename"] = Path(target_filename).name
return response
class ResetStateResponse(BaseModel):
status: str
state: Dict[str, Any]
@app.post("/state/reset", response_model=ResetStateResponse)
def reset_training_state() -> ResetStateResponse:
try:
state = _scheduler.reset_training_state()
return ResetStateResponse(
status="reset",
state=state,
)
except Exception as exc: # pylint: disable=broad-except
raise HTTPException(status_code=500, detail=f"νμ΅ μν μ΄κΈ°νμ μ€ν¨νμ΅λλ€: {exc}") from exc
@app.post("/trigger", response_model=TrainResponse)
def trigger_training(upload: bool = True) -> TrainResponse:
try:
result = _scheduler.run_scheduled_training()
except Exception as exc: # pylint: disable=broad-except
raise HTTPException(status_code=500, detail=f"νμ΅ μ€ν μ€ μ€λ₯κ° λ°μνμ΅λλ€: {exc}") from exc
message = "μλ‘μ΄ λ°μ΄ν°κ° μμ΄ νμ΅μ 건λλλλ€."
hub_url = None
if result["status"] == "trained":
message = "λͺ¨λΈ νμ΅μ΄ μλ£λμμ΅λλ€."
model_path = result.get("model_path")
if upload and model_path:
try:
hub_url = _upload_to_hub(model_path)
message = "λͺ¨λΈ νμ΅ λ° μ
λ‘λκ° μλ£λμμ΅λλ€."
except HTTPException:
raise
except Exception as exc: # pylint: disable=broad-except
raise HTTPException(status_code=500, detail=f"Hugging Face μ
λ‘λ μ€ν¨: {exc}") from exc
return TrainResponse(
status=result["status"],
new_data_count=result["new_data_count"],
model_path=result.get("model_path"),
hub_url=hub_url,
message=message,
)
__all__ = ["app"]
|