← Back to Amfor-Cast

🛠️ Developer Documentation

Architecture, setup, and contribution guide for Amfor-Cast

Architecture

┌─────────────────────────────────────────────────────────────┐ │ Open-Meteo API (free, no key) │ │ ├─ /v1/forecast (Best match) ├─ /v1/ecmwf │ │ ├─ /v1/dwd-icon (ICON) ├─ /v1/meteofrance (AROME) │ │ ├─ /v1/gfs └─ /v1/archive (history) │ └────────────────────────┬────────────────────────────────────┘ │ ┌──────────────┼──────────────────┐ ▼ ▼ ▼ ┌───────────────┐ ┌──────────────┐ ┌─────────────────────┐ │ weather- │ │ weather- │ │ model-validator/ │ │ forecast/ │ │ history/ │ │ save-forecast.py │ │ │ │ │ │ evaluate.py │ │ 8 models × │ │ 19 Chart.js │ │ evaluate-routes.py │ │ 4 cities │ │ charts │ │ report.py │ │ risk chart │ │ │ │ │ │ EN/HU summary │ │ │ │ → model-rankings.json│ └───────┬───────┘ └──────┬───────┘ └──────────┬──────────┘ │ │ │ ▼ ▼ ▼ ┌─────────────────────────────────────────────────────────────┐ │ shared/ │ │ ├─ config.py (cities, thresholds, model URLs) │ │ ├─ config_loader.py (reads config.ini — paths, DB, etc.) │ │ ├─ db.py (MySQL helper — all DB operations) │ │ ├─ model_selector.py (adaptive ranking engine) │ │ ├─ i18n.js (client-side EN/HU toggle) │ │ └─ headaches.py (headache log parser) │ └─────────────────────────────────────────────────────────────┘ │ │ │ ▼ ▼ ▼ ┌─────────────────────────────────────────────────────────────┐ │ MySQL (tarhely.com / amforcas_forecasts) │ │ ├─ stations (fixed + route-discovered) │ │ ├─ forecasts (daily model snapshot headers) │ │ ├─ forecast_hours (hourly data points per model) │ │ ├─ evaluations (forecast vs actuals scores) │ │ ├─ rankings (computed model rankings) │ │ ├─ route_logs (route feedback — future) │ │ └─ headaches (headache events) │ └─────────────────────────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────┐ │ Raspberry Pi 4 (cron + generation + API) │ │ ├─ /opt/amfor-cast/repo (git clone, auto-pulled) │ │ ├─ /opt/amfor-cast/config.ini (DB creds, paths — secret) │ │ ├─ /opt/amfor-cast/site (complete website → rsync) │ │ ├─ /opt/amfor-cast/data (internal: snapshots, logs) │ │ ├─ /opt/amfor-cast/run.sh (entry point for cron) │ │ ├─ /opt/amfor-cast/venv (Python + pymysql + markdown) │ │ │ ↓ rsync --delete │ │ └─ tarhely.com/public_html (production website) │ └─────────────────────────────────────────────────────────────┘

Quick Start

# Clone and setup
git clone https://gitlab.com/demogun1/misc_scripts.git
cd misc_scripts

# Create Python 3.12 venv
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt

# Preview reports locally (no deploy, no email)
./scripts/weather-forecast/weather-forecast.py --dry-run
./scripts/weather-history/weather-history.py --days 7 --dry-run
./scripts/headache-analyzer/headache-analyzer.py --dry-run

# Run everything (dry-run)
./run-and-publish.py --dry-run

# Run everything + deploy (verbose)
./run-and-publish.py --verbose

Project Structure

