Initial commit

This commit is contained in:
Lina Rusakova committed 2026-11-11 01:26:17 +03:00
commit efa05921fc
10 files changed
+1063

No files matched your search

+212
View File
@@ -0,0 +1,212 @@
"""Разбор страниц meteoinfo.ru (Гидрометцентр России).
У сайта нет публичного API, поэтому читаем HTML-таблицы наблюдений и прогноза.
Логика перенесена с QML-плазмоида.
"""
from __future__ import annotations
import html as _html
import re
from datetime import date, datetime, time as dt_time, timedelta
from typing import List, Optional
from .model import Forecast, Observation, Period, Trend
WIND_DEG = {
"северный": 0, "северо-восточный": 45, "восточный": 90, "юго-восточный": 135,
"южный": 180, "юго-западный": 225, "западный": 270, "северо-западный": 315,
}
MONTHS = {
"января": 1, "февраля": 2, "марта": 3, "апреля": 4, "мая": 5, "июня": 6,
"июля": 7, "августа": 8, "сентября": 9, "октября": 10, "ноября": 11, "декабря": 12,
}
WEEKDAYS = {
"понедельник": "Пн", "вторник": "Вт", "среда": "Ср", "четверг": "Чт",
"пятница": "Пт", "суббота": "Сб", "воскресенье": "Вс",
}
_RE_NUMBER = re.compile(r"-?\d+(?:\.\d+)?")
_RE_TITLE = re.compile(r"<title>\s*Погода сейчас\s*([^<]*?)\s*,", re.I)
_RE_OBS_TIME = re.compile(r"(\d{1,2}\s+[А-Яа-яЁё]+,\s*\d{1,2}:\d{2})\s*\(время местное\)")
_RE_HEAD_DAY = re.compile(r"(понедельник|вторник|среда|четверг|пятница|суббота|воскресенье)\s+\d{1,2}\s+[а-яё]+")
_RE_DAY_CELL = re.compile(r"^([А-Яа-яЁё]+)\s+(\d{1,2})\s+([А-Яа-яЁё]+)$")
_RE_UPDATED = re.compile(r"Страница обновлена в\s*(\d{1,2}:\d{2})\s*МСК")
def clean_html(src: str) -> str:
s = re.sub(r"[\r\n]+", " ", src)
s = re.sub(r"<script[\s\S]*?</script>", "", s, flags=re.I)
s = re.sub(r"<style[\s\S]*?</style>", "", s, flags=re.I)
s = re.sub(r'<img[^>]*?title="([^"]*)"[^>]*>', lambda m: " " + m.group(1) + " ", s, flags=re.I)
s = re.sub(r"</t[dh]>", "|", s, flags=re.I)
s = re.sub(r"</tr>", "\n", s, flags=re.I)
s = re.sub(r"<br\s*/?>", " ", s, flags=re.I)
s = re.sub(r"<[^>]+>", "", s)
s = _html.unescape(s).replace("\xa0", " ")
s = re.sub(r"[ \t\r]+", " ", s)
return s
def _to_rows(text: str) -> List[List[str]]:
return [[c.strip() for c in line.split("|")] for line in text.split("\n")]
def _find_value(rows: List[List[str]], labels: List[str]) -> Optional[str]:
"""Строка таблицы, чья первая ячейка начинается с подписи -> следующая непустая ячейка."""
for cells in rows:
head = (cells[0] if cells else "").lower()
for label in labels:
if head.startswith(label):
for c in cells[1:]:
if c:
return c
return None
def _num(s: Optional[str]) -> Optional[float]:
if s is None:
return None
m = _RE_NUMBER.search(s.replace(",", "."))
return float(m.group(0)) if m else None
def parse_observation(src: str) -> Observation:
title = _RE_TITLE.search(src)
text = clean_html(src)
rows = _to_rows(text)
time_m = _RE_OBS_TIME.search(text)
temp = _num(_find_value(rows, ["температура воздуха"]))
if temp is None:
raise ValueError(
"Не удалось разобрать страницу (возможно, изменилась вёрстка сайта или станция не передаёт данные)"
)
dir_text = _find_value(rows, ["направление ветра"]) or ""
return Observation(
station=title.group(1) if title else "",
time=time_m.group(1) if time_m else "",
temperature=temp,
humidity=_num(_find_value(rows, ["относительная влажность"])),
pressure=_num(_find_value(rows, ["атмосферное давление"])),
wind_speed=_num(_find_value(rows, ["средняя скорость ветра", "скорость ветра"])),
wind_dir_text=dir_text,
wind_from_deg=WIND_DEG.get(dir_text.lower()),
precipitation=_find_value(rows, ["количество осадков", "осадки"]),
cloud_score=_num(_find_value(rows, ["балл общей облачности"])),
)
class _Section:
def __init__(self) -> None:
self.cond: List[str] = []
self.temp: List[str] = []
self.prob: List[str] = []
self.wind: List[str] = []
self.press: List[str] = []
def _at(lst: List[str], i: int) -> Optional[str]:
return lst[i] if 0 <= i < len(lst) else None
def parse_forecast(src: str, now: datetime, max_periods: int = 4) -> Forecast:
rows = _to_rows(clean_html(src))
h = -1
for i, cs in enumerate(rows):
if len(cs) > 3 and _RE_HEAD_DAY.fullmatch(cs[1].lower()):
h = i
break
if h < 0:
raise ValueError("Не удалось найти таблицу прогноза (возможно, изменилась вёрстка сайта)")
days = [] # (date, weekday, day_number) | None
for cell in rows[h][1:]:
m = _RE_DAY_CELL.match(cell)
month = MONTHS.get(m.group(3).lower()) if m else None
if not m or not month:
days.append(None)
continue
year = now.year + (1 if month < now.month - 6 else 0)
try:
d = date(year, month, int(m.group(2)))
except ValueError:
days.append(None)
continue
days.append((d, WEEKDAYS.get(m.group(1).lower(), ""), m.group(2)))
day, night = _Section(), _Section()
state: Optional[_Section] = None
for cells in rows[h + 1:]:
head = (cells[0] if cells else "").lower()
rest = cells[1:]
if head == "день":
state, day.cond = day, rest
elif head == "ночь":
state, night.cond = night, rest
elif "максимальная" in head:
day.temp = rest
elif "минимальная" in head:
night.temp = rest
elif state is not None and head == "осадки, вероятность":
state.prob = rest
elif state is not None and head == "ветер, м/с":
state.wind = rest
elif state is not None and head.startswith("давление"):
state.press = rest
if state is night:
break
today = now.date()
tomorrow = today + timedelta(days=1)
periods: List[Period] = []
for idx, col in enumerate(days):
if col is None:
continue
d, wd, num = col
for is_night in (True, False):
part = night if is_night else day
t = _at(part.temp, idx)
if not t: # период прошёл / нет данных
continue
end = datetime.combine(d, dt_time(9 if is_night else 21, 0))
if end <= now:
continue
when = "Сегодня" if d == today else "Завтра" if d == tomorrow else f"{wd} {num}"
periods.append(Period(
label=f"{when}, {'ночь' if is_night else 'день'}",
temp=_num(t),
prob=_num(_at(part.prob, idx)),
wind=_num(_at(part.wind, idx)),
pressure=_num(_at(part.press, idx)),
cond=_at(part.cond, idx) or "",
))
upd = _RE_UPDATED.search(src)
return Forecast(
updated=f"{upd.group(1)} МСК" if upd else "",
periods=periods[:max_periods],
trend=pressure_trend(periods),
)
def pressure_trend(periods: List[Period]) -> Optional[Trend]:
"""Тенденция давления по прогнозу: ближайший период против периода через ~сутки.
Прогнозное давление сравнивается только с прогнозным (станционное и приведённое могут отличаться).
"""
if len(periods) < 2 or periods[0].pressure is None:
return None
idx = min(2, len(periods) - 1)
last = periods[idx].pressure
if last is None:
return None
delta = last - periods[0].pressure
per_step = delta / idx # мм за 12 ч
if abs(per_step) < 1.5:
word, arrow = "стабильно", "→"
elif per_step > 0:
word, arrow = ("быстро растёт", "⇈") if per_step >= 3 else ("растёт", "↗")
else:
word, arrow = ("быстро падает", "⇊") if per_step <= -3 else ("падает", "↘")
return Trend(arrow, word, delta, idx * 12)