# 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
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
main is blocked. All changes require a Merge Request with passing pipeline.
| Stage | Tool | What it checks | Blocking? |
|---|---|---|---|
lint | ruff | Unused imports, undefined names, syntax errors | Yes |
typecheck | mypy | Type errors, None access, wrong argument types | Yes |
test | pytest (59 tests) | Unit tests + integration import smoke test | Yes |
deploy | GitLab Pages | Copy to Pages (only if all above pass) | — |
# 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
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
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
CITIES in shared/config.pypublic_html/index.htmldata/stations.json on first evaluate runThe system learns which model is best per location/parameter/horizon:
save-forecast.py stores daily snapshots (all models)evaluate.py compares forecasts against measured actualsmodel_selector.py aggregates errors → picks best modelKey parameters in shared/model_selector.py:
| Constant | Value | Meaning |
|---|---|---|
MIN_SAMPLES | 7 | Minimum evaluations to trust a ranking |
WINDOW_DAYS | 30 | Rolling window for ranking calculation |
SIGNIFICANCE_GAP | 5.0% | Minimum advantage to prefer one model over another |
Client-side EN/HU translation using shared/i18n.js:
<span data-i18n="forecast">Forecast</span>
The key "forecast" is looked up in the TRANSLATIONS dict.
<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.
TRANSLATIONS dict in shared/i18n.jsdata-i18n="key" to the HTML elementshared/i18n.js → public_html/i18n.jsPure JavaScript, no backend needed for weather display. All client-side APIs:
| Service | Purpose | Limit |
|---|---|---|
| OSRM | Route calculation (distance, duration, polyline) | Fair use (free) |
| Open-Meteo | Weather forecast per waypoint (8 models) | 10,000/day |
| Nominatim | Geocoding + reverse geocoding | 1 req/sec |
| Leaflet + OSM | Map rendering + zone overlays | Unlimited |
| Feature | Activation | Details |
|---|---|---|
| Road conditions | Always | Ice risk, fog, aquaplaning, crosswind, wet road — per-waypoint badges + route summary |
| Weather zones | Always | Contiguous rain/storm/wind segments highlighted on map (colored dashed overlays) |
| Optimal departure | Checkbox | Scans ±3h window (7 candidates), scores by driving conditions, recommends best time |
| Multi-route comparison | Checkbox | Compare 2-3 alternative routes side by side with ranked scores and mini maps |
| Mobile responsive | Always | Touch-friendly inputs, stacked layout, 16px font (no iOS zoom), same features as desktop |
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.
PHP API on tarhely.com + client-side JS. Users can register, login, and save favorite cities.
user.js (login modal, city manager) + live-forecast.js (instant forecast for new cities)users, sessions, cities, user_cities| File | Endpoint | Description |
|---|---|---|
auth.php | ?action=register|login|logout|me | User authentication |
cities.php | ?action=list|my|search|add|remove|reorder | City management |
log-route.php | POST | Route forecast log (public, rate limited) |
| File | Purpose |
|---|---|
user.js | Login/register modal, user menu, city manager, dynamic tabs, onboarding hints |
live-forecast.js | Client-side forecast for cities without generated pages (Open-Meteo direct) |
city-nav.js | Floating city switcher — side panel (desktop) + horizontal tabs (mobile) |
cities table (if new) + user_citieslive-forecast.js fetches from Open-Meteo (4 models) → renders inlineweather-forecast-miskolc.htmlWhen a city has ranking data, the forecast page highlights the winning model:
Two levels of parallelization for fast report generation:
fetch_all_models() uses ThreadPoolExecutor(max_workers=4) — all 8 models fetched simultaneously (~2s instead of ~16s)run-and-publish.py runs 2 cities in parallel via subprocess.Popen--all-periods flag — single 30d API call → renders 3d, 7d, 30d HTML files| Metric | Before | After |
|---|---|---|
| 7 cities total | ~200s | ~35s |
| History API calls (7 cities) | 21 | 7 |
| Max concurrent requests | 1 | 8 |
Floating city switcher that appears on all pages:
window.userCities → localStorage → API → defaultscities-updated custom event to re-render when user changes citiesHeadache events are stored in MySQL (headaches table, per-user via user_id column).
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).
/api/admin.php → Headaches tab manages all users' entries.
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
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.
fetch_nowcast.py → rain detected → shared/push_notify.py → pywebpush → FCM/Mozilla Push → browser
shared/push_notify.py — send_rain_alert(city, name, intensity, minutes_away)api/push-subscribe.php — subscription management (GET vapid key, POST save, DELETE remove)public_html/notifications.js — subscribeToPush() / unsubscribeFromPush()public_html/sw.js — service worker push event handlerpush_subscriptions (user_id, endpoint, p256dh, auth)
# 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>');
| Type | Trigger | Source | Throttle |
|---|---|---|---|
| 🌧️ Rain | Radar detects rain approaching | Nowcast (every 15 min) | 1 hour/city |
| 🌪️ Severe weather | Gusts ≥ 80 km/h, rain ≥ 20mm/day, frost ≤ −5°C, heat ≥ 38°C | Forecast (hourly) | 6 hours/city |
Logged-in users can customize their alert thresholds via api/push-preferences.php:
| Setting | Default | Range |
|---|---|---|
| Rain threshold | 0.5 mm | 0–50 mm |
| Wind threshold | 60 km/h | 10–150 km/h |
| Heat alert | 38°C | 25–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().
# 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
Throttle files (.push-{type}-{city}) prevent repeated alerts:
$OUTPUT_DIR/.push-sent-{city} — 1 hour$OUTPUT_DIR/.push-headache-{city} / .push-severe-{city} — 6 hoursModel 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.
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
icon_temp, best_match_precip…), ensemble stats (temp_mean, temp_std, temp_spread, rain_models…), horizon_h, hour, day_of_year, lat/lonobs_temp, obs_precip, obs_rain (≥0.1 mm), obs_pressure, obs_cloud, obs_wind from the Archive APIforecast_date).The simple forecast page (simple-forecast-{city}.html) is a mobile-first lightweight view built from AMFOR blend data.
Function wxIcon(temp, cloud, precip, wind, hour) in template:
≥ 0.1mm (same as nowcast) — trace amounts below 0.1mm ignoredReplaces the old rain-only nowcast banner. Combines two data sources:
| Source | Checks |
|---|---|
| Radar nowcast | Rain ongoing/approaching (real-time) |
| Forecast timeline | Heat ≥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.
Shown in amber next to actual temp when difference ≥3°C (e.g. 32°~38°). Data: feels_like_c (apparent_temperature from Open-Meteo).
Fetches model-rankings.json and shows 🏆 ICON — Most accurate below the timeline header. Uses short-term temperature ranking per city.
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.
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.
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
7-day forecast includes a pollen severity row, fetched from Open-Meteo Air Quality 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.
| Level | Threshold (grains/m³) | Icon |
|---|---|---|
| None | < 10 | — |
| Low | 10–30 | 🟢 Low |
| Moderate | 30–60 | 🟡 {type} |
| High | 60–100 | 🟠 {type} |
| Very high | > 100 | 🔴 {type} |
Shows the dominant pollen type for that day (birch, grass, ragweed, mugwort, or alder).
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:
<script src="i18n.js?v=f9cbd09"></script>data-i18n on elements that need translationdata-i18n-en + data-i18n-hu attributesAll pages share the same base styles from shared/__init__.py → get_base_styles(theme):
Page-specific CSS (tables, charts, cards) is added on top. Theme overrides come from theme.css using [data-theme="name"] selectors + CSS variables.
| Page | Style source | Notes |
|---|---|---|
| Forecast | get_base_styles() via template placeholder | Template: scripts/weather-forecast/template.html |
| History | get_base_styles() via template placeholder | Template: scripts/weather-history/template.html |
| Rankings | get_base_styles() in report.py | Generated by model-validator |
| Headache | get_base_styles() in analyzer script | Inline f-string template |
| Route Weather | CSS variables + theme.css | Standalone page, same visual structure |
Never add custom fonts or hardcoded gradients to page styles. Use the shared base styles + theme.css for consistent look.
| Requirement | Value |
|---|---|
| Python | 3.11+ (Pi: 3.13, build server: 3.12) |
| Dependencies | markdown, pymysql, pywebpush (pip) |
| Database | MySQL 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) |
| Platform | Linux (GIT TS build server or Raspberry Pi 4) |
| Backup | Daily mysqldump cron → /opt/amfor-cast/backups/ (30-day retention) |
run.sh auto-deploys on every run:
rsync --delete $SITE/ → public_html/ (excludes api/)rsync api/php/ → public_html/api/ (excludes config.php and admin.php — these contain server secrets)run-log.jsonl + uptime-log.jsonl → public_html/api/New API endpoints added to api/php/ auto-deploy on next hourly cron. No manual scp needed.
Self-contained PHP admin at /api/admin.php, protected by HTTP Basic Auth (separate from user system).
| Section | Function |
|---|---|
| Dashboard | DB row counts, last run time, stale data alerts |
| Users | User list with email, display name, login history |
| Cities | All tracked cities, user counts, default flags |
| Sessions | Active/expired sessions, revoke capability |
| Headaches | Add/delete entries via form |
| Routes | Pending vs evaluated route logs |
| Evaluations | Per-city coverage statistics |
| Gaps & Failures | Days with incomplete model data (<5/8 models) |
| Security | Login attempt monitoring, rate limit hits |
| Document | Description |
|---|---|
| 🚀 Operations & Release Guide | Cron, deployment, run.sh, RPi setup, troubleshooting |
| 🗺️ Unified Product Roadmap | Feature roadmap, architecture decisions, timeline |
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).
# 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
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
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),
}
CITIES dict-hez a shared/config.py-banpublic_html/index.html-bendata/stations.json-be az első evaluate futáskorA rendszer megtanulja melyik modell a legjobb adott helyszín/paraméter/időhorizont kombinációra:
save-forecast.py napi pillanatképeket ment (minden modell)evaluate.py összehasonlítja az előrejelzést a mért adatokkalmodel_selector.py aggregálja a hibákat → kiválasztja a legjobbat| Konstans | Érték | Jelentés |
|---|---|---|
MIN_SAMPLES | 7 | Min. kiértékelések száma a rangsor elfogadásához |
WINDOW_DAYS | 30 | Gördülő ablak a rangsor számításhoz |
SIGNIFICANCE_GAP | 5.0% | Min. előny egy modell preferálásához |
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
obs_temp, obs_precip, obs_rain…)Kliens-oldali EN/HU fordítás a shared/i18n.js segítségével:
data-i18n="kulcs" → kikeresi a TRANSLATIONS dict-bőldata-i18n-en="..." + data-i18n-hu="..." attribútumokclass="lang-en" / class="lang-hu" → show/hideTisztán JavaScript, nincs szükség szerverre. Használt API-k:
| Szolgáltatás | Cél | Limit |
|---|---|---|
| OSRM | Útvonal számítás (távolság, idő, polyline) | Fair use (ingyenes) |
| Open-Meteo | Időjárás előrejelzés pontonként (4 modell) | 10.000/nap |
| Nominatim | Geokódolás + fordított geokódolás | 1 kérés/mp |
| Leaflet + OSM | Térkép megjelenítés | Korlátlan |
# 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övetelmény | Érték |
|---|---|
| Python | 3.11+ (Pi: 3.13, build szerver: 3.12) |
| Függőségek | markdown, pymysql (pip) |
| Adatbázis | MariaDB 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 |
| Platform | Linux (GIT TS build szerver vagy Raspberry Pi 4) |
| Dokumentum | Leírás |
|---|---|
| 🚀 Üzemeltetési és Release útmutató | Cron, deployment, run.sh, RPi beállítás, hibaelhárítás |
| 🗺️ Egységes Termék Ütemterv | Funkció ütemterv, architektúra döntések, idővonal |