misc_scripts/
├── run-and-publish.py          # Orchestrator: runs all scripts, generates site
├── run.sh                      # Wrapper: git pull + clean + generate + rsync (POSIX sh)
├── config.ini.example          # Config template (DB creds, paths, thresholds)
├── .gitlab-ci.yml              # CI: lint (ruff) → typecheck (mypy) → test (pytest) → redirect page
├── ruff.toml                   # Lint configuration
├── schema.sql                  # MySQL schema definition
├── requirements.txt            # Python deps (markdown, pymysql)
├── tests/                      # pytest test suite (59 tests)
│   ├── test_smoke.py           # Syntax, imports, exclusion logic
│   ├── test_scoring.py         # MAE, rain accuracy, forecast parsing
│   ├── test_shared.py          # Config, model selector, haversine
│   ├── test_forecast_modules.py # fetch, risk, charts, render
│   └── test_current_weather.py # JS validation
├── api/
│   └── php/                    # PHP API (runs on tarhely.com hosting)
│       ├── config.php.example  # Template — real config.php is gitignored
│       ├── auth.php            # Register, login, logout, rate limiting
│       ├── cities.php          # City search, add, remove, reorder
│       ├── log-route.php       # Route forecast log (auth required)
│       └── admin.php           # Admin panel (HTTP Basic Auth, server-rendered)
├── scripts/
│   ├── weather-forecast/
│   │   ├── weather-forecast.py # Thin orchestrator (247 lines)
│   │   ├── fetch.py            # API communication + parsing (179 lines)
│   │   ├── risk.py             # Headache/pressure risk scoring (174 lines)
│   │   ├── charts.py          # Chart.js generation + warnings (422 lines)
│   │   ├── render.py           # HTML rendering (629 lines)
│   │   ├── summary.py          # Weather summaries HU+EN (196 lines)
│   │   ├── template.html       # Web template (Jinja-like {{placeholders}})
│   │   └── template-email.html # Email template (inline styles, no JS)
│   ├── weather-history/
│   │   ├── weather-history.py  # History chart generator
│   │   └── template.html       # Chart.js template
│   ├── model-validator/
│   │   ├── save-forecast.py    # Daily snapshot saver (→ DB only)
│   │   ├── evaluate.py         # Compare forecast vs actuals (→ DB)
│   │   ├── evaluate-routes.py  # Score route feedback points (→ DB)
│   │   └── report.py           # Generate rankings HTML + JSON (← DB)
│   └── headache-analyzer/
│       └── headache-analyzer.py
├── shared/
│   ├── __init__.py             # get_base_styles() — unified CSS generator
│   ├── config.py               # CITIES, thresholds, URLs
│   ├── config_loader.py        # Reads config.ini (DB, paths, etc.)
│   ├── db.py                   # MySQL helper (all DB operations)
│   ├── model_selector.py       # Adaptive model ranking engine (DB-backed)
│   ├── i18n.js                 # Client-side translations
│   └── headaches.py            # Headache log (DB-backed)
└── public_html/                # Deployed web output + static assets

CI Pipeline (GitLab)

Branch protection: Direct push to main is blocked. All changes require a Merge Request with passing pipeline.
StageToolWhat it checksBlocking?
lintruffUnused imports, undefined names, syntax errorsYes
typecheckmypyType errors, None access, wrong argument typesYes
testpytest (59 tests)Unit tests + integration import smoke testYes
deployGitLab PagesCopy to Pages (only if all above pass)—

Running locally

# Lint
ruff check .

# Type check
mypy --ignore-missing-imports --no-strict-optional --check-untyped-defs shared/ scripts/model-validator/ scripts/weather-forecast/fetch.py

# Tests
pytest tests/ -v

Development workflow

git checkout -b feature/my-change    # Create branch
# ... make changes ...
pytest tests/ -v                     # Run tests locally
ruff check .                         # Lint locally
git add -A && git commit -m "..."    # Commit
git push -u origin feature/my-change # Push (creates MR link)
# → GitLab CI runs → merge when green

Configuration

All shared settings live in shared/config.py:

# Cities: key → (display_name, latitude, longitude)
CITIES = {
    "inarcs": ("Inárcs", 47.2667, 19.3500),
    "budapest": ("Budapest", 47.4979, 19.0402),
    "ivancsa": ("Iváncsa", 46.9833, 18.8167),
    "gyal": ("Gyál", 47.3833, 19.2167),
}
DEFAULT_CITY = "inarcs"

# Risk thresholds
RISK_THRESHOLD_HIGH = 5
TEMP_HOT_THRESHOLD = 35
WIND_STRONG_THRESHOLD = 50

Adding a New City

  1. Add entry to CITIES in shared/config.py
  2. Add tab + city content block in public_html/index.html
  3. Add city to cron list (if separate email needed)
  4. Station auto-registered in data/stations.json on first evaluate run

Adaptive Model Selection

The system learns which model is best per location/parameter/horizon:

  1. Collect — save-forecast.py stores daily snapshots (all models)
  2. Evaluate — evaluate.py compares forecasts against measured actuals
  3. Rank — model_selector.py aggregates errors → picks best model
  4. Select — forecast scripts and route planner use the ranked winner

