mirror of
https://github.com/Dasemu/skipredictor.git
synced 2026-11-26 15:26:15 +00:00
merge: clean predictor debt
# Conflicts: # predictor/rules.py
This commit is contained in:
commit
a70eff3e45
10 files changed
+266
-64
No files matched your search
+20
-4
@@ -6,10 +6,10 @@ import logging
|
||||
import os
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import bcrypt
|
||||
import jwt
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
|
||||
from passlib.context import CryptContext
|
||||
|
||||
from app.api.schemas import TokenResponse, UserCreate, UserResponse
|
||||
from storage import SQLiteStore
|
||||
@@ -19,7 +19,6 @@ logger = logging.getLogger(__name__)
|
||||
_TOKEN_EXPIRE_DAYS = 14
|
||||
_ALGORITHM = "HS256"
|
||||
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/login")
|
||||
|
||||
auth_router = APIRouter(prefix="/api/v1/auth", tags=["auth"])
|
||||
@@ -43,6 +42,23 @@ def _create_token(user_id: int, email: str) -> str:
|
||||
return jwt.encode(payload, _get_secret_key(), algorithm=_ALGORITHM)
|
||||
|
||||
|
||||
def _hash_password(password: str) -> str:
|
||||
"""Return a bcrypt password hash."""
|
||||
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
|
||||
|
||||
|
||||
def _verify_password(password: str, password_hash: str) -> bool:
|
||||
"""Validate a plaintext password against a stored bcrypt hash."""
|
||||
try:
|
||||
return bcrypt.checkpw(
|
||||
password.encode("utf-8"),
|
||||
password_hash.encode("utf-8"),
|
||||
)
|
||||
except ValueError:
|
||||
logger.warning("Encountered an invalid stored password hash.")
|
||||
return False
|
||||
|
||||
|
||||
def get_current_user(token: str = Depends(oauth2_scheme)) -> dict:
|
||||
"""FastAPI dependency that validates the JWT and returns user info."""
|
||||
try:
|
||||
@@ -82,7 +98,7 @@ def get_current_user(token: str = Depends(oauth2_scheme)) -> dict:
|
||||
def register(body: UserCreate) -> UserResponse:
|
||||
"""Create a new user account."""
|
||||
store = SQLiteStore()
|
||||
hashed = pwd_context.hash(body.password)
|
||||
hashed = _hash_password(body.password)
|
||||
now_iso = datetime.now(timezone.utc).isoformat()
|
||||
|
||||
with store.connect() as conn:
|
||||
@@ -117,7 +133,7 @@ def login(form: OAuth2PasswordRequestForm = Depends()) -> TokenResponse:
|
||||
(form.username,),
|
||||
).fetchone()
|
||||
|
||||
if row is None or not pwd_context.verify(form.password, row["password_hash"]):
|
||||
if row is None or not _verify_password(form.password, row["password_hash"]):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="invalid credentials",
|
||||
|
||||
+19
-17
@@ -7,7 +7,7 @@ reuse the same pipeline components as ``scripts/collect_daily_data.py``.
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from datetime import date, datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
import pandas as pd
|
||||
@@ -18,7 +18,9 @@ from pipeline.build_dataset import DatasetBuilder
|
||||
from pipeline.feature_engineering import FeatureEngineer
|
||||
from predictor.hybrid_predictor import HybridPredictor
|
||||
from scripts.collect_daily_data import (
|
||||
_available_prediction_dates,
|
||||
_load_prediction_feature_base,
|
||||
_select_forecast_row_for_date,
|
||||
_select_feature_anchor_row,
|
||||
)
|
||||
from scripts.retrain_model import main as retrain_main
|
||||
@@ -75,7 +77,7 @@ def run_forecast_cycle(run_hour: int) -> None:
|
||||
# 3. Scrape station status
|
||||
scraper = StationScraper()
|
||||
station_records: list[dict[str, Any]] = []
|
||||
for station_id in scraper._stations:
|
||||
for station_id in scraper.station_ids:
|
||||
try:
|
||||
record = scraper.scrape_station(station_id)
|
||||
station_records.append(record)
|
||||
@@ -116,12 +118,14 @@ def run_forecast_cycle(run_hour: int) -> None:
|
||||
|
||||
# 5. Determine forecast dates
|
||||
base_date = date.today()
|
||||
if run_hour >= 15:
|
||||
# Skip today, start from tomorrow
|
||||
forecast_dates = [base_date + timedelta(days=d) for d in range(1, 8)]
|
||||
else:
|
||||
# Include today
|
||||
forecast_dates = [base_date + timedelta(days=d) for d in range(8)]
|
||||
forecast_dates = _available_prediction_dates(
|
||||
weather_by_station,
|
||||
base_date=base_date,
|
||||
include_today=run_hour < 15,
|
||||
)
|
||||
if not forecast_dates:
|
||||
logger.error("No usable forecast dates were returned by the weather provider.")
|
||||
return
|
||||
|
||||
# 6. Generate predictions
|
||||
predictor = HybridPredictor()
|
||||
@@ -131,16 +135,14 @@ def run_forecast_cycle(run_hour: int) -> None:
|
||||
for station_id, weather_df in weather_by_station.items():
|
||||
station_rec = station_map.get(station_id, {})
|
||||
for target_date in forecast_dates:
|
||||
days_ahead = (target_date - base_date).days
|
||||
target_rows = weather_df[weather_df["date"] == target_date]
|
||||
if target_rows.empty:
|
||||
idx = max(0, min(days_ahead, len(weather_df) - 1))
|
||||
target_rows = weather_df.iloc[idx : idx + 1]
|
||||
if target_rows.empty:
|
||||
weather_data = _select_forecast_row_for_date(
|
||||
weather_df,
|
||||
station_id=station_id,
|
||||
target_date=target_date,
|
||||
)
|
||||
if weather_data is None:
|
||||
continue
|
||||
|
||||
weather_data = target_rows.iloc[0].to_dict()
|
||||
|
||||
# Build feature row
|
||||
features_df = None
|
||||
if not feature_base_df.empty:
|
||||
@@ -258,7 +260,7 @@ def _scrape_daily_actuals(store: SQLiteStore, scraper: StationScraper) -> None:
|
||||
today_iso = date.today().isoformat()
|
||||
records: list[dict[str, Any]] = []
|
||||
|
||||
for station_id in scraper._stations:
|
||||
for station_id in scraper.station_ids:
|
||||
try:
|
||||
data = scraper.scrape_station(station_id)
|
||||
records.append(
|
||||
|
||||
Reference in new issue
Block a user