Spaces:
Runtime error
Runtime error
Download app/api/training.py from devmurtaza/RastaAI: direct link, hf CLI and curl.
- Browser
- Download file 2.43 kB
-
https://huggingface.co/spaces/devmurtaza/RastaAI/resolve/main/app/api/training.py
- Command line
-
hf download hf://spaces/devmurtaza/RastaAI/app/api/training.py
-
curl -L -o training.py https://huggingface.co/spaces/devmurtaza/RastaAI/resolve/main/app/api/training.py
2.43 kB
| """Training trigger + model status endpoints.""" | |
| from __future__ import annotations | |
| import os | |
| import json | |
| import asyncio | |
| from datetime import datetime | |
| from fastapi import APIRouter, BackgroundTasks, Depends | |
| from sqlalchemy.ext.asyncio import AsyncSession | |
| from app.config import settings | |
| from app.database import get_db | |
| from app.models.db_models import TrainingRun | |
| from app.models.inference import bundle | |
| from app.schemas.route import TrainModelRequest, TrainModelResponse, ModelStatusResponse | |
| from app.training.train import train as run_training | |
| from app.utils.logger import logger | |
| router = APIRouter(tags=["training"]) | |
| async def train_model( | |
| req: TrainModelRequest, | |
| db: AsyncSession = Depends(get_db), | |
| ) -> TrainModelResponse: | |
| """Run a synchronous training job. Heavy but explicit. | |
| For production: enqueue this on a worker (Celery, Arq, Dramatiq). | |
| """ | |
| # Run in a thread to avoid blocking the event loop | |
| result = await asyncio.to_thread( | |
| run_training, req.synthetic_samples, req.test_size, req.model_type | |
| ) | |
| bundle.load() # hot-reload artifacts | |
| record = TrainingRun( | |
| samples=result["samples"], | |
| eta_metrics=result["eta_metrics"], | |
| fuel_metrics=result["fuel_metrics"], | |
| model_type=req.model_type, | |
| artifact_path=result["saved_to"], | |
| ) | |
| db.add(record) | |
| logger.info(f"Training complete: {result}") | |
| return TrainModelResponse( | |
| eta_metrics=result["eta_metrics"], | |
| fuel_metrics=result["fuel_metrics"], | |
| samples_trained=result["samples"], | |
| saved_to=result["saved_to"], | |
| trained_at=datetime.utcnow(), | |
| ) | |
| async def model_status() -> ModelStatusResponse: | |
| meta_path = os.path.join(settings.model_dir, "meta.json") | |
| last_trained = None | |
| if os.path.exists(meta_path): | |
| with open(meta_path) as f: | |
| meta = json.load(f) | |
| try: | |
| last_trained = datetime.fromisoformat(meta["trained_at"]) | |
| except Exception: | |
| last_trained = None | |
| return ModelStatusResponse( | |
| eta_model_loaded=bundle.eta_model is not None, | |
| fuel_model_loaded=bundle.fuel_model is not None, | |
| eta_model_path=settings.eta_model_path, | |
| fuel_model_path=settings.fuel_model_path, | |
| last_trained=last_trained, | |
| ) | |