Key parameters in shared/model_selector.py:

ConstantValueMeaning
MIN_SAMPLES7Minimum evaluations to trust a ranking
WINDOW_DAYS30Rolling window for ranking calculation
SIGNIFICANCE_GAP5.0%Minimum advantage to prefer one model over another

i18n System

Client-side EN/HU translation using shared/i18n.js:

Static labels:

<span data-i18n="forecast">Forecast</span>

The key "forecast" is looked up in the TRANSLATIONS dict.

Dynamic content (server-generated):

<span data-i18n-en="Hot day, 30°C" data-i18n-hu="Kiadós kánikula, 30°C">Hot day, 30°C</span>

Both versions stored as attributes. Toggle simply swaps innerHTML.

Adding a new translation:

  1. Add key to TRANSLATIONS dict in shared/i18n.js
  2. Add data-i18n="key" to the HTML element
  3. Copy shared/i18n.js → public_html/i18n.js

Route Weather Planner (Client-Side)

Pure JavaScript, no backend needed for weather display. All client-side APIs:

ServicePurposeLimit
OSRMRoute calculation (distance, duration, polyline)Fair use (free)
Open-MeteoWeather forecast per waypoint (8 models)10,000/day
NominatimGeocoding + reverse geocoding1 req/sec
Leaflet + OSMMap rendering + zone overlaysUnlimited

Features (v2)

FeatureActivationDetails
Road conditionsAlwaysIce risk, fog, aquaplaning, crosswind, wet road — per-waypoint badges + route summary
Weather zonesAlwaysContiguous rain/storm/wind segments highlighted on map (colored dashed overlays)
Optimal departureCheckboxScans ±3h window (7 candidates), scores by driving conditions, recommends best time
Multi-route comparisonCheckboxCompare 2-3 alternative routes side by side with ranked scores and mini maps
Mobile responsiveAlwaysTouch-friendly inputs, stacked layout, 16px font (no iOS zoom), same features as desktop

Road condition detection:

  • Black ice: dew point spread < 2°C AND temp < 3°C (high severity if temp < 0°C)
  • Fog: visibility < 1000m, or humidity > 95% with low dew spread
  • Aquaplaning: precipitation > 4 mm/h
  • Crosswind: gusts > 60 km/h (high if > 90 km/h)
  • Reduced visibility: 1–5 km (not fog — heavy rain/snow)

Feedback loop:

Route requests from logged-in users store all-model forecasts via POST /api/log-route.php → MySQL route_logs table → evaluated daily by evaluate-routes.py. Anonymous users can use the planner but their data is not stored.

User Management (v1.2)

PHP API on tarhely.com + client-side JS. Users can register, login, and save favorite cities.

Architecture

  • Auth: PHP on tarhely.com (bcrypt passwords, SHA-256 hashed session tokens, HTTP-only cookies)
  • Cities: shared global pool — each city exists once in DB, users reference via favorites
  • Frontend: user.js (login modal, city manager) + live-forecast.js (instant forecast for new cities)
  • Storage: MySQL tables: users, sessions, cities, user_cities

PHP API endpoints (api/php/)

FileEndpointDescription
auth.php?action=register|login|logout|meUser authentication
cities.php?action=list|my|search|add|remove|reorderCity management
log-route.phpPOSTRoute forecast log (public, rate limited)

Frontend scripts

FilePurpose
user.jsLogin/register modal, user menu, city manager, dynamic tabs, onboarding hints
live-forecast.jsClient-side forecast for cities without generated pages (Open-Meteo direct)
city-nav.jsFloating city switcher — side panel (desktop) + horizontal tabs (mobile)

City lifecycle

  1. User searches "Miskolc" → Nominatim geocodes → shows status badge (✅/⏳/🆕)
  2. User adds → inserted into cities table (if new) + user_cities
  3. Immediately: live-forecast.js fetches from Open-Meteo (4 models) → renders inline
  4. Next hourly cron: Pi generates full weather-forecast-miskolc.html
  5. On next page load: detects page exists → switches to link to full report
  6. After ~7 days: model rankings become available → 🏆 badges appear

Ranking badges in forecasts

When a city has ranking data, the forecast page highlights the winning model:

Performance: parallel fetching

