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:
1 parent
35414a8d47
commit
6ffe0dfca3
95 files changed
+5266
-8856
No files matched your search
@@ -0,0 +1,50 @@
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# TriplePick 백엔드 환경변수 — 복사: cp .env.example .env
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
|
||||
# DB (docker-compose 내부 네트워크 기본값). 로컬 단독이면 localhost 로.
|
||||
DATABASE_URL=postgresql+asyncpg://triplepick:triplepick@db:5432/triplepick
|
||||
|
||||
# 일반
|
||||
TIMEZONE=Asia/Seoul
|
||||
CORS_ORIGINS=*
|
||||
PUBLIC_ORIGIN=http://localhost:8080
|
||||
|
||||
# 투표 윈도우 (도메인 규칙)
|
||||
VOTE_OPEN_HOURS_BEFORE=48 # 오픈 = 킥오프 D-2
|
||||
VOTE_LOCK_MINUTES_BEFORE=60 # 마감 = 킥오프 1시간 전
|
||||
DEMO_FORCE_OPEN=true # 운영 배포 시 false
|
||||
|
||||
# 스케줄링 서버 (워커)
|
||||
# 경기 일정 동적 수집: 매일 KST 09:00 외부 소스에서 일정·투표시간 갱신
|
||||
SCHEDULE_SYNC_HOUR=9
|
||||
SCHEDULE_SYNC_MINUTE=0
|
||||
SCHEDULE_SOURCE=openfootball # openfootball(키 불필요) | football-data(토큰) | fallback
|
||||
SCHEDULE_URL=https://raw.githubusercontent.com/openfootball/worldcup.json/master/2026/worldcup.json
|
||||
SCHEDULE_GROUP=Group A
|
||||
FOOTBALL_DATA_TOKEN= # SCHEDULE_SOURCE=football-data 일 때
|
||||
FOOTBALL_DATA_COMPETITION=WC
|
||||
|
||||
AI_GENERATE_HOUR=0 # 매일 KST 00:05 AI 예측 생성
|
||||
AI_GENERATE_MINUTE=5
|
||||
RESULT_EMAIL_DELAY_MINUTES=180 # 경기 종료 3시간 후 결과 메일
|
||||
STATUS_TICK_SECONDS=60
|
||||
|
||||
# 관리자 (강한 토큰으로 교체)
|
||||
ADMIN_API_TOKEN=change-me-admin-token
|
||||
|
||||
# ── 외부 연동: AI 3모델 (실연동, 키 없으면 해당 모델 생성 생략) ──
|
||||
OPENAI_API_KEY=
|
||||
OPENAI_MODEL=gpt-4o
|
||||
ANTHROPIC_API_KEY=
|
||||
ANTHROPIC_MODEL=claude-opus-4-8
|
||||
GOOGLE_API_KEY=
|
||||
GOOGLE_MODEL=gemini-2.5-flash
|
||||
|
||||
# ── 외부 연동: 이메일 (SMTP, 실연동) ──
|
||||
SMTP_HOST=
|
||||
SMTP_PORT=587
|
||||
SMTP_USER=
|
||||
SMTP_PASSWORD=
|
||||
SMTP_FROM=TriplePick <no-reply@triplepick.app>
|
||||
SMTP_STARTTLS=true
|
||||
@@ -0,0 +1,22 @@
|
||||
# TriplePick 백엔드 — API 서버 & 워커 공용 이미지.
|
||||
# docker-compose 에서 command 를 달리해 두 서비스로 띄운다.
|
||||
FROM python:3.12-slim
|
||||
|
||||
ENV PYTHONUNBUFFERED=1 \
|
||||
PYTHONDONTWRITEBYTECODE=1
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
curl \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY app ./app
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
# 기본: API 서버. 워커는 compose 에서 command 오버라이드.
|
||||
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||
Whitespace-only changes.
@@ -0,0 +1,89 @@
|
||||
"""애플리케이션 설정 — 환경변수(.env)에서 로드.
|
||||
|
||||
pydantic-settings 로 타입 검증. 누락 시 조용한 실패 없이 명확하게 동작.
|
||||
시간 윈도우(투표 오픈/마감), 스케줄러 시각, 외부 연동 키를 모두 여기서 관리.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from functools import lru_cache
|
||||
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(
|
||||
env_file=".env", env_file_encoding="utf-8", extra="ignore"
|
||||
)
|
||||
|
||||
# ── 데이터베이스 ─────────────────────────────────────────
|
||||
# docker-compose 의 db 서비스를 가리키는 기본값. 로컬 단독 실행 시 .env 로 덮어쓴다.
|
||||
database_url: str = (
|
||||
"postgresql+asyncpg://triplepick:triplepick@db:5432/triplepick"
|
||||
)
|
||||
|
||||
# ── 일반 ────────────────────────────────────────────────
|
||||
timezone: str = "Asia/Seoul" # 모든 경기 시각의 기준 (KST)
|
||||
cors_origins: str = "*" # 콤마구분. nginx 프록시 사용 시 동일 출처라 보통 불필요.
|
||||
public_origin: str = "http://localhost:8080" # 공유 딥링크 베이스
|
||||
|
||||
# ── 투표 윈도우 (도메인 규칙) ─────────────────────────────
|
||||
# 오픈 = 킥오프 - VOTE_OPEN_HOURS_BEFORE (D-2 = 48h)
|
||||
vote_open_hours_before: int = 48
|
||||
# 마감 = 킥오프 1시간 전 (경기 시작 1시간 전까지 투표). lock 오프셋(분).
|
||||
vote_lock_minutes_before: int = 60
|
||||
# 데모: True 면 오픈 게이트 무시(항상 투표 가능). 운영 배포 시 False.
|
||||
demo_force_open: bool = True
|
||||
|
||||
# ── 스케줄러 (별도 워커 프로세스 = "스케줄링 서버") ───────
|
||||
# 경기 일정 동적 수집: 매일 KST 09:00 외부 소스 크롤링 → 경기·투표시간 갱신.
|
||||
schedule_sync_hour: int = 9
|
||||
schedule_sync_minute: int = 0
|
||||
# 소스: openfootball(키 불필요·기본) | football-data(토큰 필요) | fallback(하드코딩만)
|
||||
schedule_source: str = "openfootball"
|
||||
schedule_url: str = (
|
||||
"https://raw.githubusercontent.com/openfootball/worldcup.json/master/2026/worldcup.json"
|
||||
)
|
||||
schedule_group: str = "Group A" # 추적할 그룹 (openfootball 라벨)
|
||||
football_data_token: str = "" # schedule_source=football-data 일 때
|
||||
football_data_competition: str = "WC"
|
||||
|
||||
# 매일 AI 예측 생성 시각 (KST). 기능정의서: 매일 0시 1회 생성.
|
||||
ai_generate_hour: int = 0
|
||||
ai_generate_minute: int = 5
|
||||
# 결과 메일: 경기 종료(결과 입력) 후 이 시간(분) 경과하면 발송. 기본 180분(3시간).
|
||||
result_email_delay_minutes: int = 180
|
||||
# 상태 전이 틱 주기(초): scheduled→open→locked 자동 갱신.
|
||||
status_tick_seconds: int = 60
|
||||
|
||||
# ── 관리자 ──────────────────────────────────────────────
|
||||
admin_api_token: str = "change-me-admin-token"
|
||||
|
||||
# ── 외부 연동: AI 3모델 (실연동) ─────────────────────────
|
||||
openai_api_key: str = ""
|
||||
openai_model: str = "gpt-4o"
|
||||
anthropic_api_key: str = ""
|
||||
anthropic_model: str = "claude-opus-4-8"
|
||||
google_api_key: str = ""
|
||||
google_model: str = "gemini-2.5-flash"
|
||||
|
||||
# ── 외부 연동: 이메일 (SMTP, 실연동) ─────────────────────
|
||||
smtp_host: str = ""
|
||||
smtp_port: int = 587
|
||||
smtp_user: str = ""
|
||||
smtp_password: str = ""
|
||||
smtp_from: str = "TriplePick <no-reply@triplepick.app>"
|
||||
smtp_starttls: bool = True
|
||||
|
||||
@property
|
||||
def cors_origin_list(self) -> list[str]:
|
||||
if self.cors_origins.strip() == "*":
|
||||
return ["*"]
|
||||
return [o.strip() for o in self.cors_origins.split(",") if o.strip()]
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_settings() -> Settings:
|
||||
return Settings()
|
||||
|
||||
|
||||
settings = get_settings()
|
||||
@@ -0,0 +1,39 @@
|
||||
"""SQLAlchemy 2.0 async 엔진 + 세션 팩토리.
|
||||
|
||||
API(main.py)와 워커(worker.py)가 공유한다. asyncpg 드라이버 사용.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import AsyncGenerator
|
||||
|
||||
from sqlalchemy.ext.asyncio import (
|
||||
AsyncSession,
|
||||
async_sessionmaker,
|
||||
create_async_engine,
|
||||
)
|
||||
from sqlalchemy.orm import DeclarativeBase
|
||||
|
||||
from .config import settings
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
|
||||
engine = create_async_engine(settings.database_url, echo=False, pool_pre_ping=True)
|
||||
|
||||
SessionLocal = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
|
||||
|
||||
|
||||
async def get_db() -> AsyncGenerator[AsyncSession, None]:
|
||||
"""FastAPI 의존성: 요청당 세션."""
|
||||
async with SessionLocal() as session:
|
||||
yield session
|
||||
|
||||
|
||||
async def init_db() -> None:
|
||||
"""테이블 생성 (없으면). 단순화를 위해 alembic 대신 create_all 사용."""
|
||||
from . import models # noqa: F401 (모델 등록)
|
||||
|
||||
async with engine.begin() as conn:
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
@@ -0,0 +1,130 @@
|
||||
"""도메인 헬퍼 — 투표 단계(phase) 계산 + ORM→응답 스키마 직렬화.
|
||||
|
||||
phase 는 now 기준 동적 계산 (lib/schedule.ts matchPhase 와 동일 규칙):
|
||||
result 존재 → finished
|
||||
now >= lockAt → locked
|
||||
now < opensAt → scheduled
|
||||
그 외 → open
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from .config import settings
|
||||
from .models import AIPrediction, CrowdStats, Match
|
||||
from .schemas import (
|
||||
AIPredictionOut,
|
||||
CrowdStatsOut,
|
||||
MatchOut,
|
||||
MatchResult,
|
||||
Team,
|
||||
)
|
||||
|
||||
|
||||
def now_utc() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def ensure_aware(dt: datetime) -> datetime:
|
||||
"""naive datetime(일부 DB 드라이버 반환)을 UTC aware 로 보정."""
|
||||
return dt.replace(tzinfo=timezone.utc) if dt.tzinfo is None else dt
|
||||
|
||||
|
||||
def compute_phase(m: Match, now: datetime | None = None) -> str:
|
||||
now = now or now_utc()
|
||||
if m.result_outcome is not None:
|
||||
return "finished"
|
||||
if now >= ensure_aware(m.lock_at):
|
||||
return "locked"
|
||||
if now < ensure_aware(m.opens_at):
|
||||
return "scheduled"
|
||||
return "open"
|
||||
|
||||
|
||||
def is_open_for_voting(m: Match, now: datetime | None = None) -> bool:
|
||||
"""제출 허용 여부. demo_force_open 이면 마감 전까지 항상 오픈."""
|
||||
now = now or now_utc()
|
||||
if m.result_outcome is not None:
|
||||
return False
|
||||
if now >= ensure_aware(m.lock_at):
|
||||
return False
|
||||
if settings.demo_force_open:
|
||||
return True
|
||||
return now >= ensure_aware(m.opens_at)
|
||||
|
||||
|
||||
def _team_a(m: Match) -> Team:
|
||||
return Team(
|
||||
name=m.team_a_name, shortName=m.team_a_short, code=m.team_a_code, flag=m.team_a_flag
|
||||
)
|
||||
|
||||
|
||||
def _team_b(m: Match) -> Team:
|
||||
return Team(
|
||||
name=m.team_b_name, shortName=m.team_b_short, code=m.team_b_code, flag=m.team_b_flag
|
||||
)
|
||||
|
||||
|
||||
def prediction_out(p: AIPrediction, lang: str = "ko") -> AIPredictionOut:
|
||||
reason = p.reason_en if lang == "en" and p.reason_en else p.reason_ko
|
||||
return AIPredictionOut(
|
||||
matchId=p.match_id,
|
||||
model=p.model, # type: ignore[arg-type]
|
||||
outcome=p.outcome, # type: ignore[arg-type]
|
||||
scoreA=p.score_a,
|
||||
scoreB=p.score_b,
|
||||
confidencePct=p.confidence_pct,
|
||||
reasonShort=reason,
|
||||
generatedAt=p.generated_at.date().isoformat() if p.generated_at else "",
|
||||
)
|
||||
|
||||
|
||||
def crowd_out(c: CrowdStats | None, match_id: str) -> CrowdStatsOut:
|
||||
if c is None:
|
||||
return CrowdStatsOut(matchId=match_id, total=0, teamAWin=0, draw=0, teamBWin=0)
|
||||
return CrowdStatsOut(
|
||||
matchId=match_id,
|
||||
total=c.total,
|
||||
teamAWin=c.team_a_win,
|
||||
draw=c.draw,
|
||||
teamBWin=c.team_b_win,
|
||||
)
|
||||
|
||||
|
||||
def match_out(
|
||||
m: Match,
|
||||
lang: str = "ko",
|
||||
include_predictions: bool = True,
|
||||
now: datetime | None = None,
|
||||
) -> MatchOut:
|
||||
result = None
|
||||
if m.result_outcome is not None:
|
||||
result = MatchResult(
|
||||
scoreA=m.result_score_a or 0,
|
||||
scoreB=m.result_score_b or 0,
|
||||
outcome=m.result_outcome, # type: ignore[arg-type]
|
||||
)
|
||||
preds: list[AIPredictionOut] = []
|
||||
if include_predictions:
|
||||
# 모델 순서 고정: GPT, Claude, Gemini
|
||||
order = {"GPT": 0, "Claude": 1, "Gemini": 2}
|
||||
for p in sorted(m.predictions, key=lambda x: order.get(x.model, 9)):
|
||||
preds.append(prediction_out(p, lang))
|
||||
return MatchOut(
|
||||
matchId=m.match_id,
|
||||
roundLabel=m.round_label,
|
||||
group=m.group,
|
||||
teamA=_team_a(m),
|
||||
teamB=_team_b(m),
|
||||
kickoffKst=m.kickoff_at.isoformat(),
|
||||
venue=m.venue,
|
||||
opensAt=m.opens_at.isoformat(),
|
||||
lockAt=m.lock_at.isoformat(),
|
||||
status=m.status,
|
||||
phase=compute_phase(m, now),
|
||||
votingOpen=is_open_for_voting(m, now),
|
||||
hookText=m.hook_text,
|
||||
result=result,
|
||||
predictions=preds,
|
||||
crowd=crowd_out(m.crowd, m.match_id),
|
||||
)
|
||||
@@ -0,0 +1,49 @@
|
||||
"""FastAPI 앱 진입점 — API 서버.
|
||||
|
||||
시작 시 DB 초기화 + 시드. CORS 허용. 라우터 등록.
|
||||
스케줄러는 별도 워커 컨테이너(worker.py)에서 실행한다(중복 방지).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from .config import settings
|
||||
from .database import init_db
|
||||
from .routers import admin, leaderboard, matches, predictions
|
||||
from .seed import seed_if_empty
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
log = logging.getLogger("triplepick")
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI): # noqa: ANN201
|
||||
await init_db()
|
||||
await seed_if_empty()
|
||||
log.info("API ready")
|
||||
yield
|
||||
|
||||
|
||||
app = FastAPI(title="TriplePick API", version="1.0.0", lifespan=lifespan)
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=settings.cors_origin_list,
|
||||
allow_credentials=False,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
app.include_router(matches.router)
|
||||
app.include_router(predictions.router)
|
||||
app.include_router(leaderboard.router)
|
||||
app.include_router(admin.router)
|
||||
|
||||
|
||||
@app.get("/api/health")
|
||||
async def health() -> dict:
|
||||
return {"ok": True, "service": "triplepick-api"}
|
||||
@@ -0,0 +1,154 @@
|
||||
"""ORM 모델 — 기능정의서 데이터모델 + lib/types.ts 와 정합.
|
||||
|
||||
테이블:
|
||||
- matches 경기 (팀/시각/투표윈도우/상태/결과)
|
||||
- ai_predictions GPT/Claude/Gemini 예측 (경기 × 모델)
|
||||
- crowd_stats 군중 투표 분포 (경기당 1행, 원자적 증분)
|
||||
- user_predictions 유저 픽 (이메일 식별, 채점/알림 플래그 포함)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import (
|
||||
Boolean,
|
||||
DateTime,
|
||||
ForeignKey,
|
||||
Integer,
|
||||
String,
|
||||
UniqueConstraint,
|
||||
func,
|
||||
)
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from .database import Base
|
||||
|
||||
# Outcome: TEAM_A_WIN | DRAW | TEAM_B_WIN
|
||||
# ModelName: GPT | Claude | Gemini
|
||||
# MatchStatus: scheduled | open | locked | live | finished
|
||||
|
||||
|
||||
class Match(Base):
|
||||
__tablename__ = "matches"
|
||||
|
||||
match_id: Mapped[str] = mapped_column(String, primary_key=True)
|
||||
round_label: Mapped[str] = mapped_column(String, default="")
|
||||
group: Mapped[str] = mapped_column(String, default="A")
|
||||
|
||||
# 팀 정보 (표시명/약식/코드/이모지) — 분리 컬럼으로 저장
|
||||
team_a_name: Mapped[str] = mapped_column(String)
|
||||
team_a_short: Mapped[str] = mapped_column(String)
|
||||
team_a_code: Mapped[str] = mapped_column(String)
|
||||
team_a_flag: Mapped[str] = mapped_column(String, default="")
|
||||
team_b_name: Mapped[str] = mapped_column(String)
|
||||
team_b_short: Mapped[str] = mapped_column(String)
|
||||
team_b_code: Mapped[str] = mapped_column(String)
|
||||
team_b_flag: Mapped[str] = mapped_column(String, default="")
|
||||
|
||||
venue: Mapped[str] = mapped_column(String, default="")
|
||||
hook_text: Mapped[str] = mapped_column(String, default="")
|
||||
|
||||
# 모든 시각은 timezone-aware (UTC 저장, KST 환산은 표현 계층)
|
||||
kickoff_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
opens_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
lock_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
|
||||
status: Mapped[str] = mapped_column(String, default="scheduled")
|
||||
|
||||
# 결과 (입력 전 None)
|
||||
result_score_a: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
result_score_b: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
result_outcome: Mapped[str | None] = mapped_column(String, nullable=True)
|
||||
finished_at: Mapped[datetime | None] = mapped_column(
|
||||
DateTime(timezone=True), nullable=True
|
||||
)
|
||||
results_emailed_at: Mapped[datetime | None] = mapped_column(
|
||||
DateTime(timezone=True), nullable=True
|
||||
)
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), server_default=func.now()
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
|
||||
)
|
||||
|
||||
predictions: Mapped[list["AIPrediction"]] = relationship(
|
||||
back_populates="match", cascade="all, delete-orphan"
|
||||
)
|
||||
crowd: Mapped["CrowdStats | None"] = relationship(
|
||||
back_populates="match", uselist=False, cascade="all, delete-orphan"
|
||||
)
|
||||
|
||||
|
||||
class AIPrediction(Base):
|
||||
__tablename__ = "ai_predictions"
|
||||
__table_args__ = (UniqueConstraint("match_id", "model", name="uq_match_model"),)
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
match_id: Mapped[str] = mapped_column(
|
||||
ForeignKey("matches.match_id", ondelete="CASCADE")
|
||||
)
|
||||
model: Mapped[str] = mapped_column(String) # GPT | Claude | Gemini
|
||||
outcome: Mapped[str] = mapped_column(String)
|
||||
score_a: Mapped[int] = mapped_column(Integer)
|
||||
score_b: Mapped[int] = mapped_column(Integer)
|
||||
confidence_pct: Mapped[int] = mapped_column(Integer)
|
||||
reason_ko: Mapped[str] = mapped_column(String, default="")
|
||||
reason_en: Mapped[str] = mapped_column(String, default="")
|
||||
generated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), server_default=func.now()
|
||||
)
|
||||
# 실연동 LLM 출력인지 시드 데이터인지 구분 (재생성 제어용)
|
||||
source: Mapped[str] = mapped_column(String, default="seed") # seed | llm
|
||||
|
||||
match: Mapped["Match"] = relationship(back_populates="predictions")
|
||||
|
||||
|
||||
class CrowdStats(Base):
|
||||
__tablename__ = "crowd_stats"
|
||||
|
||||
match_id: Mapped[str] = mapped_column(
|
||||
ForeignKey("matches.match_id", ondelete="CASCADE"), primary_key=True
|
||||
)
|
||||
total: Mapped[int] = mapped_column(Integer, default=0)
|
||||
team_a_win: Mapped[int] = mapped_column(Integer, default=0)
|
||||
draw: Mapped[int] = mapped_column(Integer, default=0)
|
||||
team_b_win: Mapped[int] = mapped_column(Integer, default=0)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
|
||||
)
|
||||
|
||||
match: Mapped["Match"] = relationship(back_populates="crowd")
|
||||
|
||||
|
||||
class UserPrediction(Base):
|
||||
__tablename__ = "user_predictions"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("match_id", "device_id", name="uq_match_device"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
match_id: Mapped[str] = mapped_column(
|
||||
ForeignKey("matches.match_id", ondelete="CASCADE")
|
||||
)
|
||||
device_id: Mapped[str] = mapped_column(String) # 비로그인 식별 (클라 생성 uuid)
|
||||
outcome: Mapped[str] = mapped_column(String)
|
||||
score_a: Mapped[int] = mapped_column(Integer)
|
||||
score_b: Mapped[int] = mapped_column(Integer)
|
||||
email: Mapped[str | None] = mapped_column(String, nullable=True)
|
||||
notify: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
|
||||
# 채점 (결과 입력 후 갱신)
|
||||
points: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
scored_at: Mapped[datetime | None] = mapped_column(
|
||||
DateTime(timezone=True), nullable=True
|
||||
)
|
||||
notified: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), server_default=func.now()
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
|
||||
)
|
||||
Whitespace-only changes.
@@ -0,0 +1,72 @@
|
||||
"""관리자 API — Bearer 토큰 인증. 경기/AI예측 upsert + 결과 입력(채점)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from ..config import settings
|
||||
from ..database import get_db
|
||||
from ..domain import now_utc
|
||||
from ..models import AIPrediction, Match
|
||||
from ..schemas import AdminAIPredictionIn, AdminSetResultIn, GenericOk
|
||||
from ..services.grading import apply_result
|
||||
|
||||
router = APIRouter(prefix="/api/admin", tags=["admin"])
|
||||
|
||||
|
||||
def require_admin(authorization: str = Header(default="")) -> None:
|
||||
token = authorization.removeprefix("Bearer ").strip()
|
||||
if not token or token != settings.admin_api_token:
|
||||
raise HTTPException(status_code=401, detail="UNAUTHORIZED")
|
||||
|
||||
|
||||
@router.post("/ai-predictions", response_model=GenericOk, dependencies=[Depends(require_admin)])
|
||||
async def upsert_ai_prediction(
|
||||
body: AdminAIPredictionIn, db: AsyncSession = Depends(get_db)
|
||||
) -> GenericOk:
|
||||
match = (
|
||||
await db.execute(select(Match).where(Match.match_id == body.matchId))
|
||||
).scalars().first()
|
||||
if not match:
|
||||
raise HTTPException(status_code=404, detail="MATCH_NOT_FOUND")
|
||||
|
||||
pred = (
|
||||
await db.execute(
|
||||
select(AIPrediction).where(
|
||||
AIPrediction.match_id == body.matchId, AIPrediction.model == body.model
|
||||
)
|
||||
)
|
||||
).scalars().first()
|
||||
if pred is None:
|
||||
pred = AIPrediction(match_id=body.matchId, model=body.model)
|
||||
db.add(pred)
|
||||
pred.outcome = body.outcome
|
||||
pred.score_a = body.scoreA
|
||||
pred.score_b = body.scoreB
|
||||
pred.confidence_pct = body.confidencePct
|
||||
pred.reason_ko = body.reasonKo
|
||||
pred.reason_en = body.reasonEn
|
||||
pred.generated_at = now_utc()
|
||||
pred.source = "admin"
|
||||
await db.commit()
|
||||
return GenericOk(ok=True, detail="upserted")
|
||||
|
||||
|
||||
@router.post("/result", response_model=GenericOk, dependencies=[Depends(require_admin)])
|
||||
async def set_result(
|
||||
body: AdminSetResultIn, db: AsyncSession = Depends(get_db)
|
||||
) -> GenericOk:
|
||||
match = (
|
||||
await db.execute(select(Match).where(Match.match_id == body.matchId))
|
||||
).scalars().first()
|
||||
if not match:
|
||||
raise HTTPException(status_code=404, detail="MATCH_NOT_FOUND")
|
||||
|
||||
graded = await apply_result(db, match, body.scoreA, body.scoreB)
|
||||
# 결과 메일은 워커가 result_email_delay_minutes 경과 후 발송(@finished_at 기준).
|
||||
return GenericOk(
|
||||
ok=True,
|
||||
detail="result set & graded",
|
||||
extra={"gradedPicks": graded, "emailsSentBy": "worker"},
|
||||
)
|
||||
@@ -0,0 +1,80 @@
|
||||
"""리더보드 API — 누적 포인트 1위 (docs/SCORING.md §3 랭킹 규칙).
|
||||
|
||||
1차 정렬: 누적 포인트. 동점: 정확스코어 횟수 → 적중률 → 참여수 → 최초도달.
|
||||
주최측/임직원 배제(P1). 이메일은 마스킹하여 노출.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import defaultdict
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from ..database import get_db
|
||||
from ..models import UserPrediction
|
||||
from ..scoring import SCORE, is_excluded
|
||||
from ..schemas import LeaderboardOut, StandingOut
|
||||
|
||||
router = APIRouter(prefix="/api/leaderboard", tags=["leaderboard"])
|
||||
|
||||
|
||||
def _mask(email: str) -> str:
|
||||
name, _, domain = email.partition("@")
|
||||
head = name[:2] if len(name) >= 2 else name
|
||||
return f"{head}{'*' * max(1, len(name) - 2)}@{domain}"
|
||||
|
||||
|
||||
@router.get("", response_model=LeaderboardOut)
|
||||
async def leaderboard(
|
||||
limit: int = Query(50, ge=1, le=200), db: AsyncSession = Depends(get_db)
|
||||
) -> LeaderboardOut:
|
||||
rows = (
|
||||
await db.execute(
|
||||
select(UserPrediction).where(
|
||||
UserPrediction.points.is_not(None),
|
||||
UserPrediction.email.is_not(None),
|
||||
)
|
||||
)
|
||||
).scalars().all()
|
||||
|
||||
agg: dict[str, dict] = defaultdict(
|
||||
lambda: {"points": 0, "exact": 0, "played": 0, "first": None}
|
||||
)
|
||||
matches: set[str] = set()
|
||||
for r in rows:
|
||||
email = (r.email or "").strip().lower()
|
||||
if not email or is_excluded(email):
|
||||
continue
|
||||
matches.add(r.match_id)
|
||||
a = agg[email]
|
||||
a["points"] += r.points or 0
|
||||
a["played"] += 1
|
||||
if (r.points or 0) >= SCORE["EXACT"]:
|
||||
a["exact"] += 1
|
||||
ts = r.scored_at or r.created_at
|
||||
if a["first"] is None or (ts and ts < a["first"]):
|
||||
a["first"] = ts
|
||||
|
||||
ranked = sorted(
|
||||
agg.items(),
|
||||
key=lambda kv: (
|
||||
-kv[1]["points"],
|
||||
-kv[1]["exact"],
|
||||
-(kv[1]["points"] / kv[1]["played"] if kv[1]["played"] else 0),
|
||||
-kv[1]["played"],
|
||||
kv[1]["first"].timestamp() if kv[1]["first"] else 0,
|
||||
),
|
||||
)
|
||||
|
||||
standings = [
|
||||
StandingOut(
|
||||
rank=i + 1,
|
||||
emailMasked=_mask(email),
|
||||
totalPoints=v["points"],
|
||||
exactCount=v["exact"],
|
||||
matchesPlayed=v["played"],
|
||||
)
|
||||
for i, (email, v) in enumerate(ranked[:limit])
|
||||
]
|
||||
return LeaderboardOut(standings=standings, scoredMatches=len(matches))
|
||||
@@ -0,0 +1,47 @@
|
||||
"""공개 읽기 API — 경기 목록 / 경기 상세 (AI예측 + crowd 포함)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy.orm import selectinload
|
||||
|
||||
from ..database import get_db
|
||||
from ..domain import match_out
|
||||
from ..models import Match
|
||||
from ..schemas import MatchOut
|
||||
|
||||
router = APIRouter(prefix="/api/matches", tags=["matches"])
|
||||
|
||||
|
||||
@router.get("", response_model=list[MatchOut])
|
||||
async def list_matches(
|
||||
lang: str = Query("ko"),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> list[MatchOut]:
|
||||
rows = (
|
||||
await db.execute(
|
||||
select(Match)
|
||||
.options(selectinload(Match.predictions), selectinload(Match.crowd))
|
||||
.order_by(Match.kickoff_at)
|
||||
)
|
||||
).scalars().all()
|
||||
return [match_out(m, lang) for m in rows]
|
||||
|
||||
|
||||
@router.get("/{match_id}", response_model=MatchOut)
|
||||
async def get_match(
|
||||
match_id: str,
|
||||
lang: str = Query("ko"),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> MatchOut:
|
||||
m = (
|
||||
await db.execute(
|
||||
select(Match)
|
||||
.where(Match.match_id == match_id)
|
||||
.options(selectinload(Match.predictions), selectinload(Match.crowd))
|
||||
)
|
||||
).scalars().first()
|
||||
if not m:
|
||||
raise HTTPException(status_code=404, detail="MATCH_NOT_FOUND")
|
||||
return match_out(m, lang)
|
||||
@@ -0,0 +1,116 @@
|
||||
"""픽 제출 API — 검증 · 중복방지(1회 수정) · crowd 원자적 증분 · 매칭 모델 계산."""
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy import select, update
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy.orm import selectinload
|
||||
|
||||
from ..database import get_db
|
||||
from ..domain import crowd_out, is_open_for_voting
|
||||
from ..models import AIPrediction, CrowdStats, Match, UserPrediction
|
||||
from ..scoring import outcome_of
|
||||
from ..schemas import SubmitPredictionIn, SubmitPredictionOut
|
||||
|
||||
router = APIRouter(prefix="/api/predictions", tags=["predictions"])
|
||||
|
||||
_COL = {"TEAM_A_WIN": "team_a_win", "DRAW": "draw", "TEAM_B_WIN": "team_b_win"}
|
||||
|
||||
|
||||
async def _adjust_crowd(
|
||||
db: AsyncSession, match_id: str, *, add: str | None, remove: str | None
|
||||
) -> None:
|
||||
"""crowd_stats 원자적 증분/보정 (Postgres UPDATE)."""
|
||||
values: dict = {}
|
||||
if add:
|
||||
col = _COL[add]
|
||||
values[col] = CrowdStats.__table__.c[col] + 1
|
||||
if not remove: # 신규 제출이면 total +1
|
||||
values["total"] = CrowdStats.total + 1
|
||||
if remove and remove != add:
|
||||
col = _COL[remove]
|
||||
values[col] = CrowdStats.__table__.c[col] - 1
|
||||
if values:
|
||||
await db.execute(
|
||||
update(CrowdStats).where(CrowdStats.match_id == match_id).values(**values)
|
||||
)
|
||||
|
||||
|
||||
@router.post("", response_model=SubmitPredictionOut)
|
||||
async def submit_prediction(
|
||||
body: SubmitPredictionIn, db: AsyncSession = Depends(get_db)
|
||||
) -> SubmitPredictionOut:
|
||||
match = (
|
||||
await db.execute(
|
||||
select(Match)
|
||||
.where(Match.match_id == body.matchId)
|
||||
.options(selectinload(Match.predictions))
|
||||
)
|
||||
).scalars().first()
|
||||
if not match:
|
||||
raise HTTPException(status_code=404, detail="MATCH_NOT_FOUND")
|
||||
if not is_open_for_voting(match):
|
||||
# 마감/종료/오픈전 구분
|
||||
if match.result_outcome is not None:
|
||||
raise HTTPException(status_code=409, detail="MATCH_FINISHED")
|
||||
raise HTTPException(status_code=423, detail="MATCH_LOCKED")
|
||||
|
||||
# outcome 은 스코어에서 도출 (입력과 불일치해도 스코어 기준으로 정규화)
|
||||
outcome = outcome_of(body.scoreA, body.scoreB)
|
||||
|
||||
existing = (
|
||||
await db.execute(
|
||||
select(UserPrediction).where(
|
||||
UserPrediction.match_id == body.matchId,
|
||||
UserPrediction.device_id == body.deviceId,
|
||||
)
|
||||
)
|
||||
).scalars().first()
|
||||
|
||||
if existing:
|
||||
# 마감 전 1회 수정: 분포 보정 (이전 outcome 제거, 새 outcome 추가)
|
||||
await _adjust_crowd(db, body.matchId, add=outcome, remove=existing.outcome)
|
||||
existing.outcome = outcome
|
||||
existing.score_a = body.scoreA
|
||||
existing.score_b = body.scoreB
|
||||
if body.email:
|
||||
existing.email = str(body.email)
|
||||
existing.notify = body.notify
|
||||
pred = existing
|
||||
else:
|
||||
await _adjust_crowd(db, body.matchId, add=outcome, remove=None)
|
||||
pred = UserPrediction(
|
||||
match_id=body.matchId,
|
||||
device_id=body.deviceId,
|
||||
outcome=outcome,
|
||||
score_a=body.scoreA,
|
||||
score_b=body.scoreB,
|
||||
email=str(body.email) if body.email else None,
|
||||
notify=body.notify,
|
||||
)
|
||||
db.add(pred)
|
||||
|
||||
await db.commit()
|
||||
|
||||
# 매칭 AI 모델 (같은 outcome) + 정확스코어 일치 여부
|
||||
matched: list[str] = []
|
||||
exact = False
|
||||
for p in match.predictions:
|
||||
if p.outcome == outcome:
|
||||
matched.append(p.model)
|
||||
if p.score_a == body.scoreA and p.score_b == body.scoreB:
|
||||
exact = True
|
||||
|
||||
crowd = (
|
||||
await db.execute(
|
||||
select(CrowdStats).where(CrowdStats.match_id == body.matchId)
|
||||
)
|
||||
).scalars().first()
|
||||
|
||||
return SubmitPredictionOut(
|
||||
ok=True,
|
||||
predictionId=f"{body.matchId}_{body.deviceId}",
|
||||
matchedModels=matched, # type: ignore[arg-type]
|
||||
exactMatch=exact,
|
||||
crowd=crowd_out(crowd, body.matchId),
|
||||
)
|
||||
@@ -0,0 +1,94 @@
|
||||
"""경기 일정 SSOT — lib/schedule.ts(Group A 정식 일정, KST) 와 동일.
|
||||
|
||||
투표 오픈 = 킥오프 - settings.vote_open_hours_before (D-2 = 48h)
|
||||
투표 마감 = 킥오프 - settings.vote_lock_minutes_before (기본 0 = 킥오프 정각)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from .config import settings
|
||||
|
||||
# 팀 정의 (코드 → 표시명/약식/이모지)
|
||||
TEAMS = {
|
||||
"KOR": {"name": "Korea Republic", "shortName": "한국", "code": "KOR", "flag": "🇰🇷"},
|
||||
"CZE": {"name": "Czechia", "shortName": "체코", "code": "CZE", "flag": "🇨🇿"},
|
||||
"MEX": {"name": "Mexico", "shortName": "멕시코", "code": "MEX", "flag": "🇲🇽"},
|
||||
"RSA": {"name": "South Africa", "shortName": "남아공", "code": "RSA", "flag": "🇿🇦"},
|
||||
}
|
||||
|
||||
# 외부 소스의 팀 표기 → 내부 코드 매핑 (openfootball / football-data 등 변형 포괄).
|
||||
NAME_TO_CODE = {
|
||||
"korea republic": "KOR",
|
||||
"south korea": "KOR",
|
||||
"korea": "KOR",
|
||||
"czechia": "CZE",
|
||||
"czech republic": "CZE",
|
||||
"mexico": "MEX",
|
||||
"south africa": "RSA",
|
||||
}
|
||||
|
||||
|
||||
def code_for(name: str) -> str | None:
|
||||
return NAME_TO_CODE.get(name.strip().lower())
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MatchSeed:
|
||||
match_id: str
|
||||
round_label: str
|
||||
team_a: str # 코드
|
||||
team_b: str
|
||||
kickoff_iso: str # ISO with +09:00
|
||||
venue: str
|
||||
hook_text: str
|
||||
|
||||
|
||||
# Group A 전체 6경기 (출처: lib/schedule.ts)
|
||||
GROUP_A: list[MatchSeed] = [
|
||||
MatchSeed(
|
||||
"A_MEX_RSA_20260612", "Match 01 · 개막전", "MEX", "RSA",
|
||||
"2026-06-12T04:00:00+09:00", "Estadio Azteca · Mexico City",
|
||||
"글로벌 축구 개막전, AI는 개최국을 믿을까",
|
||||
),
|
||||
MatchSeed(
|
||||
"A_KOR_CZE_20260612", "Match 01", "KOR", "CZE",
|
||||
"2026-06-12T11:00:00+09:00", "Estadio Guadalajara (Akron)",
|
||||
"한국 첫 경기, AI의 선택은 갈렸다",
|
||||
),
|
||||
MatchSeed(
|
||||
"A_CZE_RSA_20260619", "Match 02", "CZE", "RSA",
|
||||
"2026-06-19T01:00:00+09:00", "USA (TBD)",
|
||||
"체코 vs 남아공, AI의 예측은",
|
||||
),
|
||||
MatchSeed(
|
||||
"A_MEX_KOR_20260619", "Match 02", "MEX", "KOR",
|
||||
"2026-06-19T10:00:00+09:00", "Estadio Guadalajara (Akron)",
|
||||
"개최국 멕시코 vs 한국, AI는 누구 편",
|
||||
),
|
||||
MatchSeed(
|
||||
"A_CZE_MEX_20260625", "Match 03", "CZE", "MEX",
|
||||
"2026-06-25T10:00:00+09:00", "Estadio Azteca · Mexico City",
|
||||
"체코 vs 멕시코, 운명의 최종전",
|
||||
),
|
||||
MatchSeed(
|
||||
"A_RSA_KOR_20260625", "Match 03", "RSA", "KOR",
|
||||
"2026-06-25T10:00:00+09:00", "Estadio BBVA · Monterrey",
|
||||
"한국 16강의 갈림길, AI의 마지막 예측",
|
||||
),
|
||||
]
|
||||
|
||||
FEATURED_MATCH_ID = "A_KOR_CZE_20260612"
|
||||
|
||||
|
||||
def parse_kickoff(iso: str) -> datetime:
|
||||
return datetime.fromisoformat(iso)
|
||||
|
||||
|
||||
def opens_at(kickoff: datetime) -> datetime:
|
||||
return kickoff - timedelta(hours=settings.vote_open_hours_before)
|
||||
|
||||
|
||||
def lock_at(kickoff: datetime) -> datetime:
|
||||
return kickoff - timedelta(minutes=settings.vote_lock_minutes_before)
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Pydantic 스키마 — API 요청/응답 계약.
|
||||
|
||||
프론트(lib/types.ts)와 1:1 정합. 시각은 ISO8601 문자열로 직렬화.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, EmailStr, Field, field_validator
|
||||
|
||||
Outcome = Literal["TEAM_A_WIN", "DRAW", "TEAM_B_WIN"]
|
||||
ModelName = Literal["GPT", "Claude", "Gemini"]
|
||||
|
||||
|
||||
class Team(BaseModel):
|
||||
name: str
|
||||
shortName: str
|
||||
code: str
|
||||
flag: str = ""
|
||||
|
||||
|
||||
class MatchResult(BaseModel):
|
||||
scoreA: int
|
||||
scoreB: int
|
||||
outcome: Outcome
|
||||
|
||||
|
||||
class AIPredictionOut(BaseModel):
|
||||
matchId: str
|
||||
model: ModelName
|
||||
outcome: Outcome
|
||||
scoreA: int
|
||||
scoreB: int
|
||||
confidencePct: int
|
||||
reasonShort: str
|
||||
generatedAt: str
|
||||
|
||||
|
||||
class CrowdStatsOut(BaseModel):
|
||||
matchId: str
|
||||
total: int
|
||||
teamAWin: int
|
||||
draw: int
|
||||
teamBWin: int
|
||||
|
||||
|
||||
class MatchOut(BaseModel):
|
||||
matchId: str
|
||||
roundLabel: str
|
||||
group: str
|
||||
teamA: Team
|
||||
teamB: Team
|
||||
kickoffKst: str
|
||||
venue: str
|
||||
opensAt: str
|
||||
lockAt: str
|
||||
status: str
|
||||
phase: str # scheduled | open | locked | finished (now 기준 계산)
|
||||
votingOpen: bool # 현재 제출 허용 여부 (demo_force_open 반영)
|
||||
hookText: str
|
||||
result: MatchResult | None = None
|
||||
predictions: list[AIPredictionOut] = Field(default_factory=list)
|
||||
crowd: CrowdStatsOut | None = None
|
||||
|
||||
|
||||
# ── 픽 제출 ─────────────────────────────────────────────────
|
||||
class SubmitPredictionIn(BaseModel):
|
||||
matchId: str
|
||||
deviceId: str = Field(min_length=8, max_length=64)
|
||||
outcome: Outcome
|
||||
scoreA: int = Field(ge=0, le=9)
|
||||
scoreB: int = Field(ge=0, le=9)
|
||||
email: EmailStr | None = None
|
||||
notify: bool = False
|
||||
|
||||
@field_validator("outcome")
|
||||
@classmethod
|
||||
def outcome_matches_score(cls, v: str, info): # noqa: ANN001
|
||||
# outcome 은 스코어에서 파생되어야 일관됨 — 프론트가 자동계산하지만 서버에서 재검증
|
||||
return v
|
||||
|
||||
|
||||
class SubmitPredictionOut(BaseModel):
|
||||
ok: bool
|
||||
predictionId: str
|
||||
matchedModels: list[ModelName]
|
||||
exactMatch: bool
|
||||
crowd: CrowdStatsOut
|
||||
|
||||
|
||||
# ── 리더보드 ────────────────────────────────────────────────
|
||||
class StandingOut(BaseModel):
|
||||
rank: int
|
||||
emailMasked: str
|
||||
totalPoints: int
|
||||
exactCount: int
|
||||
matchesPlayed: int
|
||||
|
||||
|
||||
class LeaderboardOut(BaseModel):
|
||||
standings: list[StandingOut]
|
||||
scoredMatches: int
|
||||
|
||||
|
||||
# ── 관리자 ──────────────────────────────────────────────────
|
||||
class AdminAIPredictionIn(BaseModel):
|
||||
matchId: str
|
||||
model: ModelName
|
||||
outcome: Outcome
|
||||
scoreA: int = Field(ge=0, le=20)
|
||||
scoreB: int = Field(ge=0, le=20)
|
||||
confidencePct: int = Field(ge=0, le=100)
|
||||
reasonKo: str = ""
|
||||
reasonEn: str = ""
|
||||
|
||||
|
||||
class AdminSetResultIn(BaseModel):
|
||||
matchId: str
|
||||
scoreA: int = Field(ge=0, le=50)
|
||||
scoreB: int = Field(ge=0, le=50)
|
||||
|
||||
|
||||
class GenericOk(BaseModel):
|
||||
ok: bool
|
||||
detail: str = ""
|
||||
extra: dict | None = None
|
||||
@@ -0,0 +1,42 @@
|
||||
"""채점 로직 — docs/SCORING.md (SSOT) 그대로 구현.
|
||||
|
||||
배점: 정확 스코어 5 · 근접(승패+득실차) 3 · 승패 2 · 부분(한 팀 득점 일치) 1 · 빗나감 0.
|
||||
단조 증가(정확>근접>승패>부분>빗나감). 배점 수치는 SCORE 상수만 교체하면 됨.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
# 팀 확정 후 이 상수만 교체 (docs/SCORING.md §2)
|
||||
SCORE = {"EXACT": 5, "CLOSE": 3, "OUTCOME": 2, "PARTIAL": 1, "MISS": 0}
|
||||
|
||||
|
||||
def outcome_of(score_a: int, score_b: int) -> str:
|
||||
if score_a > score_b:
|
||||
return "TEAM_A_WIN"
|
||||
if score_a < score_b:
|
||||
return "TEAM_B_WIN"
|
||||
return "DRAW"
|
||||
|
||||
|
||||
def score_prediction(
|
||||
pick_a: int, pick_b: int, result_a: int, result_b: int
|
||||
) -> int:
|
||||
"""내 예측 vs 실제 결과 → 적중 포인트 (결정론적)."""
|
||||
if pick_a == result_a and pick_b == result_b:
|
||||
return SCORE["EXACT"]
|
||||
if outcome_of(pick_a, pick_b) == outcome_of(result_a, result_b):
|
||||
if (pick_a - pick_b) == (result_a - result_b):
|
||||
return SCORE["CLOSE"]
|
||||
return SCORE["OUTCOME"]
|
||||
if pick_a == result_a or pick_b == result_b:
|
||||
return SCORE["PARTIAL"]
|
||||
return SCORE["MISS"]
|
||||
|
||||
|
||||
# ── 자격 · 배제 (docs/SCORING.md §4, P1 구현) ──────────────────
|
||||
STAFF_EMAILS: set[str] = set() # 운영진/임직원 블록리스트
|
||||
STAFF_DOMAINS = ["o2o.kr", "aio2o.kr"]
|
||||
|
||||
|
||||
def is_excluded(email: str) -> bool:
|
||||
e = email.strip().lower()
|
||||
return e in STAFF_EMAILS or any(e.endswith("@" + d) for d in STAFF_DOMAINS)
|
||||
@@ -0,0 +1,63 @@
|
||||
"""DB 시드 — 경기 6개 + AI 예측(부트스트랩) + crowd baseline.
|
||||
|
||||
init_db 직후 호출. 이미 경기가 있으면 건너뛴다(idempotent).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from .database import SessionLocal
|
||||
from .models import CrowdStats, Match
|
||||
from .schedule_data import GROUP_A, lock_at, opens_at, parse_kickoff, TEAMS
|
||||
from .seed_data import generate_crowd
|
||||
|
||||
log = logging.getLogger("triplepick.seed")
|
||||
|
||||
|
||||
async def seed_if_empty() -> None:
|
||||
async with SessionLocal() as db:
|
||||
existing = (await db.execute(select(Match.match_id))).scalars().first()
|
||||
if existing:
|
||||
log.info("seed: matches already present — skip")
|
||||
return
|
||||
|
||||
for s in GROUP_A:
|
||||
kickoff = parse_kickoff(s.kickoff_iso)
|
||||
ta, tb = TEAMS[s.team_a], TEAMS[s.team_b]
|
||||
match = Match(
|
||||
match_id=s.match_id,
|
||||
round_label=s.round_label,
|
||||
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=s.venue,
|
||||
hook_text=s.hook_text,
|
||||
kickoff_at=kickoff,
|
||||
opens_at=opens_at(kickoff),
|
||||
lock_at=lock_at(kickoff),
|
||||
status="scheduled",
|
||||
)
|
||||
db.add(match)
|
||||
|
||||
crowd = generate_crowd(s.match_id)
|
||||
db.add(
|
||||
CrowdStats(
|
||||
match_id=s.match_id,
|
||||
total=crowd["total"],
|
||||
team_a_win=crowd["teamAWin"],
|
||||
draw=crowd["draw"],
|
||||
team_b_win=crowd["teamBWin"],
|
||||
)
|
||||
)
|
||||
# AI 예측은 시드하지 않는다 — 워커가 실 API 로 생성.
|
||||
|
||||
await db.commit()
|
||||
log.info("seed: %d matches + crowd seeded (예측 없음 — 워커가 실 API 생성)", len(GROUP_A))
|
||||
@@ -0,0 +1,11 @@
|
||||
"""부트스트랩 데이터.
|
||||
|
||||
AI 예측은 시드하지 않는다 — 3모델 전부 워커가 실 API 로 생성(기동 시 1회 + 매일 00:05).
|
||||
crowd(참여수/분포)도 더미 baseline 없이 0 에서 시작한다 — 실제 유저 제출로만 증분.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def generate_crowd(_match_id: str) -> dict:
|
||||
"""초기 군중 = 0. 실제 유저 픽 제출로만 증가(순수 실데이터)."""
|
||||
return {"total": 0, "teamAWin": 0, "draw": 0, "teamBWin": 0}
|
||||
Whitespace-only changes.
@@ -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,
|
||||
}
|
||||
@@ -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
|
||||
@@ -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)
|
||||
@@ -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 []
|
||||
@@ -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
|
||||
@@ -0,0 +1,247 @@
|
||||
"""백그라운드 워커 — APScheduler (별도 컨테이너).
|
||||
|
||||
조사된 '필요한 시간들'을 모두 자동 처리하는 단일 프로세스:
|
||||
|
||||
1) 상태 전이 (status_tick_seconds 주기, 기본 60초)
|
||||
scheduled → open(킥오프 D-2) → locked(킥오프 정각) — now 기준 자동 갱신.
|
||||
|
||||
2) AI 예측 생성 (매일 KST ai_generate_hour:ai_generate_minute, 기본 00:05)
|
||||
남은(미종료) 경기에 대해 GPT/Claude/Gemini 실 API 호출 → ai_predictions 갱신.
|
||||
모델별 독립 처리(키 없거나 실패해도 나머지 모델은 진행).
|
||||
|
||||
3) 결과 메일 발송 (status_tick 와 함께 점검)
|
||||
경기 종료(finished_at) 후 result_email_delay_minutes(기본 180=3시간) 경과 시,
|
||||
구독자(notify=True+email)에게 개인화 결과 메일 발송 → notified 표시.
|
||||
|
||||
실행: python -m app.worker
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from datetime import timedelta
|
||||
|
||||
from apscheduler.schedulers.asyncio import AsyncIOScheduler
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import selectinload
|
||||
|
||||
from .config import settings
|
||||
from .database import SessionLocal, init_db
|
||||
from .domain import ensure_aware, now_utc
|
||||
from .models import AIPrediction, Match, UserPrediction
|
||||
from .services.ai import MatchContext, PROVIDERS, ProviderUnavailable
|
||||
from .services.email import EmailUnavailable, build_result_email, send_email
|
||||
from .services.schedule_fetch import fetch_schedule
|
||||
from .services.schedule_sync import sync_schedule
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
log = logging.getLogger("triplepick.worker")
|
||||
|
||||
|
||||
# ── 0) 경기 일정 동기화 (외부 크롤링) ──────────────────────
|
||||
async def sync_schedule_job() -> None:
|
||||
records = await fetch_schedule()
|
||||
if not records:
|
||||
return
|
||||
async with SessionLocal() as db:
|
||||
result = await sync_schedule(db, records)
|
||||
# 일정 변경 후 즉시 상태/투표시간 재평가
|
||||
await tick_status()
|
||||
# 새 경기가 삽입됐으면 그 경기 AI 예측을 바로 생성(다음 주기까지 비어있지 않게)
|
||||
if result.get("inserted"):
|
||||
log.info("schedule: 신규 %d경기 → AI 예측 즉시 생성", result["inserted"])
|
||||
await generate_ai_predictions()
|
||||
|
||||
|
||||
# ── 1) 상태 전이 ────────────────────────────────────────────
|
||||
async def tick_status() -> None:
|
||||
async with SessionLocal() as db:
|
||||
now = now_utc()
|
||||
matches = (await db.execute(select(Match))).scalars().all()
|
||||
changed = 0
|
||||
for m in matches:
|
||||
if m.result_outcome is not None:
|
||||
target = "finished"
|
||||
elif now >= ensure_aware(m.lock_at):
|
||||
target = "locked"
|
||||
elif now >= ensure_aware(m.opens_at):
|
||||
target = "open"
|
||||
else:
|
||||
target = "scheduled"
|
||||
if m.status != target:
|
||||
m.status = target
|
||||
changed += 1
|
||||
if changed:
|
||||
await db.commit()
|
||||
log.info("status_tick: %d matches updated", changed)
|
||||
await maybe_send_result_emails()
|
||||
|
||||
|
||||
# ── 2) AI 예측 생성 (실연동) ────────────────────────────────
|
||||
async def generate_ai_predictions() -> None:
|
||||
async with SessionLocal() as db:
|
||||
matches = (
|
||||
await db.execute(
|
||||
select(Match)
|
||||
.where(Match.result_outcome.is_(None))
|
||||
.options(selectinload(Match.predictions))
|
||||
)
|
||||
).scalars().all()
|
||||
|
||||
for m in matches:
|
||||
ctx = MatchContext(
|
||||
team_a=m.team_a_name,
|
||||
team_b=m.team_b_name,
|
||||
venue=m.venue,
|
||||
kickoff=m.kickoff_at.isoformat(),
|
||||
)
|
||||
for model, fn in PROVIDERS.items():
|
||||
try:
|
||||
data = await fn(ctx)
|
||||
except ProviderUnavailable as e:
|
||||
log.warning("AI %s skipped (%s)", model, e)
|
||||
continue
|
||||
except Exception as e: # noqa: BLE001
|
||||
log.error("AI %s failed for %s: %s", model, m.match_id, e)
|
||||
continue
|
||||
|
||||
pred = next((p for p in m.predictions if p.model == model), None)
|
||||
if pred is None:
|
||||
pred = AIPrediction(match_id=m.match_id, model=model)
|
||||
db.add(pred)
|
||||
m.predictions.append(pred)
|
||||
pred.outcome = data["outcome"]
|
||||
pred.score_a = data["scoreA"]
|
||||
pred.score_b = data["scoreB"]
|
||||
pred.confidence_pct = data["confidencePct"]
|
||||
pred.reason_ko = data["reasonKo"]
|
||||
pred.reason_en = data["reasonEn"]
|
||||
pred.generated_at = now_utc()
|
||||
pred.source = "llm"
|
||||
log.info("AI %s → %s %d-%d", model, m.match_id, data["scoreA"], data["scoreB"])
|
||||
await db.commit()
|
||||
|
||||
|
||||
# ── 3) 결과 메일 ────────────────────────────────────────────
|
||||
async def maybe_send_result_emails() -> None:
|
||||
async with SessionLocal() as db:
|
||||
cutoff = now_utc() - timedelta(minutes=settings.result_email_delay_minutes)
|
||||
matches = (
|
||||
await db.execute(
|
||||
select(Match)
|
||||
.where(
|
||||
Match.result_outcome.is_not(None),
|
||||
Match.finished_at.is_not(None),
|
||||
Match.results_emailed_at.is_(None),
|
||||
)
|
||||
.options(selectinload(Match.predictions))
|
||||
)
|
||||
).scalars().all()
|
||||
|
||||
for m in matches:
|
||||
if m.finished_at and ensure_aware(m.finished_at) > cutoff:
|
||||
continue # 아직 지연시간(3시간) 미경과
|
||||
|
||||
picks = (
|
||||
await db.execute(
|
||||
select(UserPrediction).where(
|
||||
UserPrediction.match_id == m.match_id,
|
||||
UserPrediction.notify.is_(True),
|
||||
UserPrediction.email.is_not(None),
|
||||
UserPrediction.notified.is_(False),
|
||||
)
|
||||
)
|
||||
).scalars().all()
|
||||
|
||||
ai_lines = [(p.model, p.outcome == m.result_outcome) for p in m.predictions]
|
||||
match_url = f"{settings.public_origin}/match/{m.match_id}"
|
||||
sent_any = False
|
||||
for pk in picks:
|
||||
subject, html, text = build_result_email(
|
||||
team_a=m.team_a_short,
|
||||
team_b=m.team_b_short,
|
||||
result_a=m.result_score_a or 0,
|
||||
result_b=m.result_score_b or 0,
|
||||
my_a=pk.score_a,
|
||||
my_b=pk.score_b,
|
||||
my_points=pk.points or 0,
|
||||
ai_lines=ai_lines,
|
||||
match_url=match_url,
|
||||
)
|
||||
try:
|
||||
await send_email(pk.email, subject, html, text) # type: ignore[arg-type]
|
||||
pk.notified = True
|
||||
sent_any = True
|
||||
except EmailUnavailable as e:
|
||||
log.warning("result email skipped (%s)", e)
|
||||
break # SMTP 미설정 — 이 경기는 다음 틱에 재시도
|
||||
except Exception as e: # noqa: BLE001
|
||||
log.error("result email failed → %s: %s", pk.email, e)
|
||||
|
||||
# 모든 구독자에게 시도 완료(또는 구독자 없음)면 발송완료 표시
|
||||
still_pending = any(
|
||||
(not pk.notified) for pk in picks
|
||||
)
|
||||
if not still_pending:
|
||||
m.results_emailed_at = now_utc()
|
||||
await db.commit()
|
||||
|
||||
|
||||
def build_scheduler() -> AsyncIOScheduler:
|
||||
sched = AsyncIOScheduler(timezone=settings.timezone)
|
||||
# 경기 일정: 매일 KST 09:00 외부 크롤링 → 경기·투표시간 갱신
|
||||
sched.add_job(
|
||||
sync_schedule_job,
|
||||
"cron",
|
||||
hour=settings.schedule_sync_hour,
|
||||
minute=settings.schedule_sync_minute,
|
||||
id="schedule_sync",
|
||||
)
|
||||
# 투표시간 상태 전이 (open/locked)
|
||||
sched.add_job(
|
||||
tick_status,
|
||||
"interval",
|
||||
seconds=settings.status_tick_seconds,
|
||||
id="status_tick",
|
||||
next_run_time=now_utc(),
|
||||
)
|
||||
# AI 예측 생성: 매일 KST 00:05 (실 API)
|
||||
sched.add_job(
|
||||
generate_ai_predictions,
|
||||
"cron",
|
||||
hour=settings.ai_generate_hour,
|
||||
minute=settings.ai_generate_minute,
|
||||
id="ai_generate",
|
||||
)
|
||||
return sched
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
await init_db() # 테이블 보장 (idempotent). 시드는 API 가 담당.
|
||||
# 기동 시 1회: 일정 동기화 → AI 예측 생성(키 있을 때 GPT·Gemini 즉시 채움)
|
||||
await sync_schedule_job()
|
||||
await generate_ai_predictions()
|
||||
|
||||
sched = build_scheduler()
|
||||
sched.start()
|
||||
log.info(
|
||||
"scheduling-server started — schedule sync daily %02d:%02d · status every %ss · "
|
||||
"AI gen daily %02d:%02d %s · result email +%dmin",
|
||||
settings.schedule_sync_hour,
|
||||
settings.schedule_sync_minute,
|
||||
settings.status_tick_seconds,
|
||||
settings.ai_generate_hour,
|
||||
settings.ai_generate_minute,
|
||||
settings.timezone,
|
||||
settings.result_email_delay_minutes,
|
||||
)
|
||||
# 영구 대기
|
||||
stop = asyncio.Event()
|
||||
try:
|
||||
await stop.wait()
|
||||
finally:
|
||||
sched.shutdown()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,13 @@
|
||||
fastapi==0.115.6
|
||||
uvicorn[standard]==0.34.0
|
||||
sqlalchemy[asyncio]==2.0.36
|
||||
asyncpg==0.30.0
|
||||
pydantic==2.10.4
|
||||
pydantic-settings==2.7.1
|
||||
email-validator==2.2.0
|
||||
apscheduler==3.11.0
|
||||
aiosmtplib==3.0.2
|
||||
httpx==0.27.2
|
||||
anthropic==0.69.0
|
||||
openai==1.59.6
|
||||
google-genai==0.8.0
|
||||
Reference in new issue
Block a user