feat: 지역 오늘·내일 페이지 절반에 검색 결과 새 문구 — 날짜·지역 먼저인 설명, 내일 제목에 내일 1위 각, 나머지 반은 예전 문구로 두고 클릭률 비교
This commit is contained in:
1 parent
ed2ab86404
commit
ce1d222216
3 files changed
+439
-14
No files matched your search
@@ -1,6 +1,8 @@
|
||||
import json
|
||||
import re
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import date, datetime, timedelta
|
||||
from html import escape
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
@@ -23,6 +25,11 @@ _CODE = re.compile(r'<meta name="region-code" content="(\d+)"')
|
||||
_DESC = re.compile(r'(<meta (?:name|property)="(?:description|og:description|twitter:description)" content=")[^"]*"')
|
||||
_NAME = re.compile(r"<h1>(.+?) (?:오늘|내일) 날씨")
|
||||
_H1 = re.compile(r"(<main><h1>[^<]*</h1>)")
|
||||
_TITLE = re.compile(r"<title>[^<]*</title>")
|
||||
_TITLE_META = re.compile(r'(<meta (?:property|name)="(?:og:title|twitter:title)" content=")[^"]*"')
|
||||
_WEEKDAY = "월화수목금토일"
|
||||
# 검색 결과 새 문구를 쓰는 페이지(나머지 반은 예전 문구로 두고 클릭률을 견준다)
|
||||
NEW_COPY = frozenset(json.loads(Path(__file__).with_name("seo_copy_test.json").read_text(encoding="utf-8"))["new"])
|
||||
|
||||
|
||||
def _clock(at: datetime) -> str:
|
||||
@@ -31,19 +38,35 @@ def _clock(at: datetime) -> str:
|
||||
return f"{'오전' if at.hour < 12 else '오후'} {h}시" + (f" {at.minute}분" if at.minute else "")
|
||||
|
||||
|
||||
def _date(day: date) -> str:
|
||||
return f"{day.month}월 {day.day}일({_WEEKDAY[day.weekday()]})"
|
||||
|
||||
|
||||
def _final(word: str) -> bool:
|
||||
"""마지막 글자에 받침이 있는지 (한글이 아니면 없다고 본다)."""
|
||||
c = ord(word[-1]) - 0xAC00
|
||||
return 0 <= c < 11172 and c % 28 != 0
|
||||
|
||||
|
||||
_SKY_WORD = {Sky.CLEAR: "맑음", Sky.PARTLY: "구름 많음", Sky.CLOUDY: "흐림"}
|
||||
_RAIN_WORD = {RainType.RAIN: "비", RainType.SLEET: "비나 눈", RainType.SNOW: "눈", RainType.SHOWER: "소나기"}
|
||||
|
||||
|
||||
def _day(rows: list[WeatherHourly]) -> tuple[int, int, int, str]:
|
||||
"""하루 예보: 최저, 최고, 강수확률, 하늘 (비·눈이 있으면 그것)."""
|
||||
temps = [float(r.temp_c) for r in rows]
|
||||
wet = next((RainType(r.rain_type) for r in rows if r.rain_type != RainType.NONE.value), None)
|
||||
day = [r for r in rows if 9 <= r.forecast_at.astimezone(KST).hour <= 18] or rows
|
||||
sky = _RAIN_WORD[wet] if wet else _SKY_WORD[Sky(max({r.sky for r in day}, key=[r.sky for r in day].count))]
|
||||
return round(min(temps)), round(max(temps)), max(r.rain_prob for r in rows), sky
|
||||
|
||||
|
||||
def day_summary(rows: list[WeatherHourly]) -> str:
|
||||
"""오늘 하루 예보 요약: 최저·최고, 강수확률, 하늘 (비·눈이 있으면 그것)."""
|
||||
if not rows:
|
||||
return ""
|
||||
temps = [float(r.temp_c) for r in rows]
|
||||
wet = next((RainType(r.rain_type) for r in rows if r.rain_type != RainType.NONE.value), None)
|
||||
day = [r for r in rows if 9 <= r.forecast_at.astimezone(KST).hour <= 18] or rows
|
||||
sky = _RAIN_WORD[wet] if wet else _SKY_WORD[Sky(max({r.sky for r in day}, key=[r.sky for r in day].count))]
|
||||
return f"최저 {round(min(temps))}°·최고 {round(max(temps))}°, 강수확률 {max(r.rain_prob for r in rows)}%, {sky}."
|
||||
lo, hi, prob, sky = _day(rows)
|
||||
return f"최저 {lo}°·최고 {hi}°, 강수확률 {prob}%, {sky}."
|
||||
|
||||
|
||||
def today_line(feed: Res_Feed, rows: list[WeatherHourly], sunset_at: Optional[datetime]) -> str:
|
||||
@@ -69,6 +92,53 @@ def tomorrow_line(rows: list[WeatherHourly], sunset_at: Optional[datetime]) -> s
|
||||
return " ".join(parts)
|
||||
|
||||
|
||||
def today_copy(day: date, place: str, feed: Res_Feed, rows: list[WeatherHourly], sunset_at: Optional[datetime]) -> str:
|
||||
"""새 문구의 오늘 설명: 날짜·지역, 하루 예보, 아침·낮 1위 각, 미세먼지·불쾌지수·자외선, 해 지는 시각."""
|
||||
weather = ""
|
||||
if rows:
|
||||
lo, hi, prob, _ = _day(rows)
|
||||
weather = f": 최저 {lo}°·최고 {hi}°, 비 올 확률 {prob}%"
|
||||
parts = [f"{_date(day)} {place} 오늘 날씨{weather}."]
|
||||
# 아침·낮 1위가 같으면 한 번만: 아침·낮엔 캠핑각
|
||||
firsts: dict[str, list[str]] = {}
|
||||
for slot, label in SLOT_LABEL.items():
|
||||
for s in feed.stories:
|
||||
if slot in ("morning", "day") and s.slot_ranks.get(slot) == 1:
|
||||
firsts.setdefault(s.name, []).append(label)
|
||||
if firsts:
|
||||
said = ", ".join("·".join(labels) + f"엔 {name}" for name, labels in firsts.items())
|
||||
parts.append(f"{said}{'이' if _final(list(firsts)[-1]) else '가'} 1위예요.")
|
||||
status = {s.label: s.value for s in feed.hero.status} if feed.hero else {}
|
||||
tail = [f"{label} {status[label]}" for label in ("미세먼지", "불쾌지수", "자외선") if label in status]
|
||||
if sunset_at:
|
||||
tail.append(f"해 지는 시각 {_clock(sunset_at)}")
|
||||
if tail:
|
||||
parts.append(", ".join(tail) + ".")
|
||||
return " ".join(parts)
|
||||
|
||||
|
||||
def tomorrow_copy(day: date, place: str, rows: list[WeatherHourly], top1: Optional[str], sunset_at: Optional[datetime]) -> str:
|
||||
"""새 문구의 내일 설명: 날짜·지역, 내일 하루 예보, 내일 1위 각, 해 지는 시각."""
|
||||
if not rows:
|
||||
return ""
|
||||
lo, hi, prob, sky = _day(rows)
|
||||
line = f"{_date(day)} {place} 내일 날씨: 최저 {lo}°·최고 {hi}°, {sky}, 비 올 확률 {prob}%."
|
||||
tail = ([f"내일 하기 좋은 일 1위는 {top1}"] if top1 else []) + ([f"해 지는 시각은 {_clock(sunset_at)}"] if sunset_at else [])
|
||||
if not tail:
|
||||
return line
|
||||
return f"{line} {', '.join(tail)}{'이에요' if _final(tail[-1]) else '예요'}."
|
||||
|
||||
|
||||
def _retitle(html: str, title: str) -> str:
|
||||
html = _TITLE.sub(lambda _: f"<title>{escape(title)}</title>", html, count=1)
|
||||
return _TITLE_META.sub(lambda m: f'{m.group(1)}{escape(title, quote=True)}"', html)
|
||||
|
||||
|
||||
def _mark(html: str, copy: str) -> str:
|
||||
"""앱이 검색 유입 GA 에 어느 문구로 들어왔는지 실어 보내게 표시한다."""
|
||||
return html.replace("</head>", f'<meta name="seo-copy" content="{copy}" />\n </head>', 1)
|
||||
|
||||
|
||||
def _put(template: str, line: str, extra: str = "") -> str:
|
||||
"""설명 메타와 본문 h1 바로 아래에 한 줄을 넣는다."""
|
||||
if not line:
|
||||
@@ -77,11 +147,14 @@ def _put(template: str, line: str, extra: str = "") -> str:
|
||||
return _H1.sub(lambda m: f"{m.group(1)}<p>{escape(line)}</p>{extra}", html, count=1)
|
||||
|
||||
|
||||
def _ranks(feed: Res_Feed, name: str) -> str:
|
||||
top = feed.bands.top5 if feed.bands else []
|
||||
return f"<h2>오늘 {escape(name)} 각 순위</h2><ol>{''.join(f'<li>{escape(t.name)} {t.score}점</li>' for t in top)}</ol>" if top else ""
|
||||
|
||||
|
||||
def fill(template: str, feed: Res_Feed, rows: list[WeatherHourly], name: str, sunset_at: Optional[datetime]) -> str:
|
||||
"""정적 지역 페이지에 오늘 값을 채운다: 설명 메타와 본문 첫 단락, 오늘 각 순위."""
|
||||
top = feed.bands.top5 if feed.bands else []
|
||||
ranks = f"<h2>오늘 {escape(name)} 각 순위</h2><ol>{''.join(f'<li>{escape(t.name)} {t.score}점</li>' for t in top)}</ol>" if top else ""
|
||||
return _put(template, today_line(feed, rows, sunset_at), ranks)
|
||||
return _put(template, today_line(feed, rows, sunset_at), _ranks(feed, name))
|
||||
|
||||
|
||||
class SeoService:
|
||||
@@ -115,7 +188,16 @@ class SeoService:
|
||||
sunset_at = sun_times(day, float(region.lat), float(region.lon)).sunset_at if region else None
|
||||
start = kst_midnight(day)
|
||||
_, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather.hourly_between(s, code, start, start + timedelta(days=1)))
|
||||
found = _NAME.search(template)
|
||||
name = found.group(1) if found else (feed.region_name or "")
|
||||
if path not in NEW_COPY:
|
||||
html = _put(template, tomorrow_line(rows or [], sunset_at)) if ahead else fill(template, feed, rows or [], name, sunset_at)
|
||||
return ErrorType.SUCCESS, _mark(html, "old")
|
||||
place = name.split(" ")[-1]
|
||||
if ahead:
|
||||
return ErrorType.SUCCESS, _put(template, tomorrow_line(rows or [], sunset_at))
|
||||
name = _NAME.search(template)
|
||||
return ErrorType.SUCCESS, fill(template, feed, rows or [], name.group(1) if name else (feed.region_name or ""), sunset_at)
|
||||
top1 = feed.hero.tomorrow.top1.name if feed.hero and feed.hero.tomorrow and feed.hero.tomorrow.top1 else None
|
||||
html = _put(template, tomorrow_copy(day, place, rows or [], top1, sunset_at))
|
||||
if top1:
|
||||
html = _retitle(html, f"{place} 내일 날씨 · 내일 1위는 {top1} | 날씨각")
|
||||
return ErrorType.SUCCESS, _mark(html, "new")
|
||||
return ErrorType.SUCCESS, _mark(_put(template, today_copy(day, place, feed, rows or [], sunset_at), _ranks(feed, name)), "new")
|
||||
Reference in new issue
Block a user