Two levels of parallelization for fast report generation:

  • Model-level: fetch_all_models() uses ThreadPoolExecutor(max_workers=4) — all 8 models fetched simultaneously (~2s instead of ~16s)
  • City-level: run-and-publish.py runs 2 cities in parallel via subprocess.Popen
  • History optimization: --all-periods flag — single 30d API call → renders 3d, 7d, 30d HTML files
  • Retry: each model retried 3× with 2s/4s backoff; fails hard if any model missing
MetricBeforeAfter
7 cities total~200s~35s
History API calls (7 cities)217
Max concurrent requests18

City navigation (city-nav.js)

Floating city switcher that appears on all pages:

Headache Log

Headache events are stored in MySQL (headaches table, per-user via user_id column).

User UI

Logged-in users can manage their own headache events via the 🤕 Headache Log button in the user menu:

API: GET/POST/DELETE /api/headaches.php (auth required, rate limited 20/hour).

Admin

/api/admin.php → Headaches tab manages all users' entries.

Analysis

The headache-analyzer script is city-independent — correlates each event with weather data from that location at that time.

-- Severity: 1 = mild, 2 = moderate, 3 = strong, 4 = severe, 5 = extreme
-- user_id: FK to users table (NULL = legacy/admin entries)
-- Unique constraint: (user_id, date, time) — same user can't double-log

Push Notifications

Server-side Web Push notifications via Web Push protocol. When the nowcast detects rain for a city, subscribed users get a push even with the browser closed.

Architecture

fetch_nowcast.py → rain detected → shared/push_notify.py → pywebpush → FCM/Mozilla Push → browser

Components

Setup

# 1. Install pywebpush on Pi
/opt/amfor-cast/venv/bin/pip install pywebpush

# 2. Generate VAPID keys (one-time)
/opt/amfor-cast/venv/bin/python3 -c "
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.backends import default_backend
import base64
private_key = ec.generate_private_key(ec.SECP256R1(), default_backend())
pn = private_key.private_numbers()
print('Private:', base64.urlsafe_b64encode(pn.private_value.to_bytes(32, 'big')).decode().rstrip('='))
x = pn.public_numbers.x.to_bytes(32, 'big')
y = pn.public_numbers.y.to_bytes(32, 'big')
print('Public:', base64.urlsafe_b64encode(b'\x04' + x + y).decode().rstrip('='))
"

# 3. Add to config.ini on Pi:
[push]
vapid_private_key = <private>
vapid_public_key = <public>
vapid_contact = mailto:info@amfor-cast.com

# 4. Add public key to DB:
INSERT INTO meta (`key`, value) VALUES ('vapid_public_key', '<public>');

Behavior

Alert Types

TypeTriggerSourceThrottle
🌧️ RainRadar detects rain approachingNowcast (every 15 min)1 hour/city
🌪️ Severe weatherGusts ≥ 80 km/h, rain ≥ 20mm/day, frost ≤ −5°C, heat ≥ 38°CForecast (hourly)6 hours/city

Personal Alert Preferences

Logged-in users can customize their alert thresholds via api/push-preferences.php:

SettingDefaultRange
Rain threshold0.5 mm0–50 mm
Wind threshold60 km/h10–150 km/h
Heat alert38°C25–50°C
Frost alert−5°C−30–10°C

DB table: push_preferences (user_id, rain_mm, wind_kmh, temp_high, temp_low). Auto-created on first API call. If no preferences set, system defaults are used.

The severe weather push sender (weather-forecast.py) checks per-user thresholds via get_subscriptions_with_prefs().

Testing Push

# Test notification (clearly labeled as test)
./scripts/test-push.sh test

# Fake rain alert
./scripts/test-push.sh rain budapest Budapest

# Fake severe weather alert
./scripts/test-push.sh severe inarcs Inárcs

Throttling

Throttle files (.push-{type}-{city}) prevent repeated alerts:

Seasonal Model Adaptation

Model rankings are computed both overall (last 30 days) and per calendar month. When enough monthly data accumulates, get_best_model() automatically prefers the seasonal winner for the current month.

model-rankings.json:
{
  "rankings": { ... },           // overall (last 30 days)
  "seasonal": {                  // per-month
    "budapest": {
      "temp": {
        "short": {
          "8": {"model": "ICON", "avg_error": 1.2, "samples": 45}  // August
        }
      }
    }
  }
}

