← 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. APIs used:

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

Feedback loop:

Every route request stores all-model forecasts in localStorage. POSTs to /api/log-route.php on tarhely.com → saved to MySQL route_logs table → evaluated daily by evaluate-routes.py.

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). Manage via the admin panel or direct SQL:

-- Add entry
INSERT INTO headaches (date, time, severity, city, notes)
VALUES ('2026-08-14', '07:30', 2, 'inarcs', 'pressure drop');

-- Severity: 1 = mild, 2 = moderate, 3 = severe
-- City: optional (NULL = applies to all cities)

Admin panel: /api/admin.php → Headaches tab provides a form for adding/deleting entries without SQL.

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

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 (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)

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

Related Documentation

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

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).