Spaces:
Sleeping
Sleeping
Download server/inference.py from budijuarto/kriyatrack: direct link, hf CLI and curl.
- Browser
- Download file 1.89 kB
-
https://huggingface.co/spaces/budijuarto/kriyatrack/resolve/main/server/inference.py
- Command line
-
hf download hf://spaces/budijuarto/kriyatrack/server/inference.py
-
curl -L -o inference.py https://huggingface.co/spaces/budijuarto/kriyatrack/resolve/main/server/inference.py
1.89 kB
| 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) | |
| 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"} | |
| 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 | |