Logic in get_best_model(): check seasonal[city][param][bucket][current_month] first → if enough samples, use it. Otherwise fall back to overall rankings.

After 12 months of data, the system will auto-adapt: e.g. ICON best for Central European summers, ECMWF for winters.

AMFOR ML — Training Dataset (Phase 2)

scripts/amfor-ml/build_features.py builds the LightGBM training set. Run it on the Pi (it needs MySQL); train on a PC or Colab.

/opt/amfor-cast/venv/bin/python3 scripts/amfor-ml/build_features.py            # all tracked cities
/opt/amfor-cast/venv/bin/python3 scripts/amfor-ml/build_features.py --city inarcs --start 2026-09-01
# → /opt/amfor-cast/data/ml/features.csv.gz

Simple Forecast Page Enhancements

The simple forecast page (simple-forecast-{city}.html) is a mobile-first lightweight view built from AMFOR blend data.

Timeline Modes

Weather Icons

Function wxIcon(temp, cloud, precip, wind, hour) in template:

Combo Warning Box

Replaces the old rain-only nowcast banner. Combines two data sources:

SourceChecks
Radar nowcastRain ongoing/approaching (real-time)
Forecast timelineHeat ≥36°C, Frost ≤0°C, Wind ≥50/70 km/h, Heavy precip ≥3mm/2h

Shows "✅ All clear for the next 2 hours" when nothing dangerous.

Feels-Like Temperature

Shown in amber next to actual temp when difference ≥3°C (e.g. 32°~38°). Data: feels_like_c (apparent_temperature from Open-Meteo).

Model Accuracy Badge

Fetches model-rankings.json and shows 🏆 ICON — Most accurate below the timeline header. Uses short-term temperature ranking per city.

Week Comparison

Client-side: fetches last 7 days from Open-Meteo Archive API, compares with forecast timeline averages. Shows trend arrows: ↑ warmer/wetter, ↓ cooler/drier.

CSP allows https://archive-api.open-meteo.com.

UV Sunburn Timer

Shown when UV ≥ 3. Formula: burn_minutes ≈ (200 × skin_factor) / (UV × 3). Default skin type II (fair European, factor=3). Stored in localStorage.amfor_skin_factor.

Weather Journal

Daily card showing yesterday's forecast vs reality. Generated by scripts/model-validator/journal.py (runs in validator flow). Output: weather-journal.json.

📓 Yesterday (Monday, Aug 25)
📊 AMFOR predicted 1.8°C warmer
🏆 Most accurate: ICON (±0.4°C)
🌧️ 2.3 mm of rain fell

Pollen Forecast

7-day forecast includes a pollen severity row, fetched from Open-Meteo Air Quality API.

API

GET https://air-quality-api.open-meteo.com/v1/air-quality
  ?latitude={lat}&longitude={lon}
  &hourly=birch_pollen,grass_pollen,ragweed_pollen,alder_pollen,mugwort_pollen
  &timezone=auto&forecast_days=5

Limit: max 7 forecast days (API returns 400 for higher values). Using 5 to be safe.

Display

LevelThreshold (grains/m³)Icon
None< 10—
Low10–30🟢 Low
Moderate30–60🟡 {type}
High60–100🟠 {type}
Very high> 100🔴 {type}

Shows the dominant pollen type for that day (birch, grass, ragweed, mugwort, or alder).

Template System

Templates use {{placeholder}} syntax (Python string replacement, not Jinja):

<h1>{{location}}</h1>
<div class="subtitle">{{generated_time}}</div>
<div class="summary">{{weather_summary}}</div>

Rules:

Unified Design System

All pages share the same base styles from shared/__init__.py → get_base_styles(theme):

  • Fonts: DM Sans (body) + JetBrains Mono (code/data)
  • Header: centered logo (64px) → h1 title → subtitle → home button (⌂ absolute right)
  • Container: max-width 900px, rounded corners, subtle shadow
  • Footer: thin top border, small text
  • Responsive: single breakpoint at 640px

Page-specific CSS (tables, charts, cards) is added on top. Theme overrides come from theme.css using [data-theme="name"] selectors + CSS variables.

PageStyle sourceNotes
Forecastget_base_styles() via template placeholderTemplate: scripts/weather-forecast/template.html
Historyget_base_styles() via template placeholderTemplate: scripts/weather-history/template.html
Rankingsget_base_styles() in report.pyGenerated by model-validator
Headacheget_base_styles() in analyzer scriptInline f-string template
Route WeatherCSS variables + theme.cssStandalone page, same visual structure

