import os from pathlib import Path from functools import lru_cache import threading import numpy as np from fastapi import FastAPI, HTTPException from pydantic import BaseModel, ConfigDict, Field, StrictInt from forecast_features import forecast_features, next_month os.environ.setdefault("KERAS_BACKEND", "torch") app=FastAPI(title="KriyaTrack ยท Prediksi",docs_url=None,redoc_url=None) lock=threading.Lock() class Point(BaseModel): model_config=ConfigDict(extra="forbid") month:str=Field(pattern=r"^[1-9]\d{3}-(0[1-9]|1[0-2])$") value:StrictInt=Field(ge=0,le=10**13) class Series(BaseModel): model_config=ConfigDict(extra="forbid") history:list[Point]=Field(min_length=12,max_length=240) @lru_cache(maxsize=1) def load_model(): import keras return keras.models.load_model(Path(__file__).resolve().parents[1]/"models/forecast-neural.keras",compile=False) def features(history): try: row=forecast_features([point.model_dump() for point in history]) return np.asarray([row],dtype=np.float32),next_month(history[-1].month) except ValueError as exc: raise HTTPException(422,str(exc)) from exc def predict_values(history): row,month=features(history) import keras with lock: result=keras.ops.convert_to_numpy(load_model()(row,training=False)).reshape(-1)[0] if not np.isfinite(result):raise ValueError("Inference yielded a non-finite value") return {"month":month,"value":max(0,int(np.floor(float(result)+.5))),"model":"neural"} @app.post("/api/predict") def predict(data:Series): try:return predict_values(data.history) except HTTPException:raise except Exception as exc: import logging logging.getLogger(__name__).exception("Forecast service not ready") raise HTTPException(503,"Model belum tersedia. Halaman pesanan dan dashboard tetap dapat digunakan.") from exc