Refactor: Next.js+Firebase → React(Vite) + FastAPI + PostgreSQL

- 백엔드: FastAPI + SQLAlchemy(async) + PostgreSQL, 별도 워커(APScheduler)
- 프론트: React 19 + Vite + TS + Tailwind v4 (기존 UI 이식, API 연동)
- docker-compose: db · api · worker · frontend 일괄 실행
- 경기 일정: openfootball 매일 09:00 크롤링 → DB upsert (신규 경기 자동 삽입+예측 생성)
- AI 예측: GPT·Claude·Gemini 실 API 매일 생성 → DB 저장 → 조회 (목데이터 제거)
- 투표창: 오픈 킥오프 D-2 / 마감 킥오프 1시간 전, lockAt 백엔드 전달→프론트 카운트다운
- 채점/리더보드: docs/SCORING.md 기준 누적 포인트
- crowd: 0 시작, 실제 제출로만 증분
- 구 Next.js/Firebase 파일 제거, README/AGENTS 갱신

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
HyeongBaeYangandClaude Opus 4.8 committed 2026-06-10 13:04:35 +09:00
1 parent 35414a8d47
commit 6ffe0dfca3
95 files changed
+5266 -8856

No files matched your search

View File
Whitespace-only changes.
+152
View File
@@ -0,0 +1,152 @@
"""AI 3모델 실연동 — GPT(OpenAI) · Claude(Anthropic) · Gemini(Google).
각 모델에 동일한 경기 컨텍스트를 주고 구조화된 예측 JSON 을 받는다.
키가 없으면 ProviderUnavailable 을 던지고(조용한 실패 0), 워커는 모델별로
독립 처리하여 가능한 것만 갱신한다.
반환 표준 dict:
{outcome, scoreA, scoreB, confidencePct, reasonKo, reasonEn}
"""
from __future__ import annotations
import json
import logging
from dataclasses import dataclass
from ..config import settings
log = logging.getLogger("triplepick.ai")
OUTCOMES = {"TEAM_A_WIN", "DRAW", "TEAM_B_WIN"}
class ProviderUnavailable(RuntimeError):
"""API 키 미설정 등으로 해당 모델을 호출할 수 없음."""
@dataclass
class MatchContext:
team_a: str # 표시명 (예: Korea Republic)
team_b: str
venue: str
kickoff: str # ISO
def _prompt(ctx: MatchContext) -> str:
return (
f"You are a football match analyst. Predict the result of this match.\n"
f"Match: {ctx.team_a} (Team A, home) vs {ctx.team_b} (Team B, away)\n"
f"Venue: {ctx.venue}\nKickoff: {ctx.kickoff}\n\n"
f"Predict the final regulation-time score. "
f"Respond with a single JSON object and nothing else, with keys:\n"
f' "scoreA": integer 0-9 (Team A goals),\n'
f' "scoreB": integer 0-9 (Team B goals),\n'
f' "outcome": one of "TEAM_A_WIN" | "DRAW" | "TEAM_B_WIN" (must match the score),\n'
f' "confidencePct": integer 0-100 (confidence in the predicted winner; '
f"for a draw, confidence in the draw),\n"
f' "reasonKo": a short one-line rationale in Korean (max ~30 chars),\n'
f' "reasonEn": a short one-line rationale in English (max ~60 chars).\n'
)
# JSON Schema (구조화 출력용 — Anthropic/OpenAI 공통)
_SCHEMA = {
"type": "object",
"additionalProperties": False,
"properties": {
"scoreA": {"type": "integer"},
"scoreB": {"type": "integer"},
"outcome": {"type": "string", "enum": ["TEAM_A_WIN", "DRAW", "TEAM_B_WIN"]},
"confidencePct": {"type": "integer"},
"reasonKo": {"type": "string"},
"reasonEn": {"type": "string"},
},
"required": ["scoreA", "scoreB", "outcome", "confidencePct", "reasonKo", "reasonEn"],
}
def _normalize(data: dict) -> dict:
a = max(0, min(9, int(data["scoreA"])))
b = max(0, min(9, int(data["scoreB"])))
# outcome 은 스코어와 일관되도록 서버에서 재도출 (모델 불일치 방지)
outcome = "TEAM_A_WIN" if a > b else "TEAM_B_WIN" if a < b else "DRAW"
conf = max(0, min(100, int(data.get("confidencePct", 50))))
return {
"outcome": outcome,
"scoreA": a,
"scoreB": b,
"confidencePct": conf,
"reasonKo": str(data.get("reasonKo", "")).strip()[:120],
"reasonEn": str(data.get("reasonEn", "")).strip()[:160],
}
# ── GPT (OpenAI) ────────────────────────────────────────────
async def predict_gpt(ctx: MatchContext) -> dict:
if not settings.openai_api_key:
raise ProviderUnavailable("OPENAI_API_KEY 미설정")
from openai import AsyncOpenAI
client = AsyncOpenAI(api_key=settings.openai_api_key)
resp = await client.chat.completions.create(
model=settings.openai_model,
messages=[
{"role": "system", "content": "You output only valid JSON."},
{"role": "user", "content": _prompt(ctx)},
],
response_format={"type": "json_object"},
)
content = resp.choices[0].message.content or "{}"
return _normalize(json.loads(content))
# ── Claude (Anthropic) ──────────────────────────────────────
async def predict_claude(ctx: MatchContext) -> dict:
if not settings.anthropic_api_key:
raise ProviderUnavailable("ANTHROPIC_API_KEY 미설정")
from anthropic import AsyncAnthropic
client = AsyncAnthropic(api_key=settings.anthropic_api_key)
async def _create(**extra): # noqa: ANN003
return await client.messages.create(
model=settings.anthropic_model,
max_tokens=1024,
messages=[{"role": "user", "content": _prompt(ctx)}],
**extra,
)
# 1순위: 구조화 출력(output_config.format) + Opus 4.8 어댑티브 thinking.
# SDK/모델 버전에 따라 미지원이면 평문 JSON 파싱으로 폴백.
try:
msg = await _create(
thinking={"type": "adaptive"},
output_config={"format": {"type": "json_schema", "schema": _SCHEMA}},
)
except TypeError:
msg = await _create()
text = "".join(b.text for b in msg.content if getattr(b, "type", "") == "text")
return _normalize(json.loads(text))
# ── Gemini (Google) ─────────────────────────────────────────
async def predict_gemini(ctx: MatchContext) -> dict:
if not settings.google_api_key:
raise ProviderUnavailable("GOOGLE_API_KEY 미설정")
from google import genai
from google.genai import types
client = genai.Client(api_key=settings.google_api_key)
resp = await client.aio.models.generate_content(
model=settings.google_model,
contents=_prompt(ctx),
config=types.GenerateContentConfig(response_mime_type="application/json"),
)
return _normalize(json.loads(resp.text or "{}"))
PROVIDERS = {
"GPT": predict_gpt,
"Claude": predict_claude,
"Gemini": predict_gemini,
}
+89
View File
@@ -0,0 +1,89 @@
"""결과 이메일 발송 — SMTP 실연동 (aiosmtplib).
SMTP 설정이 없으면 EmailUnavailable 을 던진다(조용한 실패 0).
경기 종료 후 워커가 구독자(notify=True + email)에게 개인화 결과 메일 발송.
"""
from __future__ import annotations
import logging
from email.message import EmailMessage
from ..config import settings
log = logging.getLogger("triplepick.email")
class EmailUnavailable(RuntimeError):
pass
def _ensure_configured() -> None:
if not settings.smtp_host:
raise EmailUnavailable("SMTP_HOST 미설정")
async def send_email(to: str, subject: str, html: str, text: str) -> None:
_ensure_configured()
import aiosmtplib
msg = EmailMessage()
msg["From"] = settings.smtp_from
msg["To"] = to
msg["Subject"] = subject
msg.set_content(text)
msg.add_alternative(html, subtype="html")
await aiosmtplib.send(
msg,
hostname=settings.smtp_host,
port=settings.smtp_port,
username=settings.smtp_user or None,
password=settings.smtp_password or None,
start_tls=settings.smtp_starttls,
)
log.info("email sent → %s (%s)", to, subject)
def build_result_email(
*,
team_a: str,
team_b: str,
result_a: int,
result_b: int,
my_a: int,
my_b: int,
my_points: int,
ai_lines: list[tuple[str, bool]], # (모델명, 적중여부)
match_url: str,
) -> tuple[str, str, str]:
"""제목/HTML/텍스트 반환."""
hit = my_points > 0
headline = "적중! 🎯" if hit else "아쉽네요"
subject = f"[TriplePick] {team_a} {result_a}-{result_b} {team_b} 결과 — {headline}"
ai_html = "".join(
f"<li>{m}: {'적중 ✓' if ok else '빗나감'}</li>" for m, ok in ai_lines
)
ai_text = "\n".join(
f" - {m}: {'적중' if ok else '빗나감'}" for m, ok in ai_lines
)
html = f"""\
<div style="font-family:sans-serif;max-width:480px;margin:0 auto">
<h2>경기 결과</h2>
<p style="font-size:20px;font-weight:bold">{team_a} {result_a} - {result_b} {team_b}</p>
<p>당신의 예측: {team_a} {my_a} - {my_b} {team_b} →
<strong>{my_points}점 ({headline})</strong></p>
<h3>AI 3모델 적중 여부</h3>
<ul>{ai_html}</ul>
<p><a href="{match_url}">다음 경기 예측하러 가기 →</a></p>
<p style="color:#888;font-size:12px">100만원 챌린지 — 누적 포인트 1위에게 최종 상금.</p>
</div>"""
text = (
f"경기 결과: {team_a} {result_a}-{result_b} {team_b}\n"
f"당신의 예측: {team_a} {my_a}-{my_b} {team_b} → {my_points}점 ({headline})\n\n"
f"AI 3모델 적중 여부:\n{ai_text}\n\n"
f"다음 경기 예측: {match_url}\n"
)
return subject, html, text
+39
View File
@@ -0,0 +1,39 @@
"""채점 서비스 — 결과 입력 시 해당 경기 유저 픽 전수 채점.
관리자 setResult 와 워커가 공용으로 사용. scoring.score_prediction 적용.
"""
from __future__ import annotations
import logging
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from ..domain import now_utc
from ..models import Match, UserPrediction
from ..scoring import outcome_of, score_prediction
log = logging.getLogger("triplepick.grading")
async def apply_result(db: AsyncSession, match: Match, score_a: int, score_b: int) -> int:
"""결과 기록 + 해당 경기 픽 전수 채점. 채점된 픽 수 반환."""
match.result_score_a = score_a
match.result_score_b = score_b
match.result_outcome = outcome_of(score_a, score_b)
match.status = "finished"
match.finished_at = now_utc()
picks = (
await db.execute(
select(UserPrediction).where(UserPrediction.match_id == match.match_id)
)
).scalars().all()
for p in picks:
p.points = score_prediction(p.score_a, p.score_b, score_a, score_b)
p.scored_at = now_utc()
await db.commit()
log.info("graded %d picks for %s (%d-%d)", len(picks), match.match_id, score_a, score_b)
return len(picks)
+112
View File
@@ -0,0 +1,112 @@
"""경기 일정 외부 수집 — 매일 워커가 호출(크롤링).
소스(SCHEDULE_SOURCE):
openfootball raw GitHub JSON (키 불필요, 기본). 2026 Group A = 본 서비스 6경기.
football-data football-data.org /v4/competitions/WC/matches (FOOTBALL_DATA_TOKEN 필요)
fallback 외부 호출 없이 빈 결과 → 기존(시드) 일정 유지
반환 표준 레코드:
{teamA: code, teamB: code, kickoffKst: ISO(+09:00), venue: str}
team 코드로 매핑되지 않는 경기(다른 그룹/팀)는 제외.
시각은 절대 시점(UTC)으로 환산 후 KST(+09:00) 고정 오프셋으로 표기.
"""
from __future__ import annotations
import logging
import re
from datetime import datetime, timedelta, timezone
from ..config import settings
from ..schedule_data import code_for
log = logging.getLogger("triplepick.schedule")
KST = timezone(timedelta(hours=9))
# "13:00 UTC-6" / "20:00 UTC+2" 형태 파싱
_TIME_RE = re.compile(r"(\d{1,2}):(\d{2})\s*UTC\s*([+-]\d{1,2})")
def _to_kst_iso(date_str: str, time_str: str) -> str | None:
m = _TIME_RE.search(time_str or "")
if not m:
return None
hh, mm, off = int(m.group(1)), int(m.group(2)), int(m.group(3))
try:
y, mo, d = (int(x) for x in date_str.split("-"))
except ValueError:
return None
local = datetime(y, mo, d, hh, mm, tzinfo=timezone(timedelta(hours=off)))
return local.astimezone(KST).isoformat()
async def _fetch_openfootball() -> list[dict]:
import httpx
async with httpx.AsyncClient(timeout=20) as c:
r = await c.get(settings.schedule_url)
r.raise_for_status()
data = r.json()
out: list[dict] = []
for m in data.get("matches", []):
if (m.get("group") or "").strip() != settings.schedule_group:
continue
a, b = code_for(m.get("team1", "")), code_for(m.get("team2", ""))
if not a or not b:
continue
kickoff = _to_kst_iso(m.get("date", ""), m.get("time", ""))
if not kickoff:
continue
out.append({"teamA": a, "teamB": b, "kickoffKst": kickoff, "venue": m.get("ground", "")})
return out
async def _fetch_football_data() -> list[dict]:
if not settings.football_data_token:
log.warning("schedule: football-data 토큰 미설정 — 수집 생략")
return []
import httpx
url = (
f"https://api.football-data.org/v4/competitions/"
f"{settings.football_data_competition}/matches"
)
async with httpx.AsyncClient(timeout=20) as c:
r = await c.get(url, headers={"X-Auth-Token": settings.football_data_token})
r.raise_for_status()
data = r.json()
out: list[dict] = []
for m in data.get("matches", []):
if (m.get("group") or "").replace("GROUP_", "Group ") != settings.schedule_group:
continue
a = code_for((m.get("homeTeam") or {}).get("name", "") or "")
b = code_for((m.get("awayTeam") or {}).get("name", "") or "")
if not a or not b:
continue
utc = m.get("utcDate") # ISO Z
if not utc:
continue
kickoff = (
datetime.fromisoformat(utc.replace("Z", "+00:00")).astimezone(KST).isoformat()
)
venue = m.get("venue") or ""
out.append({"teamA": a, "teamB": b, "kickoffKst": kickoff, "venue": venue})
return out
async def fetch_schedule() -> list[dict]:
"""소스에 따라 일정 수집. 실패 시 빈 리스트(기존 일정 유지)."""
src = settings.schedule_source.lower()
try:
if src == "openfootball":
records = await _fetch_openfootball()
elif src == "football-data":
records = await _fetch_football_data()
else:
return []
log.info("schedule: %s 에서 %d경기 수집", src, len(records))
return records
except Exception as e: # noqa: BLE001
log.error("schedule fetch 실패(%s): %s — 기존 일정 유지", src, e)
return []
+72
View File
@@ -0,0 +1,72 @@
"""수집한 일정을 DB에 반영 — 워커(스케줄링 서버)가 매일 호출.
매칭 키 = (teamA_code, teamB_code) 순서쌍 (그룹 라운드로빈에서 유일).
- 기존 경기: 킥오프/venue/투표시간(opens·lock) 갱신. 결과·예측·crowd·라운드/후킹은 보존.
- 신규 경기: matchId 생성 + crowd 초기화하여 삽입(예측은 워커 AI 생성이 채움).
종료(result) 경기는 시각 변경하지 않음.
"""
from __future__ import annotations
import logging
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from ..models import CrowdStats, Match
from ..schedule_data import TEAMS, lock_at, opens_at, parse_kickoff
log = logging.getLogger("triplepick.schedule")
async def sync_schedule(db: AsyncSession, records: list[dict]) -> dict:
if not records:
return {"updated": 0, "inserted": 0, "skipped": 0}
existing = (await db.execute(select(Match))).scalars().all()
by_pair = {(m.team_a_code, m.team_b_code): m for m in existing}
updated = inserted = skipped = 0
for rec in records:
a, b = rec["teamA"], rec["teamB"]
kickoff = parse_kickoff(rec["kickoffKst"])
m = by_pair.get((a, b))
if m is not None:
if m.result_outcome is not None:
skipped += 1
continue
m.kickoff_at = kickoff
m.opens_at = opens_at(kickoff)
m.lock_at = lock_at(kickoff)
if rec.get("venue"):
m.venue = rec["venue"]
updated += 1
else:
ta, tb = TEAMS.get(a), TEAMS.get(b)
if not ta or not tb:
skipped += 1
continue
match_id = f"A_{a}_{b}_{kickoff.astimezone().strftime('%Y%m%d')}"
db.add(
Match(
match_id=match_id,
round_label="Match",
group="A",
team_a_name=ta["name"], team_a_short=ta["shortName"],
team_a_code=ta["code"], team_a_flag=ta["flag"],
team_b_name=tb["name"], team_b_short=tb["shortName"],
team_b_code=tb["code"], team_b_flag=tb["flag"],
venue=rec.get("venue", ""),
hook_text=f"{ta['shortName']} vs {tb['shortName']}, AI의 예측은",
kickoff_at=kickoff,
opens_at=opens_at(kickoff),
lock_at=lock_at(kickoff),
status="scheduled",
)
)
db.add(CrowdStats(match_id=match_id, total=0, team_a_win=0, draw=0, team_b_win=0))
inserted += 1
await db.commit()
result = {"updated": updated, "inserted": inserted, "skipped": skipped}
log.info("schedule sync: %s", result)
return result