Never add custom fonts or hardcoded gradients to page styles. Use the shared base styles + theme.css for consistent look.

Environment

RequirementValue
Python3.11+ (Pi: 3.13, build server: 3.12)
Dependenciesmarkdown, pymysql, pywebpush (pip)
DatabaseMySQL on tarhely.com (config.ini for credentials)
PHP (tarhely.com)8.x with PDO, bcrypt, json (standard cPanel)
SSL fix (corporate)Handled in run.sh (SSL_CERT_FILE export)
PlatformLinux (GIT TS build server or Raspberry Pi 4)
BackupDaily mysqldump cron → /opt/amfor-cast/backups/ (30-day retention)

Deployment

run.sh auto-deploys on every run:

New API endpoints added to api/php/ auto-deploy on next hourly cron. No manual scp needed.

Admin Panel

Self-contained PHP admin at /api/admin.php, protected by HTTP Basic Auth (separate from user system).

SectionFunction
DashboardDB row counts, last run time, stale data alerts
UsersUser list with email, display name, login history
CitiesAll tracked cities, user counts, default flags
SessionsActive/expired sessions, revoke capability
HeadachesAdd/delete entries via form
RoutesPending vs evaluated route logs
EvaluationsPer-city coverage statistics
Gaps & FailuresDays with incomplete model data (<5/8 models)
SecurityLogin attempt monitoring, rate limit hits
DocumentDescription
🚀 Operations & Release GuideCron, deployment, run.sh, RPi setup, troubleshooting
🗺️ Unified Product RoadmapFeature roadmap, architecture decisions, timeline

🛠️ Fejlesztői dokumentáció

Architektúra, telepítés és hozzájárulási útmutató az Amfor-Cast-hoz

Architektúra

Az Amfor-Cast egy moduláris Python rendszer, amely több forrásból gyűjt időjárási adatokat, összehasonlítja a modelleket, és interaktív HTML riportokat generál.

A rendszer az Open-Meteo ingyenes API-ját használja (nem kell API kulcs), és naponta egyszer fut cron-ból.

Részletes architektúra diagramért lásd az angol verziót (a diagramok nyelv-függetlenek).

Gyors indulás

# Klónozás és beállítás
git clone https://gitlab.com/demogun1/misc_scripts.git
cd misc_scripts

# Python 3.12 venv létrehozása
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt

# Riportok helyi előnézete (nincs deploy, nincs email)
./scripts/weather-forecast/weather-forecast.py --dry-run
./scripts/weather-history/weather-history.py --days 7 --dry-run

# Minden futtatása (dry-run)
./run-and-publish.py --dry-run

# Minden futtatása + deploy (bőbeszédű mód)
./run-and-publish.py --verbose

Projekt struktúra

misc_scripts/
├── run-and-publish.py          # Vezénylő: generálja a site-ot (retry + email hiba esetén)
├── run.sh                      # Wrapper: git pull + clean + generálás + rsync
├── .gitlab-ci.yml              # CI: lint (ruff) → typecheck (mypy) → test (pytest) → deploy
├── ruff.toml                   # Lint konfiguráció
├── requirements.txt            # Python függőségek
├── tests/                      # pytest tesztek (59 db)
├── api/
│   └── php/                    # PHP API (tarhely.com hosting-on fut)
├── scripts/
│   ├── weather-forecast/       # Moduláris előrejelzés (fetch→risk→charts→render→summary)
│   ├── weather-history/        # Történeti grafikon generátor (19 Chart.js grafikon)
│   ├── model-validator/        # Modell pontosság kiértékelő + rangsoroló
│   └── headache-analyzer/      # Fejfájás korreláció elemző
├── shared/
│   ├── __init__.py             # get_base_styles() — egységes CSS generátor
│   ├── config.py               # Városok, küszöbértékek, URL-ek
│   ├── config_loader.py        # Reads config.ini (DB, paths, etc.)
│   ├── db.py                   # MySQL helper (minden DB művelet)
│   ├── model_selector.py       # Adaptív modellválasztó motor
│   ├── i18n.js                 # Kliens-oldali fordítások (EN/HU)
│   └── headaches.py            # Fejfájás napló parser
├── data/                       # Adat fájlok (JSON fallback)
└── public_html/                # Generált webes kimenet

