chore: main 병합 — 지금 날씨 점수 보정을 바꾸기 표로 통일

- index_service.py 충돌: main 의 오늘·내일 날씨 점수 계산은 그대로 쓰고, 보정만 strict_weather 에서 구간별 바꾸기 표(weather_slot_scores)로 바꿈
- weather_slot_scores 는 main 의 weather_why 가 쓰는 점수 근거(factors)를 그대로 둔 Result 를 돌려줌
- strict_weather 와 그 테스트(test_weather_score_is_strict_near_top) 삭제 (바꾸기 표로 통일하기로 정함)
- test_board_activates_gak_outside_its_time_window 의 ensure 스텁을 main 의 {날짜: {구간: Result}} 모양으로 맞춤
This commit is contained in:
skkim committed 2026-10-22 13:58:36 +09:00
commit 621a0cf90d
133 files changed
+8963 -489

No files matched your search

+31
View File
@@ -1,4 +1,5 @@
import re
import secrets
import uuid
from typing import Optional
@@ -6,6 +7,7 @@ from fastapi import Depends
from common.auth import PASSWORD_MAX_BYTES, decode, hash_password, issue_tokens, verify_password
from common.database.db_session_manager import DB_SESSION_MNG
from common.google_id import verify as verify_google
from common.database.model.models import User
from common.enums import ErrorType
from config.settings import settings
@@ -19,6 +21,15 @@ COLORS = ("orange", "blue", "green", "purple", "pink", "brown")
MOODS = ("clear", "partly", "cloudy", "rain", "thunder", "snow", "fog", "rainbow")
_NICK_WORDS = ("맑은", "포근한", "산들", "반짝", "느긋한", "보슬", "선선한", "따끈한")
_NICK_ANIMALS = {"rabbit": "토끼", "bear": "곰", "dog": "강아지", "sun": "해님", "moon": "달님", "cloud": "구름"}
def auto_nickname() -> str:
"""구글로 처음 들어온 사람의 이름: 맑은토끼 482. 내 정보에서 바꿀 수 있다."""
return f"{secrets.choice(_NICK_WORDS)}{secrets.choice(list(_NICK_ANIMALS.values()))} {secrets.randbelow(900) + 100}"
class AuthService:
def __init__(self, crud: UserCRUD = Depends(UserCRUD)) -> None:
self.crud = crud
@@ -47,6 +58,26 @@ class AuthService:
return ErrorType.AUTH_FAILED, None
return ErrorType.SUCCESS, user
async def google(self, credential: str) -> tuple[ErrorType, Optional[User]]:
"""구글 ID 토큰으로 로그인. 처음이면 자동 닉네임으로 계정을 만든다. 구글 이름·이메일은 저장하지 않는다."""
sub = await verify_google(credential)
if sub is None:
return ErrorType.AUTH_FAILED, None
login_id = f"google_{sub}"
err, user = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.by_login_id(s, login_id))
if err is not ErrorType.SUCCESS:
return err, None
if user is None:
err, user = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.create_google(s, sub, auto_nickname()))
if err is not ErrorType.SUCCESS:
# 같은 계정이 동시에 처음 들어온 경우엔 먼저 만들어진 쪽을 쓴다
err, user = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.by_login_id(s, login_id))
if err is not ErrorType.SUCCESS or user is None:
return ErrorType.DB_ERROR, None
if user.status != 1:
return ErrorType.AUTH_FAILED, None
return ErrorType.SUCCESS, user
async def refresh(self, refresh_token: str) -> tuple[ErrorType, Optional[User]]:
claims = decode(refresh_token, settings.jwt_refresh_secret, "refresh")
if claims is None:
+118
View File
@@ -0,0 +1,118 @@
from dataclasses import dataclass
from types import SimpleNamespace
from typing import Literal, Optional
from services.calc.day_slot import NIGHT_END_HOUR, SLOTS
Rain = Literal["dry", "wet"]
Air = Literal["good", "normal"]
# 미세먼지 허용 단계 → 초미세먼지(㎍/㎥) 점수 규칙. 단계 경계(좋음 15·보통 35)까지 100, 넘으면 깎는다
_AIR = {"good": {"zero": 35, "full": 15}, "normal": {"zero": 75, "full": 35}}
_WIND_LIMIT_OVER = 6 # 바람 상한에서 이만큼 더 세지면 0점
def _n(v: float) -> float:
"""근거 문구에 15.0° 대신 15° 로 나오게."""
return int(v) if float(v).is_integer() else v
@dataclass(frozen=True)
class MyRule:
"""사용자가 정한 내 각 조건. None 인 항목은 보지 않는다."""
temp: Optional[tuple[float, float]] = None # 체감온도 범위(°)
rain: Optional[Rain] = None # dry: 안 와야, wet: 와야
wind_max: Optional[float] = None # 바람 상한(m/s)
air: Optional[Air] = None # 미세먼지 허용 단계
humidity: Optional[tuple[int, int]] = None # 습도 범위(%)
slots: tuple[str, ...] = SLOTS # 볼 시간대
def axes(rule: MyRule) -> list[str]:
return [a for a, on in (("temp", rule.temp), ("rain", rule.rain), ("wind", rule.wind_max is not None), ("air", rule.air), ("humidity", rule.humidity)) if on]
def definition(rule: MyRule) -> SimpleNamespace:
"""공식 각과 같은 계산(evaluate)에 넣을 정의. 고른 조건끼리 가중치를 똑같이 나눈다."""
used = axes(rule)
share = {a: 100 // len(used) + (1 if i < 100 % len(used) else 0) for i, a in enumerate(used)} if used else {}
return SimpleNamespace(
**{f"weight_{a}": share.get(a, 0) for a in ("temp", "rain", "wind", "humidity", "air", "uv", "sun", "view", "time")},
factor_rules={
"temp": {"type": "range", "lo": _n(rule.temp[0]), "hi": _n(rule.temp[1])} if rule.temp else {"type": "range", "lo": -50, "hi": 60},
"rain": {"dir": rule.rain or "dry"},
"wind": {"type": "calm", "ok": _n(rule.wind_max), "limit": rule.wind_max + _WIND_LIMIT_OVER} if rule.wind_max is not None else {"type": "ignore"},
"humidity": {"type": "range", "lo": rule.humidity[0], "hi": rule.humidity[1]} if rule.humidity else {"type": "ignore"},
"air": _AIR[rule.air] if rule.air else None,
"time": {"type": "fixed", "value": 100},
},
zero_rules=[{"field": "rain", "op": "==", "value": "yes", "cap": 20}] if rule.rain == "dry" else [],
windows=[{"from": NIGHT_END_HOUR, "to": 24 + NIGHT_END_HOUR}],
)
# 공식 각을 내 각 조건으로 옮길 때 쓰는 대표 시각(해 뜨고 지는 시각은 계절마다 달라 가운데 값으로)
_SUNRISE_HOUR, _SUNSET_HOUR = 6, 18
_TEMP_MIN, _TEMP_MAX = -20, 40
def _slot_of_hour(h: int) -> str:
h %= 24
if NIGHT_END_HOUR <= h < 11:
return "morning"
if 11 <= h < _SUNSET_HOUR - 2:
return "day"
if _SUNSET_HOUR - 2 <= h < _SUNSET_HOUR + 1:
return "evening"
return "night"
def _window_slots(windows: list[dict]) -> list[str]:
hours: set[int] = set()
for w in windows:
if "around" in w:
mid = _SUNRISE_HOUR if w["around"] == "sunrise" else _SUNSET_HOUR
hours.update(range(mid - w["hours"], mid + w["hours"]))
else:
hours.update(range(w["from"], w["to"]))
got = {_slot_of_hour(h) for h in hours}
return [s for s in SLOTS if s in got]
def _preset_temp(r: dict) -> Optional[list[float]]:
off = r.get("offset", 0)
t = r["type"]
if t == "range":
lo, hi = r["lo"] - off, r["hi"] - off
elif t == "higher":
lo, hi = r["full"] - off, _TEMP_MAX
elif t == "lower":
lo, hi = _TEMP_MIN, r["full"] - off
else:
return None # 범위에서 멀수록 좋은 규칙은 범위 하나로 옮길 수 없다
lo, hi = max(_TEMP_MIN, lo), min(_TEMP_MAX, hi)
return [_n(lo), _n(hi)] if lo < hi else None
_PRESET_HUMIDITY = {"higher": [60, 100], "lower": [0, 60]}
def preset(defn) -> dict:
"""공식 각을 내 각 조건(MyGakRule 모양)으로 비슷하게 옮긴다. 비중 0인 요소와 옮길 수 없는 규칙은 뺀다."""
r = defn.factor_rules
out: dict = {"slots": _window_slots(defn.windows) or list(SLOTS)}
if defn.weight_temp and (temp := _preset_temp(r["temp"])):
out["temp"] = temp
if defn.weight_rain:
out["rain"] = r["rain"]["dir"]
wind = r.get("wind", {})
if defn.weight_wind and wind.get("type") in ("calm", "moderate"):
out["wind_max"] = _n(max(1, wind["ok"])) if wind["type"] == "calm" else 5
air = r.get("air")
if defn.weight_air and not (air and air["full"] > air["zero"]):
out["air"] = "normal"
hum = r.get("humidity", {})
if defn.weight_humidity and hum.get("type") in ("range", "higher", "lower"):
out["humidity"] = [hum["lo"], hum["hi"]] if hum["type"] == "range" else _PRESET_HUMIDITY[hum["type"]]
return out
+72 -21
View File
@@ -1,5 +1,6 @@
import asyncio
import random
import re
from dataclasses import dataclass, field
from datetime import date, datetime, time, timedelta
from typing import Optional
@@ -10,7 +11,7 @@ from redis.exceptions import RedisError
from common.cache.lock import redis_lock
from common.cache.redis_client import REDIS
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import Article, OpenMeteoHourly, Post, Region, WeatherHourly
from common.database.model.models import Article, IndexScore, OpenMeteoHourly, Post, Region, WeatherHourly
from common.enums import AirGrade, ArticleCategory, ErrorType, PostType, RainType, RefType, Sky, SkyGrade, SkySituation, SkyType, WarningType
from common.logger import LOG
from common.utils.kma_time import KST, ULTRA_DELAY, kst_midnight, latest_ultra_base, next_vilage_available, now_kst
@@ -20,8 +21,8 @@ from crud.region_crud import RegionCRUD
from crud.season_crud import SeasonCRUD
from crud.weather_crud import WeatherCRUD
from router.v1.feed.protocol import (
BandArticle, BandEvent, Bands, Cut, GakSlide, Hero, HeroStat, HourCell, HoursSlide, PostData, Res_Feed, Row, RowsSlide, SunsetSlide,
PlanSlide, PlanStep, TopIndex, WeekDay, WeekGak, WeekSlide,
BandArticle, BandEvent, Bands, Cut, GakSlide, Hero, HeroStat, HeroTomorrow, HourCell, HoursSlide, PostData, PostReaction, Res_Feed, Row, RowsSlide, SunsetSlide,
PlanSlide, PlanStep, TopIndex, WeatherWhy, WeekDay, WeekGak, WeekSlide,
)
from services.air_service import GRADE_LABEL as AIR_GRADE_LABEL
from services.air_service import pm10_grade, pm25_grade
@@ -62,7 +63,11 @@ LINEUP = [
(18, PostType.DAY_TRIP, RefType.NONE, None),
(19, PostType.MOON, RefType.NONE, None),
(20, PostType.UV, RefType.NONE, None),
(21, PostType.HERO, RefType.NONE, None),
(22, PostType.TODAY_GAK, RefType.NONE, None),
]
# 피드 목록 대신 히어로·오늘의 각 카드에 좋아요·댓글만 붙는 자리
_PINNED = {PostType.HERO: "hero_post", PostType.TODAY_GAK: "gak_post"}
# 좋아요·댓글 단위. 이 종류들은 전국이 같은 카드 하나, 나머지는 그 구 데이터로 채우는 카드라 시도마다 따로 만든다.
NATIONAL_SCOPE = "00"
NATIONAL_TYPES = frozenset({PostType.SEASON, PostType.TIP, PostType.QUOTE, PostType.MOON})
@@ -76,12 +81,13 @@ def sido_of(region_code: str) -> str:
def post_scope(post_type: PostType, region_code: str) -> str:
return NATIONAL_SCOPE if post_type in NATIONAL_TYPES else sido_of(region_code)
# 시간대별 순서. 목록에 없는 종류는 그 시간대에 꺼진다. '오늘 하루 날씨'는 히어로 바로 아래 고정이라 따로 둔다. 행사는 사이사이 무작위.
# 시간대별 순서. 목록에 없는 종류는 그 시간대에 꺼진다. '오늘 하루 날씨'는 히어로 바로 아래 고정이라 따로 둔다. 행사는 앞쪽 절반 사이사이 무작위.
# 알림은 비·특보가 있을 때만 켜지니 맨 앞, 주말·노을처럼 공유할 만한 카드를 그다음, 공기·자외선·상식 같은 평이한 정보는 뒤로.
ORDER = {
"morning": [PostType.ALERT, PostType.AIR, PostType.UV, PostType.GAK, PostType.GAK, PostType.GAK, PostType.SEASON, PostType.SUNSET, PostType.TIP, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.MOON, PostType.QUOTE],
"day": [PostType.GAK, PostType.ALERT, PostType.AIR, PostType.UV, PostType.GAK, PostType.GAK, PostType.SUNSET, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.SEASON, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.TIP, PostType.MOON, PostType.QUOTE],
"evening": [PostType.SUNSET, PostType.GAK, PostType.MOON, PostType.ALERT, PostType.GAK, PostType.GAK, PostType.AIR, PostType.TOMORROW, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.SEASON, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.TIP, PostType.QUOTE],
"night": [PostType.TOMORROW, PostType.MOON, PostType.ALERT, PostType.SUNSET, PostType.WEEK, PostType.GAK, PostType.WEEKEND_PLAN, PostType.GAK, PostType.GAK, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.AIR, PostType.SEASON, PostType.TIP, PostType.QUOTE],
"morning": [PostType.ALERT, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.SUNSET, PostType.GAK, PostType.DAY_TRIP, PostType.WEEKEND_PLAN, PostType.GAK, PostType.SEASON, PostType.GAK, PostType.MOON, PostType.AIR, PostType.UV, PostType.TIP, PostType.QUOTE],
"day": [PostType.ALERT, PostType.SUNSET, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.GAK, PostType.DAY_TRIP, PostType.WEEKEND_PLAN, PostType.GAK, PostType.SEASON, PostType.GAK, PostType.MOON, PostType.AIR, PostType.UV, PostType.TIP, PostType.QUOTE],
"evening": [PostType.SUNSET, PostType.ALERT, PostType.WEEK, PostType.MOON, PostType.WEEKEND_PLAN, PostType.GAK, PostType.TOMORROW, PostType.DAY_TRIP, PostType.WEEKEND_PLAN, PostType.GAK, PostType.SEASON, PostType.GAK, PostType.AIR, PostType.TIP, PostType.QUOTE],
"night": [PostType.TOMORROW, PostType.ALERT, PostType.MOON, PostType.WEEK, PostType.SUNSET, PostType.WEEKEND_PLAN, PostType.GAK, PostType.DAY_TRIP, PostType.WEEKEND_PLAN, PostType.GAK, PostType.SEASON, PostType.GAK, PostType.AIR, PostType.TIP, PostType.QUOTE],
}
_SKY_MODE = {"morning": "morning", "day": "day", "evening": "sunset", "night": "night"}
_CATEGORY_META = {ArticleCategory.SEASON.value: "계절 소식", ArticleCategory.TIP.value: "날씨 상식", ArticleCategory.GAK.value: "각 원리", ArticleCategory.QUOTE.value: "한 문장"}
@@ -220,7 +226,8 @@ def arrange(cards: list[PostData], slot: str, now: datetime, sunset_at: datetime
if slot == "night":
rest = [c for c in rest if c.post_type is not PostType.QUOTE] + [c for c in rest if c.post_type is PostType.QUOTE]
events = pool.get(PostType.EVENT, [])
gaps = sorted(random.Random(seed).sample(range(1, len(rest)), min(len(events), max(0, len(rest) - 1))), reverse=True)
front = range(1, max(1, len(rest) // 2 + 1))
gaps = sorted(random.Random(seed).sample(front, min(len(events), len(front))), reverse=True)
for gap, e in zip(gaps, reversed(events[:len(gaps)])):
rest.insert(gap, e)
return head + rest
@@ -234,6 +241,28 @@ def _by_position(posts: list[Post]) -> list[Post]:
return list(out.values())
def _tomorrow_best(board: IndexBoard, day: date) -> Optional[tuple[IndexItem, IndexScore]]:
"""내일 하루 점수로 1위인 각과 그 점수 (점수 × 중요도)."""
best = None
for i in board.items:
s = next((x for x in i.trend if x.score_date == day), None)
if s is not None and (best is None or rank_score(s.score, i.definition.priority) > rank_score(best[1].score, best[0].definition.priority)):
best = (i, s)
return best
def _hero_tomorrow(day: date, board: IndexBoard) -> HeroTomorrow:
best = _tomorrow_best(board, day)
top1 = None
if best is not None:
d, s = best[0].definition, best[1]
top1 = TopIndex(index_id=d.index_id, code=d.code, name=d.name, icon=d.icon, score=s.score, rank=1, summary=s.summary)
return HeroTomorrow(
day=day, weather_slots=board.tomorrow_slots, top1=top1,
weather_why={k: [WeatherWhy(label=w.label, weight=w.weight, score=w.score, note=w.note) for w in ws] for k, ws in board.tomorrow_why.items()},
)
def _top(i: IndexItem) -> TopIndex:
d = i.definition
return TopIndex(index_id=d.index_id, code=d.code, name=d.name, icon=d.icon, score=i.score.score, rank=i.rank, summary=i.score.summary, active=i.active,
@@ -366,8 +395,10 @@ class FeedService:
gak = sorted(board.ranked[:3], key=lambda i: _gak_key(i, now.hour)) if board else []
cards = []
pinned = {_PINNED[PostType(p.post_type)]: PostReaction(post_id=p.post_id, like_count=p.like_count, comment_count=p.comment_count)
for p in posts or [] if PostType(p.post_type) in _PINNED}
for p in posts or []:
if PostType(p.post_type) is PostType.GAK:
if PostType(p.post_type) is PostType.GAK or PostType(p.post_type) in _PINNED:
continue
data = self._render(p, ctx)
if data is not None:
@@ -381,7 +412,7 @@ class FeedService:
feed = Res_Feed(
region_code=region.code, region_name=region.name, slot=slot,
hero=self._hero(now, slot, hourly[0] if hourly else None, now_w, board, today, await self._uv(region.code, hour), _moon_view(region, now, hourly or [])),
stories=[_top(i) for i in items], posts=arrange(cards, slot, now, sunset_at, has_warning, f"{day}:{region.code}"),
stories=[_top(i) for i in items], posts=arrange(cards, slot, now, sunset_at, has_warning, f"{day}:{region.code}"), **pinned,
bands=Bands(
events=[BandEvent(event_id=e.event.event_id, name=e.event.name, status_label=e.status_label, icon=e.event.icon,
image=e.event.image_url, image_credit=image_credit(e.event)) for e in mix_kinds(events)[:4]],
@@ -440,10 +471,12 @@ class FeedService:
discomfort=cur.discomfort_index if cur else None, discomfort_label=discomfort_label(cur.discomfort_index) if cur else None,
rain_2h_text=now_w.rain_2h_text if now_w else None, will_rain_2h=now_w.will_rain_2h if now_w else None,
weather_score=board.weather_score if board else None, weather_slots=board.weather_slots if board else {},
weather_why={k: [WeatherWhy(label=w.label, weight=w.weight, score=w.score, note=w.note) for w in ws] for k, ws in board.weather_why.items()} if board else {},
top1=_top(top) if top else None, bubble=bubble,
moon_name=moon[0].name if moon else None, moon_pct=round(moon[0].lit * 100) if moon else None,
stats=[HeroStat(icon=x.icon, label=x.label, value=x.value, tone=x.tone) for x in hero_stats(x_in)],
status=[HeroStat(icon=x.icon, label=x.label, value=x.value, tone=x.tone) for x in hero_status(x_in)],
tomorrow=_hero_tomorrow(now.date() + timedelta(days=1), board) if board else None,
)
@staticmethod
@@ -454,7 +487,7 @@ class FeedService:
def _gak(self, p: Post, i: IndexItem) -> PostData:
d = i.definition
return PostData(**self._base(p), title=f"{d.name} {i.score.score}점", icon=d.icon, caption=_gak_caption(i),
slides=[GakSlide(kind="gak", index_id=d.index_id, code=d.code, name=d.name, rank=i.rank, score=i.score.score, line=d.description, summary=i.score.summary)],
slides=[GakSlide(kind="gak", index_id=d.index_id, code=d.code, name=d.name, rank=i.rank, score=i.score.score, line=d.description, summary=i.score.summary, rows=gak_rows(i), say=_band_sentence(d.sentences, i.score.score))],
share_messages=[f"오늘 {d.name} 어때? {d.name} {i.score.score}점이래"])
def _render(self, p: Post, c: "_Ctx") -> Optional[PostData]:
@@ -685,13 +718,8 @@ class FeedService:
return PostData(**base, title=plan.title, icon=icon, caption=caption, slides=slides, share_messages=[share])
def _tomorrow(self, base: dict, c: "_Ctx") -> PostData:
tomorrow = c.now.date() + timedelta(days=1)
rows = [Row(label=x.label, value=x.text) for x in c.now_w.commute]
best = None
for i in c.board.items if c.board else []:
s = next((x for x in i.trend if x.score_date == tomorrow), None)
if s is not None and (best is None or rank_score(s.score, i.definition.priority) > rank_score(best[1].score, best[0].definition.priority)):
best = (i, s)
best = _tomorrow_best(c.board, c.now.date() + timedelta(days=1)) if c.board else None
if best is not None:
rows.append(Row(label="내일 1위 각", value=f"{best[0].definition.name} {best[1].score}점"))
caption = _temp_change(c.today, c.tomorrow) or "출근 전에 한 번 더 확인해 주세요."
@@ -721,9 +749,32 @@ def _band_sentence(sentences: Optional[dict], score: int) -> Optional[str]:
return sentences[str(lo)] if lo is not None else None
# 각 포스트에 보일 근거 줄 이름. 시간(요일·노을 점수)은 계산 방식 설명이라 뺀다
_AXIS_NAME = {"temp": "기온", "rain": "비", "wind": "바람", "humidity": "습도", "air": "미세먼지", "uv": "자외선", "sun": "햇볕", "view": "시야"}
_NOTE_HEAD = {"wind": "바람 ", "humidity": "습도 ", "air": "초미세먼지 "}
def gak_rows(i: IndexItem, n: int = 4) -> list[Row]:
"""비중이 큰 조건부터 n개와 지금 값. 점수에 안 쓰는 조건도 n개가 될 때까지 지금 날씨로 채운다. 값은 계산 근거 문구의 첫 마디 (체감 18°, 확률 20%, 초속 3m)."""
d, notes = i.definition, i.score.notes or {}
weighted = sorted((a for a in _AXIS_NAME if getattr(d, f"weight_{a}", 0) and notes.get(a)), key=lambda a: -getattr(d, f"weight_{a}"))
axes = weighted + [a for a in ("temp", "rain", "wind", "air", "humidity") if a not in weighted and notes.get(a)]
rows = []
for a in axes[:n]:
head, _, tail = notes[a].partition(", ")
prob = re.search(r"확률 \d+%", notes[a]) if a == "rain" else None
if prob:
value = prob.group(0)
elif a == "air" and tail:
value = tail
else:
value = head.removeprefix(_NOTE_HEAD.get(a, ""))
rows.append(Row(label=_AXIS_NAME[a], value=value))
return rows
def _gak_caption(i: IndexItem) -> str:
"""점수 구간 설명 문장 + 슬라이드에 없는 내일 점수(없으면 하기 좋은 시간)."""
band = _band_sentence(i.definition.sentences, i.score.score)
"""슬라이드에 없는 내일 점수(없으면 하기 좋은 시간). 점수 구간 설명 문장은 슬라이드에 있다."""
nxt = next((x for x in i.trend if x.score_date > i.score.score_date), None)
if nxt is not None:
diff = nxt.score - i.score.score
@@ -732,7 +783,7 @@ def _gak_caption(i: IndexItem) -> str:
else:
spans = [_span(w) for w in i.definition.windows or []]
tail = f"하기 좋은 때는 {spans[0][0]}~{spans[0][1]}시예요." if spans else f"오늘의 각 {i.rank}위예요."
return f"{band} {tail}" if band else tail
return tail
def _temp_change(today: Optional[TodayWeather], tomorrow: Optional[TodayWeather]) -> Optional[str]:
+2 -3
View File
@@ -11,7 +11,6 @@ Tone = Literal["normal", "warn", "rain"]
UV_HIGH = 6.0
MUGGY_DI = 75 # 불쾌지수 '불쾌'가 시작되는 값
DISCOMFORT_MONTHS = range(6, 10) # 기상청처럼 6~9월에만. 더위 지표라 선선한 철엔 비 와도 '쾌적'으로 나온다
HUMID_DRY, HUMID_WET = 30, 60 # 습도 % : 이 아래 건조, 이 위 습함
TEMP_SWING_C = 10.0
WIND_CHILL_C = 3.0
@@ -67,11 +66,11 @@ def humidity_label(h: int) -> str:
def hero_status(x: HeroInput) -> list[HeroStatItem]:
"""히어로 상태 한 줄: 습도·불쾌지수(6~9월)·자외선(해 있을 때, 저녁 포함)·미세먼지를 단계 이름으로. 값이 없는 칸은 뺀다. 조심할 것만 warn."""
"""히어로 상태 한 줄: 습도·불쾌지수(늘)·자외선(해 있을 때, 저녁 포함)·미세먼지를 단계 이름으로. 값이 없는 칸은 뺀다. 조심할 것만 warn."""
out: list[HeroStatItem] = []
if x.humidity is not None:
out.append(HeroStatItem("humidity", "muggy", "습도", humidity_label(x.humidity)))
if x.discomfort is not None and x.now.month in DISCOMFORT_MONTHS:
if x.discomfort is not None:
out.append(HeroStatItem("discomfort", "muggy", "불쾌지수", discomfort_label(x.discomfort), "warn" if x.discomfort >= MUGGY_DI else "normal"))
if not x.after_dark and x.uv is not None:
out.append(HeroStatItem("uv", "glasses", "자외선", uv_label(x.uv), "warn" if x.uv >= UV_HIGH else "normal"))
+69 -9
View File
@@ -44,6 +44,21 @@ WEATHER_SCORE_DEF = SimpleNamespace(
# 가장 낮은 요소로 깎지 않는다: 밤엔 해 난 비율이 늘 0점이라 깎기가 밤 점수를 눌렀다
worst_pull=False,
)
WEATHER_AXIS_NAME = {"temp": "기온", "rain": "비", "wind": "바람", "humidity": "습도", "air": "미세먼지", "sun": "햇볕"}
@dataclass
class WeatherWhy:
label: str
weight: int
score: int
note: str
def weather_why(r: Result) -> list[WeatherWhy]:
"""날씨 점수를 이룬 조건들. 비중 큰 것부터."""
axes = sorted((a for a in WEATHER_AXIS_NAME if getattr(WEATHER_SCORE_DEF, f"weight_{a}")), key=lambda a: -getattr(WEATHER_SCORE_DEF, f"weight_{a}"))
return [WeatherWhy(label=WEATHER_AXIS_NAME[a], weight=getattr(WEATHER_SCORE_DEF, f"weight_{a}"), score=r.factors[a], note=r.notes.get(a, "")) for a in axes]
# 지금 날씨 점수 바꾸기 표: 구간마다 원래 점수 0~100 → 표시 점수(평균 60, 90점 이상은 드물게). scripts/gen_weather_score_table.py 가 만든다
WEATHER_SCORE_TABLE: dict[str, list[int]] = json.loads((Path(__file__).parent / "calc" / "weather_score_table.json").read_text(encoding="utf-8"))["slots"]
@@ -90,6 +105,9 @@ class IndexBoard:
weather_score: Optional[int]
items: list[IndexItem]
weather_slots: dict[str, int] = field(default_factory=dict)
weather_why: dict[str, list[WeatherWhy]] = field(default_factory=dict)
tomorrow_slots: dict[str, int] = field(default_factory=dict) # 내일 아침·낮·저녁·밤 날씨 점수
tomorrow_why: dict[str, list[WeatherWhy]] = field(default_factory=dict)
@property
def ranked(self) -> list[IndexItem]:
@@ -193,7 +211,7 @@ def shown_slot(key: str) -> str:
return "night" if key == EARLY else key
def _shown_parts(parts: dict[str, int], cur: str) -> dict[str, int]:
def _shown_parts(parts: dict, cur: str) -> dict:
"""구간 점수를 아침·낮·저녁·밤 순으로. 0~5시면 밤은 전날 밤 구간을 쓴다."""
shown = {shown_slot(k): v for k, v in parts.items() if k != ("night" if cur == EARLY else EARLY)}
return {k: shown[k] for k in SLOTS if k in shown}
@@ -204,9 +222,9 @@ def calibrated_weather(slot: str, score: int) -> int:
return WEATHER_SCORE_TABLE[shown_slot(slot)][score]
def weather_slot_scores(results: dict[str, Result]) -> dict[str, int]:
"""구간별 날씨 점수 결과를 표시 점수로."""
return {k: calibrated_weather(k, r.score) for k, r in results.items()}
def weather_slot_scores(results: dict[str, Result]) -> dict[str, Result]:
"""구간별 날씨 점수 결과의 점수를 표시 점수로 바꾼다 (점수 근거 factors 는 그대로)."""
return {k: replace(r, score=calibrated_weather(k, r.score)) for k, r in results.items()}
def rain_hours(by_at: dict[datetime, WeatherHourly], day: date) -> frozenset[int]:
@@ -326,10 +344,12 @@ class IndexService:
if region is None:
return ErrorType.NOT_FOUND, None
now = now_kst()
err, weather_parts = await self.ensure(region, now)
err, weather_days = await self.ensure(region, now)
if err is not ErrorType.SUCCESS:
return err, None
today = now.date()
weather_parts = weather_days[today]
tomorrow_parts = weather_days.get(today + timedelta(days=1), {})
cur = current_slot(now, sun_times(today, float(region.lat), float(region.lon)).sunset_at)
slots = slot_days(today)
err, defs = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.definitions(s))
@@ -369,11 +389,45 @@ class IndexService:
trend=[by_key[(d.index_id, day)] for day in slots if (d.index_id, day) in by_key], active=False, in_season=False,
))
return ErrorType.SUCCESS, IndexBoard(
region=region, day=today, weather_score=weather_parts.get(cur), items=items, weather_slots=_shown_parts(weather_parts, cur),
region=region, day=today, weather_score=weather_parts[cur].score if cur in weather_parts else None, items=items,
weather_slots=_shown_parts({k: r.score for k, r in weather_parts.items()}, cur),
weather_why=_shown_parts({k: weather_why(r) for k, r in weather_parts.items()}, cur),
tomorrow_slots=_shown_parts({k: r.score for k, r in tomorrow_parts.items()}, ""),
tomorrow_why=_shown_parts({k: weather_why(r) for k, r in tomorrow_parts.items()}, ""),
)
async def ensure(self, region: Region, now: datetime) -> tuple[ErrorType, Optional[dict[str, int]]]:
"""재료(예보·미세먼지)가 지수 계산 뒤에 바뀌었으면 오늘~모레와 이번 주말을 다시 계산한다. 오늘 구간별 날씨 점수도 같이 낸다."""
async def custom(self, region_code: str, defns: list) -> tuple[ErrorType, Optional[tuple[str, list[dict[str, Result]]]]]:
"""공식 각이 아닌 정의(내 각)들을 그 동네 오늘 아침·낮·저녁·밤으로 계산한다. (지금 구간, 정의마다 구간별 결과)"""
err, region = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.get(s, region_code))
if err is not ErrorType.SUCCESS:
return err, None
if region is None:
return ErrorType.NOT_FOUND, None
now = now_kst()
_, _, ultra = await asyncio.gather(self.weather_service.ensure_vilage(region, now), self.air_service.ensure(now), ultra_hours(region, now))
today = now.date()
start = kst_midnight(today)
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather.hourly_between(s, region.code, start - timedelta(days=1), start + timedelta(days=2)))
if err is not ErrorType.SUCCESS:
return err, None
if not rows:
return ErrorType.EXTERNAL_API_ERROR, None
air = await self.air_service.nearest(region)
by_at = with_ultra_rain({r.forecast_at: r for r in rows}, ultra)
ctx = Context(
day=today, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, rain_hours=rain_hours(by_at, today), wind_warning=False,
pm25=air.pm25 if air else None, air_label=GRADE_LABEL[AirGrade(air.grade)] if air and air.grade else None,
)
sunset_at = sun_times(today, float(region.lat), float(region.lon)).sunset_at
cur = current_slot(now, sunset_at)
out = []
for d in defns:
parts = slot_results(d, today, region, by_at, {}, ctx, sunset_at, now)
out.append({shown_slot(k): r for k, r in parts.items() if k != ("night" if cur == EARLY else EARLY)})
return ErrorType.SUCCESS, (shown_slot(cur), out)
async def ensure(self, region: Region, now: datetime) -> tuple[ErrorType, Optional[dict[date, dict[str, Result]]]]:
"""재료(예보·미세먼지)가 지수 계산 뒤에 바뀌었으면 오늘~모레와 이번 주말을 다시 계산한다. 오늘·내일 구간별 날씨 점수도 같이 낸다."""
_, _, _, warnings, ultra = await asyncio.gather(
self.weather_service.ensure_vilage(region, now), self.weather_service.ensure_mid(region, now), self.air_service.ensure(now),
self.warning_service.for_region(region, now), ultra_hours(region, now, wait=True),
@@ -403,7 +457,13 @@ class IndexService:
)
today_ctx = Context(day=today, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, rain_hours=rain_hours(by_at, today), **base_ctx)
sunset_at = sun_times(today, float(region.lat), float(region.lon)).sunset_at
weather_parts = weather_slot_scores(slot_results(WEATHER_SCORE_DEF, today, region, by_at, by_om, today_ctx, sunset_at, now))
tomorrow = today + timedelta(days=1)
tomorrow_ctx = Context(day=tomorrow, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, rain_hours=rain_hours(by_at, tomorrow), **base_ctx)
tomorrow_sunset = sun_times(tomorrow, float(region.lat), float(region.lon)).sunset_at
weather_parts = {
today: weather_slot_scores(slot_results(WEATHER_SCORE_DEF, today, region, by_at, by_om, today_ctx, sunset_at, now)),
tomorrow: weather_slot_scores(slot_results(WEATHER_SCORE_DEF, tomorrow, region, by_at, by_om, tomorrow_ctx, tomorrow_sunset)),
}
issued = max([r.issued_at for r in rows] + [d.issued_at for d in daily_rows or []])
inputs_at = max(issued, air.measured_at) if air else issued
+83
View File
@@ -0,0 +1,83 @@
import re
from typing import Optional
from fastapi import Depends
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import MyGak, User
from common.enums import ErrorType
from crud.my_gak_crud import MyGakCRUD
from services.calc.day_slot import SLOTS
from services.calc.my_gak_calc import MyRule, axes, definition, preset
from services.index_service import IndexService
# 한 사람이 만들 수 있는 내 각 수
MAX_PER_USER = 20
_LINK = re.compile(r"https?://|www\.|[a-z0-9-]+\.(?:com|net|kr|co|org|io|me|ly|gl)\b|\d{3,}", re.I)
def gak_name(name: str) -> Optional[str]:
"""앞뒤 공백을 빼고 끝에 '각'을 붙인다. 링크·긴 숫자(전화번호 등)는 받지 않는다."""
name = " ".join(name.split())
if not name or _LINK.search(name):
return None
name = name if name.endswith("각") else f"{name}각"
return name if len(name) <= 12 else None
def my_rule(rule: dict) -> MyRule:
return MyRule(
temp=tuple(rule["temp"]) if rule.get("temp") else None, rain=rule.get("rain"), wind_max=rule.get("wind_max"), air=rule.get("air"),
humidity=tuple(rule["humidity"]) if rule.get("humidity") else None, slots=tuple(s for s in SLOTS if s in (rule.get("slots") or SLOTS)),
)
class MyGakService:
def __init__(self, crud: MyGakCRUD = Depends(MyGakCRUD), index: IndexService = Depends(IndexService)) -> None:
self.crud, self.index = crud, index
async def mine(self, user: User) -> tuple[ErrorType, list[MyGak]]:
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.of_user(s, user.user_id))
return err, rows or []
async def add(self, user: User, name: str, rule: dict) -> tuple[ErrorType, Optional[MyGak]]:
name = gak_name(name)
if name is None:
return ErrorType.INVALID_INPUT, None
err, n = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.count(s, user.user_id))
if err is not ErrorType.SUCCESS:
return err, None
if n >= MAX_PER_USER:
return ErrorType.INVALID_INPUT, None
return await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add(s, user.user_id, name, rule))
async def delete(self, user: User, my_gak_id: int) -> ErrorType:
err, found = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.delete(s, user.user_id, my_gak_id))
if err is not ErrorType.SUCCESS:
return err
return ErrorType.SUCCESS if found else ErrorType.NOT_FOUND
async def presets(self) -> tuple[ErrorType, list[dict]]:
err, defs = await DB_SESSION_MNG.execute_lambda(lambda s: self.index.crud.definitions(s))
if err is not ErrorType.SUCCESS:
return err, []
return err, [{"code": d.code, "name": d.name, "icon": d.icon, "rule": preset(d)} for d in defs]
async def score(self, region_code: str, rules: list[dict]) -> tuple[ErrorType, Optional[tuple[str, list[dict]]]]:
"""조건마다 그 동네 오늘 시간대별 점수. 지금 시간대를 골랐으면 그 점수, 아니면 고른 시간대 중 가장 좋은 점수."""
mine = [my_rule(r) for r in rules]
err, got = await self.index.custom(region_code, [definition(r) for r in mine])
if err is not ErrorType.SUCCESS or got is None:
return err, None
now_slot, parts = got
out = []
for r, p in zip(mine, parts):
picked = {k: v for k, v in p.items() if k in r.slots}
key = now_slot if now_slot in picked else max(picked, key=lambda k: picked[k].score, default=None)
res = picked.get(key) if key else None
out.append({
"score": res.score if res else None, "slot": key if res else None,
"slots": {k: v.score for k, v in picked.items()},
"reasons": [res.notes[a] for a in axes(r) if res.notes.get(a)] if res else [],
})
return ErrorType.SUCCESS, (now_slot, out)
+58 -17
View File
@@ -7,10 +7,17 @@ from fastapi import Depends
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import Comment, Post, User
from common.enums import ErrorType
from common.liker import Liker
from common.utils.kma_time import kst_midnight, now_kst
from crud.feed_crud import FeedCRUD
from crud.reaction_crud import ReactionCRUD
from crud.region_crud import RegionCRUD
from services.talk_service import _LINK, _PHONE
COMMENT_MAX = 60
# 로그인 없이 IP 하나가 하루에 쓸 수 있는 댓글 수
ANON_DAILY_MAX = 20
ANON_CHARACTER, ANON_COLOR = "rabbit", "orange"
PAGE = 20
@@ -32,8 +39,8 @@ class SavedView:
class ReactionService:
def __init__(self, crud: ReactionCRUD = Depends(ReactionCRUD), feed: FeedCRUD = Depends(FeedCRUD)) -> None:
self.crud, self.feed = crud, feed
def __init__(self, crud: ReactionCRUD = Depends(ReactionCRUD), feed: FeedCRUD = Depends(FeedCRUD), regions: RegionCRUD = Depends(RegionCRUD)) -> None:
self.crud, self.feed, self.regions = crud, feed, regions
async def _post_exists(self, post_id: int) -> ErrorType:
err, post = await DB_SESSION_MNG.execute_lambda(lambda s: self.feed.get(s, post_id))
@@ -41,11 +48,11 @@ class ReactionService:
return err
return ErrorType.SUCCESS if post is not None else ErrorType.NOT_FOUND
async def like_post(self, post_id: int, user: User, on: bool) -> tuple[ErrorType, Optional[int]]:
async def like_post(self, post_id: int, who: Liker, on: bool) -> tuple[ErrorType, Optional[int]]:
err = await self._post_exists(post_id)
if err is not ErrorType.SUCCESS:
return err, None
return await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.toggle_post_like(s, post_id, user.user_id, on))
return await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.toggle_post_like(s, post_id, who, on))
async def save_post(self, post_id: int, user: User, on: bool) -> ErrorType:
err = await self._post_exists(post_id)
@@ -60,6 +67,12 @@ class ReactionService:
err, marks = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.my_marks(s, user.user_id, post_ids))
return marks if err is ErrorType.SUCCESS else (set(), set())
async def anon_liked(self, ip_hash: str, post_ids: list[int]) -> set[int]:
if not post_ids:
return set()
err, liked = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.anon_liked_posts(s, ip_hash, post_ids))
return liked if err is ErrorType.SUCCESS else set()
async def counts(self, post_ids: list[int]) -> dict[int, tuple[int, int]]:
"""피드는 캐시돼 있어서 좋아요·댓글 수는 매번 DB 에서 덮어쓴다."""
if not post_ids:
@@ -71,36 +84,64 @@ class ReactionService:
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.saved_posts(s, user.user_id, cursor, PAGE))
return err, [SavedView(post=p, saved_at=ps.created_at) for p, ps in rows or []]
async def comments(self, post_id: int, user: Optional[User], cursor: Optional[int]) -> tuple[ErrorType, list[CommentView]]:
@staticmethod
def _view(c: Comment, nickname: Optional[str], character: Optional[str], color: Optional[str], mood: Optional[str], liked: bool, who: Liker) -> CommentView:
if c.user_id is None:
mine = who.user_id is None and c.ip_hash == who.ip_hash
return CommentView(comment=c, nickname=f"{c.region_name} 익명" if c.region_name else "익명", character=ANON_CHARACTER, color=ANON_COLOR, mood=None, liked=liked, mine=mine)
return CommentView(comment=c, nickname=nickname or "", character=character or ANON_CHARACTER, color=color or ANON_COLOR, mood=mood, liked=liked, mine=c.user_id == who.user_id)
async def comments(self, post_id: int, user: Optional[User], ip_hash: str, cursor: Optional[int]) -> tuple[ErrorType, list[CommentView]]:
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.comments(s, post_id, cursor, PAGE))
if err is not ErrorType.SUCCESS:
return err, []
liked: set[int] = set()
ids = [c.comment_id for c, *_ in rows]
if user is not None and rows:
_, liked = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.liked_comments(s, user.user_id, [c.comment_id for c, *_ in rows]))
return ErrorType.SUCCESS, [
CommentView(comment=c, nickname=n, character=ch, color=co, mood=mo, liked=c.comment_id in (liked or set()), mine=user is not None and c.user_id == user.user_id)
for c, n, ch, co, mo in rows
]
_, liked = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.liked_comments(s, user.user_id, ids))
elif rows:
_, liked = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.anon_liked_comments(s, ip_hash, ids))
who = Liker(user_id=user.user_id if user else None, ip_hash=ip_hash)
return ErrorType.SUCCESS, [self._view(c, n, ch, co, mo, c.comment_id in (liked or set()), who) for c, n, ch, co, mo in rows]
async def add_comment(self, post_id: int, user: User, body: str) -> tuple[ErrorType, Optional[CommentView]]:
async def add_comment(self, post_id: int, user: Optional[User], who: Liker, body: str, region_code: Optional[str] = None) -> tuple[ErrorType, Optional[CommentView]]:
"""로그인 없이도 쓴다. 그때는 링크·전화번호를 막고 IP 하나에 하루 ANON_DAILY_MAX 개까지, 이름은 쓸 때 동네로 '마포구 익명'."""
body = body.strip()
if not body or len(body) > COMMENT_MAX:
return ErrorType.INVALID_INPUT, None
err = await self._post_exists(post_id)
if err is not ErrorType.SUCCESS:
return err, None
err, c = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add_comment(s, post_id, user.user_id, body))
return err, (CommentView(comment=c, nickname=user.nickname, character=user.character, color=user.color, mood=user.mood, liked=False, mine=True) if c else None)
region_name = None
if user is None:
if _LINK.search(body) or _PHONE.search(body):
return ErrorType.LINK_NOT_ALLOWED, None
today = kst_midnight(now_kst().date())
err, n = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.anon_comments_since(s, who.ip_hash, today))
if err is not ErrorType.SUCCESS:
return err, None
if n >= ANON_DAILY_MAX:
return ErrorType.DAILY_LIMIT, None
if region_code:
err, region = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.get(s, region_code))
if err is not ErrorType.SUCCESS:
return err, None
region_name = region.short_name if region else None
err, c = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add_comment(s, post_id, who, body, region_name))
if c is None:
return err, None
if user is None:
return err, self._view(c, None, None, None, None, False, who)
return err, self._view(c, user.nickname, user.character, user.color, user.mood, False, who)
async def delete_comment(self, comment_id: int, user: User) -> ErrorType:
err, ok = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.delete_comment(s, comment_id, user.user_id))
async def delete_comment(self, comment_id: int, who: Liker) -> ErrorType:
err, ok = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.delete_comment(s, comment_id, who))
if err is not ErrorType.SUCCESS:
return err
return ErrorType.SUCCESS if ok else ErrorType.NOT_FOUND
async def like_comment(self, comment_id: int, user: User, on: bool) -> tuple[ErrorType, Optional[int]]:
err, count = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.toggle_comment_like(s, comment_id, user.user_id, on))
async def like_comment(self, comment_id: int, who: Liker, on: bool) -> tuple[ErrorType, Optional[int]]:
err, count = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.toggle_comment_like(s, comment_id, who, on))
if err is not ErrorType.SUCCESS:
return err, None
return (ErrorType.NOT_FOUND, None) if count is None else (ErrorType.SUCCESS, count)
+24 -9
View File
@@ -21,7 +21,7 @@ from services.feed_service import FeedService
_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>(.+?) 오늘 날씨")
_NAME = re.compile(r"<h1>(.+?) (?:오늘|내일) 날씨")
_H1 = re.compile(r"(<main><h1>[^<]*</h1>)")
@@ -61,15 +61,27 @@ def today_line(feed: Res_Feed, rows: list[WeatherHourly], sunset_at: Optional[da
return " ".join(parts)
def fill(template: str, feed: Res_Feed, rows: list[WeatherHourly], name: str, sunset_at: Optional[datetime]) -> str:
"""정적 지역 페이지에 오늘 값을 채운다: 설명 메타와 본문 첫 단락, 오늘 각 순위."""
line = today_line(feed, rows, sunset_at)
def tomorrow_line(rows: list[WeatherHourly], sunset_at: Optional[datetime]) -> str:
"""내일 페이지 한 줄: 내일 하루 예보와 해 지는 시각."""
parts = [day_summary(rows)] if rows else []
if parts and sunset_at:
parts.append(f"해 지는 시각 {_clock(sunset_at)}.")
return " ".join(parts)
def _put(template: str, line: str, extra: str = "") -> str:
"""설명 메타와 본문 h1 바로 아래에 한 줄을 넣는다."""
if not line:
return template
html = _DESC.sub(lambda m: f'{m.group(1)}{escape(line, quote=True)}"', template)
return _H1.sub(lambda m: f"{m.group(1)}<p>{escape(line)}</p>{extra}", html, count=1)
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 ""
html = _DESC.sub(lambda m: f'{m.group(1)}{escape(line, quote=True)}"', template)
return _H1.sub(lambda m: f"{m.group(1)}<p>{escape(line)}</p>{ranks}", html, count=1)
return _put(template, today_line(feed, rows, sunset_at), ranks)
class SeoService:
@@ -98,9 +110,12 @@ class SeoService:
LOG.error(f"[seo] feed {code}: {err}")
return ErrorType.SUCCESS, template
_, region = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.get(s, code))
today = now_kst().date()
sunset_at = sun_times(today, float(region.lat), float(region.lon)).sunset_at if region else None
start = kst_midnight(today)
ahead = path.startswith("tomorrow/")
day = now_kst().date() + timedelta(days=1 if ahead else 0)
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)))
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)
+45
View File
@@ -0,0 +1,45 @@
import io
import os
import re
import uuid
from typing import Optional
from PIL import Image, ImageOps, UnidentifiedImageError
from config.settings import settings
from common.enums import ErrorType
MAX_BYTES = 10 * 1024 * 1024 # 올릴 수 있는 원본 크기
MAX_SIDE = 1080 # 긴 변을 이만큼으로 줄인다
URL_PREFIX = "/v1/talk/image/"
_NAME = re.compile(r"^[0-9a-f]{32}\.webp$")
def folder() -> str:
path = os.path.join(settings.upload_dir, "talk")
os.makedirs(path, exist_ok=True)
return path
def file_of(url: str) -> Optional[str]:
"""올린 사진 주소 → 저장된 파일 경로. 우리가 만든 이름이 아니거나 파일이 없으면 None."""
name = url.removeprefix(URL_PREFIX)
if not url.startswith(URL_PREFIX) or not _NAME.match(name):
return None
path = os.path.join(folder(), name)
return path if os.path.isfile(path) else None
def save(data: bytes) -> tuple[ErrorType, Optional[str]]:
"""사진을 다시 그려 저장한다. 다시 그리면 찍은 위치(GPS)·기기 같은 메타데이터가 모두 빠진다. 돌려준 값은 글에 붙일 주소."""
if len(data) > MAX_BYTES:
return ErrorType.INVALID_INPUT, None
try:
with Image.open(io.BytesIO(data)) as src:
img = ImageOps.exif_transpose(src).convert("RGB")
except (UnidentifiedImageError, OSError, Image.DecompressionBombError):
return ErrorType.INVALID_INPUT, None
img.thumbnail((MAX_SIDE, MAX_SIDE))
name = f"{uuid.uuid4().hex}.webp"
img.save(os.path.join(folder(), name), "WEBP", quality=82)
return ErrorType.SUCCESS, URL_PREFIX + name
+173
View File
@@ -0,0 +1,173 @@
import re
from dataclasses import dataclass
from datetime import timedelta
from typing import Optional
from fastapi import Depends
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import Talk, User, WeatherHourly
from common.enums import ErrorType, RainType, Sky, TalkReport
from common.liker import Liker
from common.utils.kma_time import kst_midnight, now_kst
from crud.region_crud import RegionCRUD
from crud.talk_crud import TalkCRUD
from crud.weather_crud import WeatherCRUD
from services.talk_image import file_of
BODY_MAX = 100
DAILY_MAX = 5
# 로그인한 서로 다른 사람의 신고가 이만큼 쌓이면 운영자 확인 전까지 숨긴다
HIDE_AT = 3
PAGE = 20
# 보는 사람과 같은 시도에서 쓴 글은 이만큼 늦게 쓴 글처럼 앞에 둔다
LOCAL_BOOST = timedelta(hours=12)
# 링크(http, www, 도메인 꼴)와 전화번호(010-1234-5678, 01012345678, 02-123-4567)
_LINK = re.compile(r"https?://|www\.|[a-z0-9-]+\.(?:com|net|kr|co|org|io|me|ly|gl)\b", re.I)
_PHONE = re.compile(r"0\d{1,2}[-.\s]?\d{3,4}[-.\s]?\d{4}")
_SKY = {Sky.CLEAR: "맑음", Sky.PARTLY: "구름 많음", Sky.CLOUDY: "흐림"}
_RAIN = {RainType.RAIN: "비", RainType.SLEET: "비나 눈", RainType.SNOW: "눈", RainType.SHOWER: "소나기"}
def weather_line(row: Optional[WeatherHourly]) -> Optional[str]:
"""글에 붙일 그때 날씨: 18° 맑음 / 12° 비."""
if row is None:
return None
rain = RainType(row.rain_type)
word = _RAIN.get(rain) or _SKY.get(Sky(row.sky), "")
return f"{round(float(row.temp_c))}° {word}".strip()
def spread_authors(views: list["TalkView"]) -> list["TalkView"]:
"""같은 사람 글이 붙으면 뒤에서 다른 사람 글을 당겨 끼운다."""
out = list(views)
for i in range(1, len(out)):
if out[i].author.user_id == out[i - 1].author.user_id:
j = next((k for k in range(i + 1, len(out)) if out[k].author.user_id != out[i - 1].author.user_id), None)
if j is not None:
out.insert(i, out.pop(j))
return out
def parse_cursor(cursor: str) -> Optional[tuple[int, int]]:
key, _, talk_id = cursor.partition("_")
return (int(key), int(talk_id)) if key.lstrip("-").isdigit() and talk_id.isdigit() else None
@dataclass
class TalkView:
talk: Talk
author: User
region_name: Optional[str]
liked: bool
mine: bool
class TalkService:
def __init__(self, crud: TalkCRUD = Depends(TalkCRUD), regions: RegionCRUD = Depends(RegionCRUD), weather: WeatherCRUD = Depends(WeatherCRUD)) -> None:
self.crud, self.regions, self.weather = crud, regions, weather
async def page(self, user: Optional[User], ip_hash: str, region_code: Optional[str], cursor: Optional[str]) -> tuple[ErrorType, list[TalkView], Optional[str]]:
"""한 페이지와 다음 페이지 cursor. 같은 사람 글은 페이지 안에서 떨어뜨린다."""
after = parse_cursor(cursor) if cursor else None
if cursor and after is None:
return ErrorType.INVALID_INPUT, [], None
viewer = user.user_id if user else None
sido = region_code[:2] if region_code else None
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.page(s, viewer, sido, int(LOCAL_BOOST.total_seconds()), after, PAGE))
if err is not ErrorType.SUCCESS:
return err, [], None
err, liked = await self._liked(user, ip_hash, [t.talk_id for t, *_ in rows])
if err is not ErrorType.SUCCESS:
return err, [], None
views = [TalkView(talk=t, author=u, region_name=name, liked=t.talk_id in liked, mine=viewer == t.user_id) for t, u, name, _ in rows]
last = rows[-1] if len(rows) == PAGE else None
return ErrorType.SUCCESS, spread_authors(views), f"{last[3]}_{last[0].talk_id}" if last else None
async def mine(self, user: User, cursor: Optional[int]) -> tuple[ErrorType, list[TalkView], Optional[int]]:
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.mine(s, user.user_id, cursor, PAGE))
if err is not ErrorType.SUCCESS:
return err, [], None
err, liked = await self._liked(user, "", [t.talk_id for t, _ in rows])
if err is not ErrorType.SUCCESS:
return err, [], None
views = [TalkView(talk=t, author=user, region_name=name, liked=t.talk_id in liked, mine=True) for t, name in rows]
return ErrorType.SUCCESS, views, rows[-1][0].talk_id if len(rows) == PAGE else None
async def _liked(self, user: Optional[User], ip_hash: str, ids: list[int]) -> tuple[ErrorType, set[int]]:
if not ids:
return ErrorType.SUCCESS, set()
if user is not None:
return await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.liked(s, user.user_id, ids))
return await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.anon_liked(s, ip_hash, ids))
async def _weather_now(self, region_code: str) -> Optional[str]:
"""지금 시각에 가장 가까운 예보 한 칸. 못 읽으면 날씨 없이 쓴다."""
now = now_kst()
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather.hourly_between(s, region_code, now - timedelta(hours=1), now + timedelta(hours=2)))
if err is not ErrorType.SUCCESS or not rows:
return None
return weather_line(min(rows, key=lambda r: abs(r.forecast_at - now)))
async def add(self, user: User, region_code: str, body: str, image: Optional[str] = None) -> tuple[ErrorType, Optional[TalkView]]:
body = " ".join(body.split())
if not body or len(body) > BODY_MAX:
return ErrorType.INVALID_INPUT, None
if image is not None and file_of(image) is None:
return ErrorType.INVALID_INPUT, None
if _LINK.search(body) or _PHONE.search(body):
return ErrorType.LINK_NOT_ALLOWED, None
err, region = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.get(s, region_code))
if err is not ErrorType.SUCCESS:
return err, None
if region is None:
return ErrorType.INVALID_INPUT, None
today = kst_midnight(now_kst().date())
err, n = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.count_since(s, user.user_id, today))
if err is not ErrorType.SUCCESS:
return err, None
if n >= DAILY_MAX:
return ErrorType.DAILY_LIMIT, None
weather = await self._weather_now(region_code)
err, t = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add(s, user.user_id, region_code, body, weather, image))
if err is not ErrorType.SUCCESS or t is None:
return err, None
return ErrorType.SUCCESS, TalkView(talk=t, author=user, region_name=region.short_name, liked=False, mine=True)
async def delete(self, user: User, talk_id: int) -> ErrorType:
err, ok = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.delete(s, talk_id, user.user_id))
if err is not ErrorType.SUCCESS:
return err
return ErrorType.SUCCESS if ok else ErrorType.NOT_FOUND
async def _talk(self, talk_id: int) -> tuple[ErrorType, Optional[Talk]]:
err, t = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.get(s, talk_id))
if err is not ErrorType.SUCCESS:
return err, None
return (ErrorType.SUCCESS, t) if t is not None else (ErrorType.NOT_FOUND, None)
async def like(self, who: Liker, talk_id: int, on: bool) -> tuple[ErrorType, Optional[int]]:
err, _ = await self._talk(talk_id)
if err is not ErrorType.SUCCESS:
return err, None
return await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.toggle_like(s, talk_id, who, on))
async def report(self, user: User, talk_id: int, reason: TalkReport) -> ErrorType:
err, t = await self._talk(talk_id)
if err is not ErrorType.SUCCESS or t is None:
return err
if t.user_id == user.user_id:
return ErrorType.INVALID_INPUT
err, _ = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.report(s, talk_id, user.user_id, reason.value, HIDE_AT))
return err
async def block_author(self, user: User, talk_id: int) -> ErrorType:
err, t = await self._talk(talk_id)
if err is not ErrorType.SUCCESS or t is None:
return err
if t.user_id == user.user_id:
return ErrorType.INVALID_INPUT
err, _ = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.block(s, user.user_id, t.user_id))
return err