File size: 2,428 Bytes
0ddcb86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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"])


@router.post("/train-model", response_model=TrainModelResponse)
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(),
    )


@router.get("/model/status", response_model=ModelStatusResponse)
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,
    )