Konfiguráció

Minden megosztott beállítás a shared/config.py-ban:

# Városok: kulcs → (megjelenített_név, szélesség, hosszúság)
CITIES = {
    "inarcs": ("Inárcs", 47.2667, 19.3500),
    "budapest": ("Budapest", 47.4979, 19.0402),
    "ivancsa": ("Iváncsa", 46.9833, 18.8167),
    "gyal": ("Gyál", 47.3833, 19.2167),
}

Új város hozzáadása

  1. Add hozzá a CITIES dict-hez a shared/config.py-ban
  2. Add hozzá a fül + város blokk a public_html/index.html-ben
  3. Add hozzá a cron listához (ha külön email kell)
  4. Az állomás automatikusan regisztrálódik a data/stations.json-be az első evaluate futáskor

Adaptív modellválasztás

A rendszer megtanulja melyik modell a legjobb adott helyszín/paraméter/időhorizont kombinációra:

  1. Gyűjtés — save-forecast.py napi pillanatképeket ment (minden modell)
  2. Kiértékelés — evaluate.py összehasonlítja az előrejelzést a mért adatokkal
  3. Rangsorolás — model_selector.py aggregálja a hibákat → kiválasztja a legjobbat
  4. Felhasználás — az előrejelzés scriptek és az útvonal tervező a nyertest használják
KonstansÉrtékJelentés
MIN_SAMPLES7Min. kiértékelések száma a rangsor elfogadásához
WINDOW_DAYS30Gördülő ablak a rangsor számításhoz
SIGNIFICANCE_GAP5.0%Min. előny egy modell preferálásához

AMFOR ML — tanító adathalmaz (2. fázis)

A scripts/amfor-ml/build_features.py állítja elő a LightGBM tanító adatokat. A Pi-n kell futtatni (MySQL hozzáférés kell); a tanítás PC-n vagy Colabon történik.

/opt/amfor-cast/venv/bin/python3 scripts/amfor-ml/build_features.py
# → /opt/amfor-cast/data/ml/features.csv.gz

i18n rendszer

Kliens-oldali EN/HU fordítás a shared/i18n.js segítségével:

Útvonal Időjárás Tervező (kliens-oldali)

Tisztán JavaScript, nincs szükség szerverre. Használt API-k:

SzolgáltatásCélLimit
OSRMÚtvonal számítás (távolság, idő, polyline)Fair use (ingyenes)
Open-MeteoIdőjárás előrejelzés pontonként (4 modell)10.000/nap
NominatimGeokódolás + fordított geokódolás1 kérés/mp
Leaflet + OSMTérkép megjelenítésKorlátlan

Fejfájás napló formátum

# data/headaches.txt
# Dátum, Súlyosság (1-3), Megjegyzések
2026-07-15, 2, délutáni kezdet, nyomás csökken
2026-07-22, 3, migrén, viharfront áthalad
2026-08-01, 1, enyhe, párás nap

Környezet

KövetelményÉrték
Python3.11+ (Pi: 3.13, build szerver: 3.12)
Függőségekmarkdown, pymysql (pip)
AdatbázisMariaDB a tarhely.com-on (config.ini a hitelesítő adatokhoz)
SSL javítás (céges)SSL_CERT_FILE=/etc/pki/tls/certs/ca-bundle.crt
PlatformLinux (GIT TS build szerver vagy Raspberry Pi 4)

Kapcsolódó dokumentáció

DokumentumLeírás
🚀 Üzemeltetési és Release útmutatóCron, deployment, run.sh, RPi beállítás, hibaelhárítás
🗺️ Egységes Termék ÜtemtervFunkció ütemterv, architektúra döntések, idővonal
🍓 Raspberry Pi Backend 🔒 Beolvasztva Beolvasztva az egységes ütemtervbe (2-6. fejezet) 🧠 Adaptív Modellválasztás 🔒 Beolvasztva Beolvasztva az egységes ütemtervbe (4-5. fejezet). 1-3. fázis kész. 🏗️ Web Deployment Stratégia 🔒 Beolvasztva Beolvasztva az egységes ütemtervbe (2-3. fejezet) 🗺️ Útvonal Időjárás Tervező 🔒 Beolvasztva Megvalósítva. Jövőbeli fejlesztések az egységes ütemtervben (v1.1).