Compare commits

...
55 Commits
Author SHA1 Message Date
skkim 36742042f5 fix: MLS 수집 중단·live 고착 경기 복구
- ESPN scoreboard 날짜 범위 조회가 400을 반환해 9/16부터 MLS 일정·결과·순위
  수집이 전부 실패 → 일/월 단위 조회로 분할(_fetch_events)
- MLB 연기·취소 경기는 abstractGameState 가 Final 로 와서 취소로 잡히지 않고
  live 에 고착 → detailedState 만으로 취소 판정
- settle_baseball: 소스가 연기·취소로 보고하거나 소스 일정에서 사라진
  (킥오프 후 24h 경과) 미정산 경기를 취소 처리. 수집 실패(빈 응답) 시에는
  아무것도 취소하지 않음
2026-11-11 10:57:46 +09:00
JinwooKimandClaude Fable 5 bb930cc59f 응원가 공유·플레이어 문구 '오늘의' → 제작일 표기 (예: 8월 28일 OO 응원가)
songs API에 dateKst(경기일) 추가, OG 공유 제목·프론트 shareText·artist에 적용
— 매일 갱신되는 콘텐츠임을 드러낸다

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-31 10:21:24 +09:00
JinwooKimandClaude Fable 5 df367070ce 일정 카드 AI 픽 부등호 확대(24→34px) + 글로우
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-31 10:20:11 +09:00
JinwooKimandClaude Fable 5 fdb04a2ccc 응원가 영구 보존·종료 경기 노출 — 음원 DB 저장 + 경기별 조회 API
- Suno CDN 임시 URL 만료 대비: 완성 곡 첫 트랙을 워커가 다운로드해
  song_audio(bytea)로 보존하고 audioUrl을 /api/songs/audio/{id}/{idx}로 재작성
  (틱당 5곡, 실패 3회 상한 — 기존 곡도 자동 백필)
- GET /api/songs/match/{match_id} 추가 — 날짜 무관 조회로 종료된 경기
  상세에서도 '응원가 듣기' 버튼 노출
- 프론트 getTeamSongTracks를 오늘 전체 캐시 → 경기별 조회·캐시로 전환
- 음원 서빙은 Range(206) 지원, immutable 캐시 + task_id 캐시버스터

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-28 15:39:16 +09:00
JinwooKimandClaude Fable 5 bc333d64f4 MLB 종료 판정을 detailedState→abstractGameState 기준으로 수정
우천 조기종료(detailedState="Completed Early") 등 "Final" 이외의 종료
변형 문자열은 감지되지 못해 해당 경기가 영원히 정산 안 된 채 live 로
고착되는 버그였다(MLB_PHI_BAL_20260803, 8:0 조기종료 확정임에도 누락).
abstractGameState(Preview/Live/Final 세 값만 존재)로 판정 기준 교체.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-27 15:09:05 +09:00
JinwooKimandClaude Fable 5 11dd968ced 정산 조회 범위 동적 확장 — 오래 방치된 미정산 경기가 영원히 live로 남는 버그 수정
settle_baseball 이 결과를 조회하는 윈도우(KBO/MLB=result_recheck_days 기본
3일, MLS=mls_days_back 기본 30일)가 고정폭이라, 최초 수집에 실패한 경기가
그 윈도우 밖으로 밀려나면 이후 영원히 매칭 대상에서 빠져 status=live로
고정되는 버그가 있었다(예: MLB_PHI_BAL_20260803, 8/2 이후 3주+ live 고착).

미정산 경기 중 가장 오래된 킥오프 날짜까지 덮도록 조회 범위를 매 틱 동적
계산(최대 120일 소급)하도록 수정.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-27 14:48:21 +09:00
JinwooKimandClaude Fable 5 746eaced80 가사 품질 보강 — 한국어 수사 규칙·전체 분량·캐시 TTL
- 서수 고유어(4번째→네 번째), 고유어 조수사(방·개·명·골), 아웃 카운트
  영어 수사(2아웃→투아웃)
- 가사 축약 방지: 필수 섹션 명시(Verse2·Bridge·Final Chorus), max_tokens
  3000→8000, 450자 미만은 재시도
- 프론트 곡 캐시 하루→5분 TTL (당일 재생성 교체 반영)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-27 11:40:45 +09:00
JinwooKimandClaude Fable 5 cb00945612 가사 한글화에서 [섹션 태그] 제외 — Suno 구조 인식 보존
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-27 10:24:12 +09:00
JinwooKimandClaude Fable 5 eb4064279b 가사 표기·발음 분리 — 화면엔 13:1 원문, Suno 전송본만 한글 발음 치환
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-27 10:18:20 +09:00
JinwooKimandClaude Fable 5 f8c24d1f3c AI 예측 입력 통일·데이터 전면 보강
- 3모델 페르소나 분화 제거 — 동일 프롬프트+동일 데이터 (차이는 모델 판단만)
- 순위 라인에 게임차·팀 타율·팀 ERA 추가
- 전날 결과+활약(홈런·맹타), 확정 라인업+타자 시즌 타율 주입
  (응원가 파이프라인 헬퍼 재사용, 라인업 미발표 시 생략)
- 선발 상대 ERA 0.00(기록 없음) 오표기 생략

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-27 10:08:40 +09:00
JinwooKimandClaude Fable 5 9e8993c67a 두산 상설 응원가 특례 제거 — 전 팀 동일하게 오늘의 생성곡만
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-27 10:03:03 +09:00
JinwooKimandClaude Fable 5 579ab768bf 가사 숫자 한글화 — Suno 오독 방지
- 프롬프트에 아라비아 숫자 금지 규칙+예시 추가
- 안전망 hangulize_numbers: 한자어 수사(일승·칠십팔승·이차전), 게임·경기는
  고유어(일곱 게임), 스코어 5:3→오 대 삼, 소수 타율 영점삼일이. 제목도 적용

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-26 10:18:09 +09:00
JinwooKimandClaude Fable 5 6770543318 월드컵 서비스 종료 + 응원가 MLS 확장
- 리그 탭에서 월드컵 제거, ?league=wc 는 KBO 강등, 기본 리그 kbo·mlb·mls
- index.html·OG 기본 타이틀에서 월드컵 문구 제거, 월드컵 특설 정적
  플레이리스트 제거
- 응원가 MLS 포함: 라인업 소스 없는 리그는 윈도우 진입 즉시 생성,
  스타일은 soccer 앤섬 변형, 커버 로고는 Match flag(ESPN PNG) 재사용
- MLB 도 한국 팬 표기 지시 적용, 전날 활약 조회는 kbo/mlb 만

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-25 10:47:49 +09:00
JinwooKimandClaude Fable 5 abcdf42aeb 가사 데이터 보강(활약·타율) + 커버는 팀 로고 100%
- 전날 경기 활약: KBO=네이버 record 타자 boxscore(홈런·3안타 이상),
  MLB=boxscore batting — 어제 결과 줄에 "활약: ..." 로 부가
- 확정 라인업에 타자 시즌 타율 병기 (MLB=seasonStats, KBO=최근 경기 hra 맵)
- 커버 합성에서 Suno 배경 제거 — 다크 단색 배경 + 팀 로고 최대 크기

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-25 10:42:55 +09:00
JinwooKimandClaude Fable 5 c895bc9c6b 가사 패널 스크롤바 다크 슬림 스타일 (흰색 기본 트랙 제거)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-25 10:37:51 +09:00
JinwooKimandClaude Fable 5 434f282e6b 응원가 커버를 팀 로고 합성본으로 교체
- /api/songs/cover/:matchId/:teamCode — Suno 앨범아트(감광 배경) 위에
  팀 로고 중앙 합성 (1200x630, OG 규격), 메모리 캐시 + task 캐시버스터
- 로고 소스: KBO=프론트 로컬 PNG(내부 프록시), MLB=mlbstatic spots PNG
- 플레이어 썸네일·/song OG 카드 모두 합성 커버 사용, pillow 의존성 추가

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-25 10:26:49 +09:00
JinwooKimandClaude Fable 5 dbc26a4150 곡 스타일 전곡 고정 + 팀당 1곡만 노출
- 스타일은 레퍼런스 확정본(brass fanfare·drum corps·128bpm·live stadium)
  으로 고정, LLM 은 제목·가사만 작성
- Suno 생성 2트랙 중 첫 트랙만 API 노출

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-25 10:23:51 +09:00
JinwooKimandClaude Fable 5 3a5fc36ee8 플레이어에 가사 보기·공유하기 + 응원가 전용 OG 공유 카드
- 하단 MusicBar: 가사 패널 토글(바 위로 펼침)·공유 버튼(네이티브 공유,
  폴백 클립보드) — 응원가 트랙에만 노출
- 공유 링크 /song/:matchId/:teamCode — 크롤러(카톡·페북)는 "오늘의 OO
  응원가" 제목 + Suno 앨범아트 OG 카드, 사람은 경기 페이지로 리다이렉트
  후 그 팀 응원가 자동 로드(?song=)
- nginx /song/ 크롤러 분기 추가

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-25 10:20:54 +09:00
JinwooKimandClaude Fable 5 dbd08e62c7 응원가를 MLB 로 확장 (MLS 제외)
- MLB 라인업: Stats API schedule→gamePk→boxscore battingOrder (양팀 9명 = 발표)
- 작사 프롬프트 리그 분기 (MLB 는 한국 팬 표기 지시)
- /api/songs/today league 미지정 시 전 리그 반환, 프론트는 전 리그 조회
- 상세 페이지 응원가 버튼 KBO+MLB 노출

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-25 10:05:27 +09:00
JinwooKimandClaude Fable 5 0fc7598d88 응원가 생성을 라인업 발표 이후로 게이트
- 네이버 preview fullLineUp 조회 — 양팀 타자 8명 이상이면 발표로 간주,
  확정 라인업(타순·포지션 실명)을 가사 컨텍스트에 주입
- 생성 윈도우(킥오프 150분 전~) 안에서 발표까지 대기, 킥오프 40분 전까지
  미발표면 라인업 없이 폴백 생성
- 라인업 없이 만든 곡은 발표 후 자동 재생성(업그레이드) — 기존 트랙을
  유지한 채 새 곡 완성 시점에 교체, 실패 시 이전 곡 복귀

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-25 09:59:19 +09:00
JinwooKimandClaude Fable 5 390e06113d 응원가 재생을 팀별 버튼 방식으로 전환
- 일정/메인 자동 로드 제거 — 상세 페이지 대결 카드의 팀 로고 아래
  "응원가 듣기" 버튼으로 각 팀 곡을 개별 재생 (재생 중 일시정지/이어듣기 토글)
- MusicBar 는 버튼이 실은 플레이리스트도 표시하도록 노출 조건 정리
- 두산 상설 응원가는 두산 버튼 트랙 뒤에 이어붙임

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-25 09:53:53 +09:00
JinwooKimandClaude Fable 5 277378477a 오늘의 응원가 자동 생성 파이프라인 (Suno)
- 경기 맥락(전날 결과·순위·연전 차수·선발투수) 조립 → LLM 작사
  (콜앤리스폰스·섹션 태그 형식) → Suno(sunoapi.org) 생성 → songs 테이블
- 워커: 킥오프 150분 전 윈도우 진입 시 생성 시작 + 2분 주기 폴링
- API: GET /api/songs/today · POST /api/songs/callback(싱크대)
  · POST /api/songs/generate(관리자 강제 생성)
- 프론트: MusicBar 가 경기 상세·메인에서 오늘의 응원가를 동적 로드
  (정적 플레이리스트는 폴백 유지)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-25 09:33:34 +09:00
JinwooKimandClaude Fable 5 2a8f2bc1fa 일정 카드 AI 아이콘 확대(24px)·VS를 픽 우세 부등호로
AI 픽이 있는 카드는 VS 대신 우세 방향 부등호(>, <, 팽팽하면 =) 표시.
픽 없는 경기는 기존 VS 유지.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-25 09:11:24 +09:00
JinwooKimandClaude Fable 5 8da8b7e7bd 일정 카드 AI 픽을 팀 아래 모델 아이콘으로 표시
기존 "AI 픽 삼성 3" 텍스트 줄 대신 GPT/Claude/Gemini 아이콘을
각자 픽한 팀 쪽 아래에 배치 (무승부 픽은 가운데). 참여수는 우측 유지.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-25 09:07:31 +09:00
JinwooKimandClaude Fable 5 d6b3ddeee0 SEO: 타이틀·공유카드 문구 원복 — 검색엔진용 요소만 유지
브라우저 탭 타이틀과 og/twitter 공유 카드는 기존 브랜드 문구로 되돌리고,
확장 키워드(프로야구·해외야구 승부예측)는 description·keywords·
seo-fallback 본문·JSON-LD 에만 유지.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-20 13:51:24 +09:00
JinwooKimandClaude Fable 5 6a9a7115fd SEO: 프로야구·해외야구 승부예측 정확 문구 키워드 반영
"프로야구 승부예측", "해외야구 승부예측", "메이저리그 승부예측" 등
확장 검색어의 정확 문구를 title·description·keywords·seo-fallback
본문·JSON-LD에 자연 문장으로 추가. sitemap lastmod 갱신.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-20 13:48:29 +09:00
JinwooKimandClaude Fable 5 ea4d1ab746 두산 응원가 커버 4장 추가 (gpt-image-1 생성, 640px webp)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 11:28:27 +09:00
JinwooKimandClaude Fable 5 d97023629e 두산 응원가 4곡 추가 — KBO 두산(OB) 전 경기 플레이리스트
경로 정확일치 방식은 경기 날짜마다 등록이 필요해, 두산 경기
(match_id 에 OB 포함)면 공통 플레이리스트를 반환하는 리졸버로 확장.
월드컵 경기별 목록(PATH_PLAYLISTS)은 기존대로 우선 적용.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 11:21:36 +09:00
JinwooKimandClaude Fable 5 22e2e8c29c share OG: 팀명 DB 조회(클럽 리그 한글명) + 문구 갱신 + 썸네일 캐시버스터
- /match/:id OG 프리렌더가 STL/CIN 같은 코드 대신 DB 의 한글 short 팀명을
  사용 (KBO·MLB·MLS 포함). 리그 태그도 제목에 표기
- 설명문을 멀티리그 기준 최신 카피로 갱신
- og:image 에 ?v=2 캐시버스터 — 메신저가 과거 실패/구버전 썸네일을
  캐시한 경우 재수집 유도 (index.html 정적 OG 동일 적용)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-18 09:42:10 +09:00
JinwooKimandClaude Fable 5 9b57d56daf frontend: SEO 멀티리그 전환 — 월드컵 단일 → 월드컵·KBO·MLB·MLS
- index.html: title/description/OG/twitter/keywords/JSON-LD/SEO 폴백 본문을
  "AI 스포츠 승부예측(4개 리그)" 기준으로 갱신. 문자중계·카카오 로그인 언급 추가
- sitemap.xml: 리그별 대시보드 URL(?league=kbo|mlb|mls) 추가, lastmod 갱신
- rss.xml: 채널명·설명 갱신 + 멀티리그 확장 item 추가
- llms.txt: 대상 리그·참여 방식·부가 기능(문자중계 등) 최신화
- worldcup-prediction.html 은 월드컵 전용 랜딩이라 유지

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-18 09:14:09 +09:00
JinwooKimandClaude Fable 5 b6fa863b58 frontend: 가독성 개선 — Pretendard 웹폰트 실제 로드 + 저대비 텍스트 상향
- index.html: Pretendard Variable(dynamic-subset) CDN 로드 추가.
  지금까지 font-family 에 이름만 있고 로드가 없어 Windows 에서
  맑은 고딕 폴백으로 렌더링 → 글씨가 가늘고 흐릿하게 보였음
- globals.css: 폰트 스택에 "Pretendard Variable" 추가
- ScheduleBoard: 메타/보조 텍스트 대비·크기 상향
  (11px→12px, white/35~55 → white/50~85, 상태 배지·순위 배지·칩 포함)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-18 09:02:17 +09:00
JinwooKimandClaude Opus 5 7705099c64 feat(auth): 카카오 로그인 — o2o-castad-backend 인증 스택 이식
백엔드 (castad 와 동일 흐름, triplepick 스타일로 재작성):
- users/refresh_tokens 테이블 (신규 — create_all 로 자동 생성)
- 카카오 OAuth (code → 토큰 → 사용자 정보), aiohttp 대신 httpx
- JWT HS256 access 60분 / refresh 7일, Refresh Token Rotation
  (재사용 감지 시 TOKEN_REVOKED, castad 동일 에러 코드 체계)
- /api/auth/{kakao/login, kakao/callback, refresh, logout, me}
- 콜백 → 프론트 리다이렉트는 쿼리 대신 해시 프래그먼트로 토큰 전달
  (서버 로그·Referer 에 토큰 노출 방지 — castad 방식에서 한 단계 보강)
- 크레딧·소셜계정 연동 등 castad 전용 개념은 제외

프론트:
- lib/auth.ts — 토큰 보관·자동 갱신·/me 캐시·useAuth 훅
- Hero 에 카카오 로그인 버튼(브랜드 노랑) / 프로필 칩 + 로그아웃
- 투표 폼(Arena) 이메일을 로그인 계정 이메일로 자동 채움
  (기존 이메일 기반 투표·리더보드 파이프라인은 그대로 유지)

설정: KAKAO_CLIENT_ID/SECRET/REDIRECT_URI, JWT_SECRET (.env.example 참고)

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-14 15:42:54 +09:00
JinwooKimandClaude Opus 5 e2d1647100 fix(sched): 날짜 기본 선택·가운데 정렬 전 리그 통일
- 기본 날짜: 오늘 → 경기 없으면 다음 경기일 → 시즌 종료면 마지막 날짜
  (기존엔 첫 날짜(가장 과거)로 떨어져 백필 후 3주 전이 기본 선택되던 문제)
- '오늘' 을 KST 로 계산 (기존 UTC — KST 오전 9시 전엔 어제로 잡힘)
- 선택 칩 가운데 정렬을 리그/탭 전환뿐 아니라 선택 변경·비동기 로드에도 적용
- 목록 비동기 로드 시에도 세션 저장 선택 복원 동작

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-14 15:04:17 +09:00
JinwooKimandClaude Opus 5 eecc9829b4 feat(mls): 과거 30일 백필 — 주말 위주 편성으로 일정판에 생기던 공백 해소
야구식 recheck 윈도우(3일)만으론 MLS 직전 라운드(1~2주 전)가 수집되지 않아
일정판이 비고 자체 DB 폼 데이터도 부족했음. 범위를 넓혀도 scoreboard 1콜.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-14 14:56:44 +09:00
JinwooKimandClaude Opus 5 e1b85aeba6 fix(mls): odds 원소가 null 인 경기에서 프리뷰 갱신 전체가 죽던 문제
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-14 14:50:59 +09:00
JinwooKimandClaude Opus 5 00494e9e93 feat(mlb): 문자중계 추가 — feed/live allPlays 규칙 기반 한글 변환
- 투구 호칭·eventType 한글 매핑, 타구 방향은 desc 의 야수 표현에서 추출
- 주자 이동(홈인·진루·주루사)은 정규식 파싱 — 선수명은 이니셜("J.P.")만
  마침표 허용해 문장 경계를 넘지 않게 함
- 교체는 "A replaces B" 구문 분해 (투수 교체·대타·대주자·수비 교체)
- 득점 강조는 KBO 와 동일하게 플레이 종료 점수 합 변화로 판정 + 홈런 결과 라인
- 미지원 문장·이벤트는 영문 원문 폴백. 노이즈(타자 타임·수비 위치이동 등) 제외
- KBO relay 와 동일 스키마라 프론트(LiveField RelayFeed) 변경 없음

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-14 14:38:48 +09:00
JinwooKimandClaude Opus 5 13a4997cc2 fix(mls): ESPN 403 — 브라우저 위장 UA 제거
컨테이너(httpx)에서 풀 Chrome UA 를 보내면 ESPN WAF 가 403 차단
(TLS 핑거프린트-UA 불일치 감지로 추정). httpx 기본 UA 는 통과 —
일정 동기화가 계속 실패해 로컬에서 MLS 일정이 안 뜨던 원인.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-14 14:38:48 +09:00
JinwooKimandClaude Opus 5 0415ab7636 feat(kbo): 라이브 필드에 문자중계 추가 — 네이버 relay 전 이닝
- relay 응답에서 버리던 textRelays 를 타석 단위 그룹으로 서빙 (한국어 원문 그대로)
- 기본 응답은 현재 이닝만 담아, 지난 이닝은 ?inning=N 병렬 조회 후 캐시
  (현재·직전 이닝은 매번 재조회 — 이닝 전환 직후 마지막 타석 누락 방지)
- 득점 하이라이트는 텍스트 패턴이 아니라 currentGameState 점수 합 변화로 판정
  (홈런·적시타뿐 아니라 홈인·폭투/실책 득점·밀어내기까지 정확)
- 네이버 type 코드는 kind(pitch/result/run/sub/note)로 변환해 UI 에 노출하지 않음
- 진행 중엔 최근 40타석, 종료 후엔 전 경기 중계(다시보기)
- 프론트: 투구 접기/펼치기 토글 · 이닝 구분선 · 득점 강조

MLB 는 소스(feed/live allPlays)가 영문이라 별도 작업 — 이번 커밋은 KBO 만.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-14 13:57:02 +09:00
JinwooKimandClaude Opus 5 74de57fc1c feat(mls): MLS 리그 추가 — ESPN 비공식 API 연동
- 일정·결과·컨퍼런스 순위·프리뷰(폼/시즌전적/맞대결/머니라인) 수집
- 라이브 카드: 스코어·경기시간·득점/카드·선발 라인업(피치 뷰)·교체 현황
- 문자중계: ESPN commentary 규칙 기반 한글 변환 (미지원 템플릿은 팀명만 한글화)
- MLS 레코드는 야구와 키 구조가 같아 sync_baseball_schedule/settle 재사용
- AI 예측 데이터 블록에 MLS 전용 컨텍스트 추가

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-14 13:47:13 +09:00
JinwooKim ad5bbec82e 야구 리그 랭킹 UI 비노출 2026-07-22 16:06:36 +09:00
JinwooKimandClaude Fable 5 c73a9ad9f9 관리자 조회 API 추가(경기별 투표·이메일 랭킹, 토큰 인증) + ops/ gitignore
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-22 14:04:14 +09:00
JinwooKim e1fb1f6b1d 100만원 챌린지 카드 프론트에서 임시 삭제 2026-07-22 13:21:24 +09:00
JinwooKim 4a7719895e 하단 문구 수정 2026-07-22 11:51:57 +09:00
JinwooKim bbad63ee92 ai 예측 대결 문구 변경 2026-07-22 11:26:00 +09:00
JinwooKim 4e1ebc8989 feat: KBO/MLB 운영 안정화 — 순위 탭·라이브 개선·취소/더블헤더 지원·야구 점수제
AI 예측
- 생성 시점을 킥오프 22시간 전으로 변경(선발투수 예고 이후), 잡 매시간 실행
- 경기 시작 후 생성 금지(사후 예측 방지), 경기 단위 커밋으로 중단 시 진행분 보존

일정·라이브 UI
- 야구 일정에 순위 탭 추가 (KBO 단일 순위표 · MLB 6개 디비전, /api/standings 신설)
- 경기중 카드에 현재 이닝·실시간 스코어 표시 (30s 폴링, 서버 15s 캐시)
- MLB 선발 누락 수정: statsapi 날짜 파라미터 미국 날짜 기준 보정(-1일)
- 라이브 대기타석 스크롤바 다크 테마 처리

운영 견고성
- 우천취소: 경기 삭제 → cancelled 상태 보존 (투표·예측 기록 유지, 정산/투표/AI 제외)
- 더블헤더: 시작시각순 seq로 1·2차전 분리 등록 (match_id _2, 정산·라이브·프리뷰 매핑)
- 축구 데이터 수집을 wc 리그로 한정 (야구 팀을 축구 API에 검색하던 쿼터 낭비 수정)

점수제
- 야구 판정 완화: 근접=득실차 ±1, 부분=한 팀 득점 ±1 (등급·배점은 리그 공통 유지)
- 채점 판정을 _grade_of() 단일 함수로 통합, 종료된 야구 경기 재채점
- 배점 안내 모달 야구 문구 분리, docs/SCORING.md 갱신

기타
- 야구 전용 댓글 닉네임 풀 (종목별 세션 캐시 분리)
- 리더보드 리그별 조회 연동 (?league=)
2026-07-22 11:01:10 +09:00
JinwooKim bfaf621949 시작화면 토너먼트 탭으로 변경 2026-07-09 09:05:19 +09:00
JinwooKim 0392a63d5e feat(seo): JSON-LD sameAs·parentOrganization 보강\ 2026-06-30 09:42:42 +09:00
JinwooKim 590335b005 feat(seo): 검색등록 메타·robots·sitemap·llms·rss 배포 2026-06-29 10:56:50 +09:00
JinwooKim 3864974ac0 토너먼트 추가 버그 수정 2026-06-29 09:22:20 +09:00
JinwooKim 6815540ae6 토너먼트 대진 추가 2026-06-29 09:11:58 +09:00
JinwooKim 59db1c4e9a 마스코트 한국vs남아공 only -> 전 경기에 반영 2026-06-26 17:15:26 +09:00
JinwooKim 906896afad Merge branch 'develop' of https://gitea.o2o.kr/castad/o2o-triple-pick into develop
# Please enter a commit message to explain why this merge is necessary,
# especially if it merges an updated upstream into a topic branch.
#
# Lines starting with '#' will be ignored, and an empty message aborts
# the commit.
2026-06-24 15:23:53 +09:00
JinwooKim a81c7f5644 투표 제출하기 UI 수정 2026-06-24 15:18:18 +09:00
skkim 56261e7667 Merge branch 'develop' of https://gitea.o2o.kr/castad/o2o-triple-pick into develop 2026-06-24 14:15:19 +09:00
skkim a2507439d7 seo 페이지 수정 2026-06-24 14:15:10 +09:00
86 changed files with 7837 additions and 620 deletions

No files matched your search

+3
View File
@@ -45,3 +45,6 @@ serviceAccount.json
# 로컬 전용 댓글 관리 도구 # 로컬 전용 댓글 관리 도구
tp-comment-admin/ tp-comment-admin/
# 개인 운영 대시보드 (관리자 토큰 포함 — 커밋 금지)
ops/
+13
View File
@@ -45,6 +45,15 @@ STATUS_TICK_SECONDS=60
# 관리자 (강한 토큰으로 교체) # 관리자 (강한 토큰으로 교체)
ADMIN_API_TOKEN=change-me-admin-token ADMIN_API_TOKEN=change-me-admin-token
# ── 카카오 로그인 (o2o-castad-backend 인증 이식) ──
# 카카오 개발자 콘솔(developers.kakao.com) 앱의 REST API 키.
# redirect_uri 는 콘솔 [카카오 로그인 > Redirect URI] 에 등록돼 있어야 한다.
# 운영: https://triplepick.o2o.kr/api/auth/kakao/callback
KAKAO_CLIENT_ID=
KAKAO_CLIENT_SECRET= # 콘솔에서 Client Secret 활성화한 경우만
KAKAO_REDIRECT_URI=http://localhost:8080/api/auth/kakao/callback
JWT_SECRET=change-me-triplepick-jwt-secret # 32자 이상 무작위 문자열로 교체
# ── 외부 연동: AI 3모델 (실연동, 키 없으면 해당 모델 생성 생략) ── # ── 외부 연동: AI 3모델 (실연동, 키 없으면 해당 모델 생성 생략) ──
OPENAI_API_KEY= OPENAI_API_KEY=
OPENAI_MODEL=gpt-4o OPENAI_MODEL=gpt-4o
@@ -72,3 +81,7 @@ SMTP_USER=
SMTP_PASSWORD= SMTP_PASSWORD=
SMTP_FROM=TriplePick <no-reply@triplepick.app> SMTP_FROM=TriplePick <no-reply@triplepick.app>
SMTP_STARTTLS=true SMTP_STARTTLS=true
# Suno (sunoapi.org 게이트웨이) — 오늘의 응원가 자동 생성
SUNO_API_KEY=
SONGS_ENABLED=true
+61 -4
View File
@@ -73,20 +73,61 @@ class Settings(BaseSettings):
featured_group: str = "A" featured_group: str = "A"
football_data_token: str = "" # football-data 사용 시 토큰 football_data_token: str = "" # football-data 사용 시 토큰
football_data_competition: str = "WC" football_data_competition: str = "WC"
# 결과(스코어) 소스 — 일정 소스와 분리. 빈값이면 schedule_source 사용. # 결과(스코어) 소스 — 일정 소스와 분리. 빈값이면 자동 결정(아래 effective).
# openfootball 은 결과 미게시라, 자동 종료를 쓰려면 football-data 권장. # openfootball 은 결과 미게시라, 자동 종료를 쓰려면 football-data 가 필요하다.
result_source: str = "" result_source: str = ""
@property @property
def effective_result_source(self) -> str: def effective_result_source(self) -> str:
return (self.result_source or self.schedule_source).lower() # 명시값 우선. 없으면: 전체 조 모드는 football-data 기반이므로 결과도 동일 소스로
# 자동 정렬(openfootball 폴백 시 녹아웃·타 조 결과가 영영 안 들어오는 함정 방지).
if self.result_source:
return self.result_source.lower()
if self.schedule_all_groups:
return "football-data"
return self.schedule_source.lower()
# ── 멀티리그 (kbo · mlb · mls) — 월드컵(wc)은 2026-08 종료 ──
# 활성 리그 (콤마구분). 각 리그 워커가 자기 소스에서 일정·결과를 동기화.
leagues: str = "kbo,mlb,mls"
# 야구 일정 수집 윈도우 — 오늘 기준 미래 며칠치.
# (투표 오픈·AI 예측 생성은 리그 공통: vote_open_hours_before / ai_generate_lookahead_hours)
baseball_days_ahead: int = 7
# 네이버 스포츠 비공식 API (KBO 일정·결과·프리뷰·문자중계) — 비공식, 로컬용.
naver_api_base: str = "https://api-gw.sports.naver.com"
# MLB 공식 Stats API (키 불필요).
mlb_api_base: str = "https://statsapi.mlb.com/api"
# ── 카카오 로그인 (o2o-castad-backend 인증 이식) ──────────
# 카카오 개발자 콘솔의 REST API 키. redirect_uri 는 콘솔에 등록돼 있어야 한다.
kakao_client_id: str = ""
kakao_client_secret: str = "" # 콘솔에서 활성화한 경우만
kakao_redirect_uri: str = "http://localhost:8080/api/auth/kakao/callback"
# JWT — castad 와 동일: HS256, access 60분 / refresh 7일 (rotation)
jwt_secret: str = "change-me-triplepick-jwt-secret"
jwt_access_expire_minutes: int = 60
jwt_refresh_expire_days: int = 7
# ESPN 비공식 API (MLS 일정·결과·순위·상세) — 키 불필요, 비공식.
espn_api_base: str = "https://site.api.espn.com/apis"
espn_mls_path: str = "sports/soccer/usa.1"
# MLS 과거 경기 백필 일수 — MLS 는 주말 위주 편성이라 야구식 recheck 윈도우(3일)만으론
# 일정판에 긴 공백이 생기고 자체 DB 폼 데이터도 비어서, 최근 한 달을 함께 수집한다.
# (범위를 넓혀도 scoreboard 1콜, sync 는 추가형이라 과거 경기 재수집 무해)
mls_days_back: int = 30
@property
def league_list(self) -> list[str]:
return [x.strip() for x in self.leagues.split(",") if x.strip()]
# AI 예측 생성 전체 스위치 — False 면 워커가 AI 호출을 전혀 하지 않음(로컬 테스트).
ai_enabled: bool = True
# 매일 AI 예측 생성 시각 (KST). 기능정의서: 매일 0시 1회 생성. # 매일 AI 예측 생성 시각 (KST). 기능정의서: 매일 0시 1회 생성.
ai_generate_hour: int = 0 ai_generate_hour: int = 0
ai_generate_minute: int = 5 ai_generate_minute: int = 5
# 투표 오픈(D-2) 선행 생성 시간(h). 1일 1회 생성이므로 다음 주기 전 오픈할 # 투표 오픈(D-2) 선행 생성 시간(h). 1일 1회 생성이므로 다음 주기 전 오픈할
# 경기를 미리 채우려면 ~24h 이상 필요. 30h = 하루치 + 여유. (only_missing 이라 총 호출 수 동일) # 경기를 미리 채우려면 ~24h 이상 필요. 30h = 하루치 + 여유. (only_missing 이라 총 호출 수 동일)
ai_generate_lookahead_hours: int = 30 # 킥오프 N시간 전부터 생성 — 야구 선발투수 예고(경기 전날 저녁) 이후 시점.
ai_generate_lookahead_hours: int = 22
# ── 결과 자동 정산(관리자 입력 불필요) ─────────────────── # ── 결과 자동 정산(관리자 입력 불필요) ───────────────────
# 킥오프 + 이 시간(시) 경과 후, 외부 소스에서 스코어를 자동 수집해 채점·집계·메일. # 킥오프 + 이 시간(시) 경과 후, 외부 소스에서 스코어를 자동 수집해 채점·집계·메일.
@@ -132,6 +173,22 @@ class Settings(BaseSettings):
football_refresh_hour: int = 0 football_refresh_hour: int = 0
football_refresh_minute: int = 0 football_refresh_minute: int = 0
# ── 외부 연동: Suno (sunoapi.org 서드파티 게이트웨이) ─────
# 오늘의 응원가 자동 생성. 키 미설정 시 전체 no-op.
suno_api_key: str = ""
suno_api_base: str = "https://api.sunoapi.org"
suno_model: str = "V5"
# 응원가 생성 전체 스위치 (KBO 만 대상 — 한국어 응원가)
songs_enabled: bool = True
# 킥오프 N분 전부터 생성 윈도우 시작 — 윈도우 안에서 라인업 발표를 기다린다
song_generate_minutes_before: int = 150
# 킥오프 N분 전까지 라인업이 안 뜨면 라인업 없이 폴백 생성 (곡 없는 날 방지)
song_lineup_fallback_minutes_before: int = 40
# 생성 대상 점검·생성 상태 폴링 주기(초)
song_tick_seconds: int = 120
# 응원가 커버 합성 시 KBO 로고를 가져올 내부 프론트 주소 (docker 네트워크)
internal_frontend_base: str = "http://frontend"
# ── 외부 연동: 이메일 ───────────────────────────────────── # ── 외부 연동: 이메일 ─────────────────────────────────────
# 1순위: Azure Communication Services(ACS) Email — endpoint + accesskey. # 1순위: Azure Communication Services(ACS) Email — endpoint + accesskey.
# AZURE_ACS_SENDER 는 검증된 MailFrom 주소(예: donotreply@triplepick.o2o.kr). # AZURE_ACS_SENDER 는 검증된 MailFrom 주소(예: donotreply@triplepick.o2o.kr).
+8
View File
@@ -42,6 +42,7 @@ def kst_iso(dt: datetime) -> str:
def compute_phase(m: Match, now: datetime | None = None) -> str: def compute_phase(m: Match, now: datetime | None = None) -> str:
"""투표/경기 단계: """투표/경기 단계:
cancelled 우천취소 등 취소 확정 → "취소" (투표·정산 제외, 기록은 보존)
finished 결과 입력됨 → "종료" finished 결과 입력됨 → "종료"
live 킥오프 이후, 결과 입력 전 → "경기중" live 킥오프 이후, 결과 입력 전 → "경기중"
locked 투표 마감(킥오프 1h 전) ~ 킥오프 → "투표 종료"(비활성) locked 투표 마감(킥오프 1h 전) ~ 킥오프 → "투표 종료"(비활성)
@@ -49,6 +50,8 @@ def compute_phase(m: Match, now: datetime | None = None) -> str:
open 투표 중 open 투표 중
""" """
now = now or now_utc() now = now or now_utc()
if m.status == "cancelled": # 우천취소 등 — 시간과 무관하게 고정
return "cancelled"
if m.result_outcome is not None: if m.result_outcome is not None:
return "finished" return "finished"
if now >= ensure_aware(m.kickoff_at): if now >= ensure_aware(m.kickoff_at):
@@ -71,6 +74,8 @@ def is_open_for_voting(m: Match, now: datetime | None = None) -> bool:
now = now or now_utc() now = now or now_utc()
if not is_votable(m): if not is_votable(m):
return False return False
if m.status == "cancelled":
return False
if m.result_outcome is not None: if m.result_outcome is not None:
return False return False
if now >= ensure_aware(m.lock_at): if now >= ensure_aware(m.lock_at):
@@ -146,6 +151,7 @@ def match_out(
lang: str = "ko", lang: str = "ko",
include_predictions: bool = True, include_predictions: bool = True,
now: datetime | None = None, now: datetime | None = None,
extras: dict | None = None,
) -> MatchOut: ) -> MatchOut:
result = None result = None
if m.result_outcome is not None: if m.result_outcome is not None:
@@ -164,6 +170,7 @@ def match_out(
phase = compute_phase(m, now) phase = compute_phase(m, now)
return MatchOut( return MatchOut(
matchId=m.match_id, matchId=m.match_id,
league=m.league or "wc",
roundLabel=m.round_label, roundLabel=m.round_label,
group=m.group, group=m.group,
teamA=_team_a(m), teamA=_team_a(m),
@@ -180,4 +187,5 @@ def match_out(
result=result, result=result,
predictions=preds, predictions=preds,
crowd=crowd_out(m.crowd, m.match_id), crowd=crowd_out(m.crowd, m.match_id),
extras=extras,
) )
+6
View File
@@ -15,11 +15,14 @@ from .config import settings
from .database import init_db from .database import init_db
from .routers import ( from .routers import (
admin, admin,
auth,
comments, comments,
leaderboard, leaderboard,
matches, matches,
predictions, predictions,
share, share,
songs,
standings,
visits, visits,
) )
from .scoring import load_scoring_data from .scoring import load_scoring_data
@@ -48,12 +51,15 @@ app.add_middleware(
allow_headers=["*"], allow_headers=["*"],
) )
app.include_router(auth.router)
app.include_router(matches.router) app.include_router(matches.router)
app.include_router(comments.router) app.include_router(comments.router)
app.include_router(predictions.router) app.include_router(predictions.router)
app.include_router(leaderboard.router) app.include_router(leaderboard.router)
app.include_router(standings.router)
app.include_router(admin.router) app.include_router(admin.router)
app.include_router(visits.router) app.include_router(visits.router)
app.include_router(songs.router)
# 공유 미리보기(OG) 프리렌더 — nginx 가 크롤러 UA 의 /match/:id 만 여기로 보낸다. # 공유 미리보기(OG) 프리렌더 — nginx 가 크롤러 UA 의 /match/:id 만 여기로 보낸다.
app.include_router(share.router) app.include_router(share.router)
+138
View File
@@ -13,11 +13,13 @@ from datetime import date, datetime
from sqlalchemy import ( from sqlalchemy import (
JSON, JSON,
BigInteger,
Boolean, Boolean,
Date, Date,
DateTime, DateTime,
ForeignKey, ForeignKey,
Integer, Integer,
LargeBinary,
String, String,
UniqueConstraint, UniqueConstraint,
func, func,
@@ -35,6 +37,8 @@ class Match(Base):
__tablename__ = "matches" __tablename__ = "matches"
match_id: Mapped[str] = mapped_column(String, primary_key=True) match_id: Mapped[str] = mapped_column(String, primary_key=True)
# 리그: wc(월드컵 축구) | kbo | mlb — 멀티리그 단일 서비스의 분기 키
league: Mapped[str] = mapped_column(String, default="wc", index=True)
round_label: Mapped[str] = mapped_column(String, default="") round_label: Mapped[str] = mapped_column(String, default="")
group: Mapped[str] = mapped_column(String, default="A") group: Mapped[str] = mapped_column(String, default="A")
@@ -246,3 +250,137 @@ class FootballCache(Base):
fetched_at: Mapped[datetime] = mapped_column( fetched_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now() DateTime(timezone=True), server_default=func.now()
) )
class User(Base):
"""카카오 소셜 로그인 사용자 (o2o-castad-backend 인증 이식).
투표(user_predictions)는 기존 이메일 식별을 유지하고,
로그인 시 카카오 이메일을 투표 이메일로 자동 사용해 연결한다.
"""
__tablename__ = "users"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
kakao_id: Mapped[int] = mapped_column(BigInteger, unique=True, index=True)
user_uuid: Mapped[str] = mapped_column(String, unique=True, index=True)
email: Mapped[str | None] = mapped_column(String, nullable=True)
nickname: Mapped[str | None] = mapped_column(String, nullable=True)
profile_image_url: Mapped[str | None] = mapped_column(String, nullable=True)
is_active: Mapped[bool] = mapped_column(Boolean, default=True)
last_login_at: Mapped[datetime | None] = mapped_column(
DateTime(timezone=True), nullable=True
)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now()
)
class RefreshToken(Base):
"""리프레시 토큰 (해시 저장·회전 시 폐기). castad 와 동일한 rotation 방식."""
__tablename__ = "refresh_tokens"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
user_id: Mapped[int] = mapped_column(
ForeignKey("users.id", ondelete="CASCADE"), index=True
)
user_uuid: Mapped[str] = mapped_column(String, index=True)
token_hash: Mapped[str] = mapped_column(String, unique=True, index=True)
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
is_revoked: Mapped[bool] = mapped_column(Boolean, default=False)
revoked_at: Mapped[datetime | None] = mapped_column(
DateTime(timezone=True), nullable=True
)
user_agent: Mapped[str | None] = mapped_column(String, nullable=True)
ip_address: Mapped[str | None] = mapped_column(String, nullable=True)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now()
)
class Song(Base):
"""오늘의 응원가 — 경기×팀 단위 Suno 생성 트랙.
가사·스타일은 LLM(경기 맥락 주입)이 쓰고, 음원은 Suno(sunoapi.org)가 생성.
Suno CDN URL 은 임시라 완성 후 워커가 음원을 SongAudio 로 내려받아 보존하고
tracks 의 audioUrl 을 자체 서빙 경로(/api/songs/audio/...)로 바꾼다.
"""
__tablename__ = "songs"
__table_args__ = (
UniqueConstraint("match_id", "team_code", name="uq_song_match_team"),
)
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
league: Mapped[str] = mapped_column(String, index=True)
date_kst: Mapped[date] = mapped_column(Date, index=True) # 경기일 (KST)
match_id: Mapped[str] = mapped_column(
ForeignKey("matches.match_id", ondelete="CASCADE"), index=True
)
team_code: Mapped[str] = mapped_column(String)
team_name: Mapped[str] = mapped_column(String)
title: Mapped[str] = mapped_column(String, default="")
lyrics: Mapped[str] = mapped_column(String, default="")
style: Mapped[str] = mapped_column(String, default="")
task_id: Mapped[str] = mapped_column(String, default="")
# generating(Suno 작업 대기) | complete | failed
status: Mapped[str] = mapped_column(String, default="generating", index=True)
error: Mapped[str] = mapped_column(String, default="")
attempts: Mapped[int] = mapped_column(Integer, default=0) # 실패 재시도 상한용
# 라인업 발표 후 생성했는지 — False 면 라인업 공개 시 자동 재생성(업그레이드) 대상
with_lineup: Mapped[bool] = mapped_column(Boolean, default=False)
# 완성 트랙 [{title, audioUrl, imageUrl, duration}] — 보통 생성당 2곡
tracks: Mapped[list] = mapped_column(JSON, default=list)
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()
)
class SongAudio(Base):
"""응원가 음원 원본 — Suno CDN 임시 URL 만료 대비 DB 보존.
노출 트랙(첫 트랙)만 저장한다. 업그레이드(라인업 반영 재생성) 시
같은 (song_id, track_idx) 행을 새 음원으로 교체.
"""
__tablename__ = "song_audio"
__table_args__ = (
UniqueConstraint("song_id", "track_idx", name="uq_song_audio_track"),
)
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
song_id: Mapped[int] = mapped_column(
ForeignKey("songs.id", ondelete="CASCADE"), index=True
)
track_idx: Mapped[int] = mapped_column(Integer, default=0)
mime: Mapped[str] = mapped_column(String, default="audio/mpeg")
size: Mapped[int] = mapped_column(Integer, default=0)
data: Mapped[bytes] = mapped_column(LargeBinary)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now()
)
class DataCache(Base):
"""야구(KBO/MLB) 부가 데이터 캐시 — 프리뷰·순위, API 응답·AI 프롬프트 조립용.
key 규칙:
preview:{match_id} 경기 프리뷰 요약(선발투수·시즌 상대전적)
standings:{league} 리그 순위표 (팀코드 → 순위·승률·최근5 등)
"""
__tablename__ = "data_cache"
key: Mapped[str] = mapped_column(String, primary_key=True)
payload: Mapped[dict] = mapped_column(JSON, default=dict)
fetched_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now()
)
+69
View File
@@ -132,3 +132,72 @@ async def recount_crowd(db: AsyncSession = Depends(get_db)) -> GenericOk:
fixed += 1 fixed += 1
await db.commit() await db.commit()
return GenericOk(ok=True, detail="crowd recounted", extra={"matchesFixed": fixed}) return GenericOk(ok=True, detail="crowd recounted", extra={"matchesFixed": fixed})
# ── 운영 대시보드용 읽기 API (개인 관리용 — 이메일 원본 노출 주의) ──
@router.get("/matches/{match_id}/votes", dependencies=[Depends(require_admin)])
async def match_votes(
match_id: str, db: AsyncSession = Depends(get_db)
) -> list[dict]:
"""경기별 투표 전체 — 누가(이메일 원본) 어떻게 찍었고 몇 점 받았는지."""
rows = (
await db.execute(
select(UserPrediction)
.where(UserPrediction.match_id == match_id)
.order_by(UserPrediction.created_at.desc())
)
).scalars().all()
return [
{
"email": r.email,
"outcome": r.outcome,
"scoreA": r.score_a,
"scoreB": r.score_b,
"points": r.points,
"notify": r.notify,
"createdAt": r.created_at.isoformat() if r.created_at else None,
}
for r in rows
]
@router.get("/leaderboard", dependencies=[Depends(require_admin)])
async def full_leaderboard(
league: str = "", db: AsyncSession = Depends(get_db)
) -> list[dict]:
"""이메일 원본 랭킹 — 공개 리더보드와 같은 집계(채점된 픽 재집계).
배제 대상(운영진 도메인)도 표시하되 excluded 플래그로 구분."""
from ..scoring import is_excluded
q = (
select(UserPrediction, Match)
.join(Match, Match.match_id == UserPrediction.match_id)
.where(
Match.result_outcome.is_not(None),
UserPrediction.points.is_not(None),
UserPrediction.email.is_not(None),
)
)
if league:
q = q.where(Match.league == league)
picks = (await db.execute(q)).all()
agg: dict[str, list[int]] = {}
for pk, m in picks:
row = agg.setdefault(pk.email, [0, 0, 0])
row[0] += pk.points or 0
row[1] += 1 if (
pk.score_a == m.result_score_a and pk.score_b == m.result_score_b
) else 0
row[2] += 1
ranked = sorted(agg.items(), key=lambda kv: (-kv[1][0], -kv[1][1], -kv[1][2]))
return [
{
"rank": i + 1,
"email": e,
"totalPoints": v[0],
"exactCount": v[1],
"matchesPlayed": v[2],
"excluded": is_excluded(e),
}
for i, (e, v) in enumerate(ranked)
]
+76
View File
@@ -0,0 +1,76 @@
"""인증 API — 카카오 로그인·토큰 갱신·로그아웃·내 정보 (castad 이식).
콜백은 백엔드가 받아 JWT 발급 후 프론트로 `#access_token=..&refresh_token=..`
해시 프래그먼트로 리다이렉트한다 (쿼리스트링이 아니라 해시 — 서버 로그·Referer 에
토큰이 남지 않게 castad 방식에서 한 단계 보강).
"""
from __future__ import annotations
from typing import Optional
from fastapi import APIRouter, Depends, Header, Request, status
from fastapi.responses import RedirectResponse, Response
from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession
from ..config import settings
from ..database import get_db
from ..models import User
from ..services import auth_kakao
router = APIRouter(prefix="/api/auth", tags=["auth"])
class RefreshIn(BaseModel):
refreshToken: str
def _client_ip(request: Request) -> str | None:
fwd = request.headers.get("X-Forwarded-For")
if fwd:
return fwd.split(",")[0].strip()
return request.client.host if request.client else None
@router.get("/kakao/login")
async def kakao_login_url() -> dict:
"""카카오 인증 페이지 URL — 프론트가 이 URL 로 이동시킨다."""
return {"authUrl": auth_kakao.kakao_authorization_url()}
@router.get("/kakao/callback")
async def kakao_callback(
request: Request,
code: str,
db: AsyncSession = Depends(get_db),
user_agent: Optional[str] = Header(None, alias="User-Agent"),
) -> RedirectResponse:
"""카카오 콜백 — 인가 코드로 JWT 발급 후 프론트로 리다이렉트."""
result = await auth_kakao.kakao_login(
db, code, user_agent=user_agent, ip_address=_client_ip(request)
)
redirect = (
f"{settings.public_origin}/"
f"#access_token={result['access_token']}"
f"&refresh_token={result['refresh_token']}"
)
return RedirectResponse(url=redirect, status_code=302)
@router.post("/refresh")
async def refresh(body: RefreshIn, db: AsyncSession = Depends(get_db)) -> dict:
"""리프레시 토큰 회전 — 새 access/refresh 발급, 기존 refresh 폐기."""
return await auth_kakao.refresh_tokens(db, body.refreshToken)
@router.post("/logout", status_code=status.HTTP_204_NO_CONTENT)
async def logout(body: RefreshIn, db: AsyncSession = Depends(get_db)) -> Response:
"""리프레시 토큰 폐기. access 만료 후엔 재갱신 불가."""
await auth_kakao.logout(db, body.refreshToken)
return Response(status_code=status.HTTP_204_NO_CONTENT)
@router.get("/me")
async def me(user: User = Depends(auth_kakao.get_current_user)) -> dict:
"""현재 로그인 사용자 정보."""
return auth_kakao.user_out(user)
+31 -8
View File
@@ -28,8 +28,8 @@ router = APIRouter(prefix="/api/matches", tags=["comments"])
# 같은 기기 연속 작성 최소 간격(초) — 도배 방지(기본 방어). # 같은 기기 연속 작성 최소 간격(초) — 도배 방지(기본 방어).
COMMENT_COOLDOWN_SECONDS = 5 COMMENT_COOLDOWN_SECONDS = 5
# 닉네임 조합: 2글자(코믹 수식) + 3글자(축구 역할) = 항상 한국어 5글자. # 닉네임 조합: 2글자(코믹 수식) + 3글자(스포츠 역할) = 항상 한국어 5글자.
# 40 × 30 = 1200가지. # 리그별 풀 — 축구(월드컵) / 야구(KBO·MLB). 각 40 × 30 = 1200가지.
_NICK_A = [ _NICK_A = [
"잔디", "침대", "벤치", "후보", "똥손", "헛발", "발컨", "노룩", "왼발", "멘붕", "잔디", "침대", "벤치", "후보", "똥손", "헛발", "발컨", "노룩", "왼발", "멘붕",
"국대", "동네", "주말", "폭발", "광속", "진지", "발끝", "번개", "백수", "천재", "국대", "동네", "주말", "폭발", "광속", "진지", "발끝", "번개", "백수", "천재",
@@ -42,6 +42,18 @@ _NICK_B = [
"압박왕", "태클왕", "중거리", "발리슛", "빌드업", "백패스", "자책골", "골기계", "압박왕", "태클왕", "중거리", "발리슛", "빌드업", "백패스", "자책골", "골기계",
"어시왕", "역습왕", "수문장", "골부자", "골가뭄", "발연기", "어시왕", "역습왕", "수문장", "골부자", "골가뭄", "발연기",
] ]
_NICK_A_BB = [
"잔디", "벤치", "후보", "똥손", "노룩", "멘붕", "동네", "주말", "폭발", "광속",
"진지", "번개", "백수", "천재", "괴물", "폭격", "강철", "무적", "질풍", "돌풍",
"불꽃", "분노", "음속", "폭탄", "슈퍼", "만년", "전설", "비밀", "미친", "라면",
"치킨", "출근", "직관", "치맥", "응원", "국대", "신인", "은퇴", "각성", "꾸준",
]
_NICK_B_BB = [
"홈런왕", "도루왕", "타격왕", "안타왕", "삼진왕", "수비왕", "번트왕", "대타왕",
"역전타", "끝내기", "결승타", "병살타", "유격수", "외야수", "내야수", "마무리",
"셋업맨", "불펜왕", "승리조", "강속구", "커브왕", "직구왕", "변화구", "풀스윙",
"헛스윙", "배트맨", "만루왕", "출루왕", "도루자", "홈스틸",
]
def _author_hash(device_id: str) -> str: def _author_hash(device_id: str) -> str:
@@ -49,12 +61,19 @@ def _author_hash(device_id: str) -> str:
return hashlib.sha256(device_id.encode("utf-8")).hexdigest() return hashlib.sha256(device_id.encode("utf-8")).hexdigest()
_NICK_A_SET = set(_NICK_A) # 검증은 두 리그 풀 합집합 기준(발급 리그와 작성 리그가 달라도 정상 닉이면 통과)
_NICK_B_SET = set(_NICK_B) _NICK_A_SET = set(_NICK_A) | set(_NICK_A_BB)
_NICK_B_SET = set(_NICK_B) | set(_NICK_B_BB)
def _random_nickname() -> str: def _is_baseball(match_id: str) -> bool:
"""랜덤 닉네임. 두 단어 조합으로 항상 5글자.""" return match_id.startswith(("KBO_", "MLB_"))
def _random_nickname(baseball: bool = False) -> str:
"""랜덤 닉네임. 두 단어 조합으로 항상 5글자 — 리그에 맞는 풀 사용."""
if baseball:
return random.choice(_NICK_A_BB) + random.choice(_NICK_B_BB)
return random.choice(_NICK_A) + random.choice(_NICK_B) return random.choice(_NICK_A) + random.choice(_NICK_B)
@@ -67,7 +86,7 @@ def _valid_nickname(n: str) -> bool:
@router.get("/{match_id}/comments/nickname", response_model=CommentNicknameOut) @router.get("/{match_id}/comments/nickname", response_model=CommentNicknameOut)
async def issue_nickname(match_id: str) -> CommentNicknameOut: async def issue_nickname(match_id: str) -> CommentNicknameOut:
"""세션 시작 시 랜덤 닉 발급(클라가 sessionStorage 에 캐싱해 재사용).""" """세션 시작 시 랜덤 닉 발급(클라가 sessionStorage 에 캐싱해 재사용)."""
return CommentNicknameOut(nickname=_random_nickname()) return CommentNicknameOut(nickname=_random_nickname(_is_baseball(match_id)))
def _out(c: Comment) -> CommentOut: def _out(c: Comment) -> CommentOut:
@@ -130,7 +149,11 @@ async def create_comment(
raise HTTPException(status_code=429, detail="COMMENT_COOLDOWN") raise HTTPException(status_code=429, detail="COMMENT_COOLDOWN")
# 세션 캐싱된 닉을 사용하되, 풀에 없는(조작된) 값이면 새 랜덤으로 대체 # 세션 캐싱된 닉을 사용하되, 풀에 없는(조작된) 값이면 새 랜덤으로 대체
nickname = body.nickname if _valid_nickname(body.nickname) else _random_nickname() nickname = (
body.nickname
if _valid_nickname(body.nickname)
else _random_nickname(_is_baseball(match_id))
)
comment = Comment( comment = Comment(
match_id=match_id, match_id=match_id,
author_hash=author_hash, author_hash=author_hash,
+62 -11
View File
@@ -12,7 +12,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload from sqlalchemy.orm import selectinload
from ..database import get_db from ..database import get_db
from ..models import Match, UserPoints from ..models import Match, UserPoints, UserPrediction
from ..scoring import is_excluded, score_prediction from ..scoring import is_excluded, score_prediction
from ..schemas import ( from ..schemas import (
AILeaderboardOut, AILeaderboardOut,
@@ -32,8 +32,52 @@ def _mask(email: str) -> str:
@router.get("", response_model=LeaderboardOut) @router.get("", response_model=LeaderboardOut)
async def leaderboard( async def leaderboard(
limit: int = Query(50, ge=1, le=200), db: AsyncSession = Depends(get_db) limit: int = Query(50, ge=1, le=200),
league: str = Query("", description="wc | kbo | mlb — 빈값이면 전체 합산"),
db: AsyncSession = Depends(get_db),
) -> LeaderboardOut: ) -> LeaderboardOut:
if league:
# 리그별 랭킹 — 채점된 픽(points)을 리그 경기로 한정해 이메일별 재집계.
picks = (
await db.execute(
select(UserPrediction, Match)
.join(Match, Match.match_id == UserPrediction.match_id)
.where(
Match.league == league,
Match.result_outcome.is_not(None),
UserPrediction.points.is_not(None),
UserPrediction.email.is_not(None),
)
)
).all()
agg: dict[str, list] = {} # email → [pts, exact, played, first_ts]
for pk, m in picks:
row = agg.setdefault(pk.email, [0, 0, 0, None])
row[0] += pk.points or 0
row[1] += 1 if (
pk.score_a == m.result_score_a and pk.score_b == m.result_score_b
) else 0
row[2] += 1
ranked_rows = sorted(
((e, v) for e, v in agg.items() if not is_excluded(e)),
key=lambda kv: (-kv[1][0], -kv[1][1], -kv[1][2]),
)
scored_matches = (
await db.execute(
select(func.count()).select_from(Match).where(
Match.league == league, Match.result_outcome.is_not(None)
)
)
).scalar() or 0
standings = [
StandingOut(
rank=i + 1, emailMasked=_mask(e),
totalPoints=v[0], exactCount=v[1], matchesPlayed=v[2],
)
for i, (e, v) in enumerate(ranked_rows[:limit])
]
return LeaderboardOut(standings=standings, scoredMatches=scored_matches)
rows = ( rows = (
await db.execute(select(UserPoints)) await db.execute(select(UserPoints))
).scalars().all() ).scalars().all()
@@ -71,25 +115,32 @@ async def leaderboard(
@router.get("/ai", response_model=AILeaderboardOut) @router.get("/ai", response_model=AILeaderboardOut)
async def ai_leaderboard(db: AsyncSession = Depends(get_db)) -> AILeaderboardOut: async def ai_leaderboard(
league: str = Query("", description="wc | kbo | mlb — 빈값이면 전체"),
db: AsyncSession = Depends(get_db),
) -> AILeaderboardOut:
"""AI 모델 누적 랭킹 — 종료된 경기의 AI 예측을 유저와 동일한 배점으로 채점·합산. """AI 모델 누적 랭킹 — 종료된 경기의 AI 예측을 유저와 동일한 배점으로 채점·합산.
별도 누적 테이블 없이 매 조회 시 종료 경기 전수 재계산 → 결과/배점 변동에 별도 누적 테이블 없이 매 조회 시 종료 경기 전수 재계산 → 결과/배점 변동에
항상 일관. (모델 3개 × 경기 수라 비용 무시 가능.) 항상 일관. (모델 3개 × 경기 수라 비용 무시 가능.)
""" """
matches = ( q = (
await db.execute( select(Match)
select(Match) .where(Match.result_outcome.is_not(None))
.where(Match.result_outcome.is_not(None)) .options(selectinload(Match.predictions))
.options(selectinload(Match.predictions)) )
) if league:
).scalars().all() q = q.where(Match.league == league)
matches = (await db.execute(q)).scalars().all()
# model → [points, exact_count, matches_played] # model → [points, exact_count, matches_played]
agg: dict[str, list[int]] = {} agg: dict[str, list[int]] = {}
for m in matches: for m in matches:
bb = m.league in ("kbo", "mlb")
for p in m.predictions: for p in m.predictions:
pts = score_prediction(p.score_a, p.score_b, m.result_score_a, m.result_score_b) pts = score_prediction(
p.score_a, p.score_b, m.result_score_a, m.result_score_b, baseball=bb
)
row = agg.setdefault(p.model, [0, 0, 0]) row = agg.setdefault(p.model, [0, 0, 0])
row[0] += pts row[0] += pts
row[1] += 1 if (p.score_a == m.result_score_a and p.score_b == m.result_score_b) else 0 row[1] += 1 if (p.score_a == m.result_score_a and p.score_b == m.result_score_b) else 0
+32 -9
View File
@@ -10,6 +10,7 @@ from ..database import get_db
from ..domain import match_out from ..domain import match_out
from ..models import Match from ..models import Match
from ..schemas import MatchOut from ..schemas import MatchOut
from ..services.baseball_details import fetch_live, get_extras
router = APIRouter(prefix="/api/matches", tags=["matches"]) router = APIRouter(prefix="/api/matches", tags=["matches"])
@@ -17,16 +18,19 @@ router = APIRouter(prefix="/api/matches", tags=["matches"])
@router.get("", response_model=list[MatchOut]) @router.get("", response_model=list[MatchOut])
async def list_matches( async def list_matches(
lang: str = Query("ko"), lang: str = Query("ko"),
league: str = Query("", description="wc | kbo | mlb — 빈값이면 전체"),
db: AsyncSession = Depends(get_db), db: AsyncSession = Depends(get_db),
) -> list[MatchOut]: ) -> list[MatchOut]:
rows = ( q = (
await db.execute( select(Match)
select(Match) .options(selectinload(Match.predictions), selectinload(Match.crowd))
.options(selectinload(Match.predictions), selectinload(Match.crowd)) .order_by(Match.kickoff_at)
.order_by(Match.kickoff_at) )
) if league:
).scalars().all() q = q.where(Match.league == league)
return [match_out(m, lang) for m in rows] rows = (await db.execute(q)).scalars().all()
extras = await get_extras(db, rows)
return [match_out(m, lang, extras=extras.get(m.match_id)) for m in rows]
@router.get("/{match_id}", response_model=MatchOut) @router.get("/{match_id}", response_model=MatchOut)
@@ -44,4 +48,23 @@ async def get_match(
).scalars().first() ).scalars().first()
if not m: if not m:
raise HTTPException(status_code=404, detail="MATCH_NOT_FOUND") raise HTTPException(status_code=404, detail="MATCH_NOT_FOUND")
return match_out(m, lang) extras = await get_extras(db, [m])
return match_out(m, lang, extras=extras.get(m.match_id))
@router.get("/{match_id}/live")
async def get_live(
match_id: str,
db: AsyncSession = Depends(get_db),
) -> dict:
"""라이브 뷰 (kbo=네이버 relay, mlb=공식 feed/live, mls=ESPN). 15초 TTL 캐시."""
m = await db.get(Match, match_id)
if not m:
raise HTTPException(status_code=404, detail="MATCH_NOT_FOUND")
if m.league == "mls":
from ..services.mls_espn import fetch_live_mls
return await fetch_live_mls(m)
if m.league not in ("kbo", "mlb"):
return {"available": False}
return await fetch_live(m)
+86 -7
View File
@@ -12,10 +12,14 @@ from __future__ import annotations
import html import html
from fastapi import APIRouter from fastapi import APIRouter, Depends
from fastapi.responses import HTMLResponse from fastapi.responses import HTMLResponse
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from ..config import settings from ..config import settings
from ..database import get_db
from ..models import Match, Song
from ..schedule_data import TEAMS from ..schedule_data import TEAMS
router = APIRouter() router = APIRouter()
@@ -50,8 +54,68 @@ def _team_label(code: str | None) -> str:
return _KOR_NAME.get(code, code) return _KOR_NAME.get(code, code)
@router.get("/song/{match_id}/{team_code}", response_class=HTMLResponse)
async def song_share(
match_id: str, team_code: str, db: AsyncSession = Depends(get_db)
) -> HTMLResponse:
"""응원가 공유 OG — '8월 28일 OO 응원가' 제목 + Suno 앨범아트 썸네일.
제목의 날짜는 제작일(경기일 KST) — 매일 갱신되는 콘텐츠임을 드러낸다.
"""
s = (
await db.execute(
select(Song).where(Song.match_id == match_id, Song.team_code == team_code)
)
).scalar_one_or_none()
team = (s.team_name if s else "") or _team_label(team_code) or team_code
song_title = (s.title if s else "") or f"{team} 응원가"
day = f"{s.date_kst.month}월 {s.date_kst.day}일" if s and s.date_kst else "오늘의"
title = f"{day} {team} 응원가 — {song_title}"
desc = (
"AI가 경기 당일(순위·선발 라인업·전날 결과)을 반영해 매일 새로 만드는 응원가. "
"듣고 나서 GPT·Claude·Gemini와 승부예측도 겨뤄보세요!"
)
origin = settings.public_origin.rstrip("/")
# 썸네일: 합성 커버(Suno 아트 + 팀 로고, 1200x630) → 곡 없으면 기본 카드
if s and s.tracks:
img_url = (
f"{origin}/api/songs/cover/{html.escape(match_id)}/"
f"{html.escape(team_code)}?v={(s.task_id or '')[:8]}"
)
else:
img_url = f"{origin}{DEFAULT_OG}?v=2"
page_url = f"{origin}/song/{html.escape(match_id)}/{html.escape(team_code)}"
t = html.escape(title)
d = html.escape(desc)
page = f"""<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<title>{t}</title>
<meta name="description" content="{d}" />
<meta property="og:type" content="music.song" />
<meta property="og:site_name" content="TriplePick" />
<meta property="og:title" content="{t}" />
<meta property="og:description" content="{d}" />
<meta property="og:url" content="{page_url}" />
<meta property="og:image" content="{img_url}" />
<meta property="og:image:secure_url" content="{img_url}" />
<meta property="og:locale" content="ko_KR" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="{t}" />
<meta name="twitter:description" content="{d}" />
<meta name="twitter:image" content="{img_url}" />
<link rel="canonical" href="{page_url}" />
</head>
<body><a href="{page_url}">TriplePick — {t}</a></body>
</html>"""
return HTMLResponse(page)
@router.get("/match/{match_id}", response_class=HTMLResponse) @router.get("/match/{match_id}", response_class=HTMLResponse)
async def match_share(match_id: str) -> HTMLResponse: async def match_share(match_id: str, db: AsyncSession = Depends(get_db)) -> HTMLResponse:
a, b = _parse_codes(match_id) a, b = _parse_codes(match_id)
image = DEFAULT_OG image = DEFAULT_OG
@@ -62,19 +126,34 @@ async def match_share(match_id: str) -> HTMLResponse:
image = OG_DIR + OG_IMAGES[key] image = OG_DIR + OG_IMAGES[key]
is_custom = True is_custom = True
la, lb = _team_label(a), _team_label(b) # 팀명: DB 의 경기 행이 있으면 한글 short 명(클럽 리그 포함),
# 없으면 월드컵 정적 테이블 → 코드 순으로 폴백.
m = (
await db.execute(select(Match).where(Match.match_id == match_id))
).scalar_one_or_none()
if m:
la, lb = m.team_a_short, m.team_b_short
a, b = m.team_a_code, m.team_b_code
else:
la, lb = _team_label(a), _team_label(b)
# 한국은 항상 왼쪽으로 표기(프론트 화면 규칙과 동일). # 한국은 항상 왼쪽으로 표기(프론트 화면 규칙과 동일).
if b == "KOR" and a != "KOR": if b == "KOR" and a != "KOR":
la, lb = lb, la la, lb = lb, la
league_ko = {"kbo": "KBO", "mlb": "MLB", "mls": "MLS"}.get(m.league if m else "", "")
if la and lb: if la and lb:
title = f"TriplePick 2026 — {la} vs {lb} AI 승부예측" tag = f"{league_ko} " if league_ko else ""
title = f"TriplePick — {tag}{la} vs {lb} AI 승부예측"
else: else:
title = "TriplePick 2026 — AI 2026 글로벌 축구 축전 승부예측" title = "TriplePick — AI 스포츠 승부예측 (KBO·MLB·MLS)"
desc = "AI 셋이 매 경기를 서로 다르게 예측합니다. 당신의 픽을 찍고 AI와 겨뤄보세요." desc = (
"GPT·Claude·Gemini 3대 AI가 이 경기를 서로 다르게 예측합니다. "
"당신의 픽을 찍고 AI와 겨뤄보세요."
)
origin = settings.public_origin.rstrip("/") origin = settings.public_origin.rstrip("/")
page_url = f"{origin}/match/{html.escape(match_id)}" page_url = f"{origin}/match/{html.escape(match_id)}"
img_url = f"{origin}{image}" # ?v= 캐시버스터: 메신저가 과거 실패/구버전 썸네일을 캐시한 경우 재수집 유도
img_url = f"{origin}{image}?v=2"
t = html.escape(title) t = html.escape(title)
d = html.escape(desc) d = html.escape(desc)
# 기본 썸네일만 규격이 1200x630 으로 확정 → width/height 명시. # 기본 썸네일만 규격이 1200x630 으로 확정 → width/height 명시.
+226
View File
@@ -0,0 +1,226 @@
"""오늘의 응원가 API — 조회(공개) · 커버 합성 · Suno 콜백 싱크 · 관리자 수동 생성."""
from __future__ import annotations
import logging
import re
from datetime import datetime, timedelta, timezone
from fastapi import APIRouter, Depends, HTTPException, Request, Response
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from ..config import settings
from ..database import get_db
from ..models import Match, Song, SongAudio
from ..services.songs import persist_audio, poll_generating, start_due_songs
from .admin import require_admin
router = APIRouter(prefix="/api/songs", tags=["songs"])
log = logging.getLogger("triplepick.songs")
KST = timezone(timedelta(hours=9))
def _cover_path(s: Song) -> str:
# v= 캐시버스터: 업그레이드(재생성)로 task 가 바뀌면 새 커버로
return f"/api/songs/cover/{s.match_id}/{s.team_code}?v={(s.task_id or '')[:8]}"
def _song_out(s: Song) -> dict:
# Suno 는 생성당 2트랙을 주지만 노출은 팀당 1곡만 (첫 트랙).
# 커버는 Suno 아트 + 팀 로고 합성본으로 교체.
tracks = [
{**t, "imageUrl": _cover_path(s)} for t in (s.tracks or [])[:1]
]
return {
"matchId": s.match_id,
"league": s.league,
"teamCode": s.team_code,
"teamName": s.team_name,
"title": s.title,
"lyrics": s.lyrics,
# 제작일(경기일 KST) — 공유·플레이어 문구의 "8월 28일 OO 응원가" 표기용
"dateKst": s.date_kst.isoformat() if s.date_kst else None,
"tracks": tracks,
}
# ── 커버 합성 (Suno 아트 배경 + 팀 로고 중앙) ──────────────────
_COVER_W, _COVER_H = 1200, 630 # OG 권장 규격 — 플레이어 썸네일은 중앙 크롭
_cover_cache: dict[str, bytes] = {}
async def _fetch_bytes(url: str) -> bytes | None:
import httpx
try:
async with httpx.AsyncClient(timeout=15, follow_redirects=True) as c:
r = await c.get(url)
r.raise_for_status()
return r.content
except Exception as e: # noqa: BLE001
log.warning("cover 소스 다운로드 실패 %s: %s", url, e)
return None
def _logo_url(s: Song) -> str | None:
if s.league == "kbo":
return f"{settings.internal_frontend_base}/assets/teams/kbo/{s.team_code.lower()}.png"
if s.league == "mlb":
from ..teams_baseball import MLB_TEAMS
mlb_id = (MLB_TEAMS.get(s.team_code) or {}).get("mlb_id")
if mlb_id:
return f"https://midfield.mlbstatic.com/v1/team/{mlb_id}/spots/500"
return None
def _compose(logo_bytes: bytes | None) -> bytes:
"""다크 단색 배경 + 팀 로고 최대 크기 중앙 배치 (배경 아트 없음)."""
import io
from PIL import Image
canvas = Image.new("RGB", (_COVER_W, _COVER_H), (16, 20, 26))
if logo_bytes:
try:
logo = Image.open(io.BytesIO(logo_bytes)).convert("RGBA")
# 캔버스에 여백 8%만 남기고 최대로 채운다
max_h = round(_COVER_H * 0.84)
max_w = round(_COVER_W * 0.84)
scale = min(max_w / logo.width, max_h / logo.height)
w, h = round(logo.width * scale), round(logo.height * scale)
logo = logo.resize((w, h))
canvas.paste(logo, ((_COVER_W - w) // 2, (_COVER_H - h) // 2), logo)
except Exception as e: # noqa: BLE001
log.warning("cover 로고 처리 실패: %s", e)
out = io.BytesIO()
canvas.save(out, "JPEG", quality=88)
return out.getvalue()
@router.get("/cover/{match_id}/{team_code}")
async def song_cover(
match_id: str, team_code: str, db: AsyncSession = Depends(get_db)
) -> Response:
s = (
await db.execute(
select(Song).where(Song.match_id == match_id, Song.team_code == team_code)
)
).scalar_one_or_none()
if not s:
raise HTTPException(status_code=404, detail="SONG_NOT_FOUND")
key = f"{match_id}:{team_code}"
if key not in _cover_cache:
if len(_cover_cache) > 200:
_cover_cache.clear()
logo_url = _logo_url(s)
if not logo_url and s.league == "mls":
# MLS 로고는 Match 행의 flag(ESPN PNG URL) 재사용
m = await db.get(Match, s.match_id)
if m:
logo_url = m.team_a_flag if m.team_a_code == s.team_code else m.team_b_flag
logo = await _fetch_bytes(logo_url) if logo_url else None
_cover_cache[key] = _compose(logo)
return Response(
content=_cover_cache[key],
media_type="image/jpeg",
headers={"Cache-Control": "public, max-age=86400"},
)
@router.get("/today")
async def today_songs(league: str = "", db: AsyncSession = Depends(get_db)) -> list[dict]:
"""오늘의 응원가 목록 — league 미지정 시 전 리그(kbo+mlb)."""
today = datetime.now(KST).date()
# 업그레이드(라인업 반영 재생성) 중인 곡도 이전 트랙을 계속 서빙 — 재생 공백 없음
conds = [Song.date_kst == today, Song.status.in_(("complete", "generating"))]
if league:
conds.append(Song.league == league)
rows = (
await db.execute(
select(Song).where(*conds).order_by(Song.match_id, Song.team_code)
)
).scalars().all()
return [_song_out(s) for s in rows if s.tracks]
@router.get("/match/{match_id}")
async def match_songs(match_id: str, db: AsyncSession = Depends(get_db)) -> list[dict]:
"""경기별 응원가 — 날짜 무관. 종료된 경기 상세에서도 그날 곡을 노출한다."""
rows = (
await db.execute(
select(Song)
.where(
Song.match_id == match_id,
Song.status.in_(("complete", "generating")),
)
.order_by(Song.team_code)
)
).scalars().all()
return [_song_out(s) for s in rows if s.tracks]
@router.get("/audio/{song_id}/{track_idx}")
async def song_audio_bytes(
song_id: int,
track_idx: int,
request: Request,
db: AsyncSession = Depends(get_db),
) -> Response:
"""DB 보존 음원 서빙 — Range 지원(재생 위치 탐색용). v= 쿼리로 캐시버스트."""
row = (
await db.execute(
select(SongAudio).where(
SongAudio.song_id == song_id, SongAudio.track_idx == track_idx
)
)
).scalar_one_or_none()
if not row:
raise HTTPException(status_code=404, detail="AUDIO_NOT_FOUND")
data, total = row.data, len(row.data)
headers = {
"Accept-Ranges": "bytes",
"Cache-Control": "public, max-age=31536000, immutable",
}
m = re.fullmatch(r"bytes=(\d*)-(\d*)", request.headers.get("range") or "")
if m and (m.group(1) or m.group(2)):
if m.group(1):
start = int(m.group(1))
end = int(m.group(2)) if m.group(2) else total - 1
else: # suffix range: bytes=-N (마지막 N바이트)
start = max(0, total - int(m.group(2)))
end = total - 1
if start >= total or start > end:
return Response(
status_code=416, headers={"Content-Range": f"bytes */{total}"}
)
end = min(end, total - 1)
headers["Content-Range"] = f"bytes {start}-{end}/{total}"
return Response(
content=data[start : end + 1],
status_code=206,
media_type=row.mime,
headers=headers,
)
return Response(content=data, media_type=row.mime, headers=headers)
@router.post("/callback")
async def suno_callback(request: Request) -> dict:
"""Suno 게이트웨이 callBackUrl 싱크대 — 완료 감지는 워커 폴링이 담당."""
try:
await request.json()
except Exception: # noqa: BLE001 — 본문 형식 무관
pass
return {"ok": True}
@router.post("/generate", dependencies=[Depends(require_admin)])
async def force_generate(db: AsyncSession = Depends(get_db)) -> dict:
"""관리자: 오늘 KBO 전 경기 응원가 즉시 생성 시작 + 폴링 1회."""
started = await start_due_songs(db, force_today=True)
done = await poll_generating(db)
saved = await persist_audio(db)
return {"ok": True, "started": started, "completed": done, "persisted": saved}
+65
View File
@@ -0,0 +1,65 @@
"""리그 순위표 API — 워커가 캐싱한 standings:{league} 를 팀 정보와 합쳐 서빙.
KBO: 단일 테이블(10팀, 순위순). MLB: 디비전(AL/NL × 동·중·서) 6그룹.
MLS: 컨퍼런스(동/서부) 2그룹 — 승점제.
캐시가 아직 없으면 빈 groups 를 반환한다(프론트는 안내 문구 표시).
"""
from __future__ import annotations
from fastapi import APIRouter, Depends, Query
from sqlalchemy.ext.asyncio import AsyncSession
from ..database import get_db
from ..models import DataCache
from ..teams_baseball import team_info
router = APIRouter(prefix="/api/standings", tags=["standings"])
# MLB 디비전 표시 순서 (AL 동→중→서, NL 동→중→서)
_MLB_DIV_ORDER = ["ALE", "ALC", "ALW", "NLE", "NLC", "NLW"]
# MLS 컨퍼런스 표시 순서 (동부 → 서부)
_MLS_CONF_ORDER = ["EAST", "WEST"]
@router.get("")
async def get_standings(
league: str = Query(..., description="kbo | mlb | mls"),
db: AsyncSession = Depends(get_db),
) -> dict:
if league not in ("kbo", "mlb", "mls"):
return {"league": league, "updatedAt": None, "groups": []}
row = await db.get(DataCache, f"standings:{league}")
table: dict = row.payload if row else {}
rows = [{**team_info(league, code), **st} for code, st in table.items()]
if league == "kbo":
rows.sort(key=lambda r: r.get("rank") or 99)
groups = [{"key": None, "rows": rows}] if rows else []
elif league == "mls":
by_conf: dict[str, list] = {}
for r in rows:
by_conf.setdefault(r.get("div") or "", []).append(r)
for lst in by_conf.values():
lst.sort(key=lambda r: r.get("rank") or 99)
groups = [
{"key": c, "rows": by_conf[c]} for c in _MLS_CONF_ORDER if c in by_conf
]
else:
by_div: dict[str, list] = {}
for r in rows:
by_div.setdefault(r.get("div") or "", []).append(r)
for lst in by_div.values():
lst.sort(key=lambda r: r.get("rank") or 99)
groups = [
{"key": d, "rows": by_div[d]} for d in _MLB_DIV_ORDER if d in by_div
]
if not groups and rows:
# 캐시가 div 주입 이전 버전이면 전체 승률순 단일 그룹으로 폴백
rows.sort(key=lambda r: -float(r.get("wra") or 0))
groups = [{"key": None, "rows": rows}]
return {
"league": league,
"updatedAt": row.fetched_at.isoformat() if row and row.fetched_at else None,
"groups": groups,
}
+5 -2
View File
@@ -47,6 +47,7 @@ class CrowdStatsOut(BaseModel):
class MatchOut(BaseModel): class MatchOut(BaseModel):
matchId: str matchId: str
league: str = "wc" # wc | kbo | mlb
roundLabel: str roundLabel: str
group: str group: str
teamA: Team teamA: Team
@@ -63,6 +64,8 @@ class MatchOut(BaseModel):
result: MatchResult | None = None result: MatchResult | None = None
predictions: list[AIPredictionOut] = Field(default_factory=list) predictions: list[AIPredictionOut] = Field(default_factory=list)
crowd: CrowdStatsOut | None = None crowd: CrowdStatsOut | None = None
# 야구 부가정보 (프리뷰·순위 캐시 — 축구/캐시없음이면 None)
extras: dict | None = None
# ── 픽 제출 ───────────────────────────────────────────────── # ── 픽 제출 ─────────────────────────────────────────────────
@@ -70,8 +73,8 @@ class SubmitPredictionIn(BaseModel):
matchId: str matchId: str
deviceId: str = Field(min_length=8, max_length=64) deviceId: str = Field(min_length=8, max_length=64)
outcome: Outcome outcome: Outcome
scoreA: int = Field(ge=0, le=9) scoreA: int = Field(ge=0, le=25) # 야구(득점) 상한. 축구는 UI 가 0-9 로 제한.
scoreB: int = Field(ge=0, le=9) scoreB: int = Field(ge=0, le=25)
email: EmailStr | None = None email: EmailStr | None = None
notify: bool = False notify: bool = False
+28 -21
View File
@@ -2,6 +2,8 @@
배점: 정확 스코어 5 · 근접(승패+득실차) 3 · 승패 2 · 부분(한 팀 득점 일치) 1 · 빗나감 0. 배점: 정확 스코어 5 · 근접(승패+득실차) 3 · 승패 2 · 부분(한 팀 득점 일치) 1 · 빗나감 0.
단조 증가(정확>근접>승패>부분>빗나감). 단조 증가(정확>근접>승패>부분>빗나감).
야구(KBO/MLB)는 득점 범위가 넓어 같은 등급 체계에 판정만 완화한다:
근접 = 승패 + 득실차 오차 ±1, 부분 = 한 팀 득점 오차 ±1.
배점·배제 대상은 backend/data/scoring.json 에서 기동 시 로드(없으면 아래 기본값). 배점·배제 대상은 backend/data/scoring.json 에서 기동 시 로드(없으면 아래 기본값).
""" """
from __future__ import annotations from __future__ import annotations
@@ -24,19 +26,31 @@ def outcome_of(score_a: int, score_b: int) -> str:
return "DRAW" return "DRAW"
# 야구 판정 허용 오차 — 근접(득실차)·부분(한 팀 득점) 공통 ±1
BASEBALL_TOLERANCE = 1
def _grade_of(
pick_a: int, pick_b: int, result_a: int, result_b: int, baseball: bool = False
) -> str:
"""등급 판정 (단일 SSOT) — baseball 이면 근접/부분 오차 ±1 허용."""
tol = BASEBALL_TOLERANCE if baseball else 0
if pick_a == result_a and pick_b == result_b:
return "EXACT"
if outcome_of(pick_a, pick_b) == outcome_of(result_a, result_b):
if abs((pick_a - pick_b) - (result_a - result_b)) <= tol:
return "CLOSE"
return "OUTCOME"
if abs(pick_a - result_a) <= tol or abs(pick_b - result_b) <= tol:
return "PARTIAL"
return "MISS"
def score_prediction( def score_prediction(
pick_a: int, pick_b: int, result_a: int, result_b: int pick_a: int, pick_b: int, result_a: int, result_b: int, baseball: bool = False
) -> int: ) -> int:
"""내 예측 vs 실제 결과 → 적중 포인트 (결정론적).""" """내 예측 vs 실제 결과 → 적중 포인트 (결정론적)."""
if pick_a == result_a and pick_b == result_b: return SCORE[_grade_of(pick_a, pick_b, result_a, result_b, baseball)]
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 구현) ────────────────── # ── 자격 · 배제 (docs/SCORING.md §4, P1 구현) ──────────────────
@@ -65,11 +79,12 @@ _JSON_KEY = {
def grade_prediction( def grade_prediction(
pick_a: int, pick_b: int, result_a: int, result_b: int, pick_a: int, pick_b: int, result_a: int, result_b: int,
path: Path | None = None, path: Path | None = None,
baseball: bool = False,
) -> tuple[str, int]: ) -> tuple[str, int]:
"""유저 투표(픽) vs 실제 결과 → scoring.json 에서 해당 등급의 (key, value). """유저 투표(픽) vs 실제 결과 → scoring.json 에서 해당 등급의 (key, value).
score_prediction 과 같은 판정 기준. 예: 승패+득실차 일치 → ("score_close", 3). score_prediction 과 같은 판정 기준(_grade_of 공유). 예: 승패+득실차 일치
scoring.json 이 없거나 키가 빠지면 기본 SCORE 값으로 대체. → ("score_close", 3). scoring.json 이 없거나 키가 빠지면 기본 SCORE 값으로 대체.
""" """
p = path or DATA_FILE p = path or DATA_FILE
try: try:
@@ -78,15 +93,7 @@ def grade_prediction(
log.warning("scoring data 읽기 실패 (%s): %s — 기본 배점 사용", p, e) log.warning("scoring data 읽기 실패 (%s): %s — 기본 배점 사용", p, e)
data = {} data = {}
if pick_a == result_a and pick_b == result_b: grade = _grade_of(pick_a, pick_b, result_a, result_b, baseball)
grade = "EXACT"
elif outcome_of(pick_a, pick_b) == outcome_of(result_a, result_b):
grade = "CLOSE" if (pick_a - pick_b) == (result_a - result_b) else "OUTCOME"
elif pick_a == result_a or pick_b == result_b:
grade = "PARTIAL"
else:
grade = "MISS"
key = _JSON_KEY[grade] key = _JSON_KEY[grade]
value = data[key] if isinstance(data.get(key), int) else SCORE[grade] value = data[key] if isinstance(data.get(key), int) else SCORE[grade]
return key, value return key, value
+92 -32
View File
@@ -26,42 +26,69 @@ class ProviderUnavailable(RuntimeError):
@dataclass @dataclass
class MatchContext: class MatchContext:
team_a: str # 표시명 (예: Korea Republic) team_a: str # 표시명 (예: Korea Republic / 한화 이글스)
team_b: str team_b: str
venue: str venue: str
kickoff: str # ISO kickoff: str # ISO
data_block: str | None = None # 실데이터(폼·H2H·랭킹·WC결과) 주입 블록. 없으면 이름만. data_block: str | None = None # 실데이터(폼·H2H·랭킹 등) 주입 블록. 없으면 이름만.
league: str = "wc" # wc(축구) | kbo | mlb | mls — 프롬프트·스코어 범위 분기
# 모델별 분석 관점(페르소나) — 동일 경기라도 서로 다른 시각으로 보게 해 # 공통 페르소나 — 세 모델 모두 동일한 입력(동일 프롬프트+동일 데이터)을 받는다.
# 예측이 자연스럽게 갈리도록 한다(강제 분산이 아니라 진짜 판단의 다양화). # 예측 차이는 모델 자체의 판단 차이에서만 나온다.
PERSONA = { ANALYST = (
"GPT": ( "You are an expert soccer analyst. Use ALL of the factual match data provided "
"You are a DATA-DRIVEN analyst. Base your call on recent form, head-to-head, " "below — recent form, standings, head-to-head and matchup context — and weigh "
"FIFA ranking gaps and goals-scored/conceded trends. Be objective and " "it over your prior knowledge to make the most accurate prediction possible."
"evidence-led; pick the scoreline the numbers most support." )
),
"Claude": ( BASEBALL_ANALYST = (
"You are a TACTICAL analyst. Focus on matchups, defensive organization, " "You are an expert baseball analyst. Use ALL of the factual match data provided "
"midfield control and game-state. Take low-scoring games, tight margins and " "below — recent form, standings with games-behind, team batting/ERA, "
"genuine upset potential seriously — do not just rubber-stamp the favorite." "head-to-head record, starting pitchers, confirmed lineups and yesterday's "
), "results — and weigh it over your prior knowledge to make the most accurate "
"Gemini": ( "prediction possible."
"You are an ATTACKING-MINDED analyst. Weigh momentum, attacking quality, " )
"star players and scoring potential. Lean toward open, higher-scoring "
"scenarios when the talent and tempo justify it." _LEAGUE_LABEL = {
), "kbo": "2026 KBO League (Korean professional baseball) regular-season game",
"mlb": "2026 MLB (Major League Baseball) regular-season game",
} }
def _prompt_baseball(ctx: MatchContext, model: str) -> str:
persona = BASEBALL_ANALYST # 모델 공통 — model 파라미터는 호출부 호환용
data = f"\n{ctx.data_block}\n" if ctx.data_block else ""
draw_note = (
"KBO regular-season games can end in a DRAW after 12 innings, but draws "
"are rare (~1-2% of games); only predict a draw with strong reason.\n"
if ctx.league == "kbo"
else "MLB games cannot end in a draw — never predict DRAW.\n"
)
return (
f"{persona}\n"
f"Predict the result of this {_LEAGUE_LABEL[ctx.league]}.\n"
f"Team A (away): {ctx.team_a}\nTeam B (home): {ctx.team_b}\n"
f"Ballpark: {ctx.venue}\nFirst pitch: {ctx.kickoff}\n"
f"{data}"
f"Important: Team B is the HOME team — home advantage applies. {draw_note}\n"
f"Predict the final score in runs. "
f"Respond with a single JSON object and nothing else, with keys:\n"
f' "scoreA": integer 0-25 (Team A runs),\n'
f' "scoreB": integer 0-25 (Team B runs),\n'
f' "outcome": one of "TEAM_A_WIN" | "DRAW" | "TEAM_B_WIN" (must match the score),\n'
f' "confidencePct": integer 0-100,\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'
)
def _prompt(ctx: MatchContext, persona: str) -> str: def _prompt(ctx: MatchContext, persona: str) -> str:
# 실데이터 블록이 있으면 팀/킥오프 다음에 삽입(없으면 빈 문자열 — 기존 동작 동일). # 실데이터 블록이 있으면 팀/킥오프 다음에 삽입(없으면 빈 문자열 — 기존 동작 동일).
data = f"\n{ctx.data_block}\n" if ctx.data_block else "" data = f"\n{ctx.data_block}\n" if ctx.data_block else ""
return ( return (
f"{persona}\n" f"{persona}\n"
f"Predict the result of this 2026 FIFA World Cup match using YOUR perspective " f"Predict the result of this 2026 FIFA World Cup match.\n"
f"above. Judge independently — it is fine to differ from the obvious consensus "
f"pick when your perspective warrants it.\n"
f"Team A: {ctx.team_a}\nTeam B: {ctx.team_b}\n" f"Team A: {ctx.team_a}\nTeam B: {ctx.team_b}\n"
f"Venue: {ctx.venue}\nKickoff: {ctx.kickoff}\n" f"Venue: {ctx.venue}\nKickoff: {ctx.kickoff}\n"
f"{data}" f"{data}"
@@ -80,6 +107,39 @@ def _prompt(ctx: MatchContext, persona: str) -> str:
) )
def _prompt_mls(ctx: MatchContext, persona: str) -> str:
"""MLS 정규시즌 — 월드컵과 달리 홈 어드밴티지가 있고 무승부가 흔하다."""
data = f"\n{ctx.data_block}\n" if ctx.data_block else ""
return (
f"{persona}\n"
f"Predict the result of this 2026 MLS (Major League Soccer) regular-season "
f"match.\n"
f"Team A (away): {ctx.team_a}\nTeam B (home): {ctx.team_b}\n"
f"Venue: {ctx.venue}\nKickoff: {ctx.kickoff}\n"
f"{data}"
f"Important: Team B is the HOME team — MLS home advantage is significant "
f"(long travel distances). Draws are common in MLS (~25% of matches) — "
f"predict one when the matchup genuinely points that way.\n\n"
f"Predict the final 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,\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'
)
def _build_prompt(ctx: MatchContext, model: str) -> str:
"""리그별 프롬프트 선택 — 야구(kbo/mlb)는 야구, mls 는 MLS 축구, 그 외 월드컵."""
if ctx.league in ("kbo", "mlb"):
return _prompt_baseball(ctx, model)
if ctx.league == "mls":
return _prompt_mls(ctx, ANALYST)
return _prompt(ctx, ANALYST)
# JSON Schema (구조화 출력용 — Anthropic/OpenAI 공통) # JSON Schema (구조화 출력용 — Anthropic/OpenAI 공통)
_SCHEMA = { _SCHEMA = {
"type": "object", "type": "object",
@@ -96,9 +156,9 @@ _SCHEMA = {
} }
def _normalize(data: dict) -> dict: def _normalize(data: dict, max_score: int = 9) -> dict:
a = max(0, min(9, int(data["scoreA"]))) a = max(0, min(max_score, int(data["scoreA"])))
b = max(0, min(9, int(data["scoreB"]))) b = max(0, min(max_score, int(data["scoreB"])))
# outcome 은 스코어와 일관되도록 서버에서 재도출 (모델 불일치 방지) # outcome 은 스코어와 일관되도록 서버에서 재도출 (모델 불일치 방지)
outcome = "TEAM_A_WIN" if a > b else "TEAM_B_WIN" if a < b else "DRAW" 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)))) conf = max(0, min(100, int(data.get("confidencePct", 50))))
@@ -123,12 +183,12 @@ async def predict_gpt(ctx: MatchContext) -> dict:
model=settings.openai_model, model=settings.openai_model,
messages=[ messages=[
{"role": "system", "content": "You output only valid JSON."}, {"role": "system", "content": "You output only valid JSON."},
{"role": "user", "content": _prompt(ctx, PERSONA["GPT"])}, {"role": "user", "content": _build_prompt(ctx, "GPT")},
], ],
response_format={"type": "json_object"}, response_format={"type": "json_object"},
) )
content = resp.choices[0].message.content or "{}" content = resp.choices[0].message.content or "{}"
return _normalize(json.loads(content)) return _normalize(json.loads(content), 25 if ctx.league in ("kbo", "mlb") else 9)
# ── Claude (Anthropic) ────────────────────────────────────── # ── Claude (Anthropic) ──────────────────────────────────────
@@ -143,7 +203,7 @@ async def predict_claude(ctx: MatchContext) -> dict:
return await client.messages.create( return await client.messages.create(
model=settings.anthropic_model, model=settings.anthropic_model,
max_tokens=1024, max_tokens=1024,
messages=[{"role": "user", "content": _prompt(ctx, PERSONA["Claude"])}], messages=[{"role": "user", "content": _build_prompt(ctx, "Claude")}],
**extra, **extra,
) )
@@ -157,7 +217,7 @@ async def predict_claude(ctx: MatchContext) -> dict:
except TypeError: except TypeError:
msg = await _create() msg = await _create()
text = "".join(b.text for b in msg.content if getattr(b, "type", "") == "text") text = "".join(b.text for b in msg.content if getattr(b, "type", "") == "text")
return _normalize(json.loads(text)) return _normalize(json.loads(text), 25 if ctx.league in ("kbo", "mlb") else 9)
# ── Gemini (Google) ───────────────────────────────────────── # ── Gemini (Google) ─────────────────────────────────────────
@@ -170,10 +230,10 @@ async def predict_gemini(ctx: MatchContext) -> dict:
client = genai.Client(api_key=settings.google_api_key) client = genai.Client(api_key=settings.google_api_key)
resp = await client.aio.models.generate_content( resp = await client.aio.models.generate_content(
model=settings.google_model, model=settings.google_model,
contents=_prompt(ctx, PERSONA["Gemini"]), contents=_build_prompt(ctx, "Gemini"),
config=types.GenerateContentConfig(response_mime_type="application/json"), config=types.GenerateContentConfig(response_mime_type="application/json"),
) )
return _normalize(json.loads(resp.text or "{}")) return _normalize(json.loads(resp.text or "{}"), 25 if ctx.league in ("kbo", "mlb") else 9)
PROVIDERS = { PROVIDERS = {
+342
View File
@@ -0,0 +1,342 @@
"""카카오 로그인 + JWT 인증 — o2o-castad-backend 의 인증 스택 이식.
흐름 (castad 와 동일):
1. GET /api/auth/kakao/login → 카카오 인증 페이지 URL
2. 카카오 로그인 후 redirect_uri 로 인가 코드(code) 수신
3. 코드 → 카카오 액세스 토큰 → 사용자 정보 조회
4. users 조회/생성 → JWT access(60분)/refresh(7일) 발급
5. refresh 는 해시로 DB 저장, 갱신 시 rotation(기존 폐기 + 신규 발급)
castad 대비 변경: aiohttp→httpx(프로젝트 표준), 크레딧·소셜계정 연동 제거,
설정은 triplepick settings 로 통합.
"""
from __future__ import annotations
import hashlib
import logging
from datetime import timedelta
from typing import Optional
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from jose import jwt
from jose.exceptions import ExpiredSignatureError, JWTError
from sqlalchemy import select, update
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
from ..config import settings
from ..database import get_db
from ..domain import ensure_aware, now_utc
from ..models import RefreshToken, User
log = logging.getLogger("triplepick.auth")
JWT_ALGORITHM = "HS256"
KAKAO_AUTH_URL = "https://kauth.kakao.com/oauth/authorize"
KAKAO_TOKEN_URL = "https://kauth.kakao.com/oauth/token"
KAKAO_USER_INFO_URL = "https://kapi.kakao.com/v2/user/me"
# ── 예외 (castad 코드 체계 유지) ───────────────────────────────
class AuthError(HTTPException):
def __init__(self, status_code: int, code: str, message: str):
super().__init__(
status_code=status_code, detail={"code": code, "message": message}
)
def _unauthorized(code: str, message: str) -> AuthError:
return AuthError(status.HTTP_401_UNAUTHORIZED, code, message)
# ── JWT ────────────────────────────────────────────────────────
def create_access_token(user_uuid: str) -> str:
expire = now_utc() + timedelta(minutes=settings.jwt_access_expire_minutes)
return jwt.encode(
{"sub": user_uuid, "exp": expire, "type": "access"},
settings.jwt_secret,
algorithm=JWT_ALGORITHM,
)
def create_refresh_token(user_uuid: str) -> str:
expire = now_utc() + timedelta(days=settings.jwt_refresh_expire_days)
return jwt.encode(
{"sub": user_uuid, "exp": expire, "type": "refresh"},
settings.jwt_secret,
algorithm=JWT_ALGORITHM,
)
def decode_token(token: str) -> dict | None:
"""유효하면 payload, 만료/위조면 None."""
try:
return jwt.decode(token, settings.jwt_secret, algorithms=[JWT_ALGORITHM])
except JWTError:
return None
def is_token_expired(token: str) -> bool:
try:
jwt.decode(token, settings.jwt_secret, algorithms=[JWT_ALGORITHM])
return False
except ExpiredSignatureError:
return True
except JWTError:
return False
def get_token_hash(token: str) -> str:
return hashlib.sha256(token.encode()).hexdigest()
# ── 카카오 OAuth ───────────────────────────────────────────────
def kakao_authorization_url() -> str:
return (
f"{KAKAO_AUTH_URL}?client_id={settings.kakao_client_id}"
f"&redirect_uri={settings.kakao_redirect_uri}&response_type=code"
)
async def _kakao_access_token(code: str) -> str:
import httpx
data = {
"grant_type": "authorization_code",
"client_id": settings.kakao_client_id,
"redirect_uri": settings.kakao_redirect_uri,
"code": code,
}
if settings.kakao_client_secret:
data["client_secret"] = settings.kakao_client_secret
async with httpx.AsyncClient(timeout=15) as c:
r = await c.post(KAKAO_TOKEN_URL, data=data)
result = r.json()
if "error" in result:
desc = result.get("error_description", result.get("error", "알 수 없는 오류"))
log.error("kakao 토큰 발급 실패: %s", desc)
raise AuthError(
status.HTTP_400_BAD_REQUEST, "KAKAO_AUTH_FAILED",
f"카카오 토큰 발급 실패: {desc}",
)
return result["access_token"]
async def _kakao_user_info(access_token: str) -> dict:
import httpx
async with httpx.AsyncClient(timeout=15) as c:
r = await c.get(
KAKAO_USER_INFO_URL, headers={"Authorization": f"Bearer {access_token}"}
)
result = r.json()
if "id" not in result:
log.error("kakao 사용자 정보 조회 실패: %s", result)
raise AuthError(
status.HTTP_400_BAD_REQUEST, "KAKAO_AUTH_FAILED",
"카카오 사용자 정보를 가져올 수 없습니다.",
)
return result
# ── 사용자 조회/생성 ───────────────────────────────────────────
def _profile_of(info: dict) -> tuple[str | None, str | None, str | None]:
"""카카오 응답 → (email, nickname, profile_image_url)."""
account = info.get("kakao_account") or {}
profile = account.get("profile") or {}
return (
account.get("email"),
profile.get("nickname"),
profile.get("profile_image_url"),
)
async def _get_or_create_user(db: AsyncSession, info: dict) -> tuple[User, bool]:
kakao_id = int(info["id"])
email, nickname, image = _profile_of(info)
user = (
await db.execute(select(User).where(User.kakao_id == kakao_id))
).scalar_one_or_none()
if user is not None:
# 기존 사용자 — 프로필 최신화
if nickname:
user.nickname = nickname
if image:
user.profile_image_url = image
if email:
user.email = email
await db.flush()
return user, False
import uuid
new_user = User(
kakao_id=kakao_id,
user_uuid=str(uuid.uuid4()),
email=email,
nickname=nickname,
profile_image_url=image,
)
db.add(new_user)
try:
await db.flush()
return new_user, True
except IntegrityError:
# 동시 요청으로 인한 중복 삽입 — 기존 사용자 재조회 (castad 동일 처리)
await db.rollback()
existing = (
await db.execute(select(User).where(User.kakao_id == kakao_id))
).scalar_one_or_none()
if existing is not None:
return existing, False
raise
# ── 로그인/갱신/로그아웃 ───────────────────────────────────────
async def kakao_login(
db: AsyncSession,
code: str,
user_agent: Optional[str] = None,
ip_address: Optional[str] = None,
) -> dict:
"""인가 코드 → JWT 발급. {access_token, refresh_token, expires_in, is_new_user, user}."""
kakao_token = await _kakao_access_token(code)
info = await _kakao_user_info(kakao_token)
user, is_new = await _get_or_create_user(db, info)
if not user.is_active:
raise AuthError(
status.HTTP_403_FORBIDDEN, "USER_INACTIVE", "활성화 상태가 아닌 사용자 입니다."
)
access_token = create_access_token(user.user_uuid)
refresh_token = create_refresh_token(user.user_uuid)
db.add(RefreshToken(
user_id=user.id,
user_uuid=user.user_uuid,
token_hash=get_token_hash(refresh_token),
expires_at=now_utc() + timedelta(days=settings.jwt_refresh_expire_days),
user_agent=user_agent,
ip_address=ip_address,
))
user.last_login_at = now_utc()
await db.commit()
log.info("kakao 로그인: user_id=%s new=%s", user.id, is_new)
return {
"access_token": access_token,
"refresh_token": refresh_token,
"token_type": "Bearer",
"expires_in": settings.jwt_access_expire_minutes * 60,
"is_new_user": is_new,
"user": user_out(user),
}
async def refresh_tokens(db: AsyncSession, refresh_token: str) -> dict:
"""Refresh Token Rotation — 기존 토큰 폐기 + 새 access/refresh 발급."""
payload = decode_token(refresh_token)
if payload is None:
if is_token_expired(refresh_token):
raise _unauthorized("TOKEN_EXPIRED", "토큰이 만료되었습니다. 다시 로그인해주세요.")
raise _unauthorized("INVALID_TOKEN", "유효하지 않은 토큰입니다.")
if payload.get("type") != "refresh":
raise _unauthorized("INVALID_TOKEN", "리프레시 토큰이 아닙니다.")
token_hash = get_token_hash(refresh_token)
db_token = (
await db.execute(
select(RefreshToken).where(RefreshToken.token_hash == token_hash)
)
).scalar_one_or_none()
if db_token is None:
raise _unauthorized("INVALID_TOKEN", "유효하지 않은 토큰입니다.")
if db_token.is_revoked: # 이미 폐기된 토큰 재사용 — replay 의심
log.warning("폐기된 refresh 재사용: user_uuid=%s", db_token.user_uuid)
raise _unauthorized("TOKEN_REVOKED", "취소된 토큰입니다. 다시 로그인해주세요.")
if ensure_aware(db_token.expires_at) < now_utc():
raise _unauthorized("TOKEN_EXPIRED", "토큰이 만료되었습니다. 다시 로그인해주세요.")
user = (
await db.execute(select(User).where(User.user_uuid == payload.get("sub")))
).scalar_one_or_none()
if user is None:
raise AuthError(
status.HTTP_404_NOT_FOUND, "USER_NOT_FOUND", "가입되지 않은 사용자 입니다."
)
if not user.is_active:
raise AuthError(
status.HTTP_403_FORBIDDEN, "USER_INACTIVE", "활성화 상태가 아닌 사용자 입니다."
)
db_token.is_revoked = True
db_token.revoked_at = now_utc()
new_access = create_access_token(user.user_uuid)
new_refresh = create_refresh_token(user.user_uuid)
db.add(RefreshToken(
user_id=user.id,
user_uuid=user.user_uuid,
token_hash=get_token_hash(new_refresh),
expires_at=now_utc() + timedelta(days=settings.jwt_refresh_expire_days),
))
await db.commit() # 폐기 + 저장을 한 트랜잭션으로
return {
"access_token": new_access,
"refresh_token": new_refresh,
"token_type": "Bearer",
"expires_in": settings.jwt_access_expire_minutes * 60,
}
async def logout(db: AsyncSession, refresh_token: str) -> None:
await db.execute(
update(RefreshToken)
.where(RefreshToken.token_hash == get_token_hash(refresh_token))
.values(is_revoked=True, revoked_at=now_utc())
)
await db.commit()
def user_out(user: User) -> dict:
return {
"userUuid": user.user_uuid,
"email": user.email,
"nickname": user.nickname,
"profileImageUrl": user.profile_image_url,
}
# ── FastAPI 의존성 ─────────────────────────────────────────────
_security = HTTPBearer(auto_error=False)
async def get_current_user(
credentials: HTTPAuthorizationCredentials | None = Depends(_security),
db: AsyncSession = Depends(get_db),
) -> User:
"""Bearer access 토큰 → User. 실패 시 401/403/404."""
if credentials is None:
raise _unauthorized("MISSING_TOKEN", "인증 토큰이 필요합니다.")
payload = decode_token(credentials.credentials)
if payload is None:
if is_token_expired(credentials.credentials):
raise _unauthorized("TOKEN_EXPIRED", "토큰이 만료되었습니다. 다시 로그인해주세요.")
raise _unauthorized("INVALID_TOKEN", "유효하지 않은 토큰입니다.")
if payload.get("type") != "access":
raise _unauthorized("INVALID_TOKEN", "액세스 토큰이 아닙니다.")
user = (
await db.execute(select(User).where(User.user_uuid == payload.get("sub")))
).scalar_one_or_none()
if user is None:
raise AuthError(
status.HTTP_404_NOT_FOUND, "USER_NOT_FOUND", "가입되지 않은 사용자 입니다."
)
if not user.is_active:
raise AuthError(
status.HTTP_403_FORBIDDEN, "USER_INACTIVE", "활성화 상태가 아닌 사용자 입니다."
)
return user
+196
View File
@@ -0,0 +1,196 @@
"""야구 예측 프롬프트용 데이터 블록 — 자체 DB(정산 결과) + DataCache(프리뷰·순위).
결과 동기화가 쌓은 종료 경기에서 팀 폼·시즌 성적·상대전적을 계산하고,
캐시된 선발투수·공식 상대전적·순위를 덧붙인다. 모두 없으면 None(이름만 예측).
"""
from __future__ import annotations
from sqlalchemy import or_, select
from ..models import DataCache, Match
def _wdl(gf: int, ga: int) -> str:
return "W" if gf > ga else "L" if gf < ga else "D"
async def _team_games(db, league: str, code: str, before) -> list[dict]:
rows = (await db.execute(
select(Match)
.where(
Match.league == league,
or_(Match.team_a_code == code, Match.team_b_code == code),
Match.result_outcome.isnot(None),
Match.kickoff_at < before,
)
.order_by(Match.kickoff_at)
)).scalars().all()
out = []
for m in rows:
is_a = m.team_a_code == code # team_a = 원정
gf = m.result_score_a if is_a else m.result_score_b
ga = m.result_score_b if is_a else m.result_score_a
if gf is None or ga is None:
continue
out.append({
"r": _wdl(gf, ga), "gf": gf, "ga": ga,
"opp": m.team_b_short if is_a else m.team_a_short,
})
return out
def _team_lines(name: str, games: list[dict]) -> str:
head = f"[{name}]"
if not games:
return f"{head}\n (no season data yet — use general knowledge)"
n = len(games)
w = sum(1 for g in games if g["r"] == "W")
d = sum(1 for g in games if g["r"] == "D")
l = sum(1 for g in games if g["r"] == "L")
gf_avg = round(sum(g["gf"] for g in games) / n, 2)
ga_avg = round(sum(g["ga"] for g in games) / n, 2)
recent = games[-8:]
detail = "; ".join("{r} {gf}-{ga} vs {opp}".format(**g) for g in recent[-4:])
return (
f"{head}\n"
f" Season(in our data): {w}-{d}-{l} (W-D-L), "
f"runs avg {gf_avg} scored / {ga_avg} allowed over {n} games\n"
f" Form(last{len(recent)}): {' '.join(g['r'] for g in recent)} ({detail})"
)
async def _h2h_line(db, league: str, code_a: str, code_b: str, before) -> str:
rows = (await db.execute(
select(Match)
.where(
Match.league == league,
or_(
(Match.team_a_code == code_a) & (Match.team_b_code == code_b),
(Match.team_a_code == code_b) & (Match.team_b_code == code_a),
),
Match.result_outcome.isnot(None),
Match.kickoff_at < before,
)
.order_by(Match.kickoff_at)
)).scalars().all()
parts = [
f"{m.team_a_short} {m.result_score_a}-{m.result_score_b} {m.team_b_short}"
for m in rows[-5:]
if m.result_score_a is not None
]
return "; ".join(parts) if parts else "no meetings in our data yet"
def _starter_line(side: str, s: dict | None) -> str | None:
if not s or not s.get("name"):
return None
era = f", season ERA {s['era']}" if s.get("era") else ""
rec = (
f" ({s['w']}W-{s['l']}L)"
if s.get("w") is not None and s.get("l") is not None else ""
)
# 상대 ERA 0.00 은 대부분 '대전 기록 없음' — 무실점으로 오해하지 않게 생략
vs_val = s.get("vsEra")
vs = (
f", ERA vs this opponent {vs_val}"
if vs_val not in (None, "", 0, "0", "0.00", "-")
else ""
)
return f"[{side} starting pitcher] {s['name']}{era}{rec}{vs}"
def _standing_line(name: str, st: dict | None) -> str | None:
if not st:
return None
gb = f", GB {st['gb']}" if st.get("gb") not in (None, "", 0, "0.0") else ""
ba = f", team AVG {st['avg']}" if st.get("avg") else ""
era = f", team ERA {st['era']}" if st.get("era") else ""
extra = f", last5 {st['last5']}" if st.get("last5") else ""
return (
f"[{name} standings] rank {st.get('rank')}, {st.get('w')}W-"
f"{st.get('l')}L (pct {st.get('wra')}){gb}{ba}{era}{extra}"
)
async def _cached_extras(db, match: Match) -> list[str]:
lines: list[str] = []
prev = await db.get(DataCache, f"preview:{match.match_id}")
if prev:
p = prev.payload
for line in (
_starter_line("Away", p.get("starterA")),
_starter_line("Home", p.get("starterB")),
):
if line:
lines.append(line)
vs = p.get("seasonVs")
if vs and vs.get("aWin") is not None:
lines.append(
f"[Season head-to-head (official)] away {vs['aWin']}W - "
f"{vs.get('draw', 0)}D - home {vs.get('bWin')}W"
)
st_row = await db.get(DataCache, f"standings:{match.league}")
if st_row:
table = st_row.payload
for line in (
_standing_line(match.team_a_short, table.get(match.team_a_code)),
_standing_line(match.team_b_short, table.get(match.team_b_code)),
):
if line:
lines.append(line)
return lines
async def _context_extras(db, match: Match) -> list[str]:
"""전날 결과·활약 + 확정 라인업(타자 시즌 타율) — 응원가 파이프라인 헬퍼 재사용.
라인업은 발표 전이면 생략(예측이 킥오프 22h 전부터 생성되므로 보통 미포함).
"""
from .songs import _lineup_line, _yesterday_info, fetch_lineups
lines: list[str] = []
avg_maps: dict[str, dict] = {}
for side, code, name in (
("a", match.team_a_code, match.team_a_short),
("b", match.team_b_code, match.team_b_short),
):
label = "Away" if side == "a" else "Home"
try:
y, avg_map = await _yesterday_info(db, match, code, name)
except Exception: # noqa: BLE001 — 부가 데이터 실패는 생략
y, avg_map = None, {}
avg_maps[side] = avg_map
if y:
lines.append(f"[{label} yesterday] {y}")
try:
lu = await fetch_lineups(match)
except Exception: # noqa: BLE001
lu = None
if lu and lu.get("announced"):
for side in ("a", "b"):
label = "Away" if side == "a" else "Home"
line = _lineup_line(lu, side, avg_maps.get(side))
if line:
lines.append(f"[{label}] {line}")
return lines
async def build_baseball_data_block(db, match: Match) -> str | None:
ga = await _team_games(db, match.league, match.team_a_code, match.kickoff_at)
gb = await _team_games(db, match.league, match.team_b_code, match.kickoff_at)
extras = await _cached_extras(db, match)
if not ga and not gb and not extras:
return None
h2h = await _h2h_line(
db, match.league, match.team_a_code, match.team_b_code, match.kickoff_at
)
context = await _context_extras(db, match)
return "\n".join([
"=== MATCH DATA (factual; weigh heavily over priors) ===",
"Away " + _team_lines(match.team_a_name, ga),
"Home " + _team_lines(match.team_b_name, gb),
f"[Head-to-head in our data] {h2h}",
*extras,
*context,
"===",
])
+861
View File
@@ -0,0 +1,861 @@
"""야구 부가 데이터 — 프리뷰(선발투수·상대전적)·리그 순위·라이브 필드 뷰.
KBO: 네이버 스포츠 비공식 API (프리뷰·순위·문자중계 relay)
MLB: 공식 Stats API (probablePitcher·standings·feed/live)
수집(refresh_*)은 워커가 매일, 조회(get_extras)는 라우터가 캐시만 읽음.
라이브(fetch_live)는 요청 시 프록시 + 짧은 TTL 메모리 캐시.
"""
from __future__ import annotations
import asyncio
import logging
import re
import time
from datetime import datetime, timedelta, timezone
from ..config import settings
from ..domain import ensure_aware, now_utc
from ..models import DataCache, Match
from ..teams_baseball import KBO_SHORT_TO_CODE, MLB_ID_TO_CODE, MLB_TEAMS
from .baseball_sync import match_seq
log = logging.getLogger("triplepick.baseball")
KST = timezone(timedelta(hours=9))
UA = {
"User-Agent": (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/126.0 Safari/537.36"
)
}
def naver_game_id(m: Match, game_no: str = "0") -> str:
kst = ensure_aware(m.kickoff_at).astimezone(KST)
return f"{kst.strftime('%Y%m%d')}{m.team_a_code}{m.team_b_code}{game_no}{kst.year}"
def naver_game_id_candidates(m: Match) -> list[str]:
"""더블헤더 대응 gameId 후보 — 끝번호 0(단일)/1(DH 1차전)/2(DH 2차전).
seq1 은 단일을 먼저 시도하고 DH 1차전으로 폴백, seq2 는 2차전 고정."""
nos = ["2"] if match_seq(m.match_id) == 2 else ["0", "1"]
return [naver_game_id(m, n) for n in nos]
async def _naver_get_first_with_id(
client, m: Match, suffix: str
) -> tuple[str, dict] | None:
"""gameId 후보를 순서대로 시도해 (성공한 gameId, 응답) 을 반환.
같은 경기를 추가 조회할 때(이닝별 문자중계) gameId 를 다시 찾지 않게 함께 돌려준다.
"""
for gid in naver_game_id_candidates(m):
try:
res = await _naver_get(client, f"/schedule/games/{gid}/{suffix}")
except Exception: # noqa: BLE001 — 후보 불일치(404 등)는 다음 후보로
continue
if res:
return gid, res
return None
async def _naver_get_first(client, m: Match, suffix: str) -> dict | None:
"""gameId 후보를 순서대로 시도해 첫 성공 응답을 반환."""
found = await _naver_get_first_with_id(client, m, suffix)
return found[1] if found else None
async def _naver_get(client, path: str) -> dict | None:
r = await client.get(settings.naver_api_base + path, headers=UA)
r.raise_for_status()
data = r.json()
return data.get("result") if data.get("success") else None
async def _upsert(db, key: str, payload: dict) -> None:
row = await db.get(DataCache, key)
if row:
row.payload = payload
row.fetched_at = now_utc()
else:
db.add(DataCache(key=key, payload=payload, fetched_at=now_utc()))
# ── 프리뷰 (선발투수·시즌 상대전적) ────────────────────────────
def _kbo_starter(raw: dict | None) -> dict | None:
if not raw:
return None
info = raw.get("playerInfo") or {}
season = raw.get("currentSeasonStats") or {}
vs = raw.get("currentSeasonStatsOnOpponents") or {}
out = {
"name": info.get("name", ""),
"hitType": info.get("hitType", ""),
"era": season.get("era"),
"w": season.get("w"), "l": season.get("l"),
"vsEra": vs.get("era"),
}
return out if out["name"] else None
async def _refresh_previews_kbo(db, matches: list[Match]) -> int:
import httpx
n = 0
async with httpx.AsyncClient(timeout=15) as client:
for m in matches:
try:
res = await _naver_get_first(client, m, "preview")
p = (res or {}).get("previewData") or {}
except Exception as e: # noqa: BLE001
log.warning("kbo preview 실패 %s: %s", m.match_id, e)
continue
vs = p.get("seasonVsResult") or {}
payload = {
"starterA": _kbo_starter(p.get("awayStarter")),
"starterB": _kbo_starter(p.get("homeStarter")),
"seasonVs": {
"aWin": vs.get("aw"), "draw": vs.get("ad") or 0, "bWin": vs.get("hw"),
} if vs else None,
}
if payload["starterA"] or payload["starterB"] or payload["seasonVs"]:
await _upsert(db, f"preview:{m.match_id}", payload)
n += 1
return n
_HAND_KO = {"L": "좌", "R": "우", "S": "양"}
def _mlb_starter(p: dict, stats: dict[int, dict]) -> dict | None:
if not p.get("fullName"):
return None
out: dict = {"name": p["fullName"]}
out.update(stats.get(p.get("id"), {}))
return out
async def _mlb_season_vs(c, m: Match, year: int) -> dict | None:
"""시즌 정규 상대전적 — 두 팀 간 완료 경기 승수 집계 (팀쌍당 1콜)."""
aid = (MLB_TEAMS.get(m.team_a_code) or {}).get("mlb_id")
bid = (MLB_TEAMS.get(m.team_b_code) or {}).get("mlb_id")
if not aid or not bid:
return None
r = await c.get(
f"{settings.mlb_api_base}/v1/schedule?sportId=1&season={year}&gameType=R"
f"&teamId={bid}&opponentId={aid}"
f"&startDate={year}-03-01&endDate={datetime.now(KST).date().isoformat()}"
)
r.raise_for_status()
wins = {aid: 0, bid: 0}
for day in r.json().get("dates") or []:
for g in day.get("games") or []:
if (g.get("status") or {}).get("abstractGameState") != "Final":
continue
for side in ("away", "home"):
t = g["teams"][side]
tid = (t.get("team") or {}).get("id")
if t.get("isWinner") and tid in wins:
wins[tid] += 1
if wins[aid] + wins[bid] == 0:
return None
return {"aWin": wins[aid], "draw": 0, "bWin": wins[bid]}
async def _refresh_previews_mlb(db, matches: list[Match]) -> int:
"""MLB 예고 선발(시즌 ERA·승패·투타 포함)·시즌 상대전적 — 공식 Stats API.
호출량: 일정 1콜 + 선발 스탯 일괄 1콜 + 상대전적 팀쌍당 1콜.
"""
import httpx
if not matches:
return 0
dates = sorted({ensure_aware(m.kickoff_at).astimezone(KST).date() for m in matches})
year = datetime.now(KST).year
# statsapi 의 start/endDate 는 미국 날짜 — KST 새벽~오전 경기는 미국 전날이라
# 시작일을 하루 앞당겨야 누락되지 않는다.
url = (
f"{settings.mlb_api_base}/v1/schedule?sportId=1"
f"&startDate={(dates[0] - timedelta(days=1)).isoformat()}"
f"&endDate={dates[-1].isoformat()}"
"&hydrate=probablePitcher"
)
async with httpx.AsyncClient(timeout=20) as c:
r = await c.get(url)
r.raise_for_status()
data = r.json()
# (dateKst, away, home) → (원정 선발 raw, 홈 선발 raw)
starters: dict[tuple, tuple[dict, dict]] = {}
for day in data.get("dates") or []:
for g in day.get("games") or []:
a = MLB_ID_TO_CODE.get((g["teams"]["away"]["team"] or {}).get("id"))
b = MLB_ID_TO_CODE.get((g["teams"]["home"]["team"] or {}).get("id"))
gd = g.get("gameDate")
if not a or not b or not gd:
continue
d = (
datetime.fromisoformat(gd.replace("Z", "+00:00"))
.astimezone(KST).strftime("%Y%m%d")
)
pa = g["teams"]["away"].get("probablePitcher") or {}
pb = g["teams"]["home"].get("probablePitcher") or {}
starters[(d, a, b)] = (pa, pb)
# 선발 시즌 스탯 — people 일괄 조회 1콜 (ERA·승패·투타)
pids = sorted({
p["id"] for pair in starters.values() for p in pair if p.get("id")
})
pstats: dict[int, dict] = {}
if pids:
try:
r2 = await c.get(
f"{settings.mlb_api_base}/v1/people"
f"?personIds={','.join(map(str, pids))}"
f"&hydrate=stats(group=[pitching],type=[season],season={year})"
)
r2.raise_for_status()
for p in r2.json().get("people") or []:
splits = (p.get("stats") or [{}])[0].get("splits") or []
s = splits[0].get("stat", {}) if splits else {}
hand = _HAND_KO.get((p.get("pitchHand") or {}).get("code"))
bat = _HAND_KO.get((p.get("batSide") or {}).get("code"))
pstats[p["id"]] = {
"hitType": f"{hand}투{bat}타" if hand and bat else None,
"era": s.get("era"),
"w": s.get("wins"), "l": s.get("losses"),
}
except Exception as e: # noqa: BLE001 — 스탯 실패 시 이름만 표시
log.warning("mlb 선발 스탯 실패: %s", e)
n = 0
vs_cache: dict[tuple, dict | None] = {}
for m in matches:
d = ensure_aware(m.kickoff_at).astimezone(KST).strftime("%Y%m%d")
pa, pb = starters.get((d, m.team_a_code, m.team_b_code), ({}, {}))
pair = (m.team_a_code, m.team_b_code)
if pair not in vs_cache:
try:
vs_cache[pair] = await _mlb_season_vs(c, m, year)
except Exception as e: # noqa: BLE001
log.warning("mlb 상대전적 실패 %s: %s", m.match_id, e)
vs_cache[pair] = None
sa = _mlb_starter(pa, pstats)
sb = _mlb_starter(pb, pstats)
if sa or sb or vs_cache[pair]:
await _upsert(db, f"preview:{m.match_id}", {
"starterA": sa,
"starterB": sb,
"seasonVs": vs_cache[pair],
})
n += 1
return n
# ── 리그 순위 ──────────────────────────────────────────────────
async def _refresh_standings_kbo(db) -> bool:
import httpx
year = datetime.now(KST).year
try:
async with httpx.AsyncClient(timeout=15) as client:
res = await _naver_get(client, f"/stats/categories/kbo/seasons/{year}/teams")
except Exception as e: # noqa: BLE001
log.warning("kbo standings 실패: %s", e)
return False
table: dict[str, dict] = {}
for r in (res or {}).get("seasonTeamStats") or []:
code = KBO_SHORT_TO_CODE.get(r.get("teamShortName", ""))
if code:
table[code] = {
"rank": r.get("ranking"),
"w": r.get("winGameCount"), "d": r.get("drawnGameCount"),
"l": r.get("loseGameCount"), "wra": r.get("wra"),
"gb": r.get("gameBehind"), "last5": r.get("lastFiveGames"),
"avg": r.get("offenseHra"), "era": r.get("defenseEra"),
}
if not table:
return False
await _upsert(db, "standings:kbo", table)
return True
# statsapi division.id → 순위표 그룹 키 (AL/NL × 동·중·서)
_MLB_DIV = {201: "ALE", 202: "ALC", 200: "ALW", 204: "NLE", 205: "NLC", 203: "NLW"}
async def _refresh_standings_mlb(db) -> bool:
import httpx
year = datetime.now(KST).year
table: dict[str, dict] = {}
try:
async with httpx.AsyncClient(timeout=15) as c:
for lid in (103, 104): # AL, NL
r = await c.get(
f"{settings.mlb_api_base}/v1/standings?leagueId={lid}&season={year}"
)
r.raise_for_status()
for rec_div in r.json().get("records") or []:
div = _MLB_DIV.get((rec_div.get("division") or {}).get("id"))
for t in rec_div.get("teamRecords") or []:
code = MLB_ID_TO_CODE.get((t.get("team") or {}).get("id"))
if code:
table[code] = {
"div": div,
"rank": int(t.get("divisionRank") or 0) or None,
"w": t.get("wins"), "d": 0, "l": t.get("losses"),
"wra": t.get("winningPercentage"),
"gb": t.get("gamesBack"),
"last5": None, "avg": None, "era": None,
}
except Exception as e: # noqa: BLE001
log.warning("mlb standings 실패: %s", e)
return False
if not table:
return False
await _upsert(db, "standings:mlb", table)
return True
async def refresh_baseball_details(db, league: str, matches: list[Match]) -> None:
"""임박(48h 내) 미종료 경기 프리뷰 + 리그 순위 캐시 갱신."""
horizon = now_utc() + timedelta(hours=48)
targets = [
m for m in matches
if m.result_outcome is None
and m.status != "cancelled"
and ensure_aware(m.kickoff_at) <= horizon
]
if league == "kbo":
n = await _refresh_previews_kbo(db, targets)
await _refresh_standings_kbo(db)
elif league == "mlb":
n = await _refresh_previews_mlb(db, targets)
await _refresh_standings_mlb(db)
else:
return
await db.commit()
log.info("baseball details(%s): 프리뷰 %d경기 캐싱", league, n)
# ── extras 조회 (라우터 — 캐시만) ──────────────────────────────
# MLS 도 동일 캐시 키(preview:{id}, standings:mls)를 쓰므로 여기서 함께 서빙.
async def get_extras(db, matches: list[Match]) -> dict[str, dict]:
standings_cache: dict[str, dict] = {}
out: dict[str, dict] = {}
for m in matches:
if m.league not in ("kbo", "mlb", "mls"):
continue
if m.league not in standings_cache:
row = await db.get(DataCache, f"standings:{m.league}")
standings_cache[m.league] = row.payload if row else {}
extras: dict = {}
prev = await db.get(DataCache, f"preview:{m.match_id}")
if prev:
extras.update(prev.payload)
st = standings_cache[m.league]
st_a, st_b = st.get(m.team_a_code), st.get(m.team_b_code)
if st_a or st_b:
extras["standings"] = {"a": st_a, "b": st_b}
if extras:
out[m.match_id] = extras
return out
# ── 라이브 필드 뷰 ─────────────────────────────────────────────
_LIVE_TTL_SEC = 15.0
_live_cache: dict[str, tuple[float, dict]] = {}
FIELD_POSITIONS = (
"포수", "1루수", "2루수", "3루수", "유격수", "좌익수", "중견수", "우익수",
)
# MLB 포지션 약어 → 한글 (필드 좌표 키와 통일)
MLB_POS = {
"C": "포수", "1B": "1루수", "2B": "2루수", "3B": "3루수", "SS": "유격수",
"LF": "좌익수", "CF": "중견수", "RF": "우익수",
}
def _current_slots(batters: list[dict]) -> list[dict]:
by_order: dict[int, dict] = {}
for b in batters or []:
o = b.get("batOrder")
if o is None:
continue
cur = by_order.get(o)
if cur is None or (b.get("seqno") or 0) > (cur.get("seqno") or 0):
by_order[o] = b
return [by_order[o] for o in sorted(by_order)]
def _batter_out(b: dict) -> dict:
return {
"order": b.get("batOrder"),
"name": b.get("name", ""),
"pos": b.get("posName", ""),
"avg": b.get("seasonHra"),
"sub": (b.get("seqno") or 1) > 1,
}
def _transform_naver_relay(t: dict) -> dict:
gs = t.get("currentGameState") or {}
home_batting = str(t.get("homeOrAway")) == "1"
home_lu = t.get("homeLineup") or {}
away_lu = t.get("awayLineup") or {}
offense_lu = home_lu if home_batting else away_lu
defense_lu = away_lu if home_batting else home_lu
offense = _current_slots(offense_lu.get("batter"))
defense = _current_slots(defense_lu.get("batter"))
pitchers = defense_lu.get("pitcher") or []
pitcher = max(pitchers, key=lambda p: p.get("seqno") or 0) if pitchers else {}
batter_code = str(gs.get("batter") or "")
batter = next((b for b in offense if str(b.get("pcode")) == batter_code), None)
return {
"available": True,
"inn": t.get("inn"),
"half": "B" if home_batting else "T",
"score": {"away": gs.get("awayScore"), "home": gs.get("homeScore")},
"bso": {"b": gs.get("ball"), "s": gs.get("strike"), "o": gs.get("out")},
"bases": [
str(gs.get(k) or "0") != "0" for k in ("base1", "base2", "base3")
],
"batter": _batter_out(batter) if batter else None,
"pitcher": {
"name": pitcher.get("name", ""),
"ballCount": pitcher.get("ballCount"),
} if pitcher else None,
"vsRecord": t.get("pitcherVsBatterCareerStats") or "",
"defense": [
{"pos": b.get("posName"), "name": b.get("name", "")}
for b in defense if b.get("posName") in FIELD_POSITIONS
],
"offenseLineup": [_batter_out(b) for b in offense],
}
# ── KBO 문자중계 (네이버 relay textRelays) ─────────────────────
# 네이버는 이미 한국어 중계문을 타석 단위로 묶어 준다 — 번역 없이 그대로 서빙.
# relay 기본 응답은 "현재 이닝"만 담고, 지난 이닝은 ?inning=N 으로 따로 받아야 한다.
# textOptions.type → 프론트 표시용 의미 (네이버 숫자 코드를 UI 에 노출하지 않기 위함)
_RELAY_KIND = {
0: "inning", # 이닝 시작 ("1회초 한화 공격")
1: "pitch", # 투구 ("3구 헛스윙")
2: "sub", # 선수 교체
7: "note", # 투수판 이탈·비디오 판독·마운드 방문
8: "batter", # 타석 시작 (그룹 제목과 동일)
13: "result", # 타석 결과
23: "result", # 타석 결과 (주자 있을 때 표기)
14: "run", # 주루
24: "run", # 주루·홈인
99: "end", # 경기 종료·승리투수
}
# 라이브 페이로드에 싣는 최근 타석 수 — 전 이닝(약 80타석)을 매 폴링마다 보내지 않기 위한 상한
_RELAY_MAX_GROUPS = 40
# 지난 이닝 중계 캐시 (경기 → {이닝: 그룹[]}). 종료된 이닝은 불변이라 재조회하지 않는다.
_relay_innings: dict[str, dict[int, list[dict]]] = {}
def _score_total(gs: dict) -> int | None:
try:
return int(gs.get("homeScore") or 0) + int(gs.get("awayScore") or 0)
except (TypeError, ValueError):
return None
def _relay_commentary(groups: list[dict]) -> list[dict]:
"""relay 그룹 → 문자중계 [{inn, half, no, title, events[]}] (최신 타석 순).
득점 표시는 텍스트 패턴 대신 옵션마다 실린 currentGameState 의 점수 합 변화로
판정한다 — 홈런·적시타뿐 아니라 홈인·실책 득점·밀어내기까지 정확히 잡힌다.
"""
out: list[dict] = []
prev_total: int | None = None
for r in sorted(groups, key=lambda g: g.get("no") or 0):
title = (r.get("title") or "").strip()
if not title.strip("="): # 경기 종료 구분선 그룹 — 제목 없이 내용만
title = ""
events: list[dict] = []
for o in sorted(r.get("textOptions") or [], key=lambda o: o.get("seqno") or 0):
total = _score_total(o.get("currentGameState") or {})
scored = prev_total is not None and total is not None and total > prev_total
if total is not None:
prev_total = total
text = (o.get("text") or "").strip()
# 구분선("=====")·제목 중복 라인은 버린다
if not text or text == title or not text.strip("="):
continue
ev = {"kind": _RELAY_KIND.get(o.get("type"), "note"), "text": text}
if scored:
ev["score"] = True
events.append(ev)
# 이닝 헤더 그룹은 events 가 비지만 구분선으로 쓰이므로 남긴다
if not title and not events:
continue
out.append({
"inn": r.get("inn"),
"half": "B" if str(r.get("homeOrAway")) == "1" else "T",
"no": r.get("no"),
"title": title,
"events": events,
})
out.reverse()
# 종료된 경기는 폴링이 멈추므로 전 경기 중계를 그대로 준다(다시보기).
# 진행 중엔 20초마다 다시 실리므로 최근 타석만 — 스크롤 분량으로도 충분하다.
ended = any(e["kind"] == "end" for g in out for e in g["events"])
return out if ended else out[:_RELAY_MAX_GROUPS]
async def _kbo_relay_groups(client, m: Match, gid: str, t: dict) -> list[dict]:
"""전 이닝 문자중계 그룹. 이닝별 조회를 캐시와 병렬 조회로 채운다.
현재·직전 이닝은 매번 다시 받는다 — 기본 응답은 진행 중인 half 만 담을 때가 있고,
이닝이 넘어간 직후엔 직전 이닝 마지막 타석이 캐시에 안 들어와 있을 수 있다.
그보다 앞선 이닝은 더 변하지 않으므로 한 번만 받는다.
"""
cur_groups = t.get("textRelays") or []
cur = int(t.get("inn") or max((g.get("inn") or 0) for g in cur_groups) or 1)
if len(_relay_innings) > 40: # 하루치 경기 이상 쌓이면 통째로 비움
_relay_innings.clear()
cache = _relay_innings.setdefault(m.match_id, {})
volatile = {cur - 1, cur}
need = [i for i in range(1, cur + 1) if i in volatile or i not in cache]
if need:
res = await asyncio.gather(
*(
_naver_get(client, f"/schedule/games/{gid}/relay?inning={i}")
for i in need
),
return_exceptions=True,
)
for i, r in zip(need, res):
if isinstance(r, BaseException) or not r:
continue # 실패한 이닝은 기존 캐시 유지 → 다음 폴링에서 재시도
cache[i] = ((r.get("textRelayData") or {}).get("textRelays")) or []
cache.setdefault(cur, cur_groups) # 현재 이닝 조회 실패 시 기본 응답으로 대체
return [g for i in sorted(cache) for g in cache[i]]
# ── MLB 문자중계 (feed/live allPlays 규칙 기반 한글 변환) ──────
# MLB 중계문은 정형 영문 템플릿 — eventType·투구 호칭을 한글로 매핑하고
# 타구 방향·주자 진루는 정규식으로 뽑는다. 미지원 문장은 영문 원문 폴백.
_MLB_PITCH_KO = {
"Ball": "볼", "Ball In Dirt": "볼 (원바운드)", "Intent Ball": "고의사구 볼",
"Called Strike": "스트라이크", "Swinging Strike": "헛스윙",
"Swinging Strike (Blocked)": "헛스윙", "Foul": "파울", "Foul Tip": "파울팁",
"Foul Bunt": "번트 파울", "Missed Bunt": "번트 헛스윙",
"Hit By Pitch": "몸에 맞는 볼", "Pitchout": "피치아웃",
"Automatic Ball": "자동 볼 (피치클록)", "Automatic Strike": "자동 스트라이크 (피치클록)",
"In play, out(s)": "타격", "In play, no out": "타격", "In play, run(s)": "타격",
}
_MLB_EVENT_KO = {
"Single": "1루타", "Double": "2루타", "Triple": "3루타", "Home Run": "홈런",
"Walk": "볼넷", "Intent Walk": "고의4구", "Strikeout": "삼진 아웃",
"Strikeout Double Play": "삼진 (병살)", "Groundout": "땅볼 아웃",
"Flyout": "플라이 아웃", "Lineout": "직선타 아웃", "Pop Out": "팝플라이 아웃",
"Bunt Groundout": "번트 아웃", "Bunt Pop Out": "번트 팝플라이 아웃",
"Forceout": "포스 아웃", "Grounded Into DP": "병살타", "Double Play": "병살",
"Triple Play": "삼중살", "Sac Fly": "희생플라이", "Sac Bunt": "희생번트",
"Field Error": "실책 출루", "Fielders Choice": "야수선택",
"Fielders Choice Out": "야수선택 아웃", "Hit By Pitch": "몸에 맞는 볼",
"Catcher Interference": "포수 타격방해", "Runner Out": "주자 아웃",
"Caught Stealing 2B": "도루자 (2루)", "Caught Stealing 3B": "도루자 (3루)",
"Caught Stealing Home": "도루자 (홈)", "Pickoff 1B": "견제사 (1루)",
"Pickoff 2B": "견제사 (2루)", "Pickoff 3B": "견제사 (3루)",
}
# 타구 방향/처리 야수 — desc 에서 가장 먼저 나오는 표현 (긴 표현 우선 매칭)
_MLB_DIR_KO = [
("left fielder", "좌익수"), ("left field", "좌익수"),
("center fielder", "중견수"), ("center field", "중견수"),
("right fielder", "우익수"), ("right field", "우익수"),
("shortstop", "유격수"), ("first baseman", "1루수"),
("second baseman", "2루수"), ("third baseman", "3루수"),
("first base", "1루수"), ("second base", "2루수"), ("third base", "3루수"),
("pitcher", "투수"), ("catcher", "포수"),
]
# 대문자 시작 단어 연속 = 선수명 ("J.P. Crawford", "Wenceel Pérez").
# 마침표는 이니셜("J.P.")에만 허용 — 일반 단어 끝 마침표를 막아 문장 경계를 넘지 않게 한다.
_MLB_NAME_W = r"(?:(?:[A-ZÀ-Ý]\.)+|[A-ZÀ-Ý][\w'\-]*)"
_MLB_NAME = rf"{_MLB_NAME_W}(?: {_MLB_NAME_W})*"
_BASE_KO = {"2nd": "2루", "3rd": "3루", "home": "홈"}
def _mlb_direction(desc: str) -> str:
hits = [(desc.find(en), ko) for en, ko in _MLB_DIR_KO if en in desc]
return min(hits)[1] if hits else ""
def _mlb_runs(desc: str) -> list[dict]:
"""desc 의 주자 이동 문장 → run 이벤트 (홈인·진루·주루사)."""
out: list[dict] = []
for nm in re.findall(rf"({_MLB_NAME}) scores\b", desc):
out.append({"kind": "run", "text": f"{nm} : 홈인"})
for nm, base in re.findall(rf"({_MLB_NAME})(?: advances)? to (2nd|3rd)\b", desc):
out.append({"kind": "run", "text": f"{nm} : {_BASE_KO[base]}까지 진루"})
for nm, base in re.findall(rf"({_MLB_NAME}) out at (2nd|3rd|home)\b", desc):
out.append({"kind": "run", "text": f"{nm} : {_BASE_KO[base]}에서 아웃"})
seen: set[str] = set() # "to 3rd"+"advances to 3rd" 같은 중복 문장 제거
return [e for e in out if not (e["text"] in seen or seen.add(e["text"]))]
def _tr_mlb_result(res: dict, batter: str) -> str:
event, desc = res.get("event") or "", res.get("description") or ""
ko = _MLB_EVENT_KO.get(event)
if not ko: # 미지원 이벤트 — 영문 원문 폴백
return f"{batter} : {desc}" if desc else f"{batter} : {event}"
if event == "Strikeout":
if "called out on strikes" in desc:
ko += " (루킹)"
elif "strikes out swinging" in desc:
ko += " (헛스윙)"
direction = _mlb_direction(desc)
return f"{batter} : {direction} {ko}".replace(" ", " ").replace(" : ", " : ")
def _tr_mlb_action(det: dict) -> tuple[str, str] | None:
"""playEvents 액션 → (kind, text). None 이면 표시하지 않음 (노이즈)."""
event, desc = det.get("event") or "", det.get("description") or ""
if event in ("Game Advisory", "Batter Timeout") or not (event or desc):
return None
if event.startswith("Stolen Base"):
base = "2루" if event.endswith("2B") else "3루" if event.endswith("3B") else "홈"
nm = re.match(rf"({_MLB_NAME}) steals", desc)
who = nm.group(1) if nm else ""
return "run", f"{who} : 도루로 {base}까지 진루".replace(" ", " ")
if event.startswith("Caught Stealing"):
return "run", _MLB_EVENT_KO.get(event, "도루자")
if event == "Wild Pitch":
return "note", "폭투"
if event == "Passed Ball":
return "note", "포일"
if event == "Mound Visit":
return "note", "마운드 방문"
if event in ("Pitching Substitution", "Offensive Substitution",
"Defensive Sub", "Defensive Substitution"):
label = {
"Pitching Substitution": "투수 교체",
"Offensive Substitution": "대타" if "hitter" in desc else "대주자",
}.get(event, "수비 교체")
# "Pitching Change: A replaces B." / "...: Pinch-hitter A replaces
# right fielder B, batting 2nd..." → "{label} — B → A"
body = desc.split(": ", 1)[-1].rstrip(".")
if " replaces " in body:
new, old = body.split(" replaces ", 1)
new = re.sub(r"^Pinch-(?:hitter|runner) ", "", new)
old = re.sub(r"^[a-z][a-z ]* ", "", old) # 포지션 수식어 제거
old = old.split(", batting")[0].split(" because")[0]
return "sub", f"{label} — {old} → {new}"
return "sub", desc
if event == "Defensive Switch":
return None # 포지션 이동 — 중계 피드에선 노이즈
if desc.startswith("Pickoff Attempt"):
return "note", "견제 시도"
if desc.startswith("Pitcher Step Off"):
return None
return "note", desc or event # 미지원 액션 — 영문 폴백
def _transform_mlb_relay(feed: dict, m: Match) -> list[dict]:
"""allPlays → 문자중계 그룹 (KBO relay 와 동일 스키마, 최신 타석순)."""
plays = ((feed.get("liveData") or {}).get("plays") or {}).get("allPlays") or []
away_s = m.team_a_short or m.team_a_code
home_s = m.team_b_short or m.team_b_code
groups: list[dict] = []
prev_half: tuple | None = None
prev_total = 0
no = 0
for p in plays:
about = p.get("about") or {}
inn = about.get("inning")
top = about.get("halfInning") == "top"
if (inn, top) != prev_half: # 이닝 구분 헤더 (KBO 와 동일한 빈 그룹)
prev_half = (inn, top)
no += 1
groups.append({
"inn": inn, "half": "T" if top else "B", "no": no,
"title": f"{inn}회{'초' if top else '말'} {away_s if top else home_s} 공격",
"events": [],
})
events: list[dict] = []
for ev in p.get("playEvents") or []:
det = ev.get("details") or {}
if ev.get("isPitch"):
call = det.get("description") or ""
n = ev.get("pitchNumber")
ko = _MLB_PITCH_KO.get(call, call)
events.append({"kind": "pitch", "text": f"{n}구 {ko}" if n else ko})
else:
ke = _tr_mlb_action(det)
if ke:
events.append({"kind": ke[0], "text": ke[1]})
events += _mlb_runs(det.get("description") or "") # 폭투 득점 등
res = p.get("result") or {}
batter = ((p.get("matchup") or {}).get("batter") or {}).get("fullName") or ""
if res.get("event"):
events.append({"kind": "result", "text": _tr_mlb_result(res, batter)})
events += _mlb_runs(res.get("description") or "")
# 득점 판정 — 플레이 종료 시점 점수 합 변화 (KBO 와 동일 원리)
if about.get("isComplete"):
total = int(res.get("awayScore") or 0) + int(res.get("homeScore") or 0)
if total > prev_total:
marked = False
for e in events:
if e["text"].endswith("홈인"):
e["score"] = True
marked = True
if not marked and events: # 홈인 문장 미파싱 (솔로 홈런 등) — 결과 라인 강조
events[-1]["score"] = True
# 홈런은 타자 본인 득점이 홈인 문장에 없음 — 결과 라인도 강조
if res.get("event") == "Home Run":
for e in events:
if e["kind"] == "result":
e["score"] = True
prev_total = total
if not events:
continue
no += 1
groups.append({
"inn": inn, "half": "T" if top else "B", "no": no,
"title": batter, "events": events,
})
groups.reverse()
ended = ((feed.get("gameData") or {}).get("status") or {}).get(
"abstractGameState") == "Final"
return groups if ended else groups[:_RELAY_MAX_GROUPS]
def _transform_mlb_feed(feed: dict) -> dict:
ld = feed.get("liveData") or {}
ls = ld.get("linescore") or {}
box = (ld.get("boxscore") or {}).get("teams") or {}
half_top = (ls.get("inningHalf") or "").lower() == "top"
offense_side, defense_side = ("away", "home") if half_top else ("home", "away")
off = ls.get("offense") or {}
defn = ls.get("defense") or {}
def _players(side: str) -> dict:
return (box.get(side) or {}).get("players") or {}
# 수비 배치: boxscore players 의 position + 현재 출장(battingOrder 존재)
defense = []
for p in _players(defense_side).values():
pos = MLB_POS.get(((p.get("position") or {}).get("abbreviation") or ""))
name = ((p.get("person") or {}).get("fullName")) or ""
if pos and name and p.get("gameStatus", {}).get("isCurrentBatter") is not None:
defense.append({"pos": pos, "name": name})
# 같은 포지션 중복(교체) — 마지막 것만
dedup: dict[str, dict] = {f["pos"]: f for f in defense}
order_raw = (box.get(offense_side) or {}).get("battingOrder") or []
id_to_player = _players(offense_side)
lineup = []
for i, pid in enumerate(order_raw[:9]):
p = id_to_player.get(f"ID{pid}") or {}
lineup.append({
"order": i + 1,
"name": ((p.get("person") or {}).get("fullName")) or "",
"pos": MLB_POS.get(((p.get("position") or {}).get("abbreviation") or ""), ""),
"avg": None,
"sub": False,
})
batter_name = ((off.get("batter") or {}).get("fullName")) or ""
batter = next((b for b in lineup if b["name"] == batter_name), None)
pitcher = (defn.get("pitcher") or {}).get("fullName") or \
(off.get("pitcher") or {}).get("fullName") or ""
return {
"available": bool(ls.get("currentInning")),
"inn": ls.get("currentInning"),
"half": "T" if half_top else "B",
"score": {
"away": ((ls.get("teams") or {}).get("away") or {}).get("runs"),
"home": ((ls.get("teams") or {}).get("home") or {}).get("runs"),
},
"bso": {"b": ls.get("balls"), "s": ls.get("strikes"), "o": ls.get("outs")},
"bases": [bool(off.get("first")), bool(off.get("second")), bool(off.get("third"))],
"batter": batter or ({"order": None, "name": batter_name} if batter_name else None),
"pitcher": {"name": pitcher, "ballCount": None} if pitcher else None,
"vsRecord": "",
"defense": list(dedup.values()),
"offenseLineup": lineup,
}
async def fetch_live(m: Match) -> dict:
"""라이브 필드 뷰 페이로드 (리그별 소스). 미게시면 available=False."""
import httpx
cached = _live_cache.get(m.match_id)
if cached and time.monotonic() - cached[0] < _LIVE_TTL_SEC:
return cached[1]
payload: dict = {"available": False}
try:
if m.league == "kbo":
async with httpx.AsyncClient(timeout=10) as client:
found = await _naver_get_first_with_id(client, m, "relay")
gid, res = found if found else ("", None)
t = (res or {}).get("textRelayData")
if t:
payload = _transform_naver_relay(t)
try: # 문자중계는 부가 정보 — 실패해도 필드 뷰는 그대로 서빙
payload["relay"] = _relay_commentary(
await _kbo_relay_groups(client, m, gid, t)
)
except Exception as e: # noqa: BLE001
log.warning("kbo 문자중계 실패 %s: %s", m.match_id, e)
elif m.league == "mlb":
# gamePk 를 일정에서 재조회 — MLB 일정 API 의 date 는 미국 날짜라
# KST 기준 하루 전~당일 범위로 조회 후 dateKst 로 정확히 매칭.
kst = ensure_aware(m.kickoff_at).astimezone(KST)
date_kst = kst.strftime("%Y%m%d")
start = (kst.date() - timedelta(days=1)).isoformat()
async with httpx.AsyncClient(timeout=15) as c:
r = await c.get(
f"{settings.mlb_api_base}/v1/schedule?sportId=1"
f"&startDate={start}&endDate={kst.date().isoformat()}"
)
r.raise_for_status()
# 더블헤더 대응: 같은 날짜·팀쌍 경기를 시작시각순으로 모아
# match_id 의 차수(seq)에 해당하는 경기를 고른다.
cands: list[tuple[str, int]] = []
for day in r.json().get("dates") or []:
for g in day.get("games") or []:
a = MLB_ID_TO_CODE.get((g["teams"]["away"]["team"] or {}).get("id"))
b = MLB_ID_TO_CODE.get((g["teams"]["home"]["team"] or {}).get("id"))
gd = g.get("gameDate")
if not a or not b or not gd:
continue
g_kst = (
datetime.fromisoformat(gd.replace("Z", "+00:00"))
.astimezone(KST).strftime("%Y%m%d")
)
if a == m.team_a_code and b == m.team_b_code and g_kst == date_kst:
cands.append((gd, g.get("gamePk")))
cands.sort()
idx = match_seq(m.match_id) - 1
pk = cands[idx][1] if idx < len(cands) else None
if pk:
r2 = await c.get(f"{settings.mlb_api_base}/v1.1/game/{pk}/feed/live")
r2.raise_for_status()
feed = r2.json()
payload = _transform_mlb_feed(feed)
try: # 문자중계는 부가 정보 — 실패해도 필드 뷰는 그대로 서빙
relay = _transform_mlb_relay(feed, m)
if relay:
payload["relay"] = relay
payload["available"] = True # 종료 경기 다시보기 지원
except Exception as e: # noqa: BLE001
log.warning("mlb 문자중계 실패 %s: %s", m.match_id, e)
except Exception as e: # noqa: BLE001
log.warning("live 실패 %s: %s", m.match_id, e)
payload = {"available": False}
_live_cache[m.match_id] = (time.monotonic(), payload)
return payload
+155
View File
@@ -0,0 +1,155 @@
"""야구 일정·결과 수집 — KBO(네이버 비공식) + MLB(공식 Stats API).
반환 표준 레코드 (두 리그 공통):
{league, teamA(원정), teamB(홈), dateKst 'YYYYMMDD', kickoffKst ISO(+09:00),
venue, cancelled, [scoreA, scoreB]}
야구는 같은 두 팀이 시즌 내 반복 대결 → 경기 식별에 반드시 dateKst 포함.
"""
from __future__ import annotations
import logging
from datetime import datetime, timedelta, timezone
from ..config import settings
from ..teams_baseball import KBO_TEAMS, MLB_ID_TO_CODE
log = logging.getLogger("triplepick.baseball")
KST = timezone(timedelta(hours=9))
UA = {
"User-Agent": (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/126.0 Safari/537.36"
)
}
# ── KBO (네이버) ───────────────────────────────────────────────
async def _fetch_kbo(days_back: int, days_ahead: int) -> list[dict]:
import httpx
today = datetime.now(KST).date()
url = (
f"{settings.naver_api_base}/schedule/games"
"?fields=basic,stadium,statusNum"
"&upperCategoryId=kbaseball&categoryId=kbo"
f"&fromDate={(today - timedelta(days=days_back)).isoformat()}"
f"&toDate={(today + timedelta(days=days_ahead)).isoformat()}&size=500"
)
async with httpx.AsyncClient(timeout=20) as c:
r = await c.get(url, headers=UA)
r.raise_for_status()
games = (r.json().get("result") or {}).get("games") or []
out: list[dict] = []
for g in games:
a = (g.get("awayTeamCode") or "").upper()
b = (g.get("homeTeamCode") or "").upper()
if a not in KBO_TEAMS or b not in KBO_TEAMS:
continue # 올스타/시범 등 제외
dt = g.get("gameDateTime") # KST, 오프셋 없음
if not dt:
continue
kickoff = datetime.fromisoformat(dt).replace(tzinfo=KST)
rec = {
"league": "kbo",
"teamA": a, "teamB": b,
"dateKst": kickoff.strftime("%Y%m%d"),
"kickoffKst": kickoff.isoformat(),
"venue": g.get("stadium", ""),
"cancelled": bool(g.get("cancel")),
}
if g.get("statusCode") == "RESULT" and not rec["cancelled"]:
sa, sb = g.get("awayTeamScore"), g.get("homeTeamScore")
if sa is not None and sb is not None:
rec["scoreA"], rec["scoreB"] = int(sa), int(sb)
out.append(rec)
return out
# ── MLB (공식 Stats API) ───────────────────────────────────────
async def _fetch_mlb(days_back: int, days_ahead: int) -> list[dict]:
import httpx
today = datetime.now(KST).date()
url = (
f"{settings.mlb_api_base}/v1/schedule?sportId=1"
f"&startDate={(today - timedelta(days=days_back)).isoformat()}"
f"&endDate={(today + timedelta(days=days_ahead)).isoformat()}"
)
async with httpx.AsyncClient(timeout=20) as c:
r = await c.get(url)
r.raise_for_status()
data = r.json()
out: list[dict] = []
for day in data.get("dates") or []:
for g in day.get("games") or []:
a = MLB_ID_TO_CODE.get((g["teams"]["away"]["team"] or {}).get("id"))
b = MLB_ID_TO_CODE.get((g["teams"]["home"]["team"] or {}).get("id"))
if not a or not b:
continue # 올스타전 등 제외
gd = g.get("gameDate") # ISO UTC
if not gd:
continue
kickoff = (
datetime.fromisoformat(gd.replace("Z", "+00:00")).astimezone(KST)
)
status_obj = g.get("status") or {}
# detailedState 는 "Final"/"Game Over"/"Completed Early"(우천 조기종료) 등
# 종료를 뜻하는 문자열이 여러 갈래라 그것만으로 판정하면 일부가 누락된다.
# abstractGameState 는 Preview/Live/Final 세 값만 존재하는 신뢰 가능한 판정 기준.
abstract = status_obj.get("abstractGameState", "")
detailed = status_obj.get("detailedState", "")
rec = {
"league": "mlb",
"teamA": a, "teamB": b,
"dateKst": kickoff.strftime("%Y%m%d"),
"kickoffKst": kickoff.isoformat(),
"venue": (g.get("venue") or {}).get("name", ""),
# 연기·취소 경기도 abstractGameState 는 "Final" 로 온다(스코어 없음) —
# 취소 여부는 abstract 와 무관하게 detailedState 로만 판정한다.
"cancelled": detailed.startswith(
("Postponed", "Cancelled", "Suspended")
),
"gamePk": g.get("gamePk"), # MLB 라이브 피드 키
}
if abstract == "Final" and not rec["cancelled"]:
sa = g["teams"]["away"].get("score")
sb = g["teams"]["home"].get("score")
if sa is not None and sb is not None:
rec["scoreA"], rec["scoreB"] = int(sa), int(sb)
out.append(rec)
return out
# ── 공개 API ────────────────────────────────────────────────────
async def fetch_baseball_schedule(league: str, days_back: int | None = None) -> list[dict]:
"""리그 일정+결과 수집 (취소 포함). 실패 시 빈 리스트 — 기존 일정 유지.
days_back 기본값은 result_recheck_days(짧은 재확인 윈도우). settle_baseball 은
미정산 경기 중 가장 오래된 날짜를 덮도록 더 큰 값을 넘겨, 오래 방치된
미정산 경기(수집 실패 등으로 첫 정산을 놓친 경기)도 결국 잡히게 한다.
"""
days_back = settings.result_recheck_days if days_back is None else days_back
try:
if league == "kbo":
records = await _fetch_kbo(days_back, settings.baseball_days_ahead)
elif league == "mlb":
records = await _fetch_mlb(days_back, settings.baseball_days_ahead)
else:
return []
# 더블헤더 차수 부여 — sync·정산이 같은 seq 로 경기를 식별한다.
from .baseball_sync import assign_seq
assign_seq(records)
log.info("baseball schedule(%s): %d경기 수집", league, len(records))
return records
except Exception as e: # noqa: BLE001
log.error("baseball schedule(%s) 실패: %s — 기존 일정 유지", league, e)
return []
async def fetch_baseball_results(league: str, days_back: int | None = None) -> list[dict]:
"""확정 스코어만 → [{league, teamA, teamB, dateKst, scoreA, scoreB}]."""
return [r for r in await fetch_baseball_schedule(league, days_back) if "scoreA" in r]
+130
View File
@@ -0,0 +1,130 @@
"""야구 일정 DB 반영 — (리그, KST 날짜, 팀쌍, 차수) 키 매칭. 워커가 매일 호출.
- 기존 경기: 키 매칭 → 시각/venue/투표시간 갱신 (결과·예측·crowd 보존)
- 신규 경기: 삽입 + crowd 초기화.
match_id = {LEAGUE}_{away}_{home}_{yyyymmdd} (더블헤더 2차전은 _2 접미)
- 취소(우천 등): 삭제하지 않고 status="cancelled" 로 보존 — 투표·예측 기록 유지,
정산·투표·AI 생성에서 제외. 소스가 취소를 번복하면 scheduled 로 복귀.
(보강 경기는 새 날짜의 신규 경기로 재등장)
- 더블헤더: 같은 (날짜, 팀쌍) 복수 경기를 시작시각순 seq(1,2)로 구분해 모두 등록.
- 투표창: 리그 공통 오픈 오프셋(vote_open_hours_before, 기본 -168h)
"""
from __future__ import annotations
import logging
from datetime import datetime, timedelta, timezone
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from ..config import settings
from ..models import CrowdStats, Match
from ..teams_baseball import team_info
log = logging.getLogger("triplepick.baseball")
KST = timezone(timedelta(hours=9))
def baseball_opens_at(kickoff: datetime) -> datetime:
# 축구와 동일 정책(vote_open_hours_before=168h) — 야구는 일정을 7일치만
# 수집하므로 사실상 동기화 즉시 투표 오픈된다.
return kickoff - timedelta(hours=settings.vote_open_hours_before)
def baseball_lock_at(kickoff: datetime) -> datetime:
return kickoff - timedelta(minutes=settings.vote_lock_minutes_before)
def _date_of(m: Match) -> str:
return m.kickoff_at.astimezone(KST).strftime("%Y%m%d") if m.kickoff_at else ""
def match_seq(match_id: str) -> int:
"""match_id 의 더블헤더 차수. `..._20260722` → 1, `..._20260722_2` → 2."""
tail = match_id.rsplit("_", 1)[-1]
return int(tail) if len(tail) <= 2 and tail.isdigit() else 1
def assign_seq(records: list[dict]) -> None:
"""같은 (날짜, 팀쌍) 레코드에 시작시각순 seq(1,2,…)를 부여 — 더블헤더 구분."""
groups: dict[tuple, list[dict]] = {}
for rec in records:
groups.setdefault((rec["dateKst"], rec["teamA"], rec["teamB"]), []).append(rec)
for recs in groups.values():
recs.sort(key=lambda r: r["kickoffKst"])
for i, rec in enumerate(recs, start=1):
rec["seq"] = i
async def sync_baseball_schedule(
db: AsyncSession, league: str, records: list[dict]
) -> dict:
if not records:
return {"updated": 0, "inserted": 0, "skipped": 0, "removed": 0}
assign_seq(records)
existing = (
await db.execute(select(Match).where(Match.league == league))
).scalars().all()
by_key: dict[tuple, Match] = {}
for m in existing:
d, s = _date_of(m), match_seq(m.match_id)
by_key[(d, m.team_a_code, m.team_b_code, s)] = m
by_key[(d, m.team_b_code, m.team_a_code, s)] = m
updated = inserted = skipped = removed = 0
for rec in records:
a, b, d = rec["teamA"], rec["teamB"], rec["dateKst"]
seq = rec.get("seq", 1)
m = by_key.get((d, a, b, seq))
if rec.get("cancelled"):
# 소프트 취소 — 투표/예측 기록 보존, 정산·투표·AI 대상에서 제외.
if m is not None and m.result_outcome is None and m.status != "cancelled":
m.status = "cancelled"
removed += 1
continue
kickoff = datetime.fromisoformat(rec["kickoffKst"]).astimezone(timezone.utc)
if m is not None:
if m.result_outcome is not None:
skipped += 1
continue
if m.status == "cancelled":
m.status = "scheduled" # 취소 번복 — 시간 기준 상태는 tick 이 복원
m.kickoff_at = kickoff
m.opens_at = baseball_opens_at(kickoff)
m.lock_at = baseball_lock_at(kickoff)
if rec.get("venue"):
m.venue = rec["venue"]
updated += 1
else:
ta, tb = team_info(league, a), team_info(league, b)
match_id = f"{league.upper()}_{a}_{b}_{d}" + (f"_{seq}" if seq > 1 else "")
new = Match(
match_id=match_id,
league=league,
round_label="정규시즌",
group="",
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']}",
kickoff_at=kickoff,
opens_at=baseball_opens_at(kickoff),
lock_at=baseball_lock_at(kickoff),
status="scheduled",
)
db.add(new)
db.add(CrowdStats(match_id=match_id, total=0, team_a_win=0, draw=0, team_b_win=0))
by_key[(d, a, b, seq)] = new
by_key[(d, b, a, seq)] = new
inserted += 1
await db.commit()
result = {"updated": updated, "inserted": inserted, "skipped": skipped, "removed": removed}
log.info("baseball sync(%s): %s", league, result)
return result
+4 -1
View File
@@ -32,8 +32,11 @@ async def apply_result(db: AsyncSession, match: Match, score_a: int, score_b: in
) )
).scalars().all() ).scalars().all()
baseball = match.league in ("kbo", "mlb")
for p in picks: for p in picks:
key, value = grade_prediction(p.score_a, p.score_b, score_a, score_b) key, value = grade_prediction(
p.score_a, p.score_b, score_a, score_b, baseball=baseball
)
p.points = value p.points = value
p.scored_at = now_utc() p.scored_at = now_utc()
+742
View File
@@ -0,0 +1,742 @@
"""MLS 데이터 — ESPN 비공식 API (일정·결과·순위·프리뷰·라이브).
ESPN site API 는 키 불필요·비공식. 응답 표준 레코드는 야구와 동일 형태
({league, teamA(원정), teamB(홈), dateKst, kickoffKst, venue, cancelled,
[scoreA, scoreB]})라 sync_baseball_schedule/settle 파이프라인을 그대로 탄다.
- 일정: scoreboard?dates=YYYYMMDD 또는 YYYYMM (범위 조회는 ESPN 이 400 반환 →
_fetch_events 가 일/월 단위로 분할. dates 는 미국 동부 기준 날짜라
KST 매칭은 이벤트의 UTC 시각을 KST 로 환산해 산출)
- 순위: 동부/서부 컨퍼런스 → standings:mls 캐시 (승점제)
- 프리뷰: scoreboard 의 form(최근5)·records(시즌 W-D-L)·odds(머니라인)
+ summary 의 headToHeadGames(맞대결 최근 5) → preview:{match_id} 캐시.
odds 는 AI 프롬프트 참고용으로만 쓰고 UI 에는 노출하지 않는다.
- 라이브: scoreboard 이벤트의 clock·스코어·득점 이벤트(details) — 15초 TTL
"""
from __future__ import annotations
import logging
import re
import time
import unicodedata
from datetime import date, datetime, timedelta, timezone
from difflib import SequenceMatcher
from ..config import settings
from ..domain import ensure_aware, now_utc
from ..models import DataCache, Match
from ..teams_mls import MLS_ID_TO_CODE, MLS_TEAMS
log = logging.getLogger("triplepick.mls")
KST = timezone(timedelta(hours=9))
# 주의: ESPN 은 브라우저 위장 UA(풀 Chrome 문자열)를 보내면 WAF 가 403 으로 차단한다
# (TLS 핑거프린트와 UA 불일치 감지로 추정). httpx 기본 UA 로 보내야 통과 — 헤더 없이 호출.
# 취소로 취급하는 ESPN 상태 (연기 포함 — 보강 일정이 새 이벤트로 재등장)
_CANCEL_STATUS = {"STATUS_POSTPONED", "STATUS_CANCELED", "STATUS_ABANDONED"}
def _sb_url(dates: str) -> str:
return (
f"{settings.espn_api_base}/site/v2/{settings.espn_mls_path}"
f"/scoreboard?dates={dates}&limit=200"
)
def _summary_url(event_id: str) -> str:
return (
f"{settings.espn_api_base}/site/v2/{settings.espn_mls_path}"
f"/summary?event={event_id}"
)
def _standings_url() -> str:
return f"{settings.espn_api_base}/v2/{settings.espn_mls_path}/standings"
def _parse_event(e: dict) -> dict | None:
"""scoreboard 이벤트 1건 → 표준 레코드 (+espnId·form·records·odds 원본)."""
comp = (e.get("competitions") or [{}])[0]
sides: dict[str, dict] = {}
for t in comp.get("competitors") or []:
sides[t.get("homeAway", "")] = t
away, home = sides.get("away"), sides.get("home")
if not away or not home:
return None
a = (away.get("team") or {}).get("abbreviation", "")
b = (home.get("team") or {}).get("abbreviation", "")
if a not in MLS_TEAMS or b not in MLS_TEAMS:
return None # 올스타전 등 제외
gd = e.get("date")
if not gd:
return None
kickoff = datetime.fromisoformat(gd.replace("Z", "+00:00")).astimezone(KST)
stype = (e.get("status") or {}).get("type") or {}
rec: dict = {
"league": "mls",
"teamA": a, "teamB": b,
"dateKst": kickoff.strftime("%Y%m%d"),
"kickoffKst": kickoff.isoformat(),
"venue": ((comp.get("venue") or {}).get("fullName")) or "",
"cancelled": stype.get("name") in _CANCEL_STATUS,
"espnId": e.get("id"),
"_away": away, "_home": home, "_comp": comp, "_status": e.get("status"),
}
if stype.get("state") == "post" and stype.get("completed") and not rec["cancelled"]:
sa, sb = away.get("score"), home.get("score")
if sa is not None and sb is not None:
rec["scoreA"], rec["scoreB"] = int(sa), int(sb)
return rec
# ESPN scoreboard 는 날짜 범위(dates=YYYYMMDD-YYYYMMDD) 조회에 400 을 반환한다
# (2026-09 중순부터). 단일 날짜(YYYYMMDD)·월(YYYYMM) 조회는 정상이라, 범위를
# 짧으면 일 단위·길면 월 단위 조회로 쪼갠 뒤 범위 밖 이벤트를 걸러낸다.
_DAILY_QUERY_MAX_DAYS = 3
def _split_span(dates: str) -> tuple[list[str], date, date]:
"""'YYYYMMDD-YYYYMMDD' → (ESPN dates 쿼리 목록, 시작일, 종료일)."""
start_s, _, end_s = dates.partition("-")
start = datetime.strptime(start_s, "%Y%m%d").date()
end = datetime.strptime(end_s or start_s, "%Y%m%d").date()
span_days = (end - start).days + 1
if span_days <= _DAILY_QUERY_MAX_DAYS:
queries = [
(start + timedelta(days=i)).strftime("%Y%m%d") for i in range(span_days)
]
else:
queries = []
y, mth = start.year, start.month
while (y, mth) <= (end.year, end.month):
queries.append(f"{y}{mth:02d}")
y, mth = (y + 1, 1) if mth == 12 else (y, mth + 1)
return queries, start, end
async def _fetch_events(client, dates: str) -> list[dict]:
queries, start, end = _split_span(dates)
# ESPN dates 는 미국 동부 날짜 — 이벤트의 UTC 날짜는 당일 또는 다음 날.
last_utc_day = end + timedelta(days=1)
seen: set[str] = set()
out = []
for q in queries:
r = await client.get(_sb_url(q))
r.raise_for_status()
for e in r.json().get("events") or []:
eid, gd = e.get("id"), e.get("date")
if not gd or eid in seen:
continue
utc_day = datetime.fromisoformat(gd.replace("Z", "+00:00")).date()
if not start <= utc_day <= last_utc_day:
continue
seen.add(eid)
rec = _parse_event(e)
if rec:
out.append(rec)
return out
def _clean(rec: dict) -> dict:
"""sync/정산에 넘길 때 원본 참조 필드 제거."""
return {k: v for k, v in rec.items() if not k.startswith("_")}
async def fetch_mls_schedule(days_back: int | None = None) -> list[dict]:
"""일정+결과 수집 (취소 포함). 실패 시 빈 리스트 — 기존 일정 유지.
days_back 기본값은 mls_days_back. settle_baseball 이 미정산 경기 중
가장 오래된 날짜를 덮도록 더 큰 값을 넘길 수 있다(오래 방치된 미정산 경기 구제).
"""
import httpx
today = datetime.now(KST).date()
# 시작 = 백필 윈도우(주말 위주 편성 공백 방지). ESPN dates 는 미국 동부 날짜라
# KST 범위를 놓치지 않게 하루 여유를 둔다.
start = today - timedelta(days=(days_back if days_back is not None else settings.mls_days_back) + 1)
end = today + timedelta(days=settings.baseball_days_ahead)
try:
async with httpx.AsyncClient(timeout=20) as c:
records = await _fetch_events(
c, f"{start.strftime('%Y%m%d')}-{end.strftime('%Y%m%d')}"
)
records = [_clean(r) for r in records]
from .baseball_sync import assign_seq
assign_seq(records) # MLS 는 더블헤더가 없어 전부 seq=1 이지만 키 일관성 유지
log.info("mls schedule: %d경기 수집", len(records))
return records
except Exception as e: # noqa: BLE001
log.error("mls schedule 실패: %s — 기존 일정 유지", e)
return []
async def fetch_mls_results(days_back: int | None = None) -> list[dict]:
"""확정 스코어만 → 정산(settle) 입력."""
return [r for r in await fetch_mls_schedule(days_back) if "scoreA" in r]
# ── 순위 (동/서부 컨퍼런스, 승점제) ─────────────────────────────
_CONF_KEY = {"Eastern Conference": "EAST", "Western Conference": "WEST"}
async def _refresh_standings(db) -> bool:
import httpx
table: dict[str, dict] = {}
try:
async with httpx.AsyncClient(timeout=15) as c:
r = await c.get(_standings_url())
r.raise_for_status()
data = r.json()
for conf in data.get("children") or []:
key = _CONF_KEY.get(conf.get("name", ""), conf.get("abbreviation", ""))
for ent in ((conf.get("standings") or {}).get("entries")) or []:
code = (ent.get("team") or {}).get("abbreviation", "")
if code not in MLS_TEAMS:
continue
stats = {s.get("name"): s for s in ent.get("stats") or []}
def _v(name: str): # noqa: ANN202
s = stats.get(name) or {}
return s.get("value") if s.get("value") is not None else s.get("displayValue")
table[code] = {
"div": key,
"rank": int(_v("rank") or 0) or None,
"gp": int(_v("gamesPlayed") or 0),
"w": int(_v("wins") or 0),
"d": int(_v("ties") or 0),
"l": int(_v("losses") or 0),
"pts": int(_v("points") or 0),
"gf": int(_v("pointsFor") or 0),
"ga": int(_v("pointsAgainst") or 0),
"diff": (stats.get("pointDifferential") or {}).get("displayValue"),
}
except Exception as e: # noqa: BLE001
log.warning("mls standings 실패: %s", e)
return False
if not table:
return False
row = await db.get(DataCache, "standings:mls")
if row:
row.payload = table
row.fetched_at = now_utc()
else:
db.add(DataCache(key="standings:mls", payload=table, fetched_at=now_utc()))
return True
# ── 프리뷰 (폼·시즌 성적·맞대결·머니라인) ──────────────────────
def _odds_of(comp: dict) -> dict | None:
"""scoreboard odds → {home, draw, away, provider} (없으면 None)."""
o = (comp.get("odds") or [{}])[0] or {} # odds: [null] 인 경기도 있음
ml = o.get("moneyline") or {}
def _pick(side: dict | None) -> str | None:
if not side:
return None
for k in ("current", "close", "open"):
v = (side.get(k) or {}).get("odds")
if v and v != "OFF":
return str(v)
return None
home, away = _pick(ml.get("home")), _pick(ml.get("away"))
draw = _pick(ml.get("draw")) or (
str((o.get("drawOdds") or {}).get("moneyLine") or "") or None
)
if not (home or away or draw):
return None
return {
"home": home, "draw": draw, "away": away,
"provider": ((o.get("provider") or {}).get("displayName")) or "",
}
def _h2h_of(summary: dict) -> list[dict]:
"""summary.headToHeadGames → 최근 맞대결 [{date, home, away, scoreH, scoreA}]."""
out: list[dict] = []
for grp in summary.get("headToHeadGames") or []:
for ev in grp.get("events") or []:
h = MLS_ID_TO_CODE.get(int(ev.get("homeTeamId") or 0))
a = MLS_ID_TO_CODE.get(int(ev.get("awayTeamId") or 0))
sh, sa = ev.get("homeTeamScore"), ev.get("awayTeamScore")
if not h or not a or sh is None or sa is None:
continue
out.append({
"date": (ev.get("gameDate") or "")[:10],
"home": h, "away": a,
"scoreH": int(sh), "scoreA": int(sa),
})
break # 첫 그룹(상대팀 기준)만
return out[:5]
async def _refresh_previews(db, matches: list[Match]) -> int:
import httpx
if not matches:
return 0
dates = sorted({ensure_aware(m.kickoff_at).astimezone(KST).date() for m in matches})
span = f"{(dates[0] - timedelta(days=1)).strftime('%Y%m%d')}-{dates[-1].strftime('%Y%m%d')}"
n = 0
async with httpx.AsyncClient(timeout=20) as c:
events = await _fetch_events(c, span)
by_key = {(r["dateKst"], r["teamA"], r["teamB"]): r for r in events}
for m in matches:
d = ensure_aware(m.kickoff_at).astimezone(KST).strftime("%Y%m%d")
rec = by_key.get((d, m.team_a_code, m.team_b_code))
if not rec:
continue
payload: dict = {
"formA": (rec["_away"].get("form")) or None, # 최근5 "WWLDW"
"formB": (rec["_home"].get("form")) or None,
"recordA": next( # 시즌 전적 "8-2-4" (W-L-D)
(r.get("summary") for r in rec["_away"].get("records") or []
if r.get("type") == "total"), None),
"recordB": next(
(r.get("summary") for r in rec["_home"].get("records") or []
if r.get("type") == "total"), None),
"odds": _odds_of(rec["_comp"]),
}
try: # 맞대결(h2h)은 summary 1콜 — 실패해도 나머지 프리뷰는 유지
r2 = await c.get(_summary_url(rec["espnId"]))
r2.raise_for_status()
payload["h2h"] = _h2h_of(r2.json())
except Exception as e: # noqa: BLE001
log.warning("mls summary 실패 %s: %s", m.match_id, e)
if any(v for v in payload.values()):
row = await db.get(DataCache, f"preview:{m.match_id}")
if row:
row.payload = payload
row.fetched_at = now_utc()
else:
db.add(DataCache(
key=f"preview:{m.match_id}", payload=payload,
fetched_at=now_utc(),
))
n += 1
return n
async def refresh_mls_details(db, matches: list[Match]) -> None:
"""임박(48h 내) 미종료 경기 프리뷰 + 컨퍼런스 순위 캐시 갱신."""
horizon = now_utc() + timedelta(hours=48)
targets = [
m for m in matches
if m.result_outcome is None
and m.status != "cancelled"
and ensure_aware(m.kickoff_at) <= horizon
]
n = await _refresh_previews(db, targets)
await _refresh_standings(db)
await db.commit()
log.info("mls details: 프리뷰 %d경기 캐싱", n)
# ── AI 예측 프롬프트 데이터 블록 ────────────────────────────────
async def build_mls_data_block(db, match: Match) -> str | None:
"""자체 DB 축적 결과(폼·상대전적) + ESPN 프리뷰(폼·시즌·맞대결·배당) 결합."""
from .baseball_data import _h2h_line, _team_games, _team_lines
ga = await _team_games(db, "mls", match.team_a_code, match.kickoff_at)
gb = await _team_games(db, "mls", match.team_b_code, match.kickoff_at)
lines: list[str] = []
prev = await db.get(DataCache, f"preview:{match.match_id}")
p = prev.payload if prev else {}
if p.get("formA") or p.get("recordA"):
lines.append(
f"[{match.team_a_short} season] record {p.get('recordA') or '?'} (W-L-D), "
f"last5 {p.get('formA') or '?'}"
)
if p.get("formB") or p.get("recordB"):
lines.append(
f"[{match.team_b_short} season] record {p.get('recordB') or '?'} (W-L-D), "
f"last5 {p.get('formB') or '?'}"
)
if p.get("h2h"):
h2h = "; ".join(
f"{g['away']} {g['scoreA']}-{g['scoreH']} {g['home']} (away-home, {g['date']})"
for g in p["h2h"]
)
lines.append(f"[Recent head-to-head] {h2h}")
if p.get("odds"):
o = p["odds"]
lines.append(
f"[Bookmaker moneyline ({o.get('provider')})] "
f"home {o.get('home') or '?'} / draw {o.get('draw') or '?'} / "
f"away {o.get('away') or '?'} (American odds; use as market signal)"
)
st_row = await db.get(DataCache, "standings:mls")
if st_row:
for code, name in (
(match.team_a_code, match.team_a_short),
(match.team_b_code, match.team_b_short),
):
st = st_row.payload.get(code)
if st:
lines.append(
f"[{name} standings] {st.get('div')} rank {st.get('rank')}, "
f"{st.get('w')}W-{st.get('d')}D-{st.get('l')}L, "
f"{st.get('pts')}pts, GF {st.get('gf')} GA {st.get('ga')}"
)
if not ga and not gb and not lines:
return None
h2h_db = await _h2h_line(db, "mls", match.team_a_code, match.team_b_code, match.kickoff_at)
return "\n".join([
"=== MATCH DATA (factual; weigh heavily over priors) ===",
"Away " + _team_lines(match.team_a_name, ga),
"Home " + _team_lines(match.team_b_name, gb),
f"[Head-to-head in our data] {h2h_db}",
*lines,
"===",
])
# ── 문자중계 한글 번역 (규칙 기반) ─────────────────────────────
# ESPN 중계 문장은 정형 템플릿이라 정규식으로 한국어 요약 변환. 매칭 실패 시 원문.
# 선수명은 영문 유지, 팀 풀네임은 한글 축약으로 치환.
_TEAM_EN2KO: dict[str, str] = {
**{v["en"]: v["short"] for v in MLS_TEAMS.values()},
# ESPN 표기가 우리 en 값과 다른 팀 별칭
"Red Bull New York": "레드불스",
"Vancouver Whitecaps": "밴쿠버",
"St. Louis City SC": "세인트루이스",
}
_ATTEMPT_LABEL = {"missed": "슛 빗나감", "blocked": "슛 차단", "saved": "슛 (GK 선방)"}
# ESPN 팀 표기(중계 원문) → 팀 코드 — 교체 이벤트 팀 매칭용
_TEAM_EN2CODE: dict[str, str] = {
**{v["en"]: k for k, v in MLS_TEAMS.items()},
"Red Bull New York": "RBNY",
"Vancouver Whitecaps": "VAN",
"St. Louis City SC": "STL",
}
def _ko_teams(s: str) -> str:
for en, ko in _TEAM_EN2KO.items():
s = s.replace(en, ko)
return s
def _tr_commentary(text: str) -> str: # noqa: PLR0911
t = text.strip()
if t in ("First Half begins.", "First Half Kicks Off."):
return "전반전 시작"
if t.startswith("Second Half begins"):
return "후반전 시작"
m = re.match(r"^First Half ends, (.+)\.$", t)
if m:
return f"전반전 종료 — {_ko_teams(m.group(1))}"
m = re.match(r"^Match ends, (.+)\.$", t)
if m:
return f"경기 종료 — {_ko_teams(m.group(1))}"
m = re.match(r"^Second Half ends, (.+)\.$", t)
if m:
return f"후반전 종료 — {_ko_teams(m.group(1))}"
m = re.match(r"^Goal!\s+(.+?) (\d+), (.+?) (\d+)\.\s*(.+?) \((.+?)\)(.*)$", t)
if m:
t1, s1, t2, s2, player, team, rest = m.groups()
tag = " (PK)" if "penalty" in rest else " (헤딩)" if "header" in rest else ""
return (
f"골! {_ko_teams(t1)} {s1} : {s2} {_ko_teams(t2)} — "
f"{player} ({_ko_teams(team)}){tag}"
)
m = re.match(r"^Own Goal by (.+?), (.+?) (\d+), (.+?) (\d+)\.", t)
if m:
og, t1, s1, t2, s2 = m.groups()
return f"자책골 — {_ko_teams(og)} · {_ko_teams(t1)} {s1} : {s2} {_ko_teams(t2)}"
m = re.match(r"^Attempt (missed|blocked|saved)\.\s*(.+?) \((.+?)\)(.*)$", t)
if m:
kind, player, team, rest = m.groups()
head = "헤딩 " if "header" in rest else ""
am = re.search(r"Assisted by ([^.]+?)(?: with| following|\.|$)", rest)
assist = f" · 도움 {am.group(1).strip()}" if am else ""
return f"{head}{_ATTEMPT_LABEL[kind]} — {player} ({_ko_teams(team)}){assist}"
m = re.match(r"^(.+?) \((.+?)\) hits the (left post|right post|bar|crossbar)(.*)$", t)
if m:
return f"골대! — {m.group(1)} ({_ko_teams(m.group(2))})"
m = re.match(r"^Foul by (.+?) \((.+?)\)\.$", t)
if m:
return f"파울 — {m.group(1)} ({_ko_teams(m.group(2))})"
m = re.match(r"^(.+?) \((.+?)\) wins a free kick (.+)\.$", t)
if m:
return f"프리킥 획득 — {m.group(1)} ({_ko_teams(m.group(2))})"
m = re.match(r"^(.+?) \((.+?)\) is shown the (yellow|red) card(.*)\.$", t)
if m:
card = "옐로카드" if m.group(3) == "yellow" else "레드카드"
return f"{card} — {m.group(1)} ({_ko_teams(m.group(2))})"
m = re.match(
r"^Substitution, (.+?)\.\s*(.+?) replaces (.+?)( because of [^.]*)?\.$", t
)
if m:
inj = " (부상)" if m.group(4) else ""
return f"교체 ({_ko_teams(m.group(1))}) — IN {m.group(2)} · OUT {m.group(3)}{inj}"
m = re.match(r"^Corner,\s+(.+?)\. Conceded by (.+?)\.$", t)
if m:
return f"코너킥 — {_ko_teams(m.group(1))}"
m = re.match(r"^Offside, (.+?)\.(.*)$", t)
if m:
return f"오프사이드 — {_ko_teams(m.group(1))}"
m = re.match(r"^Hand ball by (.+?) \((.+?)\)\.$", t)
if m:
return f"핸드볼 — {m.group(1)} ({_ko_teams(m.group(2))})"
m = re.match(r"^Penalty conceded by (.+?) \((.+?)\)(.*)$", t)
if m:
return f"페널티 유발 — {m.group(1)} ({_ko_teams(m.group(2))})"
m = re.match(r"^Penalty (.+?)\. (.+?) draws a foul(.*)$", t)
if m:
return f"페널티 획득 — {_ko_teams(m.group(1))} ({m.group(2)})"
if t.startswith("Delay in match"):
return "경기 지연"
if t.startswith("Delay over"):
return "경기 재개"
m = re.match(r"^Fourth official has announced (\d+) minutes? of added time\.$", t)
if m:
return f"추가시간 {m.group(1)}분"
if t.startswith("Lineups are announced"):
return "라인업 발표 · 선수 몸풀기"
return _ko_teams(t) # 미지원 템플릿 — 팀명만 한글화한 원문
# ── 라이브 (스코어·경기시간·득점 이벤트·라인업) ────────────────
_LIVE_TTL_SEC = 15.0
_live_cache: dict[str, tuple[float, dict]] = {}
def _player_out(p: dict) -> dict:
ath = p.get("athlete") or {}
return {
"name": ath.get("displayName", ""),
"pos": ((p.get("position") or {}).get("abbreviation")) or "",
"jersey": p.get("jersey", ""),
"in": bool(p.get("subbedIn")),
"out": bool(p.get("subbedOut")),
}
def _lineups_of(summary: dict) -> dict | None:
"""summary.rosters → {away, home}: {formation, starters[], bench[]}.
starters 는 formationPlace 순(1=GK). subbedIn/Out 플래그로 실시간 교체 표시.
라인업 미발표(경기 한참 전)면 rosters 가 비어 None.
"""
out: dict = {}
for r in summary.get("rosters") or []:
side = r.get("homeAway")
players = r.get("roster") or []
if side not in ("home", "away") or not players:
continue
starters = sorted(
(p for p in players if p.get("starter")),
key=lambda p: int(p.get("formationPlace") or 99),
)
bench = [p for p in players if not p.get("starter")]
out[side] = {
"formation": r.get("formation"),
"starters": [_player_out(p) for p in starters],
"bench": [_player_out(p) for p in bench],
}
return out or None
def _norm_name(s: str) -> str:
"""악센트 제거·소문자 — 선수명 비교용."""
s = unicodedata.normalize("NFKD", s)
return "".join(ch for ch in s if not unicodedata.combining(ch)).lower().strip()
def _make_name_resolver(lineups: dict | None):
"""중계 원문의 선수명 → 로스터 표기명 스냅.
ESPN 중계와 로스터가 같은 선수를 다르게 적는 경우가 흔하다
(미들네임 생략 "Sékou Bangoura"↔"Sékou Tidiany Bangoura",
철자 차이 "Akhundzada"↔"Akhundzade", 애칭 "Máximo"↔"Maxi Carrizo").
로스터명과 못 맞추면 교체 대체·골/어시 마커가 피치에 못 붙으므로
정규화 일치 → 성(姓) 유일 일치 → 유사도(≥0.75) 순으로 맞춘다.
"""
roster: list[str] = []
for side in (lineups or {}).values():
for p in (side.get("starters") or []) + (side.get("bench") or []):
if p.get("name"):
roster.append(p["name"])
by_norm = {_norm_name(n): n for n in roster}
def resolve(name: str) -> str:
if not name or name in roster:
return name
n = _norm_name(name)
if n in by_norm:
return by_norm[n]
last = n.rsplit(" ", 1)[-1]
cands = [r for r in roster if _norm_name(r).rsplit(" ", 1)[-1] == last]
if len(cands) == 1:
return cands[0]
# 토큰 순서가 뒤바뀐 표기 ("Djé D'Avilla" ↔ "D'Avilla Dje Tah") — 집합 포함 관계로 매칭
toks = set(n.split())
cands = [
r for r in roster
if toks <= set(_norm_name(r).split()) or set(_norm_name(r).split()) <= toks
]
if len(cands) == 1:
return cands[0]
best, score = name, 0.0
for r in roster:
s = SequenceMatcher(None, n, _norm_name(r)).ratio()
if s > score:
best, score = r, s
return best if score >= 0.75 else name
return resolve
async def fetch_live_mls(m: Match) -> dict:
"""라이브 페이로드 {available, soccer, clock, period, score, goals[]}."""
import httpx
cached = _live_cache.get(m.match_id)
if cached and time.monotonic() - cached[0] < _LIVE_TTL_SEC:
return cached[1]
payload: dict = {"available": False}
try:
kst = ensure_aware(m.kickoff_at).astimezone(KST)
date_kst = kst.strftime("%Y%m%d")
span = (
f"{(kst.date() - timedelta(days=1)).strftime('%Y%m%d')}"
f"-{kst.date().strftime('%Y%m%d')}"
)
async with httpx.AsyncClient(timeout=15) as c:
events = await _fetch_events(c, span)
rec = next(
(r for r in events
if r["dateKst"] == date_kst
and r["teamA"] == m.team_a_code and r["teamB"] == m.team_b_code),
None,
)
if rec:
status = rec["_status"] or {}
stype = status.get("type") or {}
# 라인업+문자중계 — summary 1콜 (경기 전 선발 발표~경기 중 교체·중계 반영)
lineups = None
subs: list[dict] = []
assist_q: dict[str, list[str]] = {}
commentary: list[dict] = []
_rn = _make_name_resolver(None) # summary 실패 시 원문 그대로
try:
async with httpx.AsyncClient(timeout=15) as c2:
r2 = await c2.get(_summary_url(rec["espnId"]))
r2.raise_for_status()
sj = r2.json()
lineups = _lineups_of(sj)
_rn = _make_name_resolver(lineups)
# 문자중계 — 규칙 기반 한글 번역, 경기 시작부터 전체(최신순).
# 교체·어시스트는 details 에 없어 중계 원문에서 함께 추출한다.
for e in sj.get("commentary") or []:
raw = e.get("text", "")
clk = (e.get("time") or {}).get("displayValue", "")
ptype = (((e.get("play") or {}).get("type")) or {}).get("type", "")
sm = re.match(
r"^Substitution, (.+?)\.\s*(.+?) replaces (.+?)(?: because of [^.]*)?\.$",
raw,
)
if sm:
subs.append({
"clock": clk,
"team": _TEAM_EN2CODE.get(sm.group(1), ""),
"inName": _rn(sm.group(2).strip()),
"outName": _rn(sm.group(3).strip()),
})
if raw.startswith("Goal!"):
gm = re.match(r"^Goal!\s+.+?\d+, .+?\d+\.\s*(.+?) \(", raw)
am = re.search(r"Assisted by ([^.]+?)(?: with| following|\.|$)", raw)
if gm and am:
assist_q.setdefault(_rn(gm.group(1).strip()), []).append(
_rn(am.group(1).strip())
)
commentary.append({
"clock": clk,
"text": _tr_commentary(raw),
"goal": (
ptype == "goal"
or raw.startswith("Goal!")
or raw.startswith("Own Goal")
),
})
commentary.reverse()
except Exception as e: # noqa: BLE001 — 라인업 실패해도 스코어는 서빙
log.warning("mls lineups 실패 %s: %s", m.match_id, e)
if stype.get("state") in ("in", "post"):
goals = []
cards = []
for det in rec["_comp"].get("details") or []:
team_id = int((det.get("team") or {}).get("id") or 0)
aths = det.get("athletesInvolved") or []
if det.get("yellowCard") or det.get("redCard"):
cards.append({
"clock": (det.get("clock") or {}).get("displayValue", ""),
"team": MLS_ID_TO_CODE.get(team_id, ""),
"player": _rn((aths[0] if aths else {}).get("displayName", "")),
"red": bool(det.get("redCard")),
})
continue
if not det.get("scoringPlay"):
continue
player = _rn((aths[0] if aths else {}).get("displayName", ""))
# 어시스트: 중계 원문 큐(시간순) 우선, 없으면 details 두 번째 선수
queue = assist_q.get(player)
assist = queue.pop(0) if queue else (
_rn(aths[1].get("displayName", ""))
if len(aths) > 1 and not det.get("ownGoal")
else ""
)
goals.append({
"clock": (det.get("clock") or {}).get("displayValue", ""),
"team": MLS_ID_TO_CODE.get(team_id, ""),
"player": player,
"assist": assist,
"ownGoal": bool(det.get("ownGoal")),
"penalty": bool(det.get("penaltyKick")),
})
payload = {
"available": True,
"soccer": True,
"clock": status.get("displayClock", ""),
"period": status.get("period"),
"state": stype.get("state"),
"score": {
"away": rec["_away"].get("score"),
"home": rec["_home"].get("score"),
},
"goals": goals,
"cards": cards,
"subs": subs,
"lineups": lineups,
"commentary": commentary,
}
elif lineups:
# 경기 전 선발 라인업 발표됨 — 스코어 없이 라인업만
payload = {
"available": True,
"soccer": True,
"state": "pre",
"lineups": lineups,
"commentary": commentary,
}
except Exception as e: # noqa: BLE001
log.warning("mls live 실패 %s: %s", m.match_id, e)
payload = {"available": False}
_live_cache[m.match_id] = (time.monotonic(), payload)
return payload
+2 -1
View File
@@ -66,7 +66,8 @@ async def accumulate_user_points(
agg: dict[str, dict] = {e: _empty() for e in targets} agg: dict[str, dict] = {e: _empty() for e in targets}
for pick, match in rows: for pick, match in rows:
key, value = grade_prediction( key, value = grade_prediction(
pick.score_a, pick.score_b, match.result_score_a, match.result_score_b pick.score_a, pick.score_b, match.result_score_a, match.result_score_b,
baseball=match.league in ("kbo", "mlb"),
) )
t = agg[pick.email.strip().lower()] t = agg[pick.email.strip().lower()]
t["total_points"] += value t["total_points"] += value
+33 -7
View File
@@ -23,6 +23,17 @@ from ..teams_data import code_for_tla
log = logging.getLogger("triplepick.schedule") log = logging.getLogger("triplepick.schedule")
KST = timezone(timedelta(hours=9)) KST = timezone(timedelta(hours=9))
# football-data stage → 녹아웃 라운드 라벨(한글). 조별리그는 group 으로 따로 처리.
# 2026 포맷(48개국)은 32강(LAST_32)부터 토너먼트가 시작된다.
KO_STAGE_LABEL = {
"LAST_32": "32강",
"LAST_16": "16강",
"QUARTER_FINALS": "8강",
"SEMI_FINALS": "4강",
"THIRD_PLACE": "3·4위전",
"FINAL": "결승",
}
# "13:00 UTC-6" / "20:00 UTC+2" 형태 파싱 # "13:00 UTC-6" / "20:00 UTC+2" 형태 파싱
_TIME_RE = re.compile(r"(\d{1,2}):(\d{2})\s*UTC\s*([+-]\d{1,2})") _TIME_RE = re.compile(r"(\d{1,2}):(\d{2})\s*UTC\s*([+-]\d{1,2})")
@@ -97,9 +108,12 @@ async def _fetch_football_data() -> list[dict]:
async def _fetch_all_groups_football_data() -> list[dict]: async def _fetch_all_groups_football_data() -> list[dict]:
"""football-data 에서 전체 조별리그(12개조 72경기) 수집. """football-data 에서 전체 조별리그 + 녹아웃 토너먼트 일정 수집.
반환: [{teamA, teamB, group('A'..'L'), kickoffKst, venue}] (tla→코드) 반환: [{teamA, teamB, group('A'..'L' 또는 ''), roundLabel('' 또는 '32강'..), kickoffKst, venue}]
조별리그는 group 으로, 32강 이후 토너먼트는 roundLabel 로 구분한다(tla→코드).
녹아웃 경기는 대진이 확정되기 전엔 팀이 TBD 라 소스가 tla 를 주지 않아 자동 제외되고,
조별리그 종료로 대진이 확정되면 다음 동기화에서 자동 등장한다.
""" """
if not settings.football_data_token: if not settings.football_data_token:
log.warning("schedule(all): football-data 토큰 미설정 — 수집 생략") log.warning("schedule(all): football-data 토큰 미설정 — 수집 생략")
@@ -117,13 +131,19 @@ async def _fetch_all_groups_football_data() -> list[dict]:
out: list[dict] = [] out: list[dict] = []
for m in data.get("matches", []): for m in data.get("matches", []):
if m.get("stage") != "GROUP_STAGE": stage = m.get("stage")
continue if stage == "GROUP_STAGE":
g = (m.get("group") or "").replace("GROUP_", "") # 'A'..'L' g = (m.get("group") or "").replace("GROUP_", "") # 'A'..'L'
round_label = ""
elif stage in KO_STAGE_LABEL:
g = "" # 녹아웃은 조 없음 — roundLabel 로 구분
round_label = KO_STAGE_LABEL[stage]
else:
continue # 예선/플레이오프 등은 제외
ht = (m.get("homeTeam") or {}).get("tla") ht = (m.get("homeTeam") or {}).get("tla")
at = (m.get("awayTeam") or {}).get("tla") at = (m.get("awayTeam") or {}).get("tla")
if not ht or not at: if not ht or not at:
continue continue # 대진 미확정(TBD) — 확정 후 다음 동기화에서 등장
utc = m.get("utcDate") utc = m.get("utcDate")
if not utc: if not utc:
continue continue
@@ -135,6 +155,7 @@ async def _fetch_all_groups_football_data() -> list[dict]:
"teamA": code_for_tla(ht), "teamA": code_for_tla(ht),
"teamB": code_for_tla(at), "teamB": code_for_tla(at),
"group": g, "group": g,
"roundLabel": round_label,
"kickoffKst": kickoff, "kickoffKst": kickoff,
"venue": m.get("venue") or "", "venue": m.get("venue") or "",
} }
@@ -232,7 +253,12 @@ async def _results_football_data() -> list[dict]:
ft = ((m.get("score") or {}).get("fullTime") or {}) ft = ((m.get("score") or {}).get("fullTime") or {})
if ft.get("home") is None or ft.get("away") is None: if ft.get("home") is None or ft.get("away") is None:
continue continue
out.append({"teamA": a, "teamB": b, "scoreA": int(ft["home"]), "scoreB": int(ft["away"])}) # 라운드 표기 — 같은 두 팀이 조별리그·토너먼트에서 만나도 정산을 구분(없으면 "").
round_label = KO_STAGE_LABEL.get(m.get("stage") or "", "")
out.append({
"teamA": a, "teamB": b, "scoreA": int(ft["home"]), "scoreB": int(ft["away"]),
"roundLabel": round_label,
})
return out return out
+23 -9
View File
@@ -21,24 +21,38 @@ from ..teams_data import team_info
log = logging.getLogger("triplepick.schedule") log = logging.getLogger("triplepick.schedule")
KST = timezone(timedelta(hours=9)) KST = timezone(timedelta(hours=9))
# 녹아웃 라운드 라벨 → match_id 접두어(조가 없는 토너먼트 경기 식별용)
KO_PREFIX = {"32강": "R32", "16강": "R16", "8강": "QF", "4강": "SF", "3·4위전": "P3", "결승": "F"}
def _stage_prefix(group: str, round_label: str) -> str:
"""경기 식별 접두어 — 조별리그는 조 문자, 녹아웃은 라운드 코드.
같은 두 팀이 조별리그와 결승에서 다시 만나도 서로 다른 경기로 구분된다."""
return group or KO_PREFIX.get(round_label, "KO")
async def sync_schedule(db: AsyncSession, records: list[dict]) -> dict: async def sync_schedule(db: AsyncSession, records: list[dict]) -> dict:
if not records: if not records:
return {"updated": 0, "inserted": 0, "skipped": 0} return {"updated": 0, "inserted": 0, "skipped": 0}
existing = (await db.execute(select(Match))).scalars().all() existing = (await db.execute(select(Match))).scalars().all()
# 순서 무관 매칭 — 소스의 홈/원정 순서가 우리와 달라도 기존 경기를 찾음(중복 방지) # 순서 무관 매칭 — 소스의 홈/원정 순서가 우리와 달라도 기존 경기를 찾음(중복 방지).
# 단계(조/라운드)도 키에 포함 — 같은 두 팀의 조별리그 경기와 토너먼트 경기를 구분.
by_pair: dict[tuple, Match] = {} by_pair: dict[tuple, Match] = {}
for m in existing: for m in existing:
by_pair[(m.team_a_code, m.team_b_code)] = m p = _stage_prefix(m.group, m.round_label)
by_pair[(m.team_b_code, m.team_a_code)] = m by_pair[(p, m.team_a_code, m.team_b_code)] = m
by_pair[(p, m.team_b_code, m.team_a_code)] = m
updated = inserted = skipped = 0 updated = inserted = skipped = 0
for rec in records: for rec in records:
a, b = rec["teamA"], rec["teamB"] a, b = rec["teamA"], rec["teamB"]
group = rec.get("group", settings.featured_group) round_label = rec.get("roundLabel", "")
# 조별리그는 조 문자, 녹아웃은 조 없음(""). roundLabel 이 있으면 토너먼트 경기.
group = "" if round_label else rec.get("group", settings.featured_group)
prefix = _stage_prefix(group, round_label)
kickoff = parse_kickoff(rec["kickoffKst"]) kickoff = parse_kickoff(rec["kickoffKst"])
m = by_pair.get((a, b)) m = by_pair.get((prefix, a, b))
if m is not None: if m is not None:
if m.result_outcome is not None: if m.result_outcome is not None:
skipped += 1 skipped += 1
@@ -52,10 +66,10 @@ async def sync_schedule(db: AsyncSession, records: list[dict]) -> dict:
else: else:
ta, tb = team_info(a), team_info(b) ta, tb = team_info(a), team_info(b)
kst_date = kickoff.astimezone(KST).strftime("%Y%m%d") kst_date = kickoff.astimezone(KST).strftime("%Y%m%d")
match_id = f"{group}_{a}_{b}_{kst_date}" match_id = f"{prefix}_{a}_{b}_{kst_date}"
new = Match( new = Match(
match_id=match_id, match_id=match_id,
round_label="", round_label=round_label,
group=group, group=group,
team_a_name=ta["name"], team_a_short=ta["shortName"], team_a_name=ta["name"], team_a_short=ta["shortName"],
team_a_code=ta["code"], team_a_flag=ta["flag"], team_a_code=ta["code"], team_a_flag=ta["flag"],
@@ -70,8 +84,8 @@ async def sync_schedule(db: AsyncSession, records: list[dict]) -> dict:
) )
db.add(new) db.add(new)
db.add(CrowdStats(match_id=match_id, total=0, team_a_win=0, draw=0, team_b_win=0)) db.add(CrowdStats(match_id=match_id, total=0, team_a_win=0, draw=0, team_b_win=0))
by_pair[(a, b)] = new by_pair[(prefix, a, b)] = new
by_pair[(b, a)] = new by_pair[(prefix, b, a)] = new
inserted += 1 inserted += 1
await db.commit() await db.commit()
+845
View File
@@ -0,0 +1,845 @@
"""오늘의 응원가 — 경기 맥락 반영 자동 생성 파이프라인 (KBO 전용).
흐름 (워커 tick_songs, song_tick_seconds 주기):
1) 킥오프 song_generate_minutes_before(기본 150분) 전에 든 경기 → 팀별로
경기 맥락(전날 결과·순위·연전 차수·선발투수) 조립 → LLM 이 가사·스타일 작성
→ Suno 생성 작업 시작 (Song status=generating)
2) generating 행 폴링 → 완료 시 트랙 URL 저장 (status=complete)
실패는 attempts 3회까지 다음 틱에 재시도. 데이터가 비어도(캐시 미스)
가사는 팀·상대·경기 정보만으로 생성한다 — 조용한 전체 실패 없음.
"""
from __future__ import annotations
import json
import logging
import re
from datetime import date, timedelta, timezone
from sqlalchemy import select
from ..config import settings
from ..database import SessionLocal
from ..domain import ensure_aware, now_utc
from ..models import DataCache, Match, Song, SongAudio
from . import suno
log = logging.getLogger("triplepick.songs")
KST = timezone(timedelta(hours=9))
MAX_ATTEMPTS = 3
GENERATE_TIMEOUT_MIN = 30 # Suno 작업이 이 시간 넘게 미완이면 실패 처리
# 곡 스타일 — 전 곡 고정 (경기장 웅장 앤섬 컨셉, 레퍼런스 확정본).
# LLM 은 가사·제목만 쓰고 스타일은 변주하지 않는다. MLS 만 soccer 로 치환.
DEFAULT_STYLE = (
"Korean baseball stadium cheer anthem, powerful brass fanfare, thumping "
"drum corps, group chant call-and-response, gang vocals, energetic male "
"crowd shouting, 128bpm, live stadium atmosphere"
)
def style_for(league: str) -> str:
if league == "mls":
return DEFAULT_STYLE.replace("baseball", "soccer")
return DEFAULT_STYLE
# LLM 에게 주는 형식 레퍼런스 (가사 구조·스타일 문구의 톤)
_REFERENCE = """[Intro - Brass Fanfare]
(두! 산! 베어스!) (두! 산! 베어스!)
[Verse 1]
잠실의 함성이 하늘을 울려
곰들의 심장이 뜨겁게 뛴다
[Chorus]
두산! (두산!) 베어스! (베어스!)
날려버려 담장 너머로
두산! (두산!) 베어스! (베어스!)
오늘 승리는 우리의 것
[Bridge - Chant]
(두산 승리! 두산 승리!)
잠실을 가득 채운 함성
[Final Chorus - Key Up]
두산! (두산!) 베어스! (베어스!)
잠실 하늘 높이 울려라
[Outro]
(두! 산! 베어스!) 최강 두산!"""
# ── 경기 맥락 조립 ─────────────────────────────────────────────
def _fmt_standing(name: str, st: dict | None) -> str:
if not st:
return f"{name}: 순위 정보 없음"
parts = [f"{st.get('rank')}위"] if st.get("rank") else []
if st.get("w") is not None:
parts.append(f"{st.get('w')}승 {st.get('d') or 0}무 {st.get('l')}패")
if st.get("wra"):
parts.append(f"승률 {st.get('wra')}")
if st.get("gb") not in (None, "", "0.0", 0):
parts.append(f"게임차 {st.get('gb')}")
if st.get("last5"):
parts.append(f"최근 5경기 {st.get('last5')}")
return f"{name}: " + ", ".join(parts)
def _fmt_starter(label: str, s: dict | None) -> str | None:
if not s or not s.get("name"):
return None
bits = [s["name"]]
if s.get("era") not in (None, ""):
bits.append(f"평균자책 {s['era']}")
if s.get("w") is not None:
bits.append(f"{s.get('w')}승 {s.get('l') or 0}패")
return f"{label} 선발: " + " ".join(bits)
async def _yesterday_info(db, m: Match, code: str, name: str) -> tuple[str | None, dict]:
"""(전날 결과 한 줄 + 활약 하이라이트, 시즌타율 맵). 경기 없으면 맵은 빈 dict."""
line, g = await _yesterday_result(db, m, code, name)
avg_map: dict = {}
if g is not None and m.league in ("kbo", "mlb"):
try:
stats = await (
_mlb_team_game_stats(g, code)
if m.league == "mlb"
else _kbo_team_game_stats(g, code)
)
except Exception as e: # noqa: BLE001
log.warning("어제 경기 기록 조회 실패 %s: %s", g.match_id, e)
stats = None
else:
stats = None
if stats:
avg_map = stats.get("avg") or {}
if line and stats.get("highlights"):
line += " · 활약: " + ", ".join(stats["highlights"])
return line, avg_map
async def _yesterday_result(
db, m: Match, code: str, name: str
) -> tuple[str | None, Match | None]:
"""해당 팀의 전날 경기 결과 한 줄 + 그 경기 행 (없으면 (안내문, None))."""
day = ensure_aware(m.kickoff_at).astimezone(KST).date() - timedelta(days=1)
lo = ensure_aware(m.kickoff_at).astimezone(KST).replace(
hour=0, minute=0, second=0, microsecond=0
) - timedelta(days=1)
hi = lo + timedelta(days=1)
rows = (
await db.execute(
select(Match).where(
Match.league == m.league,
Match.result_outcome.is_not(None),
Match.kickoff_at >= lo.astimezone(timezone.utc),
Match.kickoff_at < hi.astimezone(timezone.utc),
(Match.team_a_code == code) | (Match.team_b_code == code),
)
)
).scalars().all()
if not rows:
return f"어제({day.month}/{day.day})는 경기가 없었다", None
g = rows[-1]
is_a = g.team_a_code == code
my, opp = (
(g.result_score_a, g.result_score_b) if is_a else (g.result_score_b, g.result_score_a)
)
opp_name = g.team_b_short if is_a else g.team_a_short
if my is None or opp is None:
return None, None
verdict = "승리" if my > opp else "패배" if my < opp else "무승부"
margin = abs((my or 0) - (opp or 0))
tight = " (1점차 석패)" if verdict == "패배" and margin == 1 else (
" (1점차 신승)" if verdict == "승리" and margin == 1 else ""
)
return f"어제 {opp_name}전 {my}:{opp} {verdict}{tight}", g
async def _series_line(db, m: Match) -> str | None:
"""같은 팀 상대 연전 차수 — '3연전 중 2차전' 형태 (단일 경기면 None)."""
center = ensure_aware(m.kickoff_at).astimezone(KST).date()
lo = center - timedelta(days=3)
hi = center + timedelta(days=4)
pair = {m.team_a_code, m.team_b_code}
rows = (
await db.execute(
select(Match).where(
Match.league == m.league,
Match.team_a_code.in_(pair),
Match.team_b_code.in_(pair),
)
)
).scalars().all()
days: list[date] = sorted(
{
ensure_aware(r.kickoff_at).astimezone(KST).date()
for r in rows
if lo <= ensure_aware(r.kickoff_at).astimezone(KST).date() < hi
}
)
# 오늘을 포함해 연속된 날짜 구간만 자른다
if center not in days:
return None
run = [center]
for d in reversed([d for d in days if d < center]):
if (run[0] - d).days == 1:
run.insert(0, d)
else:
break
for d in [d for d in days if d > center]:
if (d - run[-1]).days == 1:
run.append(d)
else:
break
if len(run) < 2:
return None
idx = run.index(center) + 1
return f"{len(run)}연전 중 {idx}차전"
async def fetch_lineups(m: Match) -> dict | None:
"""오늘 선발 라인업 조회 (발표 전이면 announced=False). KBO=네이버, MLB=공식 API.
MLS 는 라인업 소스 미연동 — None (라인업 없이 생성).
"""
if m.league == "mlb":
return await _fetch_lineups_mlb(m)
if m.league == "kbo":
return await _fetch_lineups_kbo(m)
return None
async def _fetch_lineups_kbo(m: Match) -> dict | None:
"""네이버 preview fullLineUp — 발표 전엔 선발투수 1명만. 양팀 타자 8명 이상 = 발표."""
import httpx
from .baseball_details import UA, naver_game_id_candidates
async with httpx.AsyncClient(timeout=15) as client:
for gid in naver_game_id_candidates(m):
try:
r = await client.get(
f"{settings.naver_api_base}/schedule/games/{gid}/preview",
headers=UA,
)
r.raise_for_status()
data = r.json()
except Exception: # noqa: BLE001 — gameId 후보 불일치는 다음 후보로
continue
if not data.get("success"):
continue
p = (data.get("result") or {}).get("previewData") or {}
def batters(key: str) -> list[dict]:
fl = ((p.get(key) or {}).get("fullLineUp")) or []
return [
e for e in fl
if e.get("playerName") and e.get("positionName") != "선발투수"
]
away, home = batters("awayTeamLineUp"), batters("homeTeamLineUp")
return {
"away": away,
"home": home,
"announced": len(away) >= 8 and len(home) >= 8,
}
return None
async def _mlb_game_pk(m: Match) -> int | None:
"""MLB schedule 에서 이 경기의 gamePk 해석 (더블헤더는 차수 매칭)."""
import httpx
from datetime import datetime
from ..teams_baseball import MLB_ID_TO_CODE
from .baseball_sync import match_seq
kick = ensure_aware(m.kickoff_at)
date_kst = kick.astimezone(KST).strftime("%Y%m%d")
start = (kick - timedelta(days=1)).date().isoformat()
end = kick.date().isoformat()
async with httpx.AsyncClient(timeout=15) as c:
r = await c.get(
f"{settings.mlb_api_base}/v1/schedule?sportId=1"
f"&startDate={start}&endDate={end}"
)
r.raise_for_status()
cands: list[tuple[str, int]] = []
for day in r.json().get("dates") or []:
for g in day.get("games") or []:
a = MLB_ID_TO_CODE.get((g["teams"]["away"]["team"] or {}).get("id"))
b = MLB_ID_TO_CODE.get((g["teams"]["home"]["team"] or {}).get("id"))
gd = g.get("gameDate")
if not a or not b or not gd:
continue
g_kst = (
datetime.fromisoformat(gd.replace("Z", "+00:00"))
.astimezone(KST).strftime("%Y%m%d")
)
if a == m.team_a_code and b == m.team_b_code and g_kst == date_kst:
cands.append((gd, g.get("gamePk")))
cands.sort()
idx = match_seq(m.match_id) - 1
return cands[idx][1] if idx < len(cands) else None
async def _mlb_boxscore_teams(pk: int) -> dict | None:
import httpx
async with httpx.AsyncClient(timeout=15) as c:
r = await c.get(f"{settings.mlb_api_base}/v1/game/{pk}/boxscore")
r.raise_for_status()
return r.json().get("teams") or {}
async def _fetch_lineups_mlb(m: Match) -> dict | None:
"""MLB boxscore battingOrder — 발표 전엔 빈 배열. 양팀 9명 이상 = 발표.
boxscore seasonStats 로 각 타자의 시즌 타율도 함께 싣는다.
"""
pk = await _mlb_game_pk(m)
if not pk:
return None
teams = await _mlb_boxscore_teams(pk)
if teams is None:
return None
def batters(side_key: str) -> list[dict]:
t = teams.get(side_key) or {}
players = t.get("players") or {}
out = []
for pid in t.get("battingOrder") or []:
p = players.get(f"ID{pid}") or {}
name = (p.get("person") or {}).get("fullName")
if name:
avg = (((p.get("seasonStats") or {}).get("batting")) or {}).get("avg")
out.append({
"playerName": name,
"positionName": (p.get("position") or {}).get("abbreviation", ""),
"avg": avg,
})
return out
away, home = batters("away"), batters("home")
return {"away": away, "home": home, "announced": len(away) >= 9 and len(home) >= 9}
# ── 최근 경기 타자 기록 (활약 하이라이트 + 시즌 타율 맵) ────────
async def _kbo_team_game_stats(g: Match, code: str) -> dict | None:
"""종료된 KBO 경기 record → 그 팀 타자 시즌타율 맵 + 활약(홈런·멀티히트)."""
import httpx
from .baseball_details import UA, naver_game_id_candidates
is_away = g.team_a_code == code
async with httpx.AsyncClient(timeout=15) as client:
for gid in naver_game_id_candidates(g):
try:
r = await client.get(
f"{settings.naver_api_base}/schedule/games/{gid}/record",
headers=UA,
)
r.raise_for_status()
data = r.json()
except Exception: # noqa: BLE001 — gameId 후보 불일치는 다음 후보로
continue
if not data.get("success"):
continue
rec = (data.get("result") or {}).get("recordData") or {}
batters = (rec.get("battersBoxscore") or {}).get(
"away" if is_away else "home"
) or []
if not batters:
continue
avg = {b["name"]: b.get("hra") for b in batters if b.get("name")}
hi = []
for b in batters:
if b.get("hr"):
hi.append(f"{b['name']} 홈런 {b['hr']}방")
elif (b.get("hit") or 0) >= 3:
hi.append(f"{b['name']} {b['hit']}안타 맹타")
return {"avg": avg, "highlights": hi[:4]}
return None
async def _mlb_team_game_stats(g: Match, code: str) -> dict | None:
"""종료된 MLB 경기 boxscore → 그 팀 활약(홈런·멀티히트)."""
pk = await _mlb_game_pk(g)
if not pk:
return None
teams = await _mlb_boxscore_teams(pk)
t = (teams or {}).get("away" if g.team_a_code == code else "home") or {}
hi = []
for p in (t.get("players") or {}).values():
st = ((p.get("stats") or {}).get("batting")) or {}
name = (p.get("person") or {}).get("fullName")
if not name or not st:
continue
if st.get("homeRuns"):
hi.append(f"{name} 홈런 {st['homeRuns']}방")
elif (st.get("hits") or 0) >= 3:
hi.append(f"{name} {st['hits']}안타 맹타")
return {"avg": {}, "highlights": hi[:4]}
def _lineup_line(lineups: dict | None, side: str, avg_map: dict | None = None) -> str | None:
if not lineups or not lineups.get("announced"):
return None
avg_map = avg_map or {}
parts = []
for i, e in enumerate(lineups["away" if side == "a" else "home"][:10]):
avg = e.get("avg") or avg_map.get(e["playerName"])
tail = f", 타율 {avg}" if avg else ""
parts.append(f"{i + 1}번 {e['playerName']}({e.get('positionName', '')}{tail})")
return f"오늘 확정 선발 라인업: {', '.join(parts)}" if parts else None
async def build_context(
db, m: Match, side: str, lineups: dict | None = None
) -> tuple[str, str, str]:
"""(팀코드, 팀명, 맥락 텍스트). side = 'a'(원정) | 'b'(홈)."""
code = m.team_a_code if side == "a" else m.team_b_code
name = m.team_a_short if side == "a" else m.team_b_short
opp_name = m.team_b_short if side == "a" else m.team_a_short
opp_code = m.team_b_code if side == "a" else m.team_a_code
home = "홈" if side == "b" else "원정"
kick = ensure_aware(m.kickoff_at).astimezone(KST)
lines = [
f"우리 팀: {name} ({home} 경기)",
f"오늘 경기: {kick.month}/{kick.day} {kick:%H:%M} {m.venue or ''} — 상대 {opp_name}",
]
st_row = await db.get(DataCache, f"standings:{m.league}")
st = st_row.payload if st_row else {}
lines.append(_fmt_standing(name, st.get(code)))
lines.append(_fmt_standing(f"상대 {opp_name}", st.get(opp_code)))
prev_row = await db.get(DataCache, f"preview:{m.match_id}")
prev = prev_row.payload if prev_row else {}
my_starter = _fmt_starter("우리 팀", prev.get("starterA" if side == "a" else "starterB"))
opp_starter = _fmt_starter("상대", prev.get("starterB" if side == "a" else "starterA"))
for s in (my_starter, opp_starter):
if s:
lines.append(s)
vs = prev.get("seasonVs")
if vs:
mine = vs.get("aWin") if side == "a" else vs.get("bWin")
theirs = vs.get("bWin") if side == "a" else vs.get("aWin")
if mine is not None and theirs is not None:
lines.append(f"시즌 상대전적 {mine}승 {vs.get('draw') or 0}무 {theirs}패")
y, avg_map = await _yesterday_info(db, m, code, name)
if y:
lines.append(y)
series = await _series_line(db, m)
if series:
lines.append(f"오늘은 {opp_name}와의 {series}")
lu = _lineup_line(lineups, side, avg_map)
if lu:
lines.append(lu)
return code, name, "\n".join(x for x in lines if x)
# ── LLM 작사 ───────────────────────────────────────────────────
_LEAGUE_LABEL = {
"kbo": "한국 프로야구(KBO)",
"mlb": "메이저리그(MLB)",
"mls": "미국 프로축구(MLS)",
}
def _lyrics_prompt(team_name: str, context: str, league: str = "kbo") -> str:
return (
f"너는 {_LEAGUE_LABEL.get(league, '프로야구')} 응원가 전문 작사가다. "
"아래 오늘 경기 정보를 바탕으로 "
f"'{team_name}'의 **오늘의 응원가**를 한국어로 만들어라"
+ (" (팀명·선수명은 한국 팬에게 익숙한 표기로)" if league in ("mlb", "mls") else "")
+ ".\n\n"
f"[오늘 경기 정보]\n{context}\n\n"
"[요구사항]\n"
"- 경기장에서 수만 관중이 떼창하는 웅장한 스타디움 앤섬\n"
"- 오늘 경기 맥락(어제/최근 결과 설욕·기세, 순위 싸움, 연전 차수, 선발·라인업)을 "
"가사에 구체적으로 녹일 것 — 선수 실명 사용 가능\n"
"- 숫자는 자연스럽게 표기 (13:1, 78승, 2차전 등 — 발음 변환은 시스템이 처리)\n"
"- 괄호로 관중 콜앤리스폰스 파트 표기, 섹션 태그에 연주 지시 포함\n"
"- 섹션 구성 필수: [Intro] → [Verse 1] → [Chorus] → [Verse 2] → [Chorus] → "
"[Bridge] → [Final Chorus] → [Outro] 전부 포함 (생략 금지), 가사 본문 700자 이상\n\n"
f"[가사 형식 레퍼런스 — 구조와 톤만 참고, 내용은 오늘 경기에 맞게 새로 쓸 것]\n{_REFERENCE}\n\n"
"다음 키를 가진 JSON 객체 하나만 출력하라:\n"
' "title": 곡 제목 (한국어, 25자 이내, 오늘 경기 느낌이 나게),\n'
' "lyrics": 위 형식의 전체 가사\n'
)
# ── 가사 숫자 한글화 (Suno 가 아라비아 숫자를 잘못 읽는 문제 방지) ──
_SINO = "영일이삼사오육칠팔구"
_NATIVE = {
1: "한", 2: "두", 3: "세", 4: "네", 5: "다섯", 6: "여섯", 7: "일곱",
8: "여덟", 9: "아홉", 10: "열", 11: "열한", 12: "열두", 13: "열세",
14: "열네", 15: "열다섯", 16: "열여섯", 17: "열일곱", 18: "열여덟",
19: "열아홉", 20: "스무",
}
def _sino(n: int) -> str:
"""한자어 수사 — 78 → 칠십팔 (0~9999)."""
if n == 0:
return "영"
parts = []
for unit, name in ((1000, "천"), (100, "백"), (10, "십")):
d, n = divmod(n, unit)
if d:
parts.append(("" if d == 1 else _SINO[d]) + name)
if n:
parts.append(_SINO[n])
return "".join(parts)
def _native(n: int) -> str:
"""고유어 수사 — 7 → 일곱 (범위 밖은 한자어 폴백)."""
return _NATIVE.get(n) or _sino(n)
# 서수 관형형 — 1~4는 첫/두/세/네, 이후는 고유어 수사 그대로 (다섯 번째)
_ORDINAL = {1: "첫", 2: "두", 3: "세", 4: "네"}
def hangulize_numbers(text: str) -> str:
"""가사 속 아라비아 숫자를 한글 발음으로 치환 (Suno 전송본 전용).
1승→일승, 78승→칠십팔승, 7게임→일곱 게임, 5:3→오 대 삼, 0.312→영점삼일이.
[Verse 1] 같은 섹션 태그는 Suno 구조 인식용이라 건드리지 않는다.
"""
parts = re.split(r"(\[[^\]]*\])", text)
return "".join(
p if p.startswith("[") else _hangulize_plain(p) for p in parts
)
def _hangulize_plain(text: str) -> str:
# 소수(타율 등): 0.312 → 영점삼일이 (소수부는 자리별 낭독)
text = re.sub(
r"(\d)\.(\d+)",
lambda m: _sino(int(m.group(1))) + "점" + "".join(_SINO[int(c)] for c in m.group(2)),
text,
)
# 스코어: 5:3 / 5대3 → 오 대 삼
text = re.sub(
r"(\d+)\s*[:대]\s*(\d+)",
lambda m: f"{_sino(int(m.group(1)))} 대 {_sino(int(m.group(2)))}",
text,
)
# 아웃 카운트는 야구 관례상 영어 수사 (2아웃→투아웃)
text = re.sub(
r"([123])\s*아웃",
lambda m: {1: "원", 2: "투", 3: "쓰리"}[int(m.group(1))] + "아웃",
text,
)
# 서수는 관형 고유어 수사 (1번째→첫 번째, 4번째→네 번째, 5번째→다섯 번째)
text = re.sub(
r"(\d+)\s*번째",
lambda m: (_ORDINAL.get(int(m.group(1))) or _native(int(m.group(1)))) + " 번째",
text,
)
# 고유어 조수사 (7게임→일곱 게임, 2방→두 방, 3개→세 개)
text = re.sub(
r"(\d+)\s*(게임|경기|개|명|방|골|마리|살|바퀴)",
lambda m: f"{_native(int(m.group(1)))} {m.group(2)}",
text,
)
# 남은 모든 숫자는 한자어 수사 (1위→일위, 2차전→이차전, 15호→십오호)
return re.sub(r"\d+", lambda m: _sino(int(m.group(0))), text)
def _parse_json(text: str) -> dict:
t = text.strip()
t = re.sub(r"^```(?:json)?\s*|\s*```$", "", t)
m = re.search(r"\{.*\}", t, re.S)
return json.loads(m.group(0) if m else t)
async def write_lyrics(team_name: str, context: str, league: str = "kbo") -> dict:
"""LLM 으로 {title, style, lyrics} 생성 — Claude 우선, GPT 폴백."""
prompt = _lyrics_prompt(team_name, context, league)
if settings.anthropic_api_key:
from anthropic import AsyncAnthropic
client = AsyncAnthropic(api_key=settings.anthropic_api_key)
msg = await client.messages.create(
model=settings.anthropic_model,
max_tokens=8000,
messages=[{"role": "user", "content": prompt}],
)
text = "".join(b.text for b in msg.content if getattr(b, "type", "") == "text")
return _parse_json(text)
if settings.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},
],
response_format={"type": "json_object"},
)
return _parse_json(resp.choices[0].message.content or "{}")
raise RuntimeError("작사용 LLM 키 미설정 (ANTHROPIC/OPENAI)")
# ── 생성 시작 · 폴링 ───────────────────────────────────────────
SONG_LEAGUES = ("kbo", "mlb", "mls") # 응원가 대상 리그
# 라인업 발표를 기다리는 리그 — MLS 는 라인업 소스가 없어 윈도우 진입 즉시 생성
LINEUP_LEAGUES = ("kbo", "mlb")
def _song_leagues() -> list[str]:
return [l for l in SONG_LEAGUES if l in settings.league_list]
def _enabled() -> bool:
return bool(settings.songs_enabled and settings.suno_api_key and _song_leagues())
async def _start_one(db, m: Match, side: str, lineups: dict | None) -> bool:
announced = bool(lineups and lineups.get("announced"))
code, name, context = await build_context(db, m, side, lineups)
row = (
await db.execute(
select(Song).where(Song.match_id == m.match_id, Song.team_code == code)
)
).scalars().first()
if row:
if row.attempts >= MAX_ATTEMPTS:
return False
if row.status == "generating":
return False
# complete 은 '라인업 없이 만든 곡 + 라인업 발표됨'일 때만 재생성(업그레이드)
if row.status == "complete" and (row.with_lineup or not announced):
return False
piece = await write_lyrics(name, context, m.league)
title = str(piece.get("title") or f"{name} 오늘의 응원가").strip()[:40]
style = style_for(m.league) # 전 곡 고정 스타일 — LLM 변주 없음
lyrics = str(piece.get("lyrics") or "").strip()
if not lyrics:
raise RuntimeError("LLM 가사 비어있음")
if len(lyrics) < 450:
raise RuntimeError(f"가사 너무 짧음({len(lyrics)}자) — 재시도")
# 표기용(화면 '가사 보기')은 원문 그대로 저장하고,
# Suno 전송본만 숫자를 한글 발음으로 치환 (13:1 → 십삼 대 일)
sung_lyrics = hangulize_numbers(lyrics)
task_id = await suno.start_generation(title, style, sung_lyrics)
upgrade = bool(row and row.status == "complete")
if row is None:
row = Song(match_id=m.match_id, team_code=code)
db.add(row)
row.league = m.league
row.date_kst = ensure_aware(m.kickoff_at).astimezone(KST).date()
row.team_name = name
row.title = title
row.style = style
row.lyrics = lyrics
row.task_id = task_id
row.status = "generating"
row.error = ""
row.with_lineup = announced
# 업그레이드는 기존 트랙을 유지 — 새 곡 완성 시점에 교체 (재생 공백 없음)
if not upgrade:
row.tracks = []
row.attempts = (row.attempts or 0) + 1
await db.commit()
log.info(
"song 생성 시작: %s %s (task=%s, 라인업=%s%s)",
m.match_id, name, task_id, announced, ", 업그레이드" if upgrade else "",
)
return True
async def start_due_songs(db, force_today: bool = False) -> int:
"""생성 윈도우에 든 경기의 팀별 응원가 생성 시작.
윈도우 안에서는 라인업 발표를 기다렸다가 생성하고, 킥오프
song_lineup_fallback_minutes_before 전까지 미발표면 라인업 없이 생성한다.
라인업 없이 만든 곡은 발표 후 자동 재생성(업그레이드).
force_today=오늘 전 경기 즉시(라인업 대기 없이) 생성 — 테스트용.
"""
now = now_utc()
conds = [
Match.league.in_(_song_leagues()),
Match.result_outcome.is_(None),
Match.status.notin_(("cancelled", "finished")),
]
matches = (await db.execute(select(Match).where(*conds))).scalars().all()
today = now.astimezone(KST).date()
started = 0
for m in matches:
kick = ensure_aware(m.kickoff_at)
mins = (kick - now).total_seconds() / 60
if force_today:
if kick.astimezone(KST).date() != today:
continue
elif not (0 < mins <= settings.song_generate_minutes_before):
continue
try:
lineups = await fetch_lineups(m)
except Exception as e: # noqa: BLE001
log.warning("lineup 조회 실패 %s: %s", m.match_id, e)
lineups = None
announced = bool(lineups and lineups.get("announced"))
# 윈도우 내 라인업 대기 — 폴백 시점 전엔 발표될 때까지 생성 보류.
# 라인업 소스가 없는 리그(MLS)는 윈도우 진입 즉시 생성.
if (
not force_today
and m.league in LINEUP_LEAGUES
and not announced
and mins > settings.song_lineup_fallback_minutes_before
):
continue
for side in ("a", "b"):
try:
if await _start_one(db, m, side, lineups):
started += 1
except Exception as e: # noqa: BLE001 — 팀 단위 독립 실패
await db.rollback()
log.error("song 생성 실패 %s side=%s: %s", m.match_id, side, e)
return started
def _mark_failed(row: Song, error: str) -> None:
"""실패 처리 — 업그레이드 중이었으면(이전 트랙 보유) 이전 곡으로 복귀."""
row.error = error
if row.tracks:
row.status = "complete"
row.with_lineup = False # 다음 틱에 업그레이드 재시도 (attempts 상한 내)
else:
row.status = "failed"
async def poll_generating(db) -> int:
"""generating 상태 Suno 작업 폴링 → 완료/실패 반영."""
rows = (
await db.execute(select(Song).where(Song.status == "generating"))
).scalars().all()
done = 0
for row in rows:
try:
data = await suno.get_task(row.task_id)
except Exception as e: # noqa: BLE001
log.warning("song 폴링 실패 %s: %s", row.task_id, e)
continue
status = data.get("status") or ""
if status == suno.SUNO_DONE:
tracks = suno.extract_tracks(data)
if tracks:
row.tracks = tracks
row.status = "complete"
done += 1
log.info("song 완료: %s %s (%d트랙)", row.match_id, row.team_name, len(tracks))
else:
_mark_failed(row, "SUCCESS 인데 트랙 없음")
elif status in suno.SUNO_FAILED:
_mark_failed(row, f"{status}: {data.get('errorMessage') or ''}"[:300])
log.warning("song 실패: %s %s", row.match_id, row.error)
else:
# 진행 중 — 오래 걸리면 실패 처리 후 재시도 대상으로
created = ensure_aware(row.created_at) if row.created_at else now_utc()
if (now_utc() - created).total_seconds() > GENERATE_TIMEOUT_MIN * 60:
_mark_failed(row, f"타임아웃({status})")
await db.commit()
return done
PERSIST_MAX_FAILS = 3 # 트랙별 다운로드 실패 상한 (만료 URL 무한 재시도 방지)
PERSIST_PER_TICK = 5 # 틱당 다운로드 곡 수 상한 — 틱 지연 방지
async def persist_audio(db, limit: int = PERSIST_PER_TICK) -> int:
"""완성 곡의 노출 트랙(첫 트랙) 음원을 DB(SongAudio)로 보존.
Suno CDN URL 은 임시라 종료된 경기의 응원가도 계속 재생하려면 원본을
내려받아야 한다. audioUrl 이 아직 원격(http)인 complete 곡을 골라
다운로드 → SongAudio 교체 저장 → audioUrl 을 자체 경로로 재작성.
업그레이드로 트랙이 원격 URL 로 갈리면 자동으로 다시 저장된다.
"""
import httpx
rows = (
await db.execute(select(Song).where(Song.status == "complete"))
).scalars().all()
todo = []
for row in rows:
t = (row.tracks or [None])[0]
if not t or not (t.get("audioUrl") or "").startswith("http"):
continue
if (t.get("persistFails") or 0) >= PERSIST_MAX_FAILS:
continue
todo.append(row)
saved = 0
for row in todo[:limit]:
t = dict(row.tracks[0])
try:
async with httpx.AsyncClient(timeout=90, follow_redirects=True) as c:
r = await c.get(t["audioUrl"])
r.raise_for_status()
body = r.content
if not body:
raise ValueError("빈 응답")
mime = (r.headers.get("content-type") or "audio/mpeg").split(";")[0]
except Exception as e: # noqa: BLE001
t["persistFails"] = (t.get("persistFails") or 0) + 1
row.tracks = [t, *row.tracks[1:]]
await db.commit()
log.warning(
"song 음원 보존 실패 %s %s (%d회): %s",
row.match_id, row.team_code, t["persistFails"], e,
)
continue
existing = (
await db.execute(
select(SongAudio).where(
SongAudio.song_id == row.id, SongAudio.track_idx == 0
)
)
).scalar_one_or_none()
if existing:
await db.delete(existing)
await db.flush()
db.add(SongAudio(song_id=row.id, track_idx=0, mime=mime, size=len(body), data=body))
t["sourceUrl"] = t["audioUrl"]
t["audioUrl"] = f"/api/songs/audio/{row.id}/0?v={(row.task_id or '')[:8]}"
t.pop("persistFails", None)
row.tracks = [t, *row.tracks[1:]]
await db.commit()
saved += 1
log.info(
"song 음원 보존: %s %s (%.1fMB)", row.match_id, row.team_code, len(body) / 1e6
)
return saved
async def tick_songs() -> None:
"""워커 주기 작업 — 생성 시작 + 폴링 + 음원 보존. 미설정 시 no-op."""
if not _enabled():
return
async with SessionLocal() as db:
try:
await start_due_songs(db)
except Exception as e: # noqa: BLE001
log.error("song start 오류: %s", e)
try:
await poll_generating(db)
except Exception as e: # noqa: BLE001
log.error("song poll 오류: %s", e)
try:
await persist_audio(db)
except Exception as e: # noqa: BLE001
log.error("song 음원 보존 오류: %s", e)
+104
View File
@@ -0,0 +1,104 @@
"""Suno 음악 생성 클라이언트 — sunoapi.org 서드파티 게이트웨이.
공식 Suno API 가 없어 게이트웨이를 쓴다. 흐름:
POST /api/v1/generate (customMode: 가사·스타일·제목) → taskId
GET /api/v1/generate/record-info?taskId= → status 폴링 → sunoData[] (보통 2곡)
오디오/커버는 게이트웨이 CDN URL 을 그대로 쓴다 (당일 소비 콘텐츠).
"""
from __future__ import annotations
import logging
from ..config import settings
log = logging.getLogger("triplepick.suno")
# record-info status 값
SUNO_DONE = "SUCCESS"
SUNO_FAILED = {
"CREATE_TASK_FAILED",
"GENERATE_AUDIO_FAILED",
"CALLBACK_EXCEPTION",
"SENSITIVE_WORD_ERROR",
}
class SunoUnavailable(RuntimeError):
"""SUNO_API_KEY 미설정 등으로 호출 불가."""
class SunoError(RuntimeError):
"""게이트웨이가 에러 코드를 반환."""
def _headers() -> dict:
if not settings.suno_api_key:
raise SunoUnavailable("SUNO_API_KEY 미설정")
return {
"Authorization": f"Bearer {settings.suno_api_key}",
"Content-Type": "application/json",
}
async def start_generation(title: str, style: str, lyrics: str) -> str:
"""생성 작업 시작 → taskId. customMode: 가사(prompt)·style·title 을 그대로 사용."""
import httpx
payload = {
"prompt": lyrics[:4900],
"style": style[:950],
"title": title[:80],
"customMode": True,
"instrumental": False,
"model": settings.suno_model,
# 게이트웨이 필수 파라미터 — 실제 완료 감지는 폴링으로 한다(콜백은 싱크대).
"callBackUrl": f"{settings.public_origin}/api/songs/callback",
}
async with httpx.AsyncClient(timeout=30) as c:
r = await c.post(
f"{settings.suno_api_base}/api/v1/generate",
json=payload,
headers=_headers(),
)
r.raise_for_status()
data = r.json()
if data.get("code") != 200 or not (data.get("data") or {}).get("taskId"):
raise SunoError(f"generate 실패: {data.get('code')} {data.get('msg')}")
return data["data"]["taskId"]
async def get_task(task_id: str) -> dict:
"""작업 상태 조회 — {status, response: {sunoData: [...]}} 형태의 data 반환."""
import httpx
async with httpx.AsyncClient(timeout=30) as c:
r = await c.get(
f"{settings.suno_api_base}/api/v1/generate/record-info",
params={"taskId": task_id},
headers=_headers(),
)
r.raise_for_status()
data = r.json()
if data.get("code") != 200:
raise SunoError(f"record-info 실패: {data.get('code')} {data.get('msg')}")
return data.get("data") or {}
def extract_tracks(task_data: dict) -> list[dict]:
"""record-info data → 표준 트랙 목록 [{title, audioUrl, imageUrl, duration}]."""
items = ((task_data.get("response") or {}).get("sunoData")) or []
out = []
for it in items:
url = it.get("audioUrl") or it.get("sourceAudioUrl") or ""
if not url:
continue
out.append(
{
"title": it.get("title") or "",
"audioUrl": url,
"imageUrl": it.get("imageUrl") or it.get("sourceImageUrl") or "",
"duration": it.get("duration"),
}
)
return out
+85
View File
@@ -0,0 +1,85 @@
"""야구 팀 데이터 — KBO 10개 구단 + MLB 30개 구단 (코드 → 한글/약식/영문).
KBO 코드: 네이버/KBO 표준 2글자 (HT=KIA, OB=두산, WO=키움, LT=롯데, SK=SSG).
MLB 코드: 공식 약어 (NYY, LAD …) + mlb_id 는 statsapi 의 team.id (불변).
로고: frontend /assets/teams/{league}/{code소문자}.png
"""
from __future__ import annotations
# ── KBO ────────────────────────────────────────────────────────
KBO_TEAMS: dict[str, dict] = {
"HT": {"ko": "KIA 타이거즈", "short": "KIA", "en": "Kia Tigers", "home": "광주기아챔피언스필드"},
"LG": {"ko": "LG 트윈스", "short": "LG", "en": "LG Twins", "home": "잠실야구장"},
"OB": {"ko": "두산 베어스", "short": "두산", "en": "Doosan Bears", "home": "잠실야구장"},
"SS": {"ko": "삼성 라이온즈", "short": "삼성", "en": "Samsung Lions", "home": "대구삼성라이온즈파크"},
"LT": {"ko": "롯데 자이언츠", "short": "롯데", "en": "Lotte Giants", "home": "사직야구장"},
"SK": {"ko": "SSG 랜더스", "short": "SSG", "en": "SSG Landers", "home": "인천SSG랜더스필드"},
"KT": {"ko": "KT 위즈", "short": "KT", "en": "KT Wiz", "home": "수원KT위즈파크"},
"NC": {"ko": "NC 다이노스", "short": "NC", "en": "NC Dinos", "home": "창원NC파크"},
"WO": {"ko": "키움 히어로즈", "short": "키움", "en": "Kiwoom Heroes", "home": "고척스카이돔"},
"HH": {"ko": "한화 이글스", "short": "한화", "en": "Hanwha Eagles", "home": "대전한화생명볼파크"},
}
# ── MLB (statsapi team.id → 우리 코드) ─────────────────────────
MLB_TEAMS: dict[str, dict] = {
"LAD": {"ko": "LA 다저스", "short": "다저스", "en": "Los Angeles Dodgers", "mlb_id": 119},
"NYY": {"ko": "뉴욕 양키스", "short": "양키스", "en": "New York Yankees", "mlb_id": 147},
"NYM": {"ko": "뉴욕 메츠", "short": "메츠", "en": "New York Mets", "mlb_id": 121},
"BOS": {"ko": "보스턴 레드삭스", "short": "보스턴", "en": "Boston Red Sox", "mlb_id": 111},
"CHC": {"ko": "시카고 컵스", "short": "컵스", "en": "Chicago Cubs", "mlb_id": 112},
"CWS": {"ko": "시카고 화이트삭스", "short": "화이트삭스", "en": "Chicago White Sox", "mlb_id": 145},
"CLE": {"ko": "클리블랜드 가디언스", "short": "클리블랜드", "en": "Cleveland Guardians", "mlb_id": 114},
"DET": {"ko": "디트로이트 타이거스", "short": "디트로이트", "en": "Detroit Tigers", "mlb_id": 116},
"HOU": {"ko": "휴스턴 애스트로스", "short": "휴스턴", "en": "Houston Astros", "mlb_id": 117},
"KC": {"ko": "캔자스시티 로열스", "short": "캔자스시티", "en": "Kansas City Royals", "mlb_id": 118},
"LAA": {"ko": "LA 에인절스", "short": "에인절스", "en": "Los Angeles Angels", "mlb_id": 108},
"MIN": {"ko": "미네소타 트윈스", "short": "미네소타", "en": "Minnesota Twins", "mlb_id": 142},
"ATH": {"ko": "애슬레틱스", "short": "애슬레틱스", "en": "Athletics", "mlb_id": 133},
"SEA": {"ko": "시애틀 매리너스", "short": "시애틀", "en": "Seattle Mariners", "mlb_id": 136},
"TB": {"ko": "탬파베이 레이스", "short": "탬파베이", "en": "Tampa Bay Rays", "mlb_id": 139},
"TEX": {"ko": "텍사스 레인저스", "short": "텍사스", "en": "Texas Rangers", "mlb_id": 140},
"TOR": {"ko": "토론토 블루제이스", "short": "토론토", "en": "Toronto Blue Jays", "mlb_id": 141},
"ARI": {"ko": "애리조나 다이아몬드백스", "short": "애리조나", "en": "Arizona Diamondbacks", "mlb_id": 109},
"ATL": {"ko": "애틀랜타 브레이브스", "short": "애틀랜타", "en": "Atlanta Braves", "mlb_id": 144},
"BAL": {"ko": "볼티모어 오리올스", "short": "볼티모어", "en": "Baltimore Orioles", "mlb_id": 110},
"CIN": {"ko": "신시내티 레즈", "short": "신시내티", "en": "Cincinnati Reds", "mlb_id": 113},
"COL": {"ko": "콜로라도 로키스", "short": "콜로라도", "en": "Colorado Rockies", "mlb_id": 115},
"MIA": {"ko": "마이애미 말린스", "short": "마이애미", "en": "Miami Marlins", "mlb_id": 146},
"MIL": {"ko": "밀워키 브루어스", "short": "밀워키", "en": "Milwaukee Brewers", "mlb_id": 158},
"WSH": {"ko": "워싱턴 내셔널스", "short": "워싱턴", "en": "Washington Nationals", "mlb_id": 120},
"PHI": {"ko": "필라델피아 필리스", "short": "필라델피아", "en": "Philadelphia Phillies", "mlb_id": 143},
"PIT": {"ko": "피츠버그 파이리츠", "short": "피츠버그", "en": "Pittsburgh Pirates", "mlb_id": 134},
"SD": {"ko": "샌디에이고 파드리스", "short": "샌디에이고", "en": "San Diego Padres", "mlb_id": 135},
"SF": {"ko": "샌프란시스코 자이언츠", "short": "SF", "en": "San Francisco Giants", "mlb_id": 137},
"STL": {"ko": "세인트루이스 카디널스", "short": "세인트루이스", "en": "St. Louis Cardinals", "mlb_id": 138},
}
MLB_ID_TO_CODE: dict[int, str] = {v["mlb_id"]: k for k, v in MLB_TEAMS.items()}
# 순위표 등 팀 축약명 → 코드 (리그별)
KBO_SHORT_TO_CODE = {v["short"]: k for k, v in KBO_TEAMS.items()}
def teams_of(league: str) -> dict[str, dict]:
if league == "mls":
from .teams_mls import MLS_TEAMS
return MLS_TEAMS
return KBO_TEAMS if league == "kbo" else MLB_TEAMS
def team_info(league: str, code: str) -> dict:
"""flag 에 로고 경로/URL 을 실어 프론트(TeamFlag)가 그대로 렌더한다.
KBO: 로컬 자산(/assets/teams/kbo/*.png) · MLB: 공식 CDN(mlbstatic) SVG ·
MLS: ESPN CDN PNG."""
c = (code or "").strip().upper()
t = teams_of(league).get(c)
if not t:
return {"name": c, "shortName": c, "code": c, "flag": ""}
if league == "mlb":
flag = f"https://www.mlbstatic.com/team-logos/{t['mlb_id']}.svg"
elif league == "mls":
flag = f"https://a.espncdn.com/i/teamlogos/soccer/500/{t['espn_id']}.png"
else:
flag = f"/assets/teams/kbo/{c.lower()}.png"
return {"name": t["ko"], "shortName": t["short"], "code": c, "flag": flag}
+49
View File
@@ -0,0 +1,49 @@
"""MLS 팀 데이터 — 30개 구단 (ESPN 약어 코드 → 한글/약식/영문/ESPN ID).
코드: ESPN abbreviation (일정·순위·라이브 매칭 키와 동일해 변환 불필요).
espn_id: ESPN 팀 ID (불변) — 로고 CDN URL 조립에 사용.
로고: https://a.espncdn.com/i/teamlogos/soccer/500/{espn_id}.png
"""
from __future__ import annotations
MLS_TEAMS: dict[str, dict] = {
# ── 동부(Eastern Conference) ─────────────────────────────
"ATL": {"ko": "애틀랜타 유나이티드", "short": "애틀랜타", "en": "Atlanta United FC", "espn_id": 18418},
"CLT": {"ko": "샬럿 FC", "short": "샬럿", "en": "Charlotte FC", "espn_id": 21300},
"CHI": {"ko": "시카고 파이어", "short": "시카고", "en": "Chicago Fire FC", "espn_id": 182},
"CIN": {"ko": "FC 신시내티", "short": "신시내티", "en": "FC Cincinnati", "espn_id": 18267},
"CLB": {"ko": "콜럼버스 크루", "short": "콜럼버스", "en": "Columbus Crew", "espn_id": 183},
"DC": {"ko": "DC 유나이티드", "short": "DC", "en": "D.C. United", "espn_id": 193},
"MIA": {"ko": "인터 마이애미", "short": "마이애미", "en": "Inter Miami CF", "espn_id": 20232},
"MTL": {"ko": "CF 몬트리올", "short": "몬트리올", "en": "CF Montréal", "espn_id": 9720},
"NSH": {"ko": "내슈빌 SC", "short": "내슈빌", "en": "Nashville SC", "espn_id": 18986},
"NE": {"ko": "뉴잉글랜드 레볼루션", "short": "뉴잉글랜드", "en": "New England Revolution", "espn_id": 189},
"NYC": {"ko": "뉴욕 시티 FC", "short": "뉴욕시티", "en": "New York City FC", "espn_id": 17606},
"RBNY": {"ko": "뉴욕 레드불스", "short": "레드불스", "en": "New York Red Bulls", "espn_id": 190},
"ORL": {"ko": "올랜도 시티", "short": "올랜도", "en": "Orlando City SC", "espn_id": 12011},
"PHI": {"ko": "필라델피아 유니언", "short": "필라델피아", "en": "Philadelphia Union", "espn_id": 10739},
"TOR": {"ko": "토론토 FC", "short": "토론토", "en": "Toronto FC", "espn_id": 7318},
# ── 서부(Western Conference) ─────────────────────────────
"ATX": {"ko": "오스틴 FC", "short": "오스틴", "en": "Austin FC", "espn_id": 20906},
"COL": {"ko": "콜로라도 래피즈", "short": "콜로라도", "en": "Colorado Rapids", "espn_id": 184},
"DAL": {"ko": "FC 댈러스", "short": "댈러스", "en": "FC Dallas", "espn_id": 185},
"HOU": {"ko": "휴스턴 다이너모", "short": "휴스턴", "en": "Houston Dynamo FC", "espn_id": 6077},
"LA": {"ko": "LA 갤럭시", "short": "LA갤럭시", "en": "LA Galaxy", "espn_id": 187},
"LAFC": {"ko": "LAFC", "short": "LAFC", "en": "LAFC", "espn_id": 18966},
"MIN": {"ko": "미네소타 유나이티드", "short": "미네소타", "en": "Minnesota United FC", "espn_id": 17362},
"POR": {"ko": "포틀랜드 팀버스", "short": "포틀랜드", "en": "Portland Timbers", "espn_id": 9723},
"RSL": {"ko": "레알 솔트레이크", "short": "솔트레이크", "en": "Real Salt Lake", "espn_id": 4771},
"SD": {"ko": "샌디에이고 FC", "short": "샌디에이고", "en": "San Diego FC", "espn_id": 22529},
"SJ": {"ko": "산호세 어스퀘이크스", "short": "산호세", "en": "San Jose Earthquakes", "espn_id": 191},
"SEA": {"ko": "시애틀 사운더스", "short": "시애틀", "en": "Seattle Sounders FC", "espn_id": 9726},
"SKC": {"ko": "스포팅 캔자스시티", "short": "캔자스시티", "en": "Sporting Kansas City", "espn_id": 186},
"STL": {"ko": "세인트루이스 시티", "short": "세인트루이스", "en": "St. Louis CITY SC", "espn_id": 21812},
"VAN": {"ko": "밴쿠버 화이트캡스", "short": "밴쿠버", "en": "Vancouver Whitecaps FC", "espn_id": 9727},
}
MLS_ID_TO_CODE: dict[int, str] = {v["espn_id"]: k for k, v in MLS_TEAMS.items()}
def mls_logo(code: str) -> str:
t = MLS_TEAMS.get(code)
return f"https://a.espncdn.com/i/teamlogos/soccer/500/{t['espn_id']}.png" if t else ""
+227 -25
View File
@@ -19,7 +19,7 @@ from __future__ import annotations
import asyncio import asyncio
import logging import logging
from datetime import timedelta from datetime import timedelta, timezone
from apscheduler.schedulers.asyncio import AsyncIOScheduler from apscheduler.schedulers.asyncio import AsyncIOScheduler
from sqlalchemy import select from sqlalchemy import select
@@ -30,12 +30,15 @@ from .database import SessionLocal, init_db
from .domain import compute_phase, ensure_aware, now_utc from .domain import compute_phase, ensure_aware, now_utc
from .models import AIPrediction, Match, UserPrediction from .models import AIPrediction, Match, UserPrediction
from .scoring import load_scoring_data from .scoring import load_scoring_data
from .services import football_data from .services import baseball_data, baseball_details, football_data, mls_espn
from .services.ai import MatchContext, PROVIDERS, ProviderUnavailable from .services.ai import MatchContext, PROVIDERS, ProviderUnavailable
from .services.baseball_fetch import fetch_baseball_schedule
from .services.baseball_sync import match_seq, sync_baseball_schedule
from .services.email import EmailUnavailable, build_result_email, send_email from .services.email import EmailUnavailable, build_result_email, send_email
from .services.grading import apply_result from .services.grading import apply_result
from .services.schedule_fetch import fetch_results, fetch_schedule from .services.schedule_fetch import fetch_results, fetch_schedule
from .services.schedule_sync import sync_schedule from .services.schedule_sync import sync_schedule
from .services.songs import tick_songs
logging.basicConfig(level=logging.INFO) logging.basicConfig(level=logging.INFO)
log = logging.getLogger("triplepick.worker") log = logging.getLogger("triplepick.worker")
@@ -43,6 +46,9 @@ log = logging.getLogger("triplepick.worker")
# ── 0) 경기 일정 동기화 (외부 크롤링) ────────────────────── # ── 0) 경기 일정 동기화 (외부 크롤링) ──────────────────────
async def sync_schedule_job() -> None: async def sync_schedule_job() -> None:
"""월드컵(축구) 일정 동기화 — 기존 로직 그대로."""
if "wc" not in settings.league_list:
return
records = await fetch_schedule() records = await fetch_schedule()
if not records: if not records:
return return
@@ -56,6 +62,44 @@ async def sync_schedule_job() -> None:
await generate_ai_predictions() await generate_ai_predictions()
async def sync_baseball_job() -> None:
"""야구(kbo/mlb)+MLS 일정 동기화 + 프리뷰·순위 캐시 갱신.
MLS 도 (리그, KST 날짜, 팀쌍, 차수) 키 구조가 동일해 야구 sync 를 그대로 탄다.
"""
inserted_any = False
for league in settings.league_list:
if league not in ("kbo", "mlb", "mls"):
continue
records = (
await mls_espn.fetch_mls_schedule()
if league == "mls"
else await fetch_baseball_schedule(league)
)
if not records:
continue
async with SessionLocal() as db:
result = await sync_baseball_schedule(db, league, records)
rows = (
await db.execute(
select(Match).where(
Match.league == league, Match.result_outcome.is_(None)
)
)
).scalars().all()
try:
if league == "mls":
await mls_espn.refresh_mls_details(db, rows)
else:
await baseball_details.refresh_baseball_details(db, league, rows)
except Exception as e: # noqa: BLE001
log.warning("details(%s) 갱신 실패: %s", league, e)
inserted_any = inserted_any or bool(result.get("inserted"))
await tick_status()
if inserted_any:
await generate_ai_predictions()
# ── 1) 상태 전이 ──────────────────────────────────────────── # ── 1) 상태 전이 ────────────────────────────────────────────
async def tick_status() -> None: async def tick_status() -> None:
async with SessionLocal() as db: async with SessionLocal() as db:
@@ -83,11 +127,15 @@ async def generate_ai_predictions(only_missing: bool = True) -> None:
생성한다(직전에 실패/누락된 모델만 채워짐 — API 비용↓, 예측 안정). 생성한다(직전에 실패/누락된 모델만 채워짐 — API 비용↓, 예측 안정).
only_missing=False: 전부 재생성(덮어쓰기) — 수동 재생성 스크립트용. only_missing=False: 전부 재생성(덮어쓰기) — 수동 재생성 스크립트용.
""" """
if not settings.ai_enabled:
log.info("AI 예측 생성 스킵 — AI_ENABLED=false (로컬 테스트 모드)")
return
async with SessionLocal() as db: async with SessionLocal() as db:
# 투표 오픈(킥오프 D-2)이 임박/도래한 미종료 경기 — 조 무관. # 킥오프가 lookahead(기본 22h) 이내로 다가온 미시작 경기만 생성.
# lookahead_hours 만큼 선행 생성해 다음 생성 주기 전에 오픈할 경기도 미리 채운다 # 야구 선발투수 예고(전날 저녁)가 나온 뒤 시점이라 데이터 품질이 좋다.
# (1일 1회 생성 → 오픈 시점에 AI 가 비어 보이지 않도록). 더 먼 미래 경기는 제외. # 킥오프가 지난 경기는 제외(경기 중 생성 = 사후 예측 방지). 취소 경기 제외.
horizon = now_utc() + timedelta(hours=settings.ai_generate_lookahead_hours) now = now_utc()
horizon = now + timedelta(hours=settings.ai_generate_lookahead_hours)
rows = ( rows = (
await db.execute( await db.execute(
select(Match) select(Match)
@@ -95,17 +143,28 @@ async def generate_ai_predictions(only_missing: bool = True) -> None:
.options(selectinload(Match.predictions)) .options(selectinload(Match.predictions))
) )
).scalars().all() ).scalars().all()
matches = [m for m in rows if ensure_aware(m.opens_at) <= horizon] matches = [
m for m in rows
if m.status != "cancelled"
and now < ensure_aware(m.kickoff_at) <= horizon
]
for m in matches: for m in matches:
# 실데이터 블록(폼·H2H·랭킹·WC결과) — 캐시만 읽음. 없으면 None(이름만). # 실데이터 블록 — 리그별 소스(축구=API-Football 캐시, 야구=자체DB+프리뷰,
data_block = await football_data.build_data_block(db, m) # MLS=자체DB+ESPN 프리뷰).
if m.league in ("kbo", "mlb"):
data_block = await baseball_data.build_baseball_data_block(db, m)
elif m.league == "mls":
data_block = await mls_espn.build_mls_data_block(db, m)
else:
data_block = await football_data.build_data_block(db, m)
ctx = MatchContext( ctx = MatchContext(
team_a=m.team_a_name, team_a=m.team_a_name,
team_b=m.team_b_name, team_b=m.team_b_name,
venue=m.venue, venue=m.venue,
kickoff=m.kickoff_at.isoformat(), kickoff=m.kickoff_at.isoformat(),
data_block=data_block, data_block=data_block,
league=m.league,
) )
for model, fn in PROVIDERS.items(): for model, fn in PROVIDERS.items():
pred = next((p for p in m.predictions if p.model == model), None) pred = next((p for p in m.predictions if p.model == model), None)
@@ -133,7 +192,9 @@ async def generate_ai_predictions(only_missing: bool = True) -> None:
pred.generated_at = now_utc() pred.generated_at = now_utc()
pred.source = "llm" pred.source = "llm"
log.info("AI %s → %s %d-%d", model, m.match_id, data["scoreA"], data["scoreB"]) log.info("AI %s → %s %d-%d", model, m.match_id, data["scoreA"], data["scoreB"])
await db.commit() # 경기 단위 커밋 — 수백 콜 도중 재시작/오류가 나도 진행분을 잃지
# 않는다(전체 커밋이면 중단 시 API 비용을 다시 지출하게 됨).
await db.commit()
# ── 2.1) 축구 데이터 수집 (예측 생성 전에 캐시를 채워둔다) ── # ── 2.1) 축구 데이터 수집 (예측 생성 전에 캐시를 채워둔다) ──
@@ -149,7 +210,11 @@ async def refresh_football_data() -> None:
return return
async with SessionLocal() as db: async with SessionLocal() as db:
rows = ( rows = (
await db.execute(select(Match).where(Match.result_outcome.is_(None))) await db.execute(
select(Match).where(
Match.result_outcome.is_(None), Match.league == "wc"
)
)
).scalars().all() ).scalars().all()
# 가까운 경기부터 우선 수집(하루 예산 소진 시 먼 경기 팀은 다음 잡에서). # 가까운 경기부터 우선 수집(하루 예산 소진 시 먼 경기 팀은 다음 잡에서).
matches = sorted(rows, key=lambda m: ensure_aware(m.kickoff_at)) matches = sorted(rows, key=lambda m: ensure_aware(m.kickoff_at))
@@ -178,7 +243,11 @@ async def settle_matches() -> None:
) )
async with SessionLocal() as db: async with SessionLocal() as db:
pending = ( pending = (
await db.execute(select(Match).where(Match.result_outcome.is_(None))) await db.execute(
select(Match).where(
Match.league == "wc", Match.result_outcome.is_(None)
)
)
).scalars().all() ).scalars().all()
# 킥오프가 지난 경기만 (소스가 FINISHED 줄 수 있는 시점) # 킥오프가 지난 경기만 (소스가 FINISHED 줄 수 있는 시점)
due = [m.match_id for m in pending if ensure_aware(m.kickoff_at) <= now] due = [m.match_id for m in pending if ensure_aware(m.kickoff_at) <= now]
@@ -188,6 +257,7 @@ async def settle_matches() -> None:
finished = ( finished = (
await db.execute( await db.execute(
select(Match).where( select(Match).where(
Match.league == "wc",
Match.result_outcome.is_not(None), Match.result_outcome.is_not(None),
Match.finished_at.is_not(None), Match.finished_at.is_not(None),
) )
@@ -202,10 +272,23 @@ async def settle_matches() -> None:
if due or recheck_ids: if due or recheck_ids:
results = await fetch_results() results = await fetch_results()
# 정방향/역방향 키 모두 등록 — 소스의 홈/원정 순서가 우리와 달라도 매칭. # 정방향/역방향 키 모두 등록 — 소스의 홈/원정 순서가 우리와 달라도 매칭.
# 라운드(round_label)를 키에 포함해 같은 두 팀의 조별리그·토너먼트 경기를 구분.
# round_label 없는 소스(openfootball) 대비 라운드 무시 키도 함께 등록(폴백).
by_pair: dict[tuple, tuple[int, int]] = {} by_pair: dict[tuple, tuple[int, int]] = {}
for r in results: for r in results:
by_pair[(r["teamA"], r["teamB"])] = (r["scoreA"], r["scoreB"]) rl = r.get("roundLabel", "")
by_pair[(r["teamB"], r["teamA"])] = (r["scoreB"], r["scoreA"]) # 뒤집어 저장 a2, b2, sa, sb = r["teamA"], r["teamB"], r["scoreA"], r["scoreB"]
for key in ((rl, a2, b2), (a2, b2)):
by_pair[key] = (sa, sb)
for key in ((rl, b2, a2), (b2, a2)): # 뒤집어 저장
by_pair[key] = (sb, sa)
def _lookup(m: Match) -> tuple[int, int] | None:
# 라운드까지 일치하는 결과 우선, 없으면 팀쌍만으로 폴백.
return by_pair.get((m.round_label, m.team_a_code, m.team_b_code)) or by_pair.get(
(m.team_a_code, m.team_b_code)
)
settled = corrected = 0 settled = corrected = 0
async with SessionLocal() as db: async with SessionLocal() as db:
# 1) 신규 정산 — 미정산 경기에 FINISHED 스코어 반영 # 1) 신규 정산 — 미정산 경기에 FINISHED 스코어 반영
@@ -213,7 +296,7 @@ async def settle_matches() -> None:
m = await db.get(Match, mid) m = await db.get(Match, mid)
if m is None or m.result_outcome is not None: if m is None or m.result_outcome is not None:
continue continue
sc = by_pair.get((m.team_a_code, m.team_b_code)) sc = _lookup(m)
if not sc: if not sc:
continue continue
await apply_result(db, m, sc[0], sc[1]) # 우리 팀A/팀B 기준으로 채점+집계+commit await apply_result(db, m, sc[0], sc[1]) # 우리 팀A/팀B 기준으로 채점+집계+commit
@@ -224,7 +307,7 @@ async def settle_matches() -> None:
m = await db.get(Match, mid) m = await db.get(Match, mid)
if m is None or m.result_outcome is None: if m is None or m.result_outcome is None:
continue continue
sc = by_pair.get((m.team_a_code, m.team_b_code)) sc = _lookup(m)
if not sc: if not sc:
continue # 소스에 아직 없으면 기존값 유지 continue # 소스에 아직 없으면 기존값 유지
if (m.result_score_a, m.result_score_b) == (sc[0], sc[1]): if (m.result_score_a, m.result_score_b) == (sc[0], sc[1]):
@@ -244,6 +327,106 @@ async def settle_matches() -> None:
await maybe_send_result_emails() await maybe_send_result_emails()
# ── 2.6) 야구·MLS 결과 자동 정산 — (리그, KST 날짜, 팀쌍) 키 매칭 ──
# 킥오프 후 이 시간이 지나도록 소스 일정에 없는 미정산 경기는 취소로 본다.
_VANISHED_GRACE = timedelta(hours=24)
async def settle_baseball() -> None:
_KST = timedelta(hours=9)
now = now_utc()
for league in settings.league_list:
if league not in ("kbo", "mlb", "mls"):
continue
async with SessionLocal() as db:
pending = (
await db.execute(
select(Match).where(
Match.league == league,
Match.result_outcome.is_(None),
Match.status != "cancelled",
)
)
).scalars().all()
due_matches = [m for m in pending if ensure_aware(m.kickoff_at) <= now]
if not due_matches:
continue
due = [m.match_id for m in due_matches]
# 미정산 경기 중 가장 오래된 킥오프까지 덮도록 조회 범위를 동적 확장.
# 기본 윈도우(며칠)만 쓰면 첫 수집에 실패한 경기가 윈도우 밖으로
# 밀려나 영원히 "live"에 고정되는 문제가 있었다 — 최대 120일까지 소급.
oldest_kst_date = min(
ensure_aware(m.kickoff_at).astimezone(timezone(_KST)).date()
for m in due_matches
)
today_kst = now.astimezone(timezone(_KST)).date()
days_back = min((today_kst - oldest_kst_date).days + 1, 120)
# 스코어 없는 레코드(취소·진행 중)도 필요해 결과만이 아닌 일정 전체를 받는다.
records = (
await mls_espn.fetch_mls_schedule(days_back=days_back)
if league == "mls"
else await fetch_baseball_schedule(league, days_back=days_back)
)
if not records:
continue # 수집 실패 — 판단 근거 없음. 다음 틱에 재시도
by_key: dict[tuple, tuple[int, int]] = {}
cancelled_keys: set[tuple] = set()
known_keys: set[tuple] = set()
for r in records:
d, a2, b2, s = r["dateKst"], r["teamA"], r["teamB"], r.get("seq", 1)
known_keys.update({(d, a2, b2, s), (d, b2, a2, s)})
if r.get("cancelled"):
cancelled_keys.update({(d, a2, b2, s), (d, b2, a2, s)})
elif "scoreA" in r:
by_key[(d, a2, b2, s)] = (r["scoreA"], r["scoreB"])
by_key[(d, b2, a2, s)] = (r["scoreB"], r["scoreA"])
# 소스에서 사라진 경기(치러지지 않은 포스트시즌 예비 편성·일정 이동의 옛 날짜)
# 판정 범위 — 요청 윈도우와 실제 응답이 덮은 날짜가 겹치는 구간만 신뢰한다
# (응답이 잘렸을 때 멀쩡한 경기를 취소로 오판하지 않게).
rec_dates = [r["dateKst"] for r in records]
covered_from = max(
min(rec_dates), (today_kst - timedelta(days=days_back)).strftime("%Y%m%d")
)
# 네이버(KBO)는 size=500 상한으로 응답 뒤쪽이 잘릴 수 있어 응답이 덮은 마지막
# 날짜까지만 신뢰한다. MLB·ESPN 은 상한에 걸리지 않아 오늘까지 신뢰
# (시즌 종료 후 남은 예비 편성 경기가 여기에 해당).
covered_to = max(rec_dates) if league == "kbo" else today_kst.strftime("%Y%m%d")
vanished_cutoff = now - _VANISHED_GRACE
settled = cancelled = 0
async with SessionLocal() as db:
for mid in due:
m = await db.get(Match, mid)
if m is None or m.result_outcome is not None:
continue
d = (ensure_aware(m.kickoff_at) + _KST).strftime("%Y%m%d")
key = (d, m.team_a_code, m.team_b_code, match_seq(mid))
sc = by_key.get(key)
if sc:
await apply_result(db, m, sc[0], sc[1])
settled += 1
log.info("settle(%s): %s 자동 정산 %d-%d", league, mid, sc[0], sc[1])
continue
source_cancelled = key in cancelled_keys
vanished = (
key not in known_keys
and covered_from <= d <= covered_to
and ensure_aware(m.kickoff_at) <= vanished_cutoff
)
if source_cancelled or vanished:
# sync 와 같은 소프트 취소 — 투표·예측 기록은 보존.
m.status = "cancelled"
cancelled += 1
log.warning(
"settle(%s): %s 취소 처리 (%s)", league, mid,
"소스 연기·취소" if source_cancelled else "소스에서 사라짐",
)
if cancelled:
await db.commit()
if settled:
await maybe_send_result_emails()
# ── 3) 결과 메일 ──────────────────────────────────────────── # ── 3) 결과 메일 ────────────────────────────────────────────
async def maybe_send_result_emails() -> None: async def maybe_send_result_emails() -> None:
async with SessionLocal() as db: async with SessionLocal() as db:
@@ -337,13 +520,14 @@ def build_scheduler() -> AsyncIOScheduler:
minute=settings.football_refresh_minute, minute=settings.football_refresh_minute,
id="football_refresh", id="football_refresh",
) )
# AI 예측 생성: 매일 KST 00:05 (실 API) # AI 예측 생성: 매시간 — 킥오프 22h 전에 든 경기를 놓치지 않게.
# only_missing 이라 이미 생성된 (경기×모델)은 API 호출 없이 건너뜀(비용 동일).
sched.add_job( sched.add_job(
generate_ai_predictions, generate_ai_predictions,
"cron", "interval",
hour=settings.ai_generate_hour, hours=1,
minute=settings.ai_generate_minute,
id="ai_generate", id="ai_generate",
next_run_time=now_utc(),
) )
# 결과 자동 정산 + 메일: 킥오프+Nh 지난 경기 스코어 수집·채점·발송 # 결과 자동 정산 + 메일: 킥오프+Nh 지난 경기 스코어 수집·채점·발송
sched.add_job( sched.add_job(
@@ -353,29 +537,47 @@ def build_scheduler() -> AsyncIOScheduler:
id="settle", id="settle",
next_run_time=now_utc(), next_run_time=now_utc(),
) )
# 야구(kbo/mlb): 일정·프리뷰 동기화 매일 09:00 + AI 생성 직전 00:00
sched.add_job(
sync_baseball_job, "cron",
hour=settings.schedule_sync_hour, minute=settings.schedule_sync_minute,
id="baseball_sync",
)
sched.add_job(sync_baseball_job, "cron", hour=0, minute=0, id="baseball_sync_night")
# 야구 결과 정산 폴링
sched.add_job(
settle_baseball, "interval",
seconds=settings.settle_tick_seconds, id="baseball_settle",
)
# 오늘의 응원가: 킥오프 임박 경기 생성 시작 + Suno 작업 폴링
sched.add_job(
tick_songs, "interval",
seconds=settings.song_tick_seconds, id="songs",
next_run_time=now_utc(),
)
return sched return sched
async def main() -> None: async def main() -> None:
load_scoring_data() # data/scoring.json → 배점·배제 대상 (채점·결과메일에 사용) load_scoring_data() # data/scoring.json → 배점·배제 대상 (채점·결과메일에 사용)
await init_db() # 테이블 보장 (idempotent). 시드는 API 가 담당. await init_db() # 테이블 보장 (idempotent). 시드는 API 가 담당.
# 기동 시 1회: 일정 동기화 → AI 예측 생성 → 밀린 경기 자동 정산 # 기동 시 1회: 일정 동기화(축구+야구) → AI 예측 생성 → 밀린 경기 자동 정산
await sync_schedule_job() await sync_schedule_job()
await sync_baseball_job()
await refresh_football_data() # 축구 데이터 캐시 선채움 (키 없으면 no-op) await refresh_football_data() # 축구 데이터 캐시 선채움 (키 없으면 no-op)
await generate_ai_predictions() await generate_ai_predictions()
await settle_matches() await settle_matches()
await settle_baseball()
sched = build_scheduler() sched = build_scheduler()
sched.start() sched.start()
log.info( log.info(
"scheduling-server started — schedule sync daily %02d:%02d · status every %ss · " "scheduling-server started — schedule sync daily %02d:%02d · status every %ss · "
"AI gen daily %02d:%02d %s · auto-settle on FINISHED (poll every %ss) · 맞춘사람만=%s", "AI gen hourly (kickoff-%dh) · auto-settle on FINISHED (poll every %ss) · 맞춘사람만=%s",
settings.schedule_sync_hour, settings.schedule_sync_hour,
settings.schedule_sync_minute, settings.schedule_sync_minute,
settings.status_tick_seconds, settings.status_tick_seconds,
settings.ai_generate_hour, settings.ai_generate_lookahead_hours,
settings.ai_generate_minute,
settings.timezone,
settings.settle_tick_seconds, settings.settle_tick_seconds,
settings.result_email_correct_only, settings.result_email_correct_only,
) )
+2
View File
@@ -10,6 +10,8 @@ aiosmtplib==3.0.2
azure-communication-email==1.0.0 azure-communication-email==1.0.0
aiohttp==3.10.11 aiohttp==3.10.11
httpx==0.27.2 httpx==0.27.2
python-jose[cryptography]==3.5.0
anthropic==0.69.0 anthropic==0.69.0
openai==1.59.6 openai==1.59.6
google-genai==0.8.0 google-genai==0.8.0
pillow==11.1.0
+38
View File
@@ -0,0 +1,38 @@
# 야구(KBO/MLB) 데이터 소스 카탈로그 (실검증: 2026-07-21)
## 소스 총평
| 소스 | 상태 | 요약 |
|---|---|---|
| **네이버 스포츠 API** (비공식) | ✅ KBO 주력 | 일정·결과·순위·프리뷰·박스스코어·문자중계(투구 단위)까지 전부. 키 불필요, UA 헤더만 |
| **MLB 공식 Stats API** | ✅ MLB 주력 | statsapi.mlb.com — 키 불필요·공식. 일정·결과·순위·예고선발·투구 단위 라이브 피드 |
| TheSportsDB | ⚠️ 유료 전용 | 무료 키 `123`은 next/past 조회당 1경기만(전 리그 공통). 유료 ~$10/월 |
| API-Sports 야구 | ❌ 미사용 | KBO=league 5 존재하나 무료는 2022~24 시즌만 |
## 네이버 (api-gw.sports.naver.com) — KBO
- 인증 없음, User-Agent 필수. gameId = `{yyyymmdd}{원정}{홈}0{연도}`
- 팀코드: HT(KIA) LG OB(두산) SS(삼성) LT(롯데) SK(SSG) KT NC WO(키움) HH(한화)
- `GET /schedule/games?...&categoryId=kbo&fromDate=&toDate=` — 일정·스코어·statusInfo("N회초/말")·cancel·suspended
- `GET /schedule/games/{id}/preview` — 예고 선발투수(구종·상대전적)·핫콜드존·시즌 상대전적·순위
- `GET /schedule/games/{id}/record` — R/H/E/B·이닝별·타자/투수 박스스코어·교체·홈런일지
- `GET /schedule/games/{id}/relay?inning=N` — currentGameState(투수/타자/볼카운트/주자)·라인업(seqno=교체)·투구단위 텍스트
- `GET /stats/categories/kbo/seasons/{year}/teams` — 순위·승률·최근5·팀 공격/수비 풀스탯
- 리스크: 비공식(약관·차단). 로컬/데모용 — 상용 전환 시 정식 소스 교체
## MLB 공식 (statsapi.mlb.com) — MLB
- `GET /api/v1/schedule?sportId=1&startDate=&endDate=` (+`&hydrate=probablePitcher`)
- `GET /api/v1/standings?leagueId=103|104&season=` — AL/NL 지구 순위
- `GET /api/v1.1/game/{gamePk}/feed/live` — linescore(B/S/O·주자)·offense(batter/onDeck/inHole/pitcher)·boxscore(타순·포지션)·plays(투구 단위)
- 팀 로고: `https://www.mlbstatic.com/team-logos/{teamId}.svg` (공식 CDN)
- 한글 팀명은 자체 매핑(`teams_baseball.py`), 선수명은 영문
## 구현 위치 (backend/app)
- `teams_baseball.py` — KBO 10 + MLB 30 (한글·statsapi id·로고)
- `services/baseball_fetch.py` — 일정·결과 수집 (리그별 어댑터)
- `services/baseball_sync.py` — (리그, KST날짜, 팀쌍) 키 동기화 · 우천취소 제거
- `services/baseball_details.py` — 프리뷰·순위 캐시(DataCache) + 라이브 필드 뷰 프록시(15s TTL)
- `services/baseball_data.py` — AI 프롬프트 데이터 블록 (자체 DB 폼 + 캐시)
- 호출량: 동기화 하루 2회 + 정산 5분 폴링 + 라이브는 경기당 최대 4콜/분(캐시 상한)
+17 -2
View File
@@ -44,13 +44,28 @@
- 무승부: 승패 적중이면서 득실차(=0) 일치 → 정확이 아니면 **근접(3점)**. - 무승부: 승패 적중이면서 득실차(=0) 일치 → 정확이 아니면 **근접(3점)**.
- **배점 수치는 황 본부장 확정 후 dev 전달**(회의 05:48). 위는 기본 제안값. - **배점 수치는 황 본부장 확정 후 dev 전달**(회의 05:48). 위는 기본 제안값.
### 야구(KBO/MLB) 판정 완화 (2026-07-22)
야구는 득점 범위가 넓어(0~12+) 축구 기준 그대로면 정확/근접/부분이 거의 나오지
않는다. **등급 체계·배점은 리그 공통**으로 유지하고, 야구만 판정에 허용 오차
±1(`scoring.BASEBALL_TOLERANCE`)을 둔다. 리그별 시상이므로 리그 간 점수 크기
차이는 문제되지 않는다.
| 등급 | 야구 조건 | 포인트 |
|---|---|---|
| 근접 | 승패 적중 + **득실차 오차 ≤1** | 3 |
| 부분 | **한 팀 득점 오차 ≤1** | 1 |
(정확·승패·빗나감 조건은 축구와 동일)
### 채점 알고리즘 (결정론적) ### 채점 알고리즘 (결정론적)
``` ```
tol = 야구 ? 1 : 0
1) pick.scoreA == result.scoreA && pick.scoreB == result.scoreB → 정확(5) 1) pick.scoreA == result.scoreA && pick.scoreB == result.scoreB → 정확(5)
2) else if pick.outcome == result.outcome: 2) else if pick.outcome == result.outcome:
(pick.scoreA - pick.scoreB) == (result.scoreA - result.scoreB) ? 근접(3) : 승패(2) |득실차 오차| <= tol ? 근접(3) : 승패(2)
3) else if pick.scoreA == result.scoreA || pick.scoreB == result.scoreB → 부분(1) 3) else if |pick.scoreA - result.scoreA| <= tol || |pick.scoreB - result.scoreB| <= tol → 부분(1)
4) else → 0 4) else → 0
``` ```
+110 -10
View File
@@ -5,23 +5,31 @@
<link rel="icon" href="/icons/profile.png" /> <link rel="icon" href="/icons/profile.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#14171C" /> <meta name="theme-color" content="#14171C" />
<title>TriplePick 2026 | AI 2026 글로벌 축구 축전 승부예측 — GPT vs Claude vs Gemini</title>
<!-- Pretendard 웹폰트 — globals.css 의 font-family 가 참조. 미로드 시 Windows 는
맑은 고딕 폴백으로 떨어져 글씨가 가늘고 흐릿해진다. dynamic-subset: 쓰인 글자만 로드 -->
<link rel="preconnect" href="https://cdn.jsdelivr.net" crossorigin />
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/gh/orioncactus/pretendard@v1.3.9/dist/web/variable/pretendardvariable-dynamic-subset.min.css"
/>
<title>TriplePick | AI 스포츠 승부예측 — KBO·MLB·MLS, GPT vs Claude vs Gemini</title>
<meta <meta
name="description" name="description"
content="GPT·Claude·Gemini가 매 경기를 서로 다르게 예측합니다. 당신의 픽을 찍고 AI와 겨뤄보세요. 끝까지 잘 맞히면 100만 원 챌린지." content="프로야구 승부예측(KBO)부터 해외야구 승부예측(MLB 메이저리그), MLS까지 — GPT·Claude·Gemini 3대 AI가 매 경기를 서로 다르게 예측합니다. 실시간 스코어·문자중계를 보며 당신의 픽을 찍고 AI와 겨뤄보세요. 무료 참여."
/> />
<!-- 공유 썸네일 (Open Graph / Twitter) — 카카오톡 등 소셜 미리보기 --> <!-- 공유 썸네일 (Open Graph / Twitter) — 카카오톡 등 소셜 미리보기 -->
<meta property="og:type" content="website" /> <meta property="og:type" content="website" />
<meta property="og:site_name" content="TriplePick" /> <meta property="og:site_name" content="TriplePick" />
<meta property="og:title" content="TriplePick 2026 — AI 2026 글로벌 축구 축전 승부예측" /> <meta property="og:title" content="TriplePick — AI 스포츠 승부예측 (KBO·MLB·MLS)" />
<meta <meta
property="og:description" property="og:description"
content="AI 셋이 매 경기를 서로 다르게 예측합니다. 당신의 픽을 찍고 AI와 겨뤄보세요. 끝까지 잘 맞히면 100만 원 챌린지." content="GPT·Claude·Gemini 3대 AI가 KBO·MLB·MLS 매 경기를 서로 다르게 예측합니다. 당신의 픽을 찍고 AI와 겨뤄보세요. 무료 참여."
/> />
<meta property="og:url" content="https://triplepick.o2o.kr/" /> <meta property="og:url" content="https://triplepick.o2o.kr/" />
<meta property="og:image" content="https://triplepick.o2o.kr/assets/bi/og-image.png" /> <meta property="og:image" content="https://triplepick.o2o.kr/assets/bi/og-image.png?v=2" />
<meta property="og:image:secure_url" content="https://triplepick.o2o.kr/assets/bi/og-image.png" /> <meta property="og:image:secure_url" content="https://triplepick.o2o.kr/assets/bi/og-image.png?v=2" />
<meta property="og:image:type" content="image/png" /> <meta property="og:image:type" content="image/png" />
<meta property="og:image:width" content="1200" /> <meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" /> <meta property="og:image:height" content="630" />
@@ -29,15 +37,107 @@
<meta property="og:locale" content="ko_KR" /> <meta property="og:locale" content="ko_KR" />
<meta name="twitter:card" content="summary_large_image" /> <meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="TriplePick 2026 — AI 2026 글로벌 축구 축전 승부예측" /> <meta name="twitter:title" content="TriplePick — AI 스포츠 승부예측 (KBO·MLB·MLS)" />
<meta <meta
name="twitter:description" name="twitter:description"
content="AI 셋이 매 경기를 서로 다르게 예측합니다. 당신의 픽을 찍고 AI와 겨뤄보세요." content="GPT·Claude·Gemini 3대 AI가 KBO·MLB·MLS 매 경기를 예측합니다. 당신의 픽을 찍고 AI와 겨뤄보세요."
/> />
<meta name="twitter:image" content="https://triplepick.o2o.kr/assets/bi/og-image.png" /> <meta name="twitter:image" content="https://triplepick.o2o.kr/assets/bi/og-image.png?v=2" />
<!-- 검색엔진 소유확인 (verification) -->
<meta name="google-site-verification" content="ka2LWpjjrTMayrSJ4_LYowl3w1rt6-RSeaT24xvmUiQ" />
<!-- 네이버 서치어드바이저 소유확인 토큰 (2026-06-29 발급·반영 완료) -->
<meta name="naver-site-verification" content="d31508b6376797f7a8c587e4f60b72ffb6c7407c" />
<!-- 검색 키워드 / 색인 지시 -->
<meta name="keywords" content="트리플픽, AI승부예측, 스포츠 승부예측, 프로야구 승부예측, 해외야구 승부예측, 메이저리그 승부예측, MLB 승부예측, KBO 승부예측, 야구 승부예측, 축구 승부예측, 해외축구 승부예측, MLS 승부예측, 프로야구 예측, GPT 예측, 클로드 예측, 제미나이 예측, AI vs 사람, 프로야구 문자중계, TriplePick" />
<meta name="robots" content="index, follow, max-image-preview:large" />
<link rel="canonical" href="https://triplepick.o2o.kr/" />
<!-- 구조화 데이터 (JSON-LD): 브랜드 인지 + 지식그래프 보조 -->
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@graph": [
{
"@type": "Organization",
"@id": "https://triplepick.o2o.kr/#organization",
"name": "TriplePick",
"alternateName": "트리플픽",
"url": "https://triplepick.o2o.kr/",
"logo": "https://triplepick.o2o.kr/assets/bi/og-image.png",
"description": "GPT·Claude·Gemini 3대 AI가 같은 경기 데이터로 승패·스코어·승리확률을 예측·비교하는 참여형 스포츠 승부예측 서비스. KBO 프로야구 승부예측·MLB 해외야구 승부예측·MLS 지원.",
"sameAs": [
"https://www.youtube.com/channel/UCIiFvxaahQA-rLP8KpkDM0w",
"https://www.instagram.com/triplepickai"
],
"parentOrganization": {
"@type": "Organization",
"name": "AIO2O",
"alternateName": "AI오투오",
"url": "https://www.o2osolution.ai/",
"sameAs": [
"https://www.facebook.com/aio2o",
"https://www.linkedin.com/company/aio2o"
]
}
},
{
"@type": "WebSite",
"@id": "https://triplepick.o2o.kr/#website",
"url": "https://triplepick.o2o.kr/",
"name": "TriplePick — AI 스포츠 승부예측 아레나",
"inLanguage": "ko-KR",
"publisher": { "@id": "https://triplepick.o2o.kr/#organization" }
},
{
"@type": "WebApplication",
"name": "TriplePick AI 승부예측",
"url": "https://triplepick.o2o.kr/",
"applicationCategory": "SportsApplication",
"operatingSystem": "Web",
"inLanguage": "ko-KR",
"offers": { "@type": "Offer", "price": "0", "priceCurrency": "KRW" },
"description": "GPT·Claude·Gemini의 예측을 확인하고 직접 승패와 스코어를 찍어 AI와 겨루는 무료 참여형 스포츠 승부예측 서비스. KBO 프로야구·MLB 해외야구·MLS 경기 지원, 실시간 스코어·문자중계 제공."
}
]
}
</script>
</head> </head>
<body> <body>
<div id="root"></div> <div id="root">
<!-- 크롤 가능 본문 폴백(SPA 빈 root 보완). React 마운트 시 실제 앱으로 교체됨.
⚠️ CSS로 숨기지 말 것(클로킹 페널티) — 보이게 두면 React가 즉시 덮음. -->
<div class="seo-fallback">
<h1>트리플픽 — GPT·Claude·Gemini AI 스포츠 승부예측 대결</h1>
<p>
트리플픽(TriplePick)은 AI승부예측 서비스입니다. GPT·Claude·Gemini 3대 AI가
같은 경기 데이터로 승패·스코어·승리확률을 서로 다르게 예측하고, 당신은 직접
스포츠 승부예측 픽을 찍어 AI와 겨룹니다. KBO 프로야구·MLB·MLS 전 경기를
대상으로 무료로 참여할 수 있습니다.
</p>
<h2>프로야구 승부예측부터 해외야구 승부예측까지</h2>
<p>
KBO 프로야구 승부예측은 두산·LG·KIA·삼성 등 10개 구단 전 경기를 매일
지원하고, 해외야구 승부예측은 MLB 메이저리그 전 경기를 다룹니다. 야구뿐
아니라 해외축구(MLS) 승부예측까지 한 곳에서 — 3대 AI의
예측 근거와 승리확률을 비교하고 내 픽의 적중률을 확인해 보세요.
</p>
<h2>트리플픽은 이런 스포츠 승부예측 서비스입니다</h2>
<ul>
<li>KBO 프로야구·MLB 해외야구·MLS 3개 리그 경기별 승부예측 지원</li>
<li>3대 AI(GPT·Claude·Gemini)의 경기별 예측을 한눈에 비교</li>
<li>승패·정확 스코어를 직접 찍는 참여형 AI승부예측</li>
<li>진행 중 경기 실시간 스코어와 문자중계 제공</li>
<li>경기 종료 후 AI와 내 적중률을 채점·공개</li>
<li>무료 참여 — 카카오 간편 로그인 지원</li>
</ul>
<p>
AI 셋이 갈렸을 때, 당신의 픽은 누구와 같을까요? 트리플픽에서 스포츠 승부예측을
시작하세요. <a href="https://triplepick.o2o.kr/">triplepick.o2o.kr</a>
</p>
</div>
</div>
<script type="module" src="/src/main.tsx"></script> <script type="module" src="/src/main.tsx"></script>
</body> </body>
</html> </html>
+6
View File
@@ -29,6 +29,12 @@ server {
if ($is_share_crawler) { return 418; } if ($is_share_crawler) { return 418; }
try_files $uri /index.html; try_files $uri /index.html;
} }
# 응원가 공유 링크(/song/:matchId/:teamCode) — 동일 패턴
location /song/ {
error_page 418 = @og_prerender;
if ($is_share_crawler) { return 418; }
try_files $uri /index.html;
}
location @og_prerender { location @og_prerender {
proxy_pass http://api:8000; proxy_pass http://api:8000;
proxy_set_header Host $host; proxy_set_header Host $host;
-152
View File
@@ -1,152 +0,0 @@
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>AI 축구 승부예측 — GPT·Claude·Gemini의 선택은? | TriplePick</title>
<meta name="description" content="ChatGPT, Claude, Gemini 3개 AI가 2026 월드컵 경기 결과를 예측합니다. AI 예측 근거 공개, 실시간 군중 픽 비율 확인. 내 예측으로 AI를 이겨보세요." />
<meta name="keywords" content="AI 축구 예측, ChatGPT 축구, AI 승부예측, 인공지능 축구 분석, Gemini 월드컵, Claude 축구, AI 스포츠 예측, 축구 AI, GPT 월드컵 예측, 2026 월드컵 AI" />
<link rel="canonical" href="https://triplepick.o2o.kr/ai-soccer-prediction" />
<meta property="og:title" content="AI 축구 승부예측 — GPT·Claude·Gemini | TriplePick" />
<meta property="og:description" content="3개의 AI가 월드컵을 예측합니다. AI를 이기면 100만원." />
<meta property="og:url" content="https://triplepick.o2o.kr/ai-soccer-prediction" />
<meta property="og:type" content="website" />
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
background: #0a0a0f;
color: #e8e8e8;
min-height: 100vh;
}
.wrap { max-width: 680px; margin: 0 auto; padding: 48px 20px 64px; }
.badge {
display: inline-block;
background: #00ff8822;
border: 1px solid #00ff8855;
color: #00ff88;
font-size: 13px;
font-weight: 700;
padding: 4px 14px;
border-radius: 999px;
margin-bottom: 20px;
}
h1 {
font-size: clamp(26px, 6vw, 38px);
font-weight: 900;
line-height: 1.2;
margin-bottom: 16px;
}
h1 span { color: #00ff88; }
.lead {
font-size: 16px;
line-height: 1.7;
color: #b0b0c0;
margin-bottom: 36px;
}
.ai-list { margin-bottom: 36px; display: flex; flex-direction: column; gap: 12px; }
.ai-row {
background: #13131e;
border: 1px solid #ffffff14;
border-radius: 14px;
padding: 18px 20px;
display: flex;
align-items: center;
gap: 16px;
}
.ai-name { font-size: 16px; font-weight: 800; min-width: 80px; }
.ai-name.gpt { color: #10a37f; }
.ai-name.claude { color: #cc785c; }
.ai-name.gemini { color: #4285f4; }
.ai-desc { font-size: 13px; color: #8888a0; line-height: 1.5; }
h2 { font-size: 20px; font-weight: 800; margin-bottom: 16px; }
.step-list { counter-reset: step; display: flex; flex-direction: column; gap: 14px; margin-bottom: 36px; }
.step {
background: #13131e;
border: 1px solid #ffffff14;
border-radius: 14px;
padding: 16px 20px 16px 56px;
position: relative;
font-size: 14px;
line-height: 1.6;
color: #c0c0d0;
}
.step::before {
counter-increment: step;
content: counter(step);
position: absolute;
left: 18px;
top: 16px;
width: 24px;
height: 24px;
background: #00ff8820;
border: 1px solid #00ff8840;
color: #00ff88;
font-size: 12px;
font-weight: 900;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
line-height: 24px;
text-align: center;
}
.step strong { color: #ffffff; }
.cta {
display: block;
text-align: center;
background: #00ff88;
color: #000;
font-size: 17px;
font-weight: 900;
padding: 16px 32px;
border-radius: 14px;
text-decoration: none;
margin-top: 40px;
transition: opacity .15s;
}
.cta:hover { opacity: .85; }
footer { margin-top: 48px; text-align: center; font-size: 12px; color: #44445a; }
footer a { color: #44445a; }
</style>
</head>
<body>
<div class="wrap">
<div class="badge">AI vs 인간 대결</div>
<h1><span>GPT · Claude · Gemini</span><br />3개의 AI가 월드컵을 예측한다면?</h1>
<p class="lead">
세계 최고 수준의 AI 3종이 2026 FIFA 월드컵 경기 결과를 예측합니다.<br />
AI들의 예측 근거까지 공개되며, 당신이 직접 AI를 이길 수 있습니다.
</p>
<div class="ai-list">
<div class="ai-row">
<div class="ai-name gpt">GPT</div>
<div class="ai-desc">OpenAI의 GPT 모델. 방대한 축구 통계와 역대 경기 데이터를 기반으로 예측.</div>
</div>
<div class="ai-row">
<div class="ai-name claude">Claude</div>
<div class="ai-desc">Anthropic의 Claude. 팀 컨디션, 전술 분석, 최근 폼을 종합해 예측.</div>
</div>
<div class="ai-row">
<div class="ai-name gemini">Gemini</div>
<div class="ai-desc">Google의 Gemini. 최신 뉴스와 실시간 정보까지 반영한 예측.</div>
</div>
</div>
<h2>어떻게 참여하나요?</h2>
<div class="step-list">
<div class="step">사이트에 접속해 <strong>이메일로 참여 등록</strong>합니다. 완전 무료.</div>
<div class="step">경기 킥오프 5일 전부터 투표 가능. <strong>홈팀 승·무·원정팀 승</strong> 중 하나를 선택.</div>
<div class="step">킥오프 직전에 <strong>AI 3개의 예측</strong>과 전체 참여자 픽 비율이 공개됩니다.</div>
<div class="step">경기 종료 후 결과 확인. AI보다 더 많이 맞히면 <strong>100만원 상금</strong> 도전!</div>
</div>
<a class="cta" href="https://triplepick.o2o.kr/">AI 예측 보러 가기 →</a>
<footer>
<p><a href="https://triplepick.o2o.kr/">TriplePick 2026</a> &nbsp;|&nbsp; AI Prediction Arena</p>
</footer>
</div>
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 148 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 109 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 131 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 221 KiB

Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+25
View File
@@ -0,0 +1,25 @@
# TriplePick (트리플픽)
> GPT·Claude·Gemini 3대 AI가 같은 경기 데이터로 승패·스코어·승리확률을 서로 다르게 예측·비교하고, 사용자가 직접 픽을 찍어 AI와 겨루는 참여형 스포츠 승부예측 서비스. 월드컵·KBO 프로야구·MLB·MLS 4개 리그 지원, 무료 참여.
## 핵심 정보
- 서비스명: TriplePick (트리플픽)
- 카테고리: AI승부예측 · 스포츠 승부예측 · 축구/야구 승부예측
- 대상 리그: 2026 글로벌 축구 축전(월드컵) · KBO 프로야구 · MLB · MLS
- AI 모델: GPT, Claude, Gemini (3종 동시 예측·비교)
- 참여: 무료, 승패·정확 스코어 픽 (카카오 간편 로그인 지원)
- 부가 기능: 진행 중 경기 실시간 스코어·문자중계, 팀 순위표, AI 프리뷰
- 운영: AIO2O / ADO2
## 주요 링크
- 홈(월드컵): https://triplepick.o2o.kr/
- KBO 프로야구: https://triplepick.o2o.kr/?league=kbo
- MLB: https://triplepick.o2o.kr/?league=mlb
- MLS: https://triplepick.o2o.kr/?league=mls
- 경기 상세: https://triplepick.o2o.kr/match/{경기ID} (당일 경기별)
## 자주 묻는 질문
- 트리플픽이 뭔가요? GPT·Claude·Gemini 세 AI의 경기 예측을 비교하고, 내가 직접 픽을 찍어 AI와 적중률을 겨루는 무료 AI승부예측 서비스입니다.
- 어떤 경기를 예측할 수 있나요? 2026 월드컵과 KBO 프로야구·MLB·MLS 경기를 예측할 수 있습니다.
- 어떻게 참여하나요? 홈에서 리그와 경기를 고르고 승패·스코어를 찍으면 됩니다. 카카오 간편 로그인을 지원합니다.
- 경기 중에는 뭘 볼 수 있나요? 실시간 스코어와 문자중계(투구·타석·득점 등 주요 장면)를 볼 수 있습니다.
+14 -1
View File
@@ -1,2 +1,15 @@
# robots.txt — triplepick.o2o.kr
# 모든 검색엔진 크롤러 전체 허용 + 사이트맵 위치 명시
User-agent: * User-agent: *
Allow:/ Allow: /
# 네이버 크롤러(Yeti) 명시 허용
User-agent: Yeti
Allow: /
# 구글
User-agent: Googlebot
Allow: /
Sitemap: https://triplepick.o2o.kr/sitemap.xml
+30
View File
@@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
<channel>
<title>TriplePick — AI 스포츠 승부예측</title>
<link>https://triplepick.o2o.kr/</link>
<description>GPT·Claude·Gemini 3대 AI가 월드컵·KBO·MLB·MLS 매 경기를 예측·비교하는 참여형 스포츠 승부예측. 경기별 예측·결과 업데이트.</description>
<language>ko-KR</language>
<lastBuildDate>Tue, 18 Aug 2026 00:00:00 +0900</lastBuildDate>
<!--
네이버 RSS 제출용 최소본. 블로그/CMS가 없어 정적입니다.
경기별 예측/결과 페이지가 생기면 아래 <item> 을 추가해 자동/수동 갱신하세요.
네이버는 sitemap.xml 만으로도 색인되므로 RSS는 보조(우선순위 낮음).
-->
<item>
<title>트리플픽 멀티리그 확장: KBO 프로야구·MLB·MLS AI 승부예측 오픈</title>
<link>https://triplepick.o2o.kr/?league=kbo</link>
<description>월드컵에 이어 KBO 프로야구·MLB·MLS까지 GPT·Claude·Gemini 3대 AI 승부예측 지원. 실시간 스코어·문자중계 제공.</description>
<pubDate>Tue, 18 Aug 2026 00:00:00 +0900</pubDate>
<guid>https://triplepick.o2o.kr/?league=kbo</guid>
</item>
<item>
<title>트리플픽: GPT·Claude·Gemini AI 축구 승부예측 대결</title>
<link>https://triplepick.o2o.kr/</link>
<description>3대 AI의 예측을 비교하고 직접 픽을 찍어 AI와 겨루는 무료 AI승부예측 서비스.</description>
<pubDate>Wed, 17 Jun 2026 00:00:00 +0900</pubDate>
<guid>https://triplepick.o2o.kr/</guid>
</item>
</channel>
</rss>
+29 -8
View File
@@ -1,23 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<!-- 홈 = 월드컵 대시보드 (캠페인 1순위 홍보 URL) -->
<url> <url>
<loc>https://triplepick.o2o.kr/</loc> <loc>https://triplepick.o2o.kr/</loc>
<lastmod>2026-08-20</lastmod>
<changefreq>daily</changefreq> <changefreq>daily</changefreq>
<priority>1.0</priority> <priority>1.0</priority>
</url> </url>
<!-- 리그별 대시보드 (2026-08 멀티리그 확장: KBO·MLB·MLS) -->
<url> <url>
<loc>https://triplepick.o2o.kr/leaderboard</loc> <loc>https://triplepick.o2o.kr/?league=kbo</loc>
<lastmod>2026-08-20</lastmod>
<changefreq>daily</changefreq> <changefreq>daily</changefreq>
<priority>0.8</priority> <priority>0.9</priority>
</url> </url>
<url> <url>
<loc>https://triplepick.o2o.kr/worldcup-prediction.html</loc> <loc>https://triplepick.o2o.kr/?league=mlb</loc>
<changefreq>weekly</changefreq> <lastmod>2026-08-20</lastmod>
<priority>0.7</priority> <changefreq>daily</changefreq>
<priority>0.9</priority>
</url> </url>
<url> <url>
<loc>https://triplepick.o2o.kr/ai-soccer-prediction.html</loc> <loc>https://triplepick.o2o.kr/?league=mls</loc>
<changefreq>weekly</changefreq> <lastmod>2026-08-20</lastmod>
<priority>0.7</priority> <changefreq>daily</changefreq>
<priority>0.9</priority>
</url> </url>
<!--
매치 상세 페이지는 의도적으로 제외했습니다.
라이브 사이트의 매치 URL은 날짜별로 매일 바뀌는 동적 경로이며
(형식: /match/{조}_{홈}_{원정}_{YYYYMMDD}, 예: /match/I_FRA_SEN_20260617),
정적 sitemap에 넣으면 매일 stale 됩니다.
→ 홈(/)의 내부 링크를 통해 구글봇이 자동 크롤·발견하도록 둡니다.
(라이브 사이트에 /leaderboard 라우트는 없음 — Next.js 빌드 전용이었음)
[선택] 특정 경기를 빠르게 색인하고 싶으면 GSC URL검사로 개별 색인요청하거나,
서버에서 sitemap을 동적 생성(당일 경기 목록)하도록 확장하세요.
-->
</urlset> </urlset>
Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 103 KiB

+22 -5
View File
@@ -3,16 +3,16 @@
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>2026 월드컵 승부예측 — AI vs 나의 픽, 100만원 상금 | TriplePick</title> <title>2026 월드컵 승부예측 — AI vs 나의 픽, 100만원 상금 | TriplePick(트리플픽)</title>
<meta name="description" content="2026 FIFA 월드컵 승부예측을 GPT·Claude·Gemini AI와 함께! AI의 예측과 내 픽을 비교하고, 정답을 맞히면 100만원 상금. 무료 참여, 실시간 결과 확인. 한국 vs 체코, 한국 vs 멕시코 경기 예측 가능." /> <meta name="description" content="2026 FIFA 월드컵 승부예측을 GPT·Claude·Gemini AI와 함께! AI의 예측과 내 픽을 비교하고, 정답을 맞히면 100만원 상금. 무료 참여, 실시간 결과 확인. 한국 vs 체코, 한국 vs 멕시코 경기 예측 가능." />
<meta name="keywords" content="2026 월드컵 승부예측, 월드컵 예측, AI 축구 예측, FIFA 월드컵 2026, 월드컵 픽, 한국 월드컵, 축구 승부예측, 월드컵 결과 예측, 트리플픽, 한국 체코, 한국 멕시코, 월드컵 무료 이벤트, 월드컵 상금, 인공지능 축구, 2026 FIFA, 월드컵 그룹A, 한국 16강, 월드컵 투표" /> <meta name="keywords" content="2026 월드컵 승부예측, 월드컵 예측, AI 축구 예측, FIFA 월드컵 2026, 월드컵 픽, 한국 월드컵, 축구 승부예측, 월드컵 결과 예측, 트리플픽, 한국 체코, 한국 멕시코, 월드컵 무료 이벤트, 월드컵 상금, 인공지능 축구, 2026 FIFA, 월드컵 그룹A, 한국 16강, 월드컵 투표, 메시 월드컵, 호날두 월드컵, 메시 2026, 호날두 2026, 음바페 월드컵, 손흥민 월드컵, 스타 선수 출전" />
<link rel="canonical" href="https://triplepick.o2o.kr/worldcup-prediction.html" /> <link rel="canonical" href="https://triplepick.o2o.kr/worldcup-prediction.html" />
<meta property="og:title" content="2026 월드컵 승부예측 | TriplePick — AI vs 나의 픽" /> <meta property="og:title" content="2026 월드컵 승부예측 | TriplePick(트리플픽) — AI vs 나의 픽" />
<meta property="og:description" content="GPT·Claude·Gemini AI와 승부예측 대결! 한국 경기 결과를 맞히면 100만원. 무료 참여." /> <meta property="og:description" content="GPT·Claude·Gemini AI와 승부예측 대결! 한국 경기 결과를 맞히면 100만원. 무료 참여." />
<meta property="og:url" content="https://triplepick.o2o.kr/worldcup-prediction.html" /> <meta property="og:url" content="https://triplepick.o2o.kr/worldcup-prediction.html" />
<meta property="og:type" content="website" /> <meta property="og:type" content="website" />
<meta name="twitter:card" content="summary_large_image" /> <meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="2026 월드컵 승부예측 | TriplePick" /> <meta name="twitter:title" content="2026 월드컵 승부예측 | TriplePick(트리플픽)" />
<meta name="twitter:description" content="AI 3종과 승부예측 대결. 정답 맞히면 100만원. 무료 참여." /> <meta name="twitter:description" content="AI 3종과 승부예측 대결. 정답 맞히면 100만원. 무료 참여." />
<script type="application/ld+json"> <script type="application/ld+json">
{ {
@@ -302,6 +302,15 @@
한국의 16강 가능성을 AI는 어떻게 예측할까요? 한국의 16강 가능성을 AI는 어떻게 예측할까요?
</p> </p>
<div class="highlight-box">
<p>
🌟 <strong>레전드들의 마지막 무대 — 메시·호날두·음바페 출전!</strong><br />
리오넬 메시(아르헨티나)와 크리스티아누 호날두(포르투갈)가 함께하는 마지막 월드컵이 될 수 있습니다.
킬리안 음바페(프랑스), 엘링 홀란드(노르웨이), 손흥민(한국) 등 세계 최정상 스타들이
총출동하는 역대급 대회. AI는 이 슈퍼스타들의 활약을 어떻게 예측할까요?
</p>
</div>
<div class="highlight-box"> <div class="highlight-box">
<p> <p>
💡 <strong>AI 3종이 모두 한국 패를 예측한다면?</strong><br /> 💡 <strong>AI 3종이 모두 한국 패를 예측한다면?</strong><br />
@@ -334,6 +343,10 @@
<p class="faq-q">예측 변경이 가능한가요?</p> <p class="faq-q">예측 변경이 가능한가요?</p>
<p class="faq-a">킥오프 5분 전 마감 전까지는 예측을 자유롭게 변경할 수 있습니다. 마감 이후에는 변경이 불가합니다.</p> <p class="faq-a">킥오프 5분 전 마감 전까지는 예측을 자유롭게 변경할 수 있습니다. 마감 이후에는 변경이 불가합니다.</p>
</div> </div>
<div class="faq-item">
<p class="faq-q">메시·호날두 같은 스타 선수가 출전하는 경기도 예측할 수 있나요?</p>
<p class="faq-a">TriplePick은 2026 월드컵 그룹 A 전 경기를 대상으로 합니다. 메시(아르헨티나), 호날두(포르투갈), 음바페(프랑스) 등 레전드 선수들이 출전하는 경기는 그룹 A 외 경기이지만, AI 예측 근거 코멘트에서 이 선수들의 영향력 분석을 확인할 수 있습니다. 향후 서비스 확장 시 더 많은 경기를 포함할 예정입니다.</p>
</div>
<div class="faq-item"> <div class="faq-item">
<p class="faq-q">모바일에서도 사용할 수 있나요?</p> <p class="faq-q">모바일에서도 사용할 수 있나요?</p>
<p class="faq-a">모바일 최적화 서비스입니다. 스마트폰 브라우저에서 바로 참여 가능하며, 별도 앱 설치가 필요 없습니다.</p> <p class="faq-a">모바일 최적화 서비스입니다. 스마트폰 브라우저에서 바로 참여 가능하며, 별도 앱 설치가 필요 없습니다.</p>
@@ -354,13 +367,17 @@
<span class="tag">한국 16강</span> <span class="tag">한국 16강</span>
<span class="tag">월드컵 상금</span> <span class="tag">월드컵 상금</span>
<span class="tag">그룹A</span> <span class="tag">그룹A</span>
<span class="tag">메시 2026</span>
<span class="tag">호날두 2026</span>
<span class="tag">음바페</span>
<span class="tag">손흥민 월드컵</span>
<span class="tag">스타 선수 출전</span>
</div> </div>
<a class="cta" href="https://triplepick.o2o.kr/">지금 무료로 예측하러 가기 →</a> <a class="cta" href="https://triplepick.o2o.kr/">지금 무료로 예측하러 가기 →</a>
<footer> <footer>
<p><a href="https://triplepick.o2o.kr/">TriplePick 2026</a> &nbsp;|&nbsp; AI Prediction Arena</p> <p><a href="https://triplepick.o2o.kr/">TriplePick 2026</a> &nbsp;|&nbsp; AI Prediction Arena</p>
<p style="margin-top:8px"><a href="https://triplepick.o2o.kr/ai-soccer-prediction.html">AI 축구 예측이란?</a> &nbsp;|&nbsp; <a href="https://triplepick.o2o.kr/leaderboard">리더보드</a></p>
</footer> </footer>
</div> </div>
</body> </body>
+9 -1
View File
@@ -1,5 +1,5 @@
import { useEffect } from "react"; import { useEffect } from "react";
import { Routes, Route } from "react-router-dom"; import { Routes, Route, Navigate, useParams } from "react-router-dom";
import Dashboard from "./pages/Dashboard"; import Dashboard from "./pages/Dashboard";
import MatchDetail from "./pages/MatchDetail"; import MatchDetail from "./pages/MatchDetail";
import Leaderboard from "./pages/Leaderboard"; import Leaderboard from "./pages/Leaderboard";
@@ -8,6 +8,13 @@ import { recordVisit } from "./lib/api";
import { PlayerProvider } from "./lib/usePlayer"; import { PlayerProvider } from "./lib/usePlayer";
import MusicBar from "./components/MusicBar"; import MusicBar from "./components/MusicBar";
// 응원가 공유 링크(/song/:matchId/:teamCode) — 크롤러는 nginx 가 OG 프리렌더로
// 보내고, 사람은 여기로 와서 경기 페이지 + 해당 팀 응원가 자동 로드로 이동.
function SongShareRedirect() {
const { matchId = "", teamCode = "" } = useParams();
return <Navigate to={`/match/${matchId}?song=${teamCode}`} replace />;
}
export default function App() { export default function App() {
// 접속 시 1회 방문 기록 (하루 1기기 1회 집계는 백엔드가 처리) // 접속 시 1회 방문 기록 (하루 1기기 1회 집계는 백엔드가 처리)
useEffect(() => { useEffect(() => {
@@ -19,6 +26,7 @@ export default function App() {
<Routes> <Routes>
<Route path="/" element={<Dashboard />} /> <Route path="/" element={<Dashboard />} />
<Route path="/match/:matchId" element={<MatchDetail />} /> <Route path="/match/:matchId" element={<MatchDetail />} />
<Route path="/song/:matchId/:teamCode" element={<SongShareRedirect />} />
<Route path="/leaderboard" element={<Leaderboard />} /> <Route path="/leaderboard" element={<Leaderboard />} />
<Route path="*" element={<NotFound />} /> <Route path="*" element={<NotFound />} />
</Routes> </Routes>
+120 -99
View File
@@ -1,6 +1,7 @@
import { useEffect, useMemo, useState } from "react"; import { useEffect, useMemo, useState } from "react";
import { outcomeLabel, pctParts, kickoffDisplay, winProb } from "@/lib/format"; import { outcomeLabel, pctParts, kickoffDisplay, winProb } from "@/lib/format";
import { type Lang, dict, teamShort } from "@/lib/i18n"; import { type Lang, dict, teamShort } from "@/lib/i18n";
import { useAuth } from "@/lib/auth";
import type { import type {
Outcome, Outcome,
CrowdStats, CrowdStats,
@@ -41,14 +42,14 @@ const DOG_LINES = [
]; ];
const TIGER_LINES = [ const TIGER_LINES = [
"👈 여기서 투표하는 거야", "👈 여기서 투표하는 거야",
"한국 몇 대 몇? 찍어봐! 🇰🇷", "몇 대 몇? 찍어봐! 🎯",
"투표하고 AI랑 붙자 🔥", "투표하고 AI랑 붙자 🔥",
"네 픽 보여줘 봐!", "네 픽 보여줘 봐!",
"정확히 맞히면 네가 레전드 🏆", "정확히 맞히면 네가 레전드 🏆",
"망설이면 마감된다 ⏰", "망설이면 마감된다 ⏰",
"감으로라도 일단 ㄱㄱ", "감으로라도 일단 ㄱㄱ",
"예측 한 방에 인생역전? ㅋㅋ", "예측 한 방에 인생역전? ㅋㅋ",
"한국 이긴다에 한 표! 🇰🇷", "네 승부 예측은? 🤔",
"스코어까지 맞혀봐 🎯", "스코어까지 맞혀봐 🎯",
]; ];
// AI 박스 사자 — AI 예측에 대한 멘트. // AI 박스 사자 — AI 예측에 대한 멘트.
@@ -95,20 +96,28 @@ export default function Arena({
const t = dict(lang); const t = dict(lang);
const aShort = teamShort(match.teamA, lang); const aShort = teamShort(match.teamA, lang);
const bShort = teamShort(match.teamB, lang); const bShort = teamShort(match.teamB, lang);
// 한국을 항상 왼쪽에 표시(요청). 상태·투표 제출은 원본 A/B 프레임 그대로, 화면 좌우만 교체. // 월드컵: 한국을 항상 왼쪽에. MLS: 홈 팀을 왼쪽에(축구 관례).
const flip = match.teamB.code === "KOR" && match.teamA.code !== "KOR"; // 상태·투표 제출은 원본 A/B 프레임 그대로, 화면 좌우만 교체.
const flip =
match.league === "mls" ||
(match.teamB.code === "KOR" && match.teamA.code !== "KOR");
const leftShort = flip ? bShort : aShort; const leftShort = flip ? bShort : aShort;
const rightShort = flip ? aShort : bShort; const rightShort = flip ? aShort : bShort;
// 마스코트(사자·버튼 양옆 캐릭터)는 한국-남아공 경기에서만 노출. // 마스코트(사자·버튼 양옆 캐릭터)는 모든 경기에서 노출.
const isKorRsa =
[match.teamA.code, match.teamB.code].includes("KOR") &&
[match.teamA.code, match.teamB.code].includes("RSA");
const [outcome, setOutcome] = useState<Outcome | null>("DRAW"); const [outcome, setOutcome] = useState<Outcome | null>("DRAW");
// 야구(KBO/MLB): 스코어 상한 25, 마스코트 미노출
const isBaseball = match.league === "kbo" || match.league === "mlb";
const maxScore = isBaseball ? 25 : 9;
const [scoreA, setScoreA] = useState(0); const [scoreA, setScoreA] = useState(0);
const [scoreB, setScoreB] = useState(0); const [scoreB, setScoreB] = useState(0);
const [step, setStep] = useState<Step>("form"); const [step, setStep] = useState<Step>("form");
const [recentEmails, setRecentEmails] = useState<string[]>(getRecentEmails); const [recentEmails, setRecentEmails] = useState<string[]>(getRecentEmails);
const [email, setEmail] = useState(""); // 칸은 비우고, 입력/포커스 시 datalist 드롭다운으로만 자동완성 const [email, setEmail] = useState(""); // 칸은 비우고, 입력/포커스 시 datalist 드롭다운으로만 자동완성
// 카카오 로그인 시 계정 이메일을 투표 이메일로 자동 채움 (수정은 자유)
const { user: authUser } = useAuth();
useEffect(() => {
if (authUser?.email) setEmail((cur) => cur || authUser.email!);
}, [authUser]);
const [notify, setNotify] = useState(true); const [notify, setNotify] = useState(true);
const [crowd, setCrowd] = useState<CrowdStats>(initialCrowd); const [crowd, setCrowd] = useState<CrowdStats>(initialCrowd);
const [copied, setCopied] = useState(false); const [copied, setCopied] = useState(false);
@@ -230,21 +239,28 @@ export default function Arena({
{/* ===== 레이어드 화이트 시트 (002) ===== */} {/* ===== 레이어드 화이트 시트 (002) ===== */}
<section className="sheet relative mt-4 p-5 text-[var(--ink)]"> <section className="sheet relative mt-4 p-5 text-[var(--ink)]">
{/* AI 박스 오른쪽 위 사자 — 한국-남아공전 전용 */} {/* AI 박스 오른쪽 위 사자 — 월드컵 전용 (야구·MLS 미노출) */}
{isKorRsa && ( {match.league === "wc" && (
<div className="absolute right-1 -top-4 z-10 h-20 sm:h-24"> <div className="absolute right-1 -top-4 z-10 h-20 sm:h-24">
<TalkingMascot <TalkingMascot
src="/assets/mascots/lion_point.webp" src="/assets/mascots/lion_point.webp"
lines={LION_LINES} lines={LION_LINES}
className="h-20 w-auto sm:h-24" className="h-20 w-auto sm:h-24"
draggable draggable
/> />
</div> </div>
)} )}
<div className="mb-3"> <div className="mb-3">
<h2 className="text-[22px] font-extrabold">{t.aiBattle}</h2> <h2 className="text-[22px] font-extrabold">{t.aiBattle}</h2>
</div> </div>
{predictions.length === 0 && (
<p className="rounded-xl bg-black/[0.04] px-3 py-2.5 text-[12px] font-semibold text-[var(--ink-muted)]">
{lang === "en"
? "AI picks are generated 22 hours before first pitch — check back closer to game time."
: "AI 예측은 경기 시작 22시간 전부터 생성됩니다. 경기가 가까워지면 다시 확인해주세요."}
</p>
)}
<div className="flex flex-col gap-3"> <div className="flex flex-col gap-3">
{predictions.map((p) => { {predictions.map((p) => {
const wp = winProb(match, p); const wp = winProb(match, p);
@@ -289,9 +305,12 @@ export default function Arena({
); );
})} })}
</div> </div>
</section>
{/* ===== 내 예측 카드 (당신의 선택 + 스코어 + 제출) — AI 예측과 분리 ===== */}
<section className="mt-5 rounded-2xl border-2 border-[var(--green)]/60 bg-[var(--bg2)] p-5 shadow-[0_0_24px_rgba(74,255,160,0.08)]">
{/* 당신의 선택 */} {/* 당신의 선택 */}
<div className="mt-5 flex items-center justify-between"> <div className="flex items-center justify-between">
<span className="text-[13px] font-bold text-[var(--ink-muted)]"> <span className="text-[13px] font-bold text-[var(--ink-muted)]">
{t.yourPickLabel} {t.yourPickLabel}
</span> </span>
@@ -330,18 +349,82 @@ export default function Arena({
<div className="mt-3 flex items-center justify-center gap-5 rounded-xl border border-[var(--line-l)] bg-white py-3"> <div className="mt-3 flex items-center justify-center gap-5 rounded-xl border border-[var(--line-l)] bg-white py-3">
{flip ? ( {flip ? (
<> <>
<Stepper label={bShort} value={scoreB} onChange={setScoreB} disabled={disabled} /> <Stepper label={bShort} value={scoreB} onChange={setScoreB} disabled={disabled} max={maxScore} />
<span className="text-[26px] font-extrabold text-[var(--ink-muted)]">:</span> <span className="text-[26px] font-extrabold text-[var(--ink-muted)]">:</span>
<Stepper label={aShort} value={scoreA} onChange={setScoreA} disabled={disabled} /> <Stepper label={aShort} value={scoreA} onChange={setScoreA} disabled={disabled} max={maxScore} />
</> </>
) : ( ) : (
<> <>
<Stepper label={aShort} value={scoreA} onChange={setScoreA} disabled={disabled} /> <Stepper label={aShort} value={scoreA} onChange={setScoreA} disabled={disabled} max={maxScore} />
<span className="text-[26px] font-extrabold text-[var(--ink-muted)]">:</span> <span className="text-[26px] font-extrabold text-[var(--ink-muted)]">:</span>
<Stepper label={bShort} value={scoreB} onChange={setScoreB} disabled={disabled} /> <Stepper label={bShort} value={scoreB} onChange={setScoreB} disabled={disabled} max={maxScore} />
</> </>
)} )}
</div> </div>
{/* 투표 제출 (이메일 + CTA) — '당신의 선택' 카드 안으로 통합 */}
{!finished && !disabled && step === "form" && (
<div className="mt-4 border-t border-[var(--line-d)] pt-4">
<div className="mb-2.5 text-center text-[15px] font-extrabold text-[var(--green)]">
{t.emailGate}
</div>
<input
type="email"
inputMode="email"
list="tp-email-suggestions"
autoComplete="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder={t.emailPh}
className="w-full rounded-2xl border border-[var(--share)] bg-[#0f1217] px-4 py-3 text-[16px] text-white shadow-[0_0_0_2px_rgba(166,94,255,0.12)] outline-none focus:shadow-[0_0_0_2px_rgba(166,94,255,0.3)]"
/>
{recentEmails.length > 0 && (
<datalist id="tp-email-suggestions">
{recentEmails.map((e) => (
<option key={e} value={e} />
))}
</datalist>
)}
<label className="mt-2.5 flex items-start gap-2 text-[13px] leading-snug text-[var(--ink-muted)]">
<input
type="checkbox"
checked={notify}
onChange={(e) => setNotify(e.target.checked)}
className="mt-0.5 accent-[var(--share)]"
/>
{t.notify}
</label>
{error && (
<p className="mt-2 text-[13px] font-bold text-[#ff6b6b]">{error}</p>
)}
{/* 투표하기 버튼 — 모든 경기에서 양옆에 캐릭터(자동 말풍선) */}
<div className="mt-3.5 flex items-end justify-center gap-1">
{match.league === "wc" && <TalkingMascot
src="/assets/mascots/dog_point.webp"
lines={DOG_LINES}
className="h-16 w-auto select-none sm:h-20"
auto
autoDelayMs={1200}
autoIntervalMs={6000}
/>}
<button
onClick={confirmSubmit}
disabled={!emailValid || submitting}
className="btn-share flex flex-1 items-center justify-center gap-1.5 rounded-2xl py-3 text-[15px] font-extrabold transition active:scale-[0.99] disabled:opacity-[0.72]"
>
{submitting ? "…" : <>{t.submit} <span aria-hidden>→</span></>}
</button>
{match.league === "wc" && <TalkingMascot
src="/assets/mascots/tiger_point.webp"
lines={TIGER_LINES}
className="h-16 w-auto select-none sm:h-20"
auto
autoDelayMs={4200}
autoIntervalMs={6000}
/>}
</div>
</div>
)}
</section> </section>
{/* ===== 종료된 경기: 결과 보기 ===== */} {/* ===== 종료된 경기: 결과 보기 ===== */}
@@ -387,74 +470,6 @@ export default function Arena({
</button> </button>
)} )}
{/* ===== 투표 제출 (D5): 이메일 + 단일 CTA를 한 카드로 통합 ===== */}
{!finished && !disabled && step === "form" && (
<div className="mt-5 rounded-2xl border-2 border-[var(--green)]/60 bg-[var(--bg2)] p-4 shadow-[0_0_24px_rgba(74,255,160,0.08)]">
<div className="mb-2.5 text-center text-[15px] font-extrabold text-[var(--green)]">
{t.emailGate}
</div>
<input
type="email"
inputMode="email"
list="tp-email-suggestions"
autoComplete="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder={t.emailPh}
className="w-full rounded-2xl border border-[var(--share)] bg-[#0f1217] px-4 py-3 text-[16px] text-white shadow-[0_0_0_2px_rgba(166,94,255,0.12)] outline-none focus:shadow-[0_0_0_2px_rgba(166,94,255,0.3)]"
/>
{recentEmails.length > 0 && (
<datalist id="tp-email-suggestions">
{recentEmails.map((e) => (
<option key={e} value={e} />
))}
</datalist>
)}
<label className="mt-2.5 flex items-start gap-2 text-[13px] leading-snug text-[var(--ink-muted)]">
<input
type="checkbox"
checked={notify}
onChange={(e) => setNotify(e.target.checked)}
className="mt-0.5 accent-[var(--share)]"
/>
{t.notify}
</label>
{error && (
<p className="mt-2 text-[13px] font-bold text-[#ff6b6b]">{error}</p>
)}
{/* 투표하기 버튼 — 한국-남아공전에서만 양옆에 한국·일본 캐릭터(탭 시 투표 말풍선) */}
<div className="mt-3.5 flex items-end justify-center gap-1">
{isKorRsa && (
<TalkingMascot
src="/assets/mascots/dog_point.webp"
lines={DOG_LINES}
className="h-16 w-auto select-none sm:h-20"
auto
autoDelayMs={1200}
autoIntervalMs={6000}
/>
)}
<button
onClick={confirmSubmit}
disabled={!emailValid || submitting}
className="btn-share flex flex-1 items-center justify-center gap-1.5 rounded-2xl py-3 text-[15px] font-extrabold transition active:scale-[0.99] disabled:opacity-[0.72]"
>
{submitting ? "…" : <>{t.submit} <span aria-hidden>→</span></>}
</button>
{isKorRsa && (
<TalkingMascot
src="/assets/mascots/tiger_point.webp"
lines={TIGER_LINES}
className="h-16 w-auto select-none sm:h-20"
auto
autoDelayMs={4200}
autoIntervalMs={6000}
/>
)}
</div>
</div>
)}
{/* ===== 제출 완료: 같은 AI + 경기별 공유 (D8) ===== */} {/* ===== 제출 완료: 같은 AI + 경기별 공유 (D8) ===== */}
{!finished && step === "done" && outcome && ( {!finished && step === "done" && outcome && (
<div className="mt-5 rounded-2xl border border-[var(--green)]/50 bg-[var(--bg2)] p-5"> <div className="mt-5 rounded-2xl border border-[var(--green)]/50 bg-[var(--bg2)] p-5">
@@ -496,7 +511,9 @@ export default function Arena({
<ul className="flex flex-col gap-2"> <ul className="flex flex-col gap-2">
{(votesExpanded ? myPreds : myPreds.slice(0, 1)).map((p) => { {(votesExpanded ? myPreds : myPreds.slice(0, 1)).map((p) => {
const isThis = p.matchId === match.matchId; const isThis = p.matchId === match.matchId;
const pFlip = p.teamB.code === "KOR" && p.teamA.code !== "KOR"; const pFlip =
/^MLS_/.test(p.matchId) ||
(p.teamB.code === "KOR" && p.teamA.code !== "KOR");
const pA = teamShort(p.teamA, lang); const pA = teamShort(p.teamA, lang);
const pB = teamShort(p.teamB, lang); const pB = teamShort(p.teamB, lang);
const pLeft = pFlip ? pB : pA; const pLeft = pFlip ? pB : pA;
@@ -560,10 +577,11 @@ export default function Arena({
</section> </section>
)} )}
{/* ===== 누적 랭킹 TOP 10 (골드 카드 위 · 폴딩) — 랭킹→상금 도전 흐름 ===== */} {/* ===== 누적 랭킹 TOP 10 (골드 카드 위 · 폴딩) — 월드컵 외 리그는 임시 비노출(운영 방침 미확정) ===== */}
<RankingBoard lang={lang} /> {match.league === "wc" && <RankingBoard lang={lang} league={match.league} />}
{/* ===== 골드 상금 (003) ===== */} {/* ===== 골드 상금 (003) — 월드컵 외 리그는 임시 비노출 ===== */}
{match.league === "wc" && (
<section className="gold-card mt-5 rounded-2xl p-5"> <section className="gold-card mt-5 rounded-2xl p-5">
<div className="flex items-center justify-between gap-3"> <div className="flex items-center justify-between gap-3">
<div className="min-w-0"> <div className="min-w-0">
@@ -583,6 +601,7 @@ export default function Arena({
</button> </button>
</div> </div>
</section> </section>
)}
{/* ===== 룰 설명 모달 ===== */} {/* ===== 룰 설명 모달 ===== */}
{showRules && ( {showRules && (
@@ -605,9 +624,9 @@ export default function Arena({
{( {(
[ [
[t.rulesExact, 5], [t.rulesExact, 5],
[t.rulesCloseGrade, 3], [isBaseball ? t.rulesCloseGradeBB : t.rulesCloseGrade, 3],
[t.rulesOutcome, 2], [t.rulesOutcome, 2],
[t.rulesPartial, 1], [isBaseball ? t.rulesPartialBB : t.rulesPartial, 1],
[t.rulesMiss, 0], [t.rulesMiss, 0],
] as [string, number][] ] as [string, number][]
).map(([label, pt]) => ( ).map(([label, pt]) => (
@@ -676,11 +695,13 @@ function Stepper({
value, value,
onChange, onChange,
disabled, disabled,
max = 9,
}: { }: {
label: string; label: string;
value: number; value: number;
onChange: (n: number) => void; onChange: (n: number) => void;
disabled?: boolean; disabled?: boolean;
max?: number;
}) { }) {
return ( return (
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
@@ -688,12 +709,12 @@ function Stepper({
− −
</StepBtn> </StepBtn>
<div className="flex w-12 flex-col items-center"> <div className="flex w-12 flex-col items-center">
<span className="font-mono text-[32px] font-extrabold leading-none tabular-nums"> <span className="font-mono text-[32px] font-extrabold leading-none tabular-nums text-[var(--ink)]">
{value} {value}
</span> </span>
<span className="mt-1 text-[11px] text-[var(--ink-muted)]">{label}</span> <span className="mt-1 text-[11px] text-[var(--ink-muted)]">{label}</span>
</div> </div>
<StepBtn disabled={disabled || value >= 9} onClick={() => onChange(Math.min(9, value + 1))}> <StepBtn disabled={disabled || value >= max} onClick={() => onChange(Math.min(max, value + 1))}>
+ +
</StepBtn> </StepBtn>
</div> </div>
+1 -1
View File
@@ -129,7 +129,7 @@ export default function Comments({
<div className="mt-3 space-y-2"> <div className="mt-3 space-y-2">
{nickname && ( {nickname && (
<p className="flex items-center gap-1.5 text-[12px] font-bold text-white/45"> <p className="flex items-center gap-1.5 text-[12px] font-bold text-white/45">
⚽ {t.commentAs}{" "} {/^(KBO|MLB)_/.test(matchId) ? "⚾" : "⚽"} {t.commentAs}{" "}
<span className="text-[var(--green)]">{nickname}</span> <span className="text-[var(--green)]">{nickname}</span>
<button <button
type="button" type="button"
+11 -3
View File
@@ -1,14 +1,22 @@
import { type Lang, dict } from "@/lib/i18n"; import { type Lang, dict } from "@/lib/i18n";
export default function Footer({ lang = "ko" }: { lang?: Lang }) { // league 를 주면 비제휴 고지를 리그에 맞게 표시 (클럽 리그 = KBO/MLB/MLS, 기본 = 월드컵)
export default function Footer({
lang = "ko",
league = "wc",
}: {
lang?: Lang;
league?: string;
}) {
const t = dict(lang); const t = dict(lang);
const isBaseball = league !== "wc";
return ( return (
<footer className="mt-6 text-center"> <footer className="mt-6 text-center">
<p className="text-[10.5px] font-semibold text-white/75"> <p className="text-[10.5px] font-semibold text-white/75">
{t.footerNotOfficial} {isBaseball ? t.footerNotOfficialBB : t.footerNotOfficial}
</p> </p>
<p className="mt-1 text-[10.5px] leading-relaxed text-white/60"> <p className="mt-1 text-[10.5px] leading-relaxed text-white/60">
{t.footerDisc1} {isBaseball ? t.footerDisc1BB : t.footerDisc1}
</p> </p>
<div className="mx-auto mt-3 max-w-[400px] space-y-1 text-[9.5px] leading-relaxed text-white/55"> <div className="mx-auto mt-3 max-w-[400px] space-y-1 text-[9.5px] leading-relaxed text-white/55">
+112 -5
View File
@@ -2,6 +2,53 @@ import { Link, useNavigate } from "react-router-dom";
import ShareButton from "./ShareButton"; import ShareButton from "./ShareButton";
import LangSwitch from "./LangSwitch"; import LangSwitch from "./LangSwitch";
import { type Lang, dict } from "@/lib/i18n"; import { type Lang, dict } from "@/lib/i18n";
import { useAuth } from "@/lib/auth";
import type { League } from "@/lib/types";
// 카카오 로그인 버튼(브랜드 노랑) ↔ 로그인 시 프로필 칩 + 로그아웃
function AuthChip({ lang }: { lang: Lang }) {
const { user, login, logout } = useAuth();
if (user) {
return (
<span className="flex items-center gap-1.5">
<span className="flex max-w-[130px] items-center gap-1.5 rounded-full border border-white/12 bg-white/8 py-1 pl-1 pr-2.5">
{user.profileImageUrl ? (
<img
src={user.profileImageUrl}
alt=""
className="h-5 w-5 rounded-full object-cover"
/>
) : (
<span className="grid h-5 w-5 place-items-center rounded-full bg-white/15 text-[10px]">
👤
</span>
)}
<span className="truncate text-[11px] font-bold text-white/85">
{user.nickname || user.email || "회원"}
</span>
</span>
<button
onClick={logout}
className="rounded-full border border-white/12 px-2 py-1 text-[10px] font-bold text-white/45 transition active:scale-95"
>
{lang === "en" ? "Sign out" : "로그아웃"}
</button>
</span>
);
}
return (
<button
onClick={login}
className="flex items-center gap-1 rounded-full bg-[#FEE500] px-2.5 py-1 text-[11px] font-extrabold text-[#191919] transition active:scale-95"
>
{/* 카카오 말풍선 심볼 */}
<svg viewBox="0 0 24 24" className="h-3.5 w-3.5" fill="#191919">
<path d="M12 3C6.48 3 2 6.58 2 11c0 2.84 1.87 5.33 4.68 6.75-.15.53-.97 3.36-1 3.58 0 0-.02.17.09.24.11.07.24.02.24.02.32-.05 3.7-2.42 4.28-2.83.55.08 1.12.12 1.71.12 5.52 0 10-3.58 10-8S17.52 3 12 3z" />
</svg>
{lang === "en" ? "Sign in" : "로그인"}
</button>
);
}
type Share = { url: string; title: string; text: string }; type Share = { url: string; title: string; text: string };
@@ -10,10 +57,12 @@ export default function Hero({
back = false, back = false,
share, share,
lang = "ko", lang = "ko",
league = "wc",
}: { }: {
back?: boolean; back?: boolean;
share?: Share; share?: Share;
lang?: Lang; lang?: Lang;
league?: League;
}) { }) {
const t = dict(lang); const t = dict(lang);
const navigate = useNavigate(); const navigate = useNavigate();
@@ -28,7 +77,7 @@ export default function Hero({
}; };
return ( return (
<header className="pt-5 text-center"> <header className="pt-5 text-center">
{back && ( {back ? (
<div className="mb-3 flex items-center justify-between"> <div className="mb-3 flex items-center justify-between">
<Link <Link
to={home} to={home}
@@ -37,9 +86,16 @@ export default function Hero({
> >
{t.back} {t.back}
</Link> </Link>
{share && ( <span className="flex items-center gap-2">
<ShareButton {...share} label={t.share} copiedLabel={t.shareCopied} /> <AuthChip lang={lang} />
)} {share && (
<ShareButton {...share} label={t.share} copiedLabel={t.shareCopied} />
)}
</span>
</div>
) : (
<div className="mb-1 flex justify-end">
<AuthChip lang={lang} />
</div> </div>
)} )}
<div className="font-impact text-[44px] leading-none tracking-tight"> <div className="font-impact text-[44px] leading-none tracking-tight">
@@ -54,8 +110,59 @@ export default function Hero({
</div> </div>
</div> </div>
<div className="mt-2 inline-block rounded-full border border-white/12 bg-white/8 px-3 py-1 text-[13px] font-semibold text-white/85"> <div className="mt-2 inline-block rounded-full border border-white/12 bg-white/8 px-3 py-1 text-[13px] font-semibold text-white/85">
{t.heroPill} {league === "kbo"
? lang === "en"
? "AI-powered 2026 KBO League game predictions"
: "AI와 함께하는 2026 프로야구 KBO 승부예측 챌린지"
: league === "mlb"
? lang === "en"
? "AI-powered 2026 MLB game predictions"
: "AI와 함께하는 2026 MLB 승부예측 챌린지"
: league === "mls"
? lang === "en"
? "AI-powered 2026 MLS game predictions"
: "AI와 함께하는 2026 MLS 승부예측 챌린지"
: t.heroPill}
</div> </div>
<LeagueTabs lang={lang} current={league} />
</header> </header>
); );
} }
// 리그 전환 탭 — 단일 앱 내 전환. 탭 클릭 시 해당 리그 대시보드로 이동.
function LeagueTabs({ lang, current }: { lang: Lang; current: League }) {
const navigate = useNavigate();
const tabs: { key: League; label: string }[] = [
{ key: "kbo", label: "KBO" },
{ key: "mlb", label: "MLB" },
{ key: "mls", label: "MLS" },
];
return (
<div className="mt-3 flex justify-center">
<div className="inline-flex rounded-full border border-white/12 bg-white/5 p-1 text-[13px] font-bold">
{tabs.map((tab) =>
tab.key === current ? (
<span
key={tab.key}
className="rounded-full bg-[var(--green)] px-4 py-1.5 text-black"
>
{tab.label}
</span>
) : (
<button
key={tab.key}
onClick={() =>
navigate(
`/?league=${tab.key}${lang === "en" ? "&lang=en" : ""}`
)
}
className="rounded-full px-4 py-1.5 text-white/45 transition hover:text-white/75"
>
{tab.label}
</button>
),
)}
</div>
</div>
);
}
+383
View File
@@ -0,0 +1,383 @@
import { useEffect, useState } from "react";
import type { Lang } from "@/lib/i18n";
import { timeOnly } from "@/lib/format";
import { getLive, type LiveData, type RelayEvent, type RelayGroup } from "@/lib/api";
import type { Match } from "@/lib/types";
// 라이브 필드 뷰 — 수비 배치 다이아몬드 + 현재 타자/투수 + B/S/O + 주자 + 대기타석.
// phase === "live" 일 때 20초 폴링. (?debugLive=1 로 종료 경기에서도 강제 표시)
// 포지션 → 필드 위 좌표(%) — left/top (SVG viewBox 100×70 과 동일 비율)
const POS_XY: Record<string, [number, number]> = {
포수: [50, 90],
"1루수": [71, 55],
"2루수": [61, 39],
유격수: [39, 39],
"3루수": [29, 55],
좌익수: [20, 26],
중견수: [50, 14],
우익수: [80, 26],
};
// 필드 SVG 상 베이스 좌표 (viewBox 0 0 100 70) — 1루·2루·3루
const BASE_XY: [number, number][] = [
[63.5, 42.5],
[50, 29],
[36.5, 42.5],
];
function NameChip({
name,
sub,
accent = false,
x,
y,
}: {
name: string;
sub?: string;
accent?: boolean;
x: number;
y: number;
}) {
return (
<div
className="absolute -translate-x-1/2 -translate-y-1/2 text-center"
style={{ left: `${x}%`, top: `${y}%` }}
>
<div
className={`whitespace-nowrap rounded-full px-2.5 py-1 text-[11px] font-bold shadow-[0_1px_3px_rgba(0,0,0,0.25)] ${
accent ? "bg-[#d94141] text-white" : "bg-white text-[#222]"
}`}
>
{name}
</div>
{sub && (
<div className="mt-0.5 text-[9px] font-bold text-[#245c2a]/80">{sub}</div>
)}
</div>
);
}
function Dot({ on, color }: { on: boolean; color: string }) {
return (
<span
className="inline-block h-2.5 w-2.5 rounded-full"
style={{ background: on ? color : "rgba(255,255,255,0.14)" }}
/>
);
}
// 구장 SVG — 부채꼴 외야 + 파울라인 + 흙 내야 + 마운드 + 베이스(주자 점등).
// 경기 전(빈 구장)·경기 중·종료 스냅샷 모두 공용.
function BallparkSvg({ bases }: { bases?: boolean[] }) {
return (
<svg
viewBox="0 0 100 70"
preserveAspectRatio="none"
className="absolute inset-0 h-full w-full"
>
<rect width="100" height="70" fill="#4e8a48" />
<path
d="M50,62 L8,20 A60,60 0 0 1 92,20 Z"
fill="#6cb163"
stroke="rgba(255,255,255,0.85)"
strokeWidth="0.5"
/>
<polygon points="50,20 73,43 50,66 27,43" fill="#cd9f63" />
<polygon
points="50,29 63.5,42.5 50,56 36.5,42.5"
fill="#6cb163"
stroke="rgba(255,255,255,0.4)"
strokeWidth="0.4"
/>
<circle cx="50" cy="43" r="3.2" fill="#cd9f63" />
<circle cx="50" cy="60.5" r="4.2" fill="#cd9f63" />
{BASE_XY.map(([cx, cy], i) => (
<rect
key={i}
x={cx - 1.5}
y={cy - 1.5}
width="3"
height="3"
rx="0.5"
transform={`rotate(45 ${cx} ${cy})`}
fill={bases?.[i] ? "#ffd23e" : "#ffffff"}
stroke="rgba(0,0,0,0.15)"
strokeWidth="0.3"
/>
))}
<rect x="48.8" y="59.3" width="2.4" height="2.4" rx="0.4" fill="#ffffff" />
</svg>
);
}
// 이벤트 종류별 텍스트 스타일 — 투구는 흐리게, 타석 결과는 강조.
const RELAY_STYLE: Record<RelayEvent["kind"], string> = {
pitch: "text-white/35",
result: "font-extrabold text-white/90",
run: "text-[#8FD3FF]",
sub: "text-white/45",
note: "text-white/40",
inning: "text-white/60",
batter: "text-white/60",
end: "font-bold text-white/70",
};
// 문자중계 — 타석 단위 그룹(최신순). events 가 비면 이닝 구분 헤더.
// 원문이 한국어(네이버)라 영문 모드에서도 그대로 노출한다.
function RelayFeed({ groups, lang }: { groups: RelayGroup[]; lang: Lang }) {
const [showPitches, setShowPitches] = useState(true);
return (
<div className="mt-3 border-t border-white/10 pt-2.5">
<div className="mb-1.5 flex items-baseline justify-between">
<span className="text-[10px] font-bold text-white/35">
{lang === "en" ? "PLAY-BY-PLAY" : "문자중계"}
</span>
<div className="flex items-baseline gap-2">
<button
onClick={() => setShowPitches((v) => !v)}
className="text-[10px] font-bold text-white/45 transition active:scale-95"
>
{showPitches
? lang === "en" ? "Hide pitches" : "투구 접기"
: lang === "en" ? "Show pitches" : "투구 펼치기"}
</button>
<span className="text-[9px] text-white/25">NAVER</span>
</div>
</div>
<ul className="max-h-[260px] space-y-2 overflow-y-auto pr-1 [scrollbar-width:thin] [scrollbar-color:rgba(255,255,255,.22)_transparent] [&::-webkit-scrollbar]:w-1.5 [&::-webkit-scrollbar-track]:bg-transparent [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:bg-white/20">
{groups.map((g) => {
const events = showPitches ? g.events : g.events.filter((e) => e.kind !== "pitch");
// 이닝 구분 헤더 (내용 없는 그룹)
if (g.events.length === 0) {
return (
<li key={g.no} className="flex items-center gap-2 pt-1">
<span className="h-px flex-1 bg-white/10" />
<span className="text-[10px] font-extrabold text-white/40">{g.title}</span>
<span className="h-px flex-1 bg-white/10" />
</li>
);
}
if (events.length === 0) return null; // 투구만 있던 타석 — 접기 모드에선 숨김
return (
<li key={g.no}>
{g.title && (
<div className="flex items-baseline gap-1.5">
{g.inn != null && (
<span className="shrink-0 font-mono text-[10px] font-bold text-white/30">
{g.inn}
{g.half === "B" ? "말" : "초"}
</span>
)}
<span className="text-[11px] font-extrabold text-white/75">{g.title}</span>
</div>
)}
<ul className="mt-0.5 space-y-px pl-1.5 text-[11px] leading-snug">
{events.map((e, i) => (
<li
key={i}
className={
e.score
? "rounded-lg border border-[#94FBE0]/30 bg-[#94FBE0]/10 px-1.5 py-1 font-extrabold text-[#94FBE0]"
: RELAY_STYLE[e.kind]
}
>
{e.text}
</li>
))}
</ul>
</li>
);
})}
</ul>
</div>
);
}
export default function LiveField({ match, lang = "ko" }: { match: Match; lang?: Lang }) {
const isLive = match.phase === "live";
// 경기 중엔 20초 폴링, 그 외(경기 전·종료)는 1회 로드.
// 경기 전엔 중계 미게시(available=false)라도 빈 구장 + "경기 전"으로 표시.
const [data, setData] = useState<LiveData | null>(null);
const isBaseball = match.league === "kbo" || match.league === "mlb";
useEffect(() => {
if (!isBaseball) return;
let alive = true;
const load = () =>
getLive(match.matchId)
.then((d) => alive && setData(d))
.catch(() => {});
load();
if (!isLive) return () => { alive = false; };
const id = setInterval(load, 20_000);
return () => {
alive = false;
clearInterval(id);
};
}, [isBaseball, isLive, match.matchId]);
// 야구 전용 위젯 — 축구(월드컵)에서는 렌더하지 않음
if (!isBaseball) return null;
// 중계 데이터 없음 (경기 전 또는 시작 직후) — 빈 구장 + 상태 라벨
if (!data?.available) {
if (match.phase === "finished") return null; // 종료인데 기록 없음 — 표시할 것 없음
return (
<section className="mt-4">
<div className="rounded-3xl border border-white/10 bg-[#171b21] p-4">
<div className="flex items-center justify-between">
<span className="text-[13px] font-extrabold text-white/45">
{lang === "en" ? "FIELD" : "필드"}
</span>
<span className="font-mono text-[13px] font-bold text-white/55">
{timeOnly(match.kickoffKst)} KST
</span>
</div>
<div className="relative mt-3 aspect-[10/7] overflow-hidden rounded-2xl">
<BallparkSvg />
<div className="absolute inset-0 grid place-items-center">
<span className="rounded-full bg-black/50 px-4 py-1.5 text-[13px] font-extrabold text-white/95">
{isLive
? lang === "en"
? "Starting soon…"
: "경기 시작 대기 중"
: lang === "en"
? "Pre-game · lineups TBA"
: "경기 전 · 라인업 발표 전"}
</span>
</div>
</div>
</div>
</section>
);
}
const half = data.half === "B" ? (lang === "en" ? "Bot" : "말") : lang === "en" ? "Top" : "초";
const battingTeam = data.half === "B" ? match.teamB : match.teamA;
const num = (v: unknown) => Number(v ?? 0) || 0;
return (
<section className="mt-4">
<div className="rounded-3xl border border-white/10 bg-[#171b21] p-4">
{/* 헤더: 이닝·스코어·B/S/O */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
{isLive ? (
<>
<span className="flex h-2 w-2">
<span className="absolute inline-flex h-2 w-2 animate-ping rounded-full bg-[#FF5B5B] opacity-60" />
<span className="relative inline-flex h-2 w-2 rounded-full bg-[#FF5B5B]" />
</span>
<span className="text-[13px] font-extrabold text-[#FF5B5B]">
LIVE · {data.inn}
{lang === "en" ? ` (${half})` : `회${half}`}
</span>
</>
) : (
<span className="text-[13px] font-extrabold text-white/45">
{lang === "en" ? "FINAL" : "경기 종료"} · {data.inn}
{lang === "en" ? ` (${half})` : `회${half}`}
</span>
)}
</div>
<span className="font-mono text-[18px] font-extrabold tabular-nums">
{match.teamA.shortName} {num(data.score?.away)}
<span className="px-1 text-white/40">:</span>
{num(data.score?.home)} {match.teamB.shortName}
</span>
</div>
{/* B/S/O + 주자 다이아몬드 */}
<div className="mt-3 flex items-center justify-between rounded-2xl bg-white/[0.04] px-3 py-2">
<div className="space-y-1 text-[10px] font-bold text-white/50">
<div className="flex items-center gap-1.5">
B{" "}
{[0, 1, 2].map((i) => (
<Dot key={i} on={num(data.bso?.b) > i} color="#4ade80" />
))}
</div>
<div className="flex items-center gap-1.5">
S{" "}
{[0, 1].map((i) => (
<Dot key={i} on={num(data.bso?.s) > i} color="#facc15" />
))}
</div>
<div className="flex items-center gap-1.5">
O{" "}
{[0, 1].map((i) => (
<Dot key={i} on={num(data.bso?.o) > i} color="#f87171" />
))}
</div>
</div>
<div className="text-right text-[11px] font-semibold text-white/55">
<div>
{lang === "en" ? "AB" : "타석"}{" "}
<span className="font-extrabold text-white/90">{battingTeam.shortName}</span>
</div>
{data.vsRecord && <div className="mt-0.5 text-[10px] text-white/35">{data.vsRecord}</div>}
</div>
</div>
{/* 필드: 구장 SVG + 수비 배치/투수/타자 칩 */}
<div className="relative mt-3 aspect-[10/7] overflow-hidden rounded-2xl">
<BallparkSvg bases={data.bases} />
{data.defense?.map((f) => {
const xy = POS_XY[f.pos ?? ""];
if (!xy) return null;
return <NameChip key={f.pos} name={f.name} sub={f.pos} x={xy[0]} y={xy[1]} />;
})}
{data.pitcher && (
<NameChip
name={data.pitcher.name}
sub={`${lang === "en" ? "P" : "투구수"} ${num(data.pitcher.ballCount)}`}
x={50}
y={61}
/>
)}
{data.batter && (
<NameChip
name={`${data.batter.order ?? ""}. ${data.batter.name}`}
accent
x={50}
y={79}
/>
)}
</div>
{/* 대기타석 */}
{data.batter && data.offenseLineup && (
<div className="mt-3 flex items-center gap-2 overflow-x-auto pb-1 text-[11px] font-semibold text-white/55 [scrollbar-width:thin] [scrollbar-color:rgba(255,255,255,.22)_transparent] [&::-webkit-scrollbar]:h-1.5 [&::-webkit-scrollbar-track]:bg-transparent [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:bg-white/20">
<span className="shrink-0 text-white/35">{lang === "en" ? "Next" : "대기타석"}</span>
{data.offenseLineup
.filter((b) => {
const cur = data.batter!.order ?? 0;
const diff = ((b.order ?? 0) - cur + 9) % 9;
return diff >= 1 && diff <= 3;
})
.sort((a, b) => {
const cur = data.batter!.order ?? 0;
return (((a.order ?? 0) - cur + 9) % 9) - (((b.order ?? 0) - cur + 9) % 9);
})
.map((b) => (
<span
key={b.order}
className="shrink-0 rounded-full border border-white/10 px-2 py-0.5"
>
{b.order}. {b.name}
{b.sub ? " ↺" : ""}
</span>
))}
</div>
)}
{/* 문자중계 (KBO 만 — MLB 는 소스 미연동) */}
{(data.relay?.length ?? 0) > 0 && <RelayFeed groups={data.relay!} lang={lang} />}
</div>
</section>
);
}
+563
View File
@@ -0,0 +1,563 @@
import { useEffect, useMemo, useState } from "react";
import type { Lang } from "@/lib/i18n";
import { teamShort } from "@/lib/i18n";
import { getLive, type LiveData, type SoccerLineup, type SoccerPlayer } from "@/lib/api";
import type { Match } from "@/lib/types";
const POLL_MS = 20_000;
// 라인업은 보통 킥오프 60~75분 전 발표 — 이 시간부터 경기 전 폴링 시작
const PREGAME_MIN = 90;
// 자책골 마커 — 빨간 축구공 (이모지는 색 변경이 안 돼 인라인 SVG 로 그린다)
function OgBall() {
return (
<svg viewBox="0 0 12 12" className="inline h-[11px] w-[11px] align-[-1.5px]">
<circle cx="6" cy="6" r="5.4" fill="#E5484D" stroke="#fff" strokeWidth="0.9" />
<path d="M6 3.1 4.2 4.4l.7 2.1h2.2l.7-2.1z" fill="#fff" />
</svg>
);
}
// MLS 라이브 카드 — 경기 분·스코어·득점·선발 라인업·실시간 교체 현황.
// 경기 전(킥오프 90분 이내, 라인업 발표 시)·경기 중·종료 후(경기 기록) 렌더. (서버 15초 캐시)
export default function LiveSoccer({ match, lang = "ko" }: { match: Match; lang?: Lang }) {
const isMls = match.league === "mls";
const isLive = match.phase === "live";
const isDone = match.phase === "finished";
// 경기 전 폴링 여부 — 킥오프까지 90분 이내
const nearKickoff = useMemo(() => {
const diff = new Date(match.kickoffKst).getTime() - Date.now();
return diff > 0 && diff <= PREGAME_MIN * 60_000;
}, [match.kickoffKst]);
const active = isMls && (isLive || isDone || nearKickoff);
const [live, setLive] = useState<LiveData | null>(null);
const [showBench, setShowBench] = useState(false);
useEffect(() => {
if (!active) return;
let alive = true;
const load = () =>
getLive(match.matchId)
.then((d) => {
if (alive && d.available) setLive(d);
})
.catch(() => {});
load();
if (isDone) return () => { alive = false; }; // 종료 경기는 1회 조회로 충분
const t = setInterval(load, POLL_MS);
return () => {
alive = false;
clearInterval(t);
};
}, [active, isDone, match.matchId]);
if (!active || !live?.available) return null;
const inPlay = live.state !== "pre";
const ended = live.state === "post";
const awayGoals = (live.goals ?? []).filter((g) => g.team === match.teamA.code);
const homeGoals = (live.goals ?? []).filter((g) => g.team === match.teamB.code);
// 득점 표기: 첫 줄 득점자 ⚽ / 둘째 줄(들여쓰기) 도움 선수 👟 — 줄바꿈 어색함 방지
const goalLine = (
g: {
clock: string;
player: string;
assist?: string;
ownGoal?: boolean;
penalty?: boolean;
},
right = false,
) => (
<>
<div>
{g.clock} {g.player}
{g.penalty ? " (PK)" : ""}
{g.ownGoal ? " (OG)" : ""}{" "}
{g.ownGoal ? <OgBall /> : "⚽"}
</div>
{g.assist && (
<div className={`text-white/35 ${right ? "pr-4" : "pl-4"}`}>
{g.assist} 👟
</div>
)}
</>
);
// 교체 시각 매핑 (선수명 → 분) — 라인업 옆에 표시
const subClock = new Map<string, string>();
// 나간 선수 → 들어온 선수 매핑 — 피치에서 투입 선수가 그 자리를 대체
const outToIn = new Map<string, { inName: string; clock: string }>();
for (const s of live.subs ?? []) {
if (s.inName) subClock.set(s.inName, s.clock);
if (s.outName) subClock.set(s.outName, s.clock);
if (s.outName && s.inName) outToIn.set(s.outName, { inName: s.inName, clock: s.clock });
}
// 득점(⚽)·도움(👟)·자책골(빨간 ⚽) 횟수 — 피치 이름표에 표시
const goalsBy = new Map<string, number>();
const assistsBy = new Map<string, number>();
const ogBy = new Map<string, number>();
for (const g of live.goals ?? []) {
if (g.player && !g.ownGoal) goalsBy.set(g.player, (goalsBy.get(g.player) ?? 0) + 1);
if (g.player && g.ownGoal) ogBy.set(g.player, (ogBy.get(g.player) ?? 0) + 1);
if (g.assist) assistsBy.set(g.assist, (assistsBy.get(g.assist) ?? 0) + 1);
}
// 카드(🟨/🟥) 누적 — 피치·교체 명단 이름표에 표시
const cardsBy = new Map<string, { y: number; red: boolean }>();
for (const c of live.cards ?? []) {
if (!c.player) continue;
const cur = cardsBy.get(c.player) ?? { y: 0, red: false };
if (c.red) cur.red = true;
else cur.y += 1;
cardsBy.set(c.player, cur);
}
return (
<section
className={`mt-5 rounded-2xl border bg-[var(--bg2)] p-4 ${
inPlay && !ended ? "border-[#FF5B5B]/40" : "border-[var(--line-d)]"
}`}
>
{/* 헤더: LIVE/경기 기록/선발 라인업 + 경기 시간 */}
<div className="flex items-center justify-between">
{ended ? (
<span className="text-[13px] font-extrabold text-white">
{lang === "en" ? "Match recap" : "경기 기록"}
</span>
) : inPlay ? (
<span className="flex items-center gap-1.5 text-[12px] font-extrabold text-[#FF5B5B]">
<span className="inline-block h-2 w-2 animate-pulse rounded-full bg-[#FF5B5B]" />
LIVE
</span>
) : (
<span className="text-[13px] font-extrabold text-white">
{lang === "en" ? "Starting lineups" : "선발 라인업"}
</span>
)}
{inPlay && (
<span className="font-mono text-[13px] font-extrabold text-white/80">
{ended ? (
<span className="text-[11px] font-bold text-white/40">
{lang === "en" ? "FT" : "경기 종료"}
</span>
) : (
<>
{live.clock}
{live.period != null && (
<span className="ml-1.5 text-[11px] font-bold text-white/40">
{live.period === 1
? lang === "en" ? "1st half" : "전반"
: live.period === 2
? lang === "en" ? "2nd half" : "후반"
: lang === "en" ? "ET" : "연장"}
</span>
)}
</>
)}
</span>
)}
</div>
{/* 스코어 (경기 중에만) — 홈 팀 먼저 (축구 관례) */}
{inPlay && (
<div className="mt-3 grid grid-cols-[1fr_auto_1fr] items-center gap-2">
<span className="truncate text-[15px] font-extrabold">{teamShort(match.teamB, lang)}</span>
<span className="whitespace-nowrap font-mono text-[26px] font-extrabold tabular-nums text-white">
{live.score?.home ?? 0}
<span className="px-2 text-[#FF5B5B]">:</span>
{live.score?.away ?? 0}
</span>
<span className="truncate text-right text-[15px] font-extrabold">
{teamShort(match.teamA, lang)}
</span>
</div>
)}
{/* 득점 이벤트 (양 팀 분리, 시간순) — 좌=홈 / 우=원정 */}
{(awayGoals.length > 0 || homeGoals.length > 0) && (
<div className="mt-3 grid grid-cols-2 gap-2 border-t border-white/10 pt-2.5 text-[11px] font-semibold text-white/60">
<div className="space-y-0.5">
{homeGoals.map((g, i) => (
<div key={i}>{goalLine(g)}</div>
))}
</div>
<div className="space-y-0.5 text-right">
{awayGoals.map((g, i) => (
<div key={i}>{goalLine(g, true)}</div>
))}
</div>
</div>
)}
{/* 문자중계 (최신순) — 세로 스크롤 (다크 스크롤바, 흰 배경 없음) */}
{(live.commentary?.length ?? 0) > 0 && (
<div className="mt-3 border-t border-white/10 pt-2.5">
<div className="mb-1 flex items-baseline justify-between">
<span className="text-[10px] font-bold text-white/35">
{lang === "en" ? "PLAY-BY-PLAY" : "문자중계"}
</span>
<span className="text-[9px] text-white/25">ESPN</span>
</div>
<ul className="max-h-[200px] space-y-1 overflow-y-auto pr-1 text-[11px] leading-snug [scrollbar-width:thin] [scrollbar-color:rgba(255,255,255,.22)_transparent] [&::-webkit-scrollbar]:w-1.5 [&::-webkit-scrollbar-track]:bg-transparent [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:bg-white/20">
{live.commentary!.map((c, i) => (
<li
key={`${c.clock}-${i}`}
className={`flex gap-1.5 ${
c.goal
? "rounded-lg border border-[#94FBE0]/30 bg-[#94FBE0]/10 px-1.5 py-1"
: ""
}`}
>
<span
className={`w-7 shrink-0 text-right font-mono font-bold ${
c.goal ? "text-[#94FBE0]" : "text-white/40"
}`}
>
{c.clock}
</span>
<span
className={
c.goal ? "font-extrabold text-[#94FBE0]" : "font-medium text-white/65"
}
>
{c.text}
</span>
</li>
))}
</ul>
</div>
)}
{/* 선발 라인업 — 축구장 하나에 반코트씩 (위=홈 · 아래=원정), 교체 아웃은 흐리게 */}
{live.lineups?.away && live.lineups?.home && (
<div className="mt-3 border-t border-white/10 pt-2.5">
<div className="mb-1.5 flex items-center justify-between text-[11px] font-extrabold text-white/85">
<span>
{teamShort(match.teamB, lang)}
{live.lineups.home.formation && (
<span className="ml-1 font-mono text-[10px] font-bold text-white/40">
{live.lineups.home.formation}
</span>
)}
</span>
<span className="text-[10px] font-bold text-white/35">
{lang === "en" ? "STARTING XI" : "선발 라인업"}
</span>
<span className="text-right">
{live.lineups.away.formation && (
<span className="mr-1 font-mono text-[10px] font-bold text-white/40">
{live.lineups.away.formation}
</span>
)}
{teamShort(match.teamA, lang)}
</span>
</div>
<Pitch
away={live.lineups.away}
home={live.lineups.home}
outToIn={outToIn}
goalsBy={goalsBy}
assistsBy={assistsBy}
ogBy={ogBy}
cardsBy={cardsBy}
/>
{/* 교체 명단 (벤치) — 투입된 선수는 ▲분 표시 */}
<button
onClick={() => setShowBench((v) => !v)}
className="mt-2.5 flex w-full items-center justify-center gap-1 rounded-xl border border-[var(--line-d)] py-2 text-[12px] font-bold text-[var(--ink-muted)] transition active:scale-[0.99]"
>
{showBench
? lang === "en" ? "Hide bench" : "교체 명단 접기"
: lang === "en" ? "Show bench" : "교체 명단 보기"}
<span aria-hidden>{showBench ? "▲" : "▼"}</span>
</button>
{showBench && (
<div className="mt-2 grid grid-cols-2 gap-3 text-[11px]">
<BenchList
lu={live.lineups.home}
subClock={subClock}
goalsBy={goalsBy}
assistsBy={assistsBy}
ogBy={ogBy}
cardsBy={cardsBy}
/>
<BenchList
lu={live.lineups.away}
subClock={subClock}
goalsBy={goalsBy}
assistsBy={assistsBy}
ogBy={ogBy}
cardsBy={cardsBy}
right
/>
</div>
)}
</div>
)}
</section>
);
}
// 포메이션 문자열("4-2-3-1") → 줄별 인원. 합이 필드 플레이어 수와 다르면 4-4-2 폴백.
function parseRows(formation: string | null | undefined, n: number): number[] {
const rows = (formation ?? "").split("-").map(Number).filter((x) => x > 0);
if (rows.length && rows.reduce((a, b) => a + b, 0) === n) return rows;
return n === 10 ? [4, 4, 2] : [n];
}
// 포지션 약어 → 세로 라인 가중치 (작을수록 수비 라인)
// F/ST 는 CF 보다 반 칸 앞 — 3-4-2-1 의 섀도 투톱(CF-R/CF-L) 뒤 원톱(F) 구분.
// 실제로 같은 줄인 4-3-3 등은 아래 병합 단계가 포메이션 숫자에 맞춰 다시 합친다.
const POS_LINE: Record<string, number> = {
G: 0,
RB: 1, LB: 1, CD: 1, CB: 1, SW: 1,
RWB: 1.5, LWB: 1.5,
DM: 2,
CM: 2.5,
RM: 3, LM: 3,
AM: 3.5,
RW: 3.7, LW: 3.7,
RF: 4, LF: 4, CF: 4,
F: 4.2, ST: 4.2,
};
const posBase = (pos: string) => pos.toUpperCase().replace(/-[RL]$/, "");
// 줄 안 좌→우 정렬 키 (상단 팀 기준; 하단 팀은 미러로 좌우 반전)
function posX(pos: string): number {
const P = pos.toUpperCase();
if (P.startsWith("L")) return 0;
if (P.startsWith("R")) return 4;
if (P.endsWith("-L")) return 1;
if (P.endsWith("-R")) return 3;
return 2;
}
// ESPN formationPlace 는 줄 순서가 아니라 전통 등번호식 슬롯(2=RB, 3=LB, 4=CM…)이라
// 순서대로 줄에 채우면 배치가 어긋난다 → 포지션 약어(CD-R, CM-L…) 기반으로 줄 구성.
function layoutRows(field: SoccerPlayer[], formation?: string | null): SoccerPlayer[][] {
const lines = field.map((p) => POS_LINE[posBase(p.pos || "")]);
let rows: SoccerPlayer[][];
if (lines.some((l) => l == null)) {
// 포지션 불명 선수가 있으면 formationPlace 순 폴백
const cnts = parseRows(formation, field.length);
let i = 0;
rows = cnts.map((c) => field.slice(i, (i += c)));
} else {
const groups = new Map<number, SoccerPlayer[]>();
field.forEach((p, i) => {
const arr = groups.get(lines[i]) ?? [];
arr.push(p);
groups.set(lines[i], arr);
});
rows = [...groups.entries()].sort((a, b) => a[0] - b[0]).map(([, ps]) => ps);
// 포메이션 숫자에 줄 수 맞추기 — 앞 줄부터 인원수대로 병합 (4-4-2 의 중미+윙미 등)
const target = parseRows(formation, field.length);
if (target.reduce((a, b) => a + b, 0) === field.length && target.length < rows.length) {
const merged: SoccerPlayer[][] = [];
let gi = 0;
let ok = true;
for (const cnt of target) {
let acc: SoccerPlayer[] = [];
while (acc.length < cnt && gi < rows.length) acc = acc.concat(rows[gi++]);
if (acc.length !== cnt) { ok = false; break; }
merged.push(acc);
}
if (ok && gi === rows.length) rows = merged;
}
}
return rows.map((r) => r.slice().sort((a, b) => posX(a.pos || "") - posX(b.pos || "")));
}
// 축구장 피치 — 세로형 풀피치, 위 반코트=홈 / 아래 반코트=원정 (홈 먼저 — 축구 관례).
// 각 포메이션 라인이 화면 가로폭 전체를 쓰므로 이름 공간이 넓다.
// 현재 그라운드 기준: 교체 투입 선수가 나간 선수 자리를 대체(빨간 ▲분),
// 나간 선수는 교체 명단(BenchList)에 ▼로 표시된다.
function Pitch({
away,
home,
outToIn,
goalsBy,
assistsBy,
ogBy,
cardsBy,
}: {
away: SoccerLineup;
home: SoccerLineup;
outToIn?: Map<string, { inName: string; clock: string }>;
goalsBy?: Map<string, number>;
assistsBy?: Map<string, number>;
ogBy?: Map<string, number>;
cardsBy?: Map<string, { y: number; red: boolean }>;
}) {
const place = (lu: SoccerLineup, half: "top" | "bottom") => {
const [gk, ...field] = lu.starters;
const out: { p: SoccerPlayer; x: number; y: number }[] = [];
if (gk) out.push({ p: gk, x: 0.5, y: 0.055 });
const rows = layoutRows(field, lu.formation);
rows.forEach((row, r) => {
// 반코트(0.055~0.45) 안에서 줄을 균등 배치, 마지막 줄이 센터라인 쪽
const y = 0.055 + ((r + 1) / (rows.length + 1)) * (0.45 - 0.055);
row.forEach((p, i) => out.push({ p, x: (i + 0.5) / row.length, y }));
});
// 위 팀은 아래로 공격 → 뷰어 기준 좌우 반전. 아래 팀은 위로 공격 → 좌우 그대로, 상하만 미러.
return half === "top"
? out.map((o) => ({ ...o, x: 1 - o.x }))
: out.map((o) => ({ ...o, y: 1 - o.y }));
};
const markers = [
...place(home, "top").map((o) => ({ ...o, side: "home" as const })),
...place(away, "bottom").map((o) => ({ ...o, side: "away" as const })),
];
const lastName = (name: string) => name.split(" ").slice(-1)[0];
return (
<div
className="relative w-full overflow-hidden rounded-xl border border-white/10"
style={{
aspectRatio: "3 / 4",
background:
"repeating-linear-gradient(0deg, #2e7d46 0 12.5%, #2a7340 12.5% 25%)",
}}
>
{/* 피치 라인: 외곽·센터라인·센터서클·페널티박스 (세로형) */}
<div className="pointer-events-none absolute inset-[2.5%] rounded-sm border border-white/30" />
<div className="pointer-events-none absolute inset-x-[2.5%] top-1/2 h-px -translate-y-1/2 bg-white/30" />
<div className="pointer-events-none absolute left-1/2 top-1/2 w-[22%] aspect-square -translate-x-1/2 -translate-y-1/2 rounded-full border border-white/30" />
<div className="pointer-events-none absolute left-1/2 top-[2.5%] h-[10%] w-[46%] -translate-x-1/2 border border-t-0 border-white/30" />
<div className="pointer-events-none absolute bottom-[2.5%] left-1/2 h-[10%] w-[46%] -translate-x-1/2 border border-b-0 border-white/30" />
{markers.map(({ p, x, y, side }) => {
// 교체됐으면 투입 선수가 그 자리를 대체 (빨간 ▲분). 매핑 없으면 기존 흐림 표시.
const sub = p.out ? outToIn?.get(p.name) : undefined;
const lu = side === "away" ? away : home;
const shown = sub
? lu.bench.find((b) => b.name === sub.inName) ?? { ...p, name: sub.inName, jersey: "" }
: p;
const dimmed = p.out && !sub;
const nGoals = goalsBy?.get(shown.name) ?? 0;
const nAssists = assistsBy?.get(shown.name) ?? 0;
const nOgs = ogBy?.get(shown.name) ?? 0;
const card = cardsBy?.get(shown.name);
return (
<div
key={`${side}-${p.name}`}
className={`absolute flex -translate-x-1/2 -translate-y-1/2 flex-col items-center ${
dimmed ? "opacity-45" : ""
}`}
style={{ left: `${x * 100}%`, top: `${y * 100}%` }}
>
<span
className={`grid h-[24px] w-[24px] place-items-center rounded-full font-mono text-[11px] font-extrabold shadow ${
side === "away"
? "bg-[#0f1216] text-[#94FBE0] ring-1 ring-[#94FBE0]/60"
: "bg-white text-black ring-1 ring-black/20"
}`}
>
{shown.jersey || "·"}
</span>
<span className="mt-0.5 max-w-[96px] truncate rounded bg-black/45 px-1 py-px text-[10px] font-bold leading-tight text-white">
{nGoals > 0 && <span>{"⚽".repeat(Math.min(nGoals, 3))} </span>}
{nOgs > 0 && (
<span>
{Array.from({ length: Math.min(nOgs, 2) }, (_, i) => (
<OgBall key={i} />
))}{" "}
</span>
)}
{nAssists > 0 && <span>👟 </span>}
{card && (
<span>{"🟨".repeat(Math.min(card.y, 2))}{card.red ? "🟥" : ""} </span>
)}
{lastName(shown.name)}
{sub && <span className="text-[#FF7B7B]"> ▲{sub.clock}</span>}
{dimmed && <span className="text-[#ffb3b3]"> ▼</span>}
</span>
</div>
);
})}
</div>
);
}
// 교체 명단 — 교체 아웃된 선수(▼분)를 먼저, 이어서 미투입 벤치.
// 투입된 선수는 피치 위로 올라가므로 여기서는 제외.
function BenchList({
lu,
subClock,
goalsBy,
assistsBy,
ogBy,
cardsBy,
right = false,
}: {
lu: SoccerLineup;
subClock: Map<string, string>;
goalsBy?: Map<string, number>;
assistsBy?: Map<string, number>;
ogBy?: Map<string, number>;
cardsBy?: Map<string, { y: number; red: boolean }>;
right?: boolean;
}) {
const rows = [
...lu.starters.filter((p) => p.out).map((p) => ({ p, kind: "out" as const })),
...lu.bench.filter((p) => !p.in).map((p) => ({ p, kind: "bench" as const })),
];
return (
<ul className={`space-y-0.5 ${right ? "text-right" : "text-left"}`}>
{rows.map(({ p, kind }, i) => {
const clock = subClock.get(p.name);
const mark =
kind === "out" ? (
<span className="text-[#FF7B7B]"> ▼{clock ? ` ${clock}` : ""}</span>
) : null;
// 교체 아웃 전 기록한 득점·자책골·도움·카드도 표시
const nGoals = goalsBy?.get(p.name) ?? 0;
const nAssists = assistsBy?.get(p.name) ?? 0;
const nOgs = ogBy?.get(p.name) ?? 0;
const card = cardsBy?.get(p.name);
const feats = (
<>
{nGoals > 0 && <span>{"⚽".repeat(Math.min(nGoals, 3))} </span>}
{nOgs > 0 && (
<span>
{Array.from({ length: Math.min(nOgs, 2) }, (_, i) => (
<OgBall key={i} />
))}{" "}
</span>
)}
{nAssists > 0 && <span>👟 </span>}
{card && (
<span>{"🟨".repeat(Math.min(card.y, 2))}{card.red ? "🟥" : ""} </span>
)}
</>
);
return (
<li
key={`${p.name}-${i}`}
className={`truncate ${kind === "out" ? "text-white/75" : "text-white/45"}`}
>
{right ? (
<>
{mark}
{feats}
<span className="font-semibold">{p.name}</span>{" "}
<span className="font-mono text-[10px] text-white/35">
{p.jersey}{p.pos ? ` ${p.pos}` : ""}
</span>
</>
) : (
<>
<span className="font-mono text-[10px] text-white/35">
{p.jersey}{p.pos ? ` ${p.pos}` : ""}
</span>{" "}
{feats}
<span className="font-semibold">{p.name}</span>
{mark}
</>
)}
</li>
);
})}
</ul>
);
}
+265 -14
View File
@@ -1,23 +1,136 @@
import type { Match } from "@/lib/types"; import { useEffect, useRef, useState } from "react";
import type { Match, TeamStanding } from "@/lib/types";
import { kickoffDisplay } from "@/lib/format"; import { kickoffDisplay } from "@/lib/format";
import { type Lang, dict, teamShort } from "@/lib/i18n"; import { type Lang, dict, teamShort, roundLabel as tRound } from "@/lib/i18n";
import { getTeamSongTracks, type Track } from "@/lib/playlist";
import { usePlayer } from "@/lib/usePlayer";
import BallIcon from "./BallIcon"; import BallIcon from "./BallIcon";
import { FormBadges } from "./ScheduleBoard";
import TeamFlag from "./TeamFlag"; import TeamFlag from "./TeamFlag";
import WaveStrip from "./WaveStrip"; import WaveStrip from "./WaveStrip";
// 팀별 '응원가 듣기' 버튼 — 오늘의 응원가(Suno 자동 생성)를 플레이어에 싣는다.
// 이 팀 곡이 재생 중이면 일시정지/이어듣기 토글. 곡이 없으면 렌더 안 함.
function CheerSongButton({
matchId,
teamCode,
lang,
}: {
matchId: string;
teamCode: string;
lang: Lang;
}) {
const { currentTrack, isPlaying, toggle, loadPlaylist, open } = usePlayer();
const [tracks, setTracks] = useState<Track[]>([]);
useEffect(() => {
let alive = true;
getTeamSongTracks(matchId, teamCode).then((ts) => alive && setTracks(ts));
return () => {
alive = false;
};
}, [matchId, teamCode]);
// 공유 링크(/song/...→ ?song=팀코드) 진입 시 그 팀 응원가 자동 로드 (1회)
const autoLoaded = useRef(false);
useEffect(() => {
if (autoLoaded.current || tracks.length === 0) return;
const q = new URLSearchParams(window.location.search).get("song");
if (q === teamCode) {
autoLoaded.current = true;
loadPlaylist(tracks);
open();
}
}, [tracks, teamCode, loadPlaylist, open]);
if (tracks.length === 0) return null;
const active = !!currentTrack && tracks.some((t) => t.src === currentTrack.src);
const label = active
? isPlaying
? lang === "en" ? "⏸ Pause" : "⏸ 일시정지"
: lang === "en" ? "▶ Resume" : "▶ 이어 듣기"
: lang === "en" ? "♪ Cheer song" : "♪ 응원가 듣기";
return (
<button
type="button"
onClick={() => {
if (active) toggle();
else {
loadPlaylist(tracks);
open();
}
}}
className={`rounded-full border px-3 py-1 text-[12px] font-bold transition active:scale-95 ${
active
? "border-[var(--green)] bg-[var(--green)]/15 text-[var(--green)]"
: "border-[var(--green)]/50 text-[var(--green)] hover:bg-[var(--green)]/10"
}`}
>
{label}
</button>
);
}
// 순위 캐시 → "3위 · 52승37패 (0.584)" 한 줄 (야구)
function standingLine(
st: { rank?: number | null; w?: number; l?: number; wra?: string | number } | null | undefined,
lang: Lang,
): string | null {
if (!st?.rank) return null;
const rank = lang === "en" ? `#${st.rank}` : `${st.rank}위`;
if (st.w == null || st.l == null) return rank;
const rec = lang === "en" ? `${st.w}W ${st.l}L` : `${st.w}승${st.l}패`;
return `${rank} · ${rec}${st.wra ? ` (${st.wra})` : ""}`;
}
// MLS 순위 캐시 → "동부 3위 · 8승2무4패 (승점 26)" 한 줄
function mlsStandingLine(st: TeamStanding & { div?: string | null } | null | undefined, lang: Lang): string | null {
if (!st?.rank) return null;
const conf =
st.div === "EAST"
? lang === "en" ? "East" : "동부"
: st.div === "WEST"
? lang === "en" ? "West" : "서부"
: "";
const rank = lang === "en" ? `#${st.rank}` : `${st.rank}위`;
const rec =
st.w != null && st.l != null
? lang === "en"
? ` · ${st.w}W-${st.d ?? 0}D-${st.l}L`
: ` · ${st.w}승${st.d ?? 0}무${st.l}패`
: "";
const pts = st.pts != null ? (lang === "en" ? ` (${st.pts}pts)` : ` (승점 ${st.pts})`) : "";
return `${conf} ${rank}${rec}${pts}`.trim();
}
export default function MatchupHUD({ match, lang = "ko" }: { match: Match; lang?: Lang }) { export default function MatchupHUD({ match, lang = "ko" }: { match: Match; lang?: Lang }) {
const t = dict(lang); const t = dict(lang);
const { group } = match; const { group } = match;
const finished = !!match.result; const finished = !!match.result;
// 한국을 항상 왼쪽에 표시(요청). 데이터/투표는 원본 A/B 프레임 유지, 화면 좌우만 교체. const isBaseball = match.league === "kbo" || match.league === "mlb";
const flip = match.teamB.code === "KOR" && match.teamA.code !== "KOR"; const isMls = match.league === "mls";
const isClub = isBaseball || isMls; // 클럽 리그 공통 분기 (로고·venue 등)
// 월드컵: 한국을 항상 왼쪽에. 야구: 원정-홈. MLS: 홈-원정 (축구 관례 — 화면만 교체).
const flip =
isMls || (!isClub && match.teamB.code === "KOR" && match.teamA.code !== "KOR");
const left = flip ? match.teamB : match.teamA; const left = flip ? match.teamB : match.teamA;
const right = flip ? match.teamA : match.teamB; const right = flip ? match.teamA : match.teamB;
const leftScore = flip ? match.result?.scoreB : match.result?.scoreA; const leftScore = flip ? match.result?.scoreB : match.result?.scoreA;
const rightScore = flip ? match.result?.scoreA : match.result?.scoreB; const rightScore = flip ? match.result?.scoreA : match.result?.scoreB;
// 마스코트(파도타기 등)는 한국-남아공 경기에서만 노출.
const codes = [match.teamA.code, match.teamB.code]; const ex = match.extras;
const isKorRsa = codes.includes("KOR") && codes.includes("RSA"); const spL = ex?.starterA;
const spR = ex?.starterB;
const stL = standingLine(ex?.standings?.a, lang);
const stR = standingLine(ex?.standings?.b, lang);
const vs = ex?.seasonVs;
const hasVs = !!vs && vs.aWin != null && vs.bWin != null;
// MLS 프리뷰 (폼·시즌 전적·순위·맞대결) — 왼쪽=홈(teamB) 기준으로 교체
const mlsStL = mlsStandingLine(ex?.standings?.b, lang);
const mlsStR = mlsStandingLine(ex?.standings?.a, lang);
const h2h = ex?.h2h ?? [];
const flagCls = isClub ? "mx-auto h-[72px] w-[72px]" : "mx-auto h-[68px] w-[104px]";
return ( return (
<section className="mt-6"> <section className="mt-6">
{/* 대결 카드 (녹색 글로우 보더) */} {/* 대결 카드 (녹색 글로우 보더) */}
@@ -25,8 +138,8 @@ export default function MatchupHUD({ match, lang = "ko" }: { match: Match; lang?
className="relative rounded-3xl border-2 border-[var(--green)] bg-[#171b21] p-5" className="relative rounded-3xl border-2 border-[var(--green)] bg-[#171b21] p-5"
style={{ boxShadow: "0 0 28px rgba(74,255,160,0.35), inset 0 0 24px rgba(74,255,160,0.06)" }} style={{ boxShadow: "0 0 28px rgba(74,255,160,0.35), inset 0 0 24px rgba(74,255,160,0.06)" }}
> >
{/* 박스 오른쪽 상단 파도타기 (응원 5마리) — 한국-남아공전 전용 */} {/* 파도타기 마스코트 — 월드컵 전용 (야구·MLS 미노출) */}
{isKorRsa && ( {!isClub && (
<div className="absolute right-2 top-2 z-10"> <div className="absolute right-2 top-2 z-10">
<WaveStrip /> <WaveStrip />
</div> </div>
@@ -41,15 +154,28 @@ export default function MatchupHUD({ match, lang = "ko" }: { match: Match; lang?
{teamShort(right, lang)} {teamShort(right, lang)}
</div> </div>
<div className="mt-1 text-[15px] font-bold text-[var(--green)]"> <div className="mt-1 text-[15px] font-bold text-[var(--green)]">
{kickoffDisplay(match.kickoffKst, lang)} · {t.group(group)} {kickoffDisplay(match.kickoffKst, lang)} ·{" "}
{!isBaseball && group ? t.group(group) : tRound(match.roundLabel, lang)}
</div>
<div className="mt-0.5 text-[12px] text-white/65">
{match.venue}
{isClub && (
<span className="text-white/40">
{" "}· {lang === "en" ? "Home: " : "홈 "}{teamShort(match.teamB, lang)}
</span>
)}
</div> </div>
<div className="mt-0.5 text-[12px] text-white/65">{match.venue}</div>
</div> </div>
</div> </div>
{/* 국기 + 라이트닝 VS (종료 시 최종 스코어) */} {/* 국기/로고 + 라이트닝 VS (종료 시 최종 스코어) + 팀별 응원가 버튼(KBO) */}
<div className="mt-5 grid grid-cols-[1fr_auto_1fr] items-center gap-3"> <div className="mt-5 grid grid-cols-[1fr_auto_1fr] items-center gap-3">
<TeamFlag team={left} className="mx-auto h-[68px] w-[104px]" /> <div className="flex flex-col items-center gap-2.5">
<TeamFlag team={left} className={flagCls} />
{isClub && (
<CheerSongButton matchId={match.matchId} teamCode={left.code} lang={lang} />
)}
</div>
<div className="relative grid place-items-center"> <div className="relative grid place-items-center">
<div className="vs-glow absolute h-28 w-28" /> <div className="vs-glow absolute h-28 w-28" />
{finished && match.result ? ( {finished && match.result ? (
@@ -67,9 +193,134 @@ export default function MatchupHUD({ match, lang = "ko" }: { match: Match; lang?
</span> </span>
)} )}
</div> </div>
<TeamFlag team={right} className="mx-auto h-[68px] w-[104px]" /> <div className="flex flex-col items-center gap-2.5">
<TeamFlag team={right} className={flagCls} />
{isClub && (
<CheerSongButton matchId={match.matchId} teamCode={right.code} lang={lang} />
)}
</div>
</div> </div>
{/* 야구 정보 패널: 선발 매치업 · 순위 · 시즌 상대전적 (캐시 있을 때만) */}
{isBaseball && (spL || spR || stL || stR || hasVs) && (
<div className="mt-4 rounded-2xl bg-white/[0.04] p-3.5 text-[12px]">
{(spL || spR) && (
<div className="grid grid-cols-[1fr_auto_1fr] items-start gap-2">
<div className="min-w-0">
<div className="truncate font-extrabold text-white/90">
{spL?.name ?? (lang === "en" ? "TBA" : "미정")}
{spL?.hitType ? (
<span className="ml-1 font-semibold text-white/40">{spL.hitType.slice(0, 2)}</span>
) : null}
</div>
{spL?.era != null && (
<div className="mt-0.5 text-white/50">
ERA {spL.era}
{spL.w != null ? ` · ${spL.w}${lang === "en" ? "W" : "승"}${spL.l ?? 0}${lang === "en" ? "L" : "패"}` : ""}
</div>
)}
</div>
<span className="pt-0.5 text-[11px] font-bold text-[var(--green)]">
{lang === "en" ? "Starting P" : "선발 투수"}
</span>
<div className="min-w-0 text-right">
<div className="truncate font-extrabold text-white/90">
{spR?.hitType ? (
<span className="mr-1 font-semibold text-white/40">{spR.hitType.slice(0, 2)}</span>
) : null}
{spR?.name ?? (lang === "en" ? "TBA" : "미정")}
</div>
{spR?.era != null && (
<div className="mt-0.5 text-white/50">
ERA {spR.era}
{spR.w != null ? ` · ${spR.w}${lang === "en" ? "W" : "승"}${spR.l ?? 0}${lang === "en" ? "L" : "패"}` : ""}
</div>
)}
</div>
</div>
)}
{(stL || stR) && (
<div className="mt-2.5 flex items-center justify-between border-t border-white/10 pt-2.5 text-white/55">
<span className="truncate">{stL ?? "—"}</span>
<span className="px-2 text-[10px] text-white/30">{lang === "en" ? "STANDINGS" : "순위"}</span>
<span className="truncate text-right">{stR ?? "—"}</span>
</div>
)}
{hasVs && (
<div className="mt-2.5 border-t border-white/10 pt-2.5">
<div className="flex items-center justify-between font-bold text-white/75">
<span>{vs!.aWin}{lang === "en" ? "W" : "승"}</span>
<span className="text-[10px] text-white/35">
{lang === "en" ? "SEASON H2H" : "시즌 상대전적"}
{vs!.draw ? ` · ${vs!.draw}${lang === "en" ? "D" : "무"}` : ""}
</span>
<span>{vs!.bWin}{lang === "en" ? "W" : "승"}</span>
</div>
<div className="mt-1.5 flex h-1.5 gap-0.5 overflow-hidden rounded-full">
<div
className="bg-[var(--green)]/80"
style={{ width: `${(100 * (vs!.aWin ?? 0)) / Math.max(1, (vs!.aWin ?? 0) + (vs!.bWin ?? 0))}%` }}
/>
<div className="flex-1 bg-white/20" />
</div>
</div>
)}
</div>
)}
{/* MLS 정보 패널: 최근 5경기 폼 · 컨퍼런스 순위 · 최근 맞대결 (캐시 있을 때만) */}
{isMls && (ex?.formA || ex?.formB || mlsStL || mlsStR || h2h.length > 0) && (
<div className="mt-4 rounded-2xl bg-white/[0.04] p-3.5 text-[12px]">
{(ex?.formA || ex?.formB) && (
<div className="grid grid-cols-[1fr_auto_1fr] items-center gap-2">
<div className="min-w-0">
<FormBadges form={ex?.formB} />
{ex?.recordB && (
<span className="ml-1.5 text-white/45">{ex.recordB}</span>
)}
</div>
<span className="text-[11px] font-bold text-[var(--green)]">
{lang === "en" ? "Last 5 · W-L-D" : "최근 5경기 · 시즌"}
</span>
<div className="min-w-0 text-right">
{ex?.recordA && (
<span className="mr-1.5 text-white/45">{ex.recordA}</span>
)}
<FormBadges form={ex?.formA} />
</div>
</div>
)}
{(mlsStL || mlsStR) && (
<div className="mt-2.5 flex items-center justify-between border-t border-white/10 pt-2.5 text-white/55">
<span className="truncate">{mlsStL ?? "—"}</span>
<span className="px-2 text-[10px] text-white/30">{lang === "en" ? "STANDINGS" : "순위"}</span>
<span className="truncate text-right">{mlsStR ?? "—"}</span>
</div>
)}
{h2h.length > 0 && (
<div className="mt-2.5 border-t border-white/10 pt-2.5">
<div className="mb-1 text-center text-[10px] text-white/35">
{lang === "en" ? "RECENT H2H" : "최근 맞대결"}
</div>
<ul className="space-y-0.5 text-center font-mono text-[11px] text-white/60">
{h2h.slice(0, 3).map((g, i) => (
<li key={i}>
<span className="text-white/35">{g.date.slice(5).replace("-", ".")}</span>{" "}
{g.home} {g.scoreH}
<span className="px-1 text-white/30">:</span>
{g.scoreA} {g.away}
</li>
))}
</ul>
</div>
)}
</div>
)}
{finished && ( {finished && (
<div className="mt-3 text-center text-[12px] font-bold text-[var(--green)]"> <div className="mt-3 text-center text-[12px] font-bold text-[var(--green)]">
{t.matchEnded} {t.matchEnded}
+111 -12
View File
@@ -1,9 +1,9 @@
import { useEffect } from "react"; import { useEffect, useState } from "react";
import { useLocation } from "react-router-dom"; import { useLocation } from "react-router-dom";
import { usePlayer } from "@/lib/usePlayer"; import { usePlayer } from "@/lib/usePlayer";
import { useLang } from "@/lib/useLang"; import { useLang } from "@/lib/useLang";
import { dict } from "@/lib/i18n"; import { dict } from "@/lib/i18n";
import { VISIBLE_PATHS, PATH_PLAYLISTS } from "@/lib/playlist"; import { getTracksForPath } from "@/lib/playlist";
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// 시간 포맷 // 시간 포맷
@@ -53,6 +53,27 @@ function IconMusic() {
</svg> </svg>
); );
} }
function IconLyrics() {
return (
<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
<path d="M3 5h18v2H3V5zm0 4h12v2H3V9zm0 4h18v2H3v-2zm0 4h12v2H3v-2z" />
</svg>
);
}
function IconShare() {
return (
<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
<path d="M18 16.08c-.76 0-1.44.3-1.96.77L8.91 12.7c.05-.23.09-.46.09-.7s-.04-.47-.09-.7l7.05-4.11c.54.5 1.25.81 2.04.81 1.66 0 3-1.34 3-3s-1.34-3-3-3-3 1.34-3 3c0 .24.04.47.09.7L8.04 9.81C7.5 9.31 6.79 9 6 9c-1.66 0-3 1.34-3 3s1.34 3 3 3c.79 0 1.5-.31 2.04-.81l7.12 4.16c-.05.21-.08.43-.08.65 0 1.61 1.31 2.92 2.92 2.92 1.61 0 2.92-1.31 2.92-2.92s-1.31-2.92-2.92-2.92z" />
</svg>
);
}
function IconCheck() {
return (
<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
<path d="M9 16.17 4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z" />
</svg>
);
}
function IconVolume({ level }: { level: number }) { function IconVolume({ level }: { level: number }) {
if (level === 0) { if (level === 0) {
return ( return (
@@ -145,20 +166,44 @@ export default function MusicBar() {
loadPlaylist, loadPlaylist,
} = usePlayer(); } = usePlayer();
// 경로가 바뀌면 해당 경로의 플레이리스트 로드, 없으면 초기화 // 경로가 바뀌면 해당 경로의 자동 플레이리스트 로드(월드컵 특설), 그 외는 초기화.
// KBO 응원가는 상세 페이지 '응원가 듣기' 버튼이 loadPlaylist 로 직접 채운다.
useEffect(() => { useEffect(() => {
const tracks = PATH_PLAYLISTS[pathname]; loadPlaylist(getTracksForPath(pathname));
loadPlaylist(tracks ?? []);
}, [pathname, loadPlaylist]); }, [pathname, loadPlaylist]);
if (!hasTrack) return null; // 가사 패널·공유 상태
const [showLyrics, setShowLyrics] = useState(false);
const [shared, setShared] = useState(false);
const canLyrics = !!currentTrack?.lyrics;
const canShare = !!currentTrack?.shareUrl;
useEffect(() => {
if (!canLyrics) setShowLyrics(false);
}, [canLyrics]);
if (VISIBLE_PATHS.length > 0) { const doShare = async () => {
const visible = VISIBLE_PATHS.some( const tr = currentTrack;
(p: string) => pathname === p || pathname.startsWith(p) if (!tr?.shareUrl) return;
); const text = tr.shareText ?? tr.title;
if (!visible) return null; if (navigator.share) {
} try {
await navigator.share({ title: text, text, url: tr.shareUrl });
} catch {
/* cancelled */
}
} else {
try {
await navigator.clipboard.writeText(`${text}\n${tr.shareUrl}`);
setShared(true);
setTimeout(() => setShared(false), 1800);
} catch {
/* noop */
}
}
};
// 자동이든 버튼이든 플레이리스트가 실리면 바 노출, 비면 숨김
if (!hasTrack) return null;
const handleProgressClick = (e: React.MouseEvent<HTMLDivElement>) => { const handleProgressClick = (e: React.MouseEvent<HTMLDivElement>) => {
const rect = e.currentTarget.getBoundingClientRect(); const rect = e.currentTarget.getBoundingClientRect();
@@ -233,6 +278,29 @@ export default function MusicBar() {
<div className="relative"> <div className="relative">
<CollapseTab minimized={false} onToggle={close} /> <CollapseTab minimized={false} onToggle={close} />
{/* 가사 패널 — 바 위로 펼침 */}
{showLyrics && currentTrack?.lyrics && (
<div className="border-t border-[var(--line-d)] bg-[var(--bg2)]/95 backdrop-blur-sm">
<div className="mx-auto max-w-5xl px-4 py-3 md:px-6">
<div className="mb-1.5 flex items-center justify-between">
<p className="text-[13px] font-bold text-[var(--green)]">
♪ {currentTrack.title}
</p>
<button
onClick={() => setShowLyrics(false)}
aria-label={lang === "en" ? "Close lyrics" : "가사 닫기"}
className="px-1 text-[18px] leading-none text-white/50 hover:text-white/80"
>
×
</button>
</div>
<pre className="max-h-[40vh] overflow-y-auto whitespace-pre-wrap font-sans text-[13px] leading-relaxed text-white/80 [scrollbar-width:thin] [scrollbar-color:rgba(255,255,255,0.25)_transparent] [&::-webkit-scrollbar]:w-1.5 [&::-webkit-scrollbar-track]:bg-transparent [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:bg-white/20">
{currentTrack.lyrics}
</pre>
</div>
</div>
)}
<div <div
className="border-t border-[var(--line-d)] bg-[var(--bg2)]/95 backdrop-blur-sm" className="border-t border-[var(--line-d)] bg-[var(--bg2)]/95 backdrop-blur-sm"
style={{ boxShadow: "0 -4px 24px rgba(0,0,0,0.45)" }} style={{ boxShadow: "0 -4px 24px rgba(0,0,0,0.45)" }}
@@ -329,6 +397,37 @@ export default function MusicBar() {
style={{ width: `${displayVolume * 100}%`, background: "rgba(255,255,255,0.85)" }} style={{ width: `${displayVolume * 100}%`, background: "rgba(255,255,255,0.85)" }}
/> />
</div> </div>
{/* 가사 보기 · 공유 — 응원가(가사·공유 정보 보유 트랙)만 노출 */}
{canLyrics && (
<button
onClick={() => setShowLyrics((v) => !v)}
aria-label={lang === "en" ? "Lyrics" : "가사 보기"}
title={lang === "en" ? "Lyrics" : "가사 보기"}
className={`p-1 shrink-0 transition-colors ${
showLyrics
? "text-[var(--green)]"
: "text-white/45 hover:text-white/80"
}`}
>
<IconLyrics />
</button>
)}
{canShare && (
<button
onClick={doShare}
aria-label={lang === "en" ? "Share" : "공유하기"}
title={
shared
? lang === "en" ? "Link copied!" : "링크 복사됨!"
: lang === "en" ? "Share" : "공유하기"
}
className={`p-1 shrink-0 transition-colors ${
shared ? "text-[var(--green)]" : "text-white/45 hover:text-white/80"
}`}
>
{shared ? <IconCheck /> : <IconShare />}
</button>
)}
</div> </div>
</div> </div>
+4 -2
View File
@@ -9,9 +9,11 @@ import type { RankingEntry, RankingTab } from "@/lib/types";
export default function RankingBoard({ export default function RankingBoard({
lang = "ko", lang = "ko",
defaultOpen = false, defaultOpen = false,
league = "",
}: { }: {
lang?: Lang; lang?: Lang;
defaultOpen?: boolean; defaultOpen?: boolean;
league?: string; // 리그별 집계 ("" = 전체 통합)
}) { }) {
const t = dict(lang); const t = dict(lang);
const [open, setOpen] = useState(defaultOpen); const [open, setOpen] = useState(defaultOpen);
@@ -24,7 +26,7 @@ export default function RankingBoard({
if (!open) return; if (!open) return;
let alive = true; let alive = true;
setLoaded(false); setLoaded(false);
fetchRanking(tab) fetchRanking(tab, league)
.then((r) => { .then((r) => {
if (!alive) return; if (!alive) return;
setRows(r); setRows(r);
@@ -38,7 +40,7 @@ export default function RankingBoard({
return () => { return () => {
alive = false; alive = false;
}; };
}, [open, tab]); }, [open, tab, league]);
return ( return (
<section className="mt-5 rounded-2xl border border-[var(--line-d)] bg-[var(--bg2)] p-4"> <section className="mt-5 rounded-2xl border border-[var(--line-d)] bg-[var(--bg2)] p-4">
+420 -68
View File
@@ -1,9 +1,11 @@
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { Link } from "react-router-dom"; import { Link } from "react-router-dom";
import { timeOnly, dateKey } from "@/lib/format"; import { timeOnly, dateKey } from "@/lib/format";
import { getLive, type LiveData } from "@/lib/api";
import { type Lang, dict, teamShort, roundLabel as tRound, dayName, monthEn } from "@/lib/i18n"; import { type Lang, dict, teamShort, roundLabel as tRound, dayName, monthEn } from "@/lib/i18n";
import type { Match, MatchPhase } from "@/lib/types"; import type { League, Match, MatchPhase, ModelName, Outcome } from "@/lib/types";
import TeamFlag from "./TeamFlag"; import TeamFlag from "./TeamFlag";
import StandingsTable from "./StandingsTable";
// 칩용 짧은 날짜: "6.12 (금)" / "Jun 12 (Fri)" // 칩용 짧은 날짜: "6.12 (금)" / "Jun 12 (Fri)"
function shortDate(iso: string, lang: Lang): string { function shortDate(iso: string, lang: Lang): string {
@@ -16,49 +18,114 @@ function shortDate(iso: string, lang: Lang): string {
const PHASE_CLS: Record<MatchPhase, string> = { const PHASE_CLS: Record<MatchPhase, string> = {
open: "border-[#94FBE0] text-[#94FBE0]", open: "border-[#94FBE0] text-[#94FBE0]",
scheduled: "border-[var(--line-d)] text-[var(--ink-muted)]", scheduled: "border-white/20 text-white/60",
locked: "border-[var(--line-d)] text-white/45", locked: "border-white/20 text-white/60",
live: "border-[#FF5B5B] text-[#FF5B5B]", live: "border-[#FF5B5B] text-[#FF5B5B]",
finished: "border-white/15 text-white/55", finished: "border-white/25 text-white/70",
cancelled: "border-white/10 text-white/40",
}; };
type Tab = "date" | "group"; // 토너먼트 탭 라운드 칩 정렬(대진 순서)
const KO_ROUND_ORDER = ["32강", "16강", "8강", "4강", "3·4위전", "결승"];
const isGroupLetter = (s: string) => /^[A-Z]$/.test(s);
type Tab = "date" | "group" | "tournament" | "team" | "rank";
export default function ScheduleBoard({ export default function ScheduleBoard({
matches, matches,
lang = "ko", lang = "ko",
league = "wc",
}: { }: {
matches: Match[]; matches: Match[];
lang?: Lang; lang?: Lang;
league?: League;
}) { }) {
const t = dict(lang); const t = dict(lang);
const [tab, setTab] = useState<Tab>(() => // 야구(KBO/MLB)는 조/토너먼트 대신 날짜별/팀별 탭 제공
sessionStorage.getItem("tp.sched.tab") === "group" ? "group" : "date", const isBaseball = league !== "wc";
);
// 날짜·조 목록 (정렬) // 날짜 목록 (정렬)
const dates = useMemo( const dates = useMemo(
() => Array.from(new Set(matches.map((m) => dateKey(m.kickoffKst)))).sort(), () => Array.from(new Set(matches.map((m) => dateKey(m.kickoffKst)))).sort(),
[matches], [matches],
); );
const groups = useMemo( // 조별리그 탭 칩: 조 문자(A~L)
() => Array.from(new Set(matches.map((m) => m.group))).sort(), const groups = useMemo(() => {
[matches], const set = new Set(matches.map((m) => m.group).filter(Boolean));
); return [...set].filter(isGroupLetter).sort();
}, [matches]);
// 토너먼트 탭 칩: 등장한 라운드(32강~결승), 대진 순서
const rounds = useMemo(() => {
const set = new Set(matches.map((m) => m.roundLabel).filter(Boolean));
return KO_ROUND_ORDER.filter((r) => set.has(r));
}, [matches]);
// 현재 진행 라운드: 아직 종료되지 않은 경기가 있는 가장 이른 라운드.
// (8강 진행 중이면 8강, 8강이 다 끝나 4강 대진이 뜨면 4강.) 전부 종료면 가장 진행된 라운드.
const currentRound = useMemo(() => {
for (const r of rounds) {
if (matches.some((m) => m.roundLabel === r && !m.result)) return r;
}
return rounds[rounds.length - 1] ?? "";
}, [matches, rounds]);
// 기본 선택: 오늘(없으면 첫 날짜) / A조. // 시작 탭: 토너먼트가 시작됐으면 '토너먼트', 아니면 '날짜별'.
// 단, 직전 세션 선택이 있으면 우선(상세 진입 후 뒤로가기 복원).
const [tab, setTabRaw] = useState<Tab>(() => {
const saved = sessionStorage.getItem("tp.sched.tab");
if (
saved === "date" || saved === "group" || saved === "tournament" ||
saved === "team" || saved === "rank"
)
return saved;
if (isBaseball) return "date";
return rounds.length > 0 ? "tournament" : "date";
});
// 리그에 없는 탭이 저장돼 있으면 날짜별로 강등 (야구↔축구 전환 시)
const effTab: Tab = isBaseball
? (tab === "team" || tab === "rank" ? tab : "date")
: (tab === "team" || tab === "rank" ? "date" : tab);
const setTab = setTabRaw;
// 팀별 탭: 등장 팀 목록 (짧은 이름 가나다/알파벳 순)
const teams = useMemo(() => {
if (!isBaseball) return [];
const byCode = new Map<string, Match["teamA"]>();
for (const m of matches) {
byCode.set(m.teamA.code, m.teamA);
byCode.set(m.teamB.code, m.teamB);
}
return [...byCode.values()].sort((a, b) =>
teamShort(a, lang).localeCompare(teamShort(b, lang), lang === "en" ? "en" : "ko"),
);
}, [matches, isBaseball, lang]);
// 기본 선택: 오늘(경기 없으면 다음 경기일, 시즌 종료면 마지막 날짜) / A조 / 현재 진행 라운드.
// 단, 직전 세션 선택을 sessionStorage 에 보관 → 상세 진입 후 뒤로가기 시 그대로 복원(오늘로 초기화 X). // 단, 직전 세션 선택을 sessionStorage 에 보관 → 상세 진입 후 뒤로가기 시 그대로 복원(오늘로 초기화 X).
const todayKey = useMemo(() => new Date().toISOString().slice(0, 10), []); // 사이트 전체가 KST 기준이라 "오늘"도 클라이언트 시간대와 무관하게 KST 로 계산.
const todayKey = useMemo(
() => new Date(Date.now() + 9 * 3600_000).toISOString().slice(0, 10),
[],
);
const defaultDate = (ds: string[], today: string) =>
(ds.includes(today) ? today : ds.find((d) => d > today) ?? ds[ds.length - 1]) ?? "";
const [selDate, setSelDate] = useState(() => { const [selDate, setSelDate] = useState(() => {
const saved = sessionStorage.getItem("tp.sched.date"); const saved = sessionStorage.getItem("tp.sched.date");
if (saved && dates.includes(saved)) return saved; if (saved && dates.includes(saved)) return saved;
return (dates.includes(todayKey) ? todayKey : dates[0]) ?? ""; return defaultDate(dates, todayKey);
}); });
const [selGroup, setSelGroup] = useState(() => { const [selGroup, setSelGroup] = useState(() => {
const saved = sessionStorage.getItem("tp.sched.group"); const saved = sessionStorage.getItem("tp.sched.group");
if (saved && groups.includes(saved)) return saved; if (saved && isGroupLetter(saved)) return saved;
return (groups.includes("A") ? "A" : groups[0]) ?? ""; return (groups.includes("A") ? "A" : groups[0]) ?? "";
}); });
const [selRound, setSelRound] = useState(() => {
const saved = sessionStorage.getItem("tp.sched.round");
if (saved && rounds.includes(saved)) return saved;
return currentRound;
});
const [selTeam, setSelTeam] = useState(
() => sessionStorage.getItem("tp.sched.team") ?? "",
);
// 선택 변경 시 보관(다음 진입/뒤로가기에서 복원) // 선택 변경 시 보관(다음 진입/뒤로가기에서 복원)
useEffect(() => { useEffect(() => {
@@ -67,40 +134,86 @@ export default function ScheduleBoard({
useEffect(() => { useEffect(() => {
if (selGroup) sessionStorage.setItem("tp.sched.group", selGroup); if (selGroup) sessionStorage.setItem("tp.sched.group", selGroup);
}, [selGroup]); }, [selGroup]);
useEffect(() => {
if (selRound) sessionStorage.setItem("tp.sched.round", selRound);
}, [selRound]);
useEffect(() => { useEffect(() => {
sessionStorage.setItem("tp.sched.tab", tab); sessionStorage.setItem("tp.sched.tab", tab);
}, [tab]); }, [tab]);
useEffect(() => {
if (selTeam) sessionStorage.setItem("tp.sched.team", selTeam);
}, [selTeam]);
useEffect(() => {
if (dates.length && !dates.includes(selDate)) {
// 목록이 비동기 로드될 때도 세션 복원이 동작하게 saved 를 우선 확인
const saved = sessionStorage.getItem("tp.sched.date");
setSelDate(
saved && dates.includes(saved) ? saved : defaultDate(dates, todayKey),
);
}
}, [dates, selDate, todayKey]);
// 리그 전환 시 목록에 없는 팀이면 첫 팀으로
useEffect(() => {
if (teams.length && !teams.some((tm) => tm.code === selTeam)) {
setSelTeam(teams[0].code);
}
}, [teams, selTeam]);
const shown = useMemo(() => { const shown = useMemo(() => {
const list = let list: Match[];
tab === "date" if (effTab === "date") list = matches.filter((m) => dateKey(m.kickoffKst) === selDate);
? matches.filter((m) => dateKey(m.kickoffKst) === selDate) else if (effTab === "team")
: matches.filter((m) => m.group === selGroup); list = matches.filter((m) => m.teamA.code === selTeam || m.teamB.code === selTeam);
else if (effTab === "group") list = matches.filter((m) => !!m.group && m.group === selGroup);
else list = matches.filter((m) => m.roundLabel === selRound); // 토너먼트
return [...list].sort( return [...list].sort(
(a, b) => new Date(a.kickoffKst).getTime() - new Date(b.kickoffKst).getTime(), (a, b) => new Date(a.kickoffKst).getTime() - new Date(b.kickoffKst).getTime(),
); );
}, [matches, tab, selDate, selGroup]); }, [matches, effTab, selDate, selGroup, selRound, selTeam]);
const tabLabel = (k: Tab) => const tabLabel = (k: Tab) =>
k === "date" ? (lang === "en" ? "By date" : "날짜별") : lang === "en" ? "Groups" : "조별리그"; k === "date"
? lang === "en"
? "By date"
: "날짜별"
: k === "team"
? lang === "en"
? "By team"
: "팀별"
: k === "rank"
? lang === "en"
? "Standings"
: "순위"
: k === "group"
? lang === "en"
? "Groups"
: "조별리그"
: lang === "en"
? "Tournament"
: "토너먼트";
const leagueTabs: Tab[] = isBaseball
? ["date", "team", "rank"]
: ["date", "group", "tournament"];
return ( return (
<section className="mt-6"> <section className="mt-6">
<div className="mb-3 flex items-baseline gap-2.5"> <div className="mb-3 flex items-baseline gap-2.5">
<h2 className="shrink-0 text-[22px] font-extrabold">{t.schedTitle}</h2> <h2 className="shrink-0 text-[22px] font-extrabold">{t.schedTitle}</h2>
<span className="whitespace-nowrap text-[12px] text-white/55">{t.schedGuide}</span> <span className="whitespace-nowrap text-[12px] text-white/65">{t.schedGuide}</span>
</div> </div>
{/* 탭: 날짜별 / 조별리그 */} {/* 탭: 축구 = 날짜별/조별리그/토너먼트 · 야구 = 날짜별/팀별 */}
<div className="mb-3 flex gap-5 border-b border-[var(--line-d)]"> <div className="mb-3 flex gap-5 border-b border-[var(--line-d)]">
{(["date", "group"] as Tab[]).map((k) => ( {leagueTabs.map((k) => (
<button <button
key={k} key={k}
onClick={() => setTab(k)} onClick={() => setTab(k)}
className={`-mb-px border-b-2 pb-2 text-[15px] font-bold transition ${ className={`-mb-px border-b-2 pb-2 text-[15px] font-bold transition ${
tab === k effTab === k
? "border-[var(--green)] text-white" ? "border-[var(--green)] text-white"
: "border-transparent text-white/45" : "border-transparent text-white/60"
}`} }`}
> >
{tabLabel(k)} {tabLabel(k)}
@@ -108,32 +221,71 @@ export default function ScheduleBoard({
))} ))}
</div> </div>
{/* 칩: 날짜 또는 조 — 단일 줄 가로 스크롤 + 양 끝 화살표(PC에서 마우스로 넘김, 끝 도달 시 숨김) */} {/* 순위 탭: 칩/카드 대신 순위표 */}
<ChipScroller resetKey={tab}> {effTab === "rank" && <StandingsTable league={league} lang={lang} />}
{tab === "date"
{/* 칩: 날짜 / 조 / 라운드 — 단일 줄 가로 스크롤 + 양 끝 화살표(PC에서 마우스로 넘김, 끝 도달 시 숨김) */}
{effTab !== "rank" && (
<ChipScroller
resetKey={`${league}:${effTab}`}
centerKey={
effTab === "date"
? selDate
: effTab === "team"
? selTeam
: effTab === "group"
? selGroup
: selRound
}
>
{effTab === "date"
? dates.map((d) => ( ? dates.map((d) => (
<Chip key={d} active={d === selDate} onClick={() => setSelDate(d)}> <Chip key={d} active={d === selDate} onClick={() => setSelDate(d)}>
{shortDate(d, lang)} {shortDate(d, lang)}
</Chip> </Chip>
)) ))
: groups.map((g) => ( : effTab === "team"
<Chip key={g} active={g === selGroup} onClick={() => setSelGroup(g)}> ? teams.map((tm) => (
{lang === "en" ? `Group ${g}` : `${g}조`} <Chip key={tm.code} active={tm.code === selTeam} onClick={() => setSelTeam(tm.code)}>
</Chip> <span className="flex items-center gap-1.5">
))} <TeamFlag team={tm} className="h-4 w-4 shrink-0" />
{teamShort(tm, lang)}
</span>
</Chip>
))
: effTab === "group"
? groups.map((g) => (
<Chip key={g} active={g === selGroup} onClick={() => setSelGroup(g)}>
{lang === "en" ? `Group ${g}` : `${g}조`}
</Chip>
))
: rounds.map((r) => (
<Chip key={r} active={r === selRound} onClick={() => setSelRound(r)}>
{tRound(r, lang)}
</Chip>
))}
</ChipScroller> </ChipScroller>
)}
{/* 경기 카드 */} {/* 경기 카드 */}
{effTab !== "rank" && (
<div className="flex flex-col gap-2.5"> <div className="flex flex-col gap-2.5">
{shown.length === 0 && ( {shown.length === 0 && (
<p className="py-6 text-center text-[13px] text-white/45"> <p className="py-6 text-center text-[13px] text-white/60">
{lang === "en" ? "No matches" : "경기가 없습니다"} {effTab === "tournament"
? lang === "en"
? "Bracket is set after the group stage."
: "토너먼트 대진은 조별리그 종료 후 확정됩니다"
: lang === "en"
? "No matches"
: "경기가 없습니다"}
</p> </p>
)} )}
{shown.map((m) => ( {shown.map((m) => (
<MatchCard key={m.matchId} match={m} lang={lang} /> <MatchCard key={m.matchId} match={m} lang={lang} showDate={effTab === "team"} />
))} ))}
</div> </div>
)}
</section> </section>
); );
} }
@@ -143,9 +295,11 @@ export default function ScheduleBoard({
function ChipScroller({ function ChipScroller({
children, children,
resetKey, resetKey,
centerKey,
}: { }: {
children: React.ReactNode; children: React.ReactNode;
resetKey?: string | number; resetKey?: string | number;
centerKey?: string; // 현재 선택값 — 바뀔 때마다 선택 칩을 가운데로 (비동기 로드·칩 클릭 포함)
}) { }) {
const ref = useRef<HTMLDivElement>(null); const ref = useRef<HTMLDivElement>(null);
const [atStart, setAtStart] = useState(true); const [atStart, setAtStart] = useState(true);
@@ -159,7 +313,7 @@ function ChipScroller({
setAtEnd(el.scrollLeft >= max - 1); setAtEnd(el.scrollLeft >= max - 1);
}; };
// 탭/목록 변경 시: 선택된 칩을 가운데로 + 재측정 (레이아웃 확정 후) // 탭/목록/선택 변경 시: 선택된 칩을 가운데로 + 재측정 (레이아웃 확정 후)
// 선택 칩이 없으면 맨 앞으로 되감는다. // 선택 칩이 없으면 맨 앞으로 되감는다.
useLayoutEffect(() => { useLayoutEffect(() => {
const el = ref.current; const el = ref.current;
@@ -170,7 +324,7 @@ function ChipScroller({
: 0; : 0;
} }
measure(); measure();
}, [resetKey]); }, [resetKey, centerKey]);
useEffect(() => { useEffect(() => {
measure(); measure();
@@ -240,7 +394,7 @@ function Chip({
className={`shrink-0 whitespace-nowrap rounded-full border px-3.5 py-1.5 text-[13px] font-bold transition ${ className={`shrink-0 whitespace-nowrap rounded-full border px-3.5 py-1.5 text-[13px] font-bold transition ${
active active
? "border-[#94FBE0] text-[#94FBE0]" ? "border-[#94FBE0] text-[#94FBE0]"
: "border-[var(--line-d)] text-white/55" : "border-white/20 text-white/70"
}`} }`}
> >
{children} {children}
@@ -248,39 +402,178 @@ function Chip({
); );
} }
function MatchCard({ match, lang }: { match: Match; lang: Lang }) { // MLS 최근 5경기 폼 — "WWLDW" 를 W/D/L 색으로 표시
export function FormBadges({ form }: { form?: string | null }) {
if (!form) return <span className="text-white/50">?</span>;
return (
<span className="inline-flex gap-px font-mono font-extrabold tracking-tight">
{form.split("").map((c, i) => (
<span
key={i}
className={
c === "W"
? "text-[#94FBE0]"
: c === "L"
? "text-[#FF5B5B]/80"
: "text-white/60"
}
>
{c}
</span>
))}
</span>
);
}
// 팀명 옆 순위 배지 (야구·MLS — 순위 캐시 없으면 렌더 안 함)
function RankBadge({ rank, lang = "ko" }: { rank?: number | null; lang?: Lang }) {
if (!rank) return null;
return (
<span className="shrink-0 rounded border border-white/25 px-1 py-px text-[11px] font-bold text-white/60">
{lang === "en" ? `#${rank}` : `${rank}위`}
</span>
);
}
// AI 픽 아이콘 (일정 카드용 — Arena 와 동일 공식 로고)
const MODEL_ICON: Record<ModelName, string> = {
GPT: "/icons/gpt.png",
Claude: "/icons/claude.jpg",
Gemini: "/icons/gemini.jpeg",
};
function AiPickIcons({ models }: { models: ModelName[] }) {
return (
<>
{models.map((m) => (
<img
key={m}
src={MODEL_ICON[m]}
alt={m}
title={m}
className="h-6 w-6 shrink-0 rounded-full border border-white/25 object-cover"
/>
))}
</>
);
}
function MatchCard({
match,
lang,
showDate = false,
}: {
match: Match;
lang: Lang;
showDate?: boolean;
}) {
const t = dict(lang); const t = dict(lang);
const phase = match.phase; const phase = match.phase;
const finished = !!match.result; const finished = !!match.result;
// 한국을 항상 왼쪽에 표시(상세 페이지와 동일 규칙). 데이터는 원본 A/B 유지, 화면 좌우만 교체. const isBaseball = match.league === "kbo" || match.league === "mlb";
const flip = match.teamB.code === "KOR" && match.teamA.code !== "KOR"; const isMls = match.league === "mls";
const isClub = isBaseball || isMls; // 클럽 리그 공통 UI (원정-홈 고정·로고·순위 뱃지)
// 진행 중: 회차(야구)/경기 분(MLS)·스코어 표시 (서버 15초 캐시, 30초 폴링)
const [live, setLive] = useState<LiveData | null>(null);
useEffect(() => {
if (phase !== "live" || !isClub) return;
let alive = true;
const load = () =>
getLive(match.matchId)
.then((d) => {
if (alive && d.available) setLive(d);
})
.catch(() => {});
load();
const id = setInterval(load, 30_000);
return () => {
alive = false;
clearInterval(id);
};
}, [match.matchId, phase, isClub]);
// 야구 "6회초" / "Top 6" · MLS 경기 분 "45'"
const liveBadge = isMls
? live?.clock || null
: live?.inn != null
? lang === "en"
? `${live.half === "B" ? "Bot" : "Top"} ${live.inn}`
: `${live.inn}회${live.half === "B" ? "말" : "초"}`
: null;
// 킥오프 시각은 지났지만 소스가 아직 시작 전(state=pre)이라는 경기 — 지연 등
const notStarted = isMls && phase === "live" && live?.state === "pre";
// 월드컵: 한국을 항상 왼쪽에. MLS: 홈 팀을 왼쪽에(축구 관례). 데이터는 원본 A/B 유지, 화면 좌우만 교체.
const flip =
isMls || (!isClub && match.teamB.code === "KOR" && match.teamA.code !== "KOR");
const left = flip ? match.teamB : match.teamA; const left = flip ? match.teamB : match.teamA;
const right = flip ? match.teamA : match.teamB; const right = flip ? match.teamA : match.teamB;
const leftScore = flip ? match.result?.scoreB : match.result?.scoreA; const leftScore = flip ? match.result?.scoreB : match.result?.scoreA;
const rightScore = flip ? match.result?.scoreA : match.result?.scoreB; const rightScore = flip ? match.result?.scoreA : match.result?.scoreB;
const leftSt = flip ? match.extras?.standings?.b : match.extras?.standings?.a;
const rightSt = flip ? match.extras?.standings?.a : match.extras?.standings?.b;
const flagCls = isClub ? "h-7 w-7 shrink-0" : "h-6 w-9 shrink-0";
// AI 픽: 픽한 팀 아래에 모델 아이콘 배치 (무승부 픽은 가운데)
const picksFor = (o: Outcome) =>
match.predictions.filter((p) => p.outcome === o).map((p) => p.model);
const leftPicks = picksFor(flip ? "TEAM_B_WIN" : "TEAM_A_WIN");
const rightPicks = picksFor(flip ? "TEAM_A_WIN" : "TEAM_B_WIN");
const drawPicks = picksFor("DRAW");
const showAiRow =
match.votable && phase !== "cancelled" && match.predictions.length > 0;
// AI 픽 우세 방향 부등호 — VS 자리에 표시 (팽팽하면 =, 픽 없으면 VS 유지)
const vsSign = !showAiRow
? null
: leftPicks.length > rightPicks.length
? ">"
: leftPicks.length < rightPicks.length
? "<"
: "=";
// 비투표(타 조)는 클릭 비활성, 투표 가능 조(A)는 상세로 이동 // 비투표(타 조)는 클릭 비활성, 투표 가능 조(A)는 상세로 이동
const inner = ( const inner = (
<> <>
<div className="flex items-center justify-between text-[11px]"> <div className="flex items-center justify-between text-[12px]">
<span className="font-mono font-bold text-white/70"> <span className="font-mono font-bold text-white/85">
{timeOnly(match.kickoffKst)} <span className="text-white/40">KST</span> {showDate && (
{match.roundLabel ? <> · {tRound(match.roundLabel, lang)}</> : null} <span className="text-white/65">{shortDate(dateKey(match.kickoffKst), lang)} </span>
)}
{timeOnly(match.kickoffKst)} <span className="text-white/55">KST</span>
{isClub && match.venue ? (
<span className="text-white/55"> · {match.venue}</span>
) : match.group && match.roundLabel ? (
<> · {tRound(match.roundLabel, lang)}</>
) : null}
</span> </span>
<span className="flex items-center gap-1.5"> <span className="flex items-center gap-1.5">
<span className="text-[11px] font-bold text-white/45"> {!isClub && (
{lang === "en" ? `Group ${match.group}` : `${match.group}조`} <span className="text-[11px] font-bold text-white/60">
</span> {match.group
<span className={`rounded-md border px-2 py-0.5 font-semibold ${PHASE_CLS[phase]}`}> ? lang === "en"
{t.phase[phase]} ? `Group ${match.group}`
: `${match.group}조`
: tRound(match.roundLabel, lang)}
</span>
)}
<span
className={`rounded-md border px-2 py-0.5 font-semibold ${
notStarted ? PHASE_CLS.scheduled : PHASE_CLS[phase]
}`}
>
{notStarted
? lang === "en" ? "Not started" : "시작 전"
: phase === "live" && liveBadge
? liveBadge
: t.phase[phase]}
</span> </span>
</span> </span>
</div> </div>
<div className="mt-3 grid grid-cols-[1fr_auto_1fr] items-center gap-2"> <div className="mt-3 grid grid-cols-[1fr_auto_1fr] items-center gap-2">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<TeamFlag team={left} className="h-6 w-9 shrink-0" /> <TeamFlag team={left} className={flagCls} />
<span className="truncate text-[15px] font-extrabold">{teamShort(left, lang)}</span> <span className="truncate text-[15px] font-extrabold">{teamShort(left, lang)}</span>
{isClub && <RankBadge rank={leftSt?.rank} lang={lang} />}
</div> </div>
{match.result ? ( {match.result ? (
<span className="whitespace-nowrap font-mono text-[18px] font-extrabold tabular-nums text-white"> <span className="whitespace-nowrap font-mono text-[18px] font-extrabold tabular-nums text-white">
@@ -288,22 +581,74 @@ function MatchCard({ match, lang }: { match: Match; lang: Lang }) {
<span className="px-1.5 text-white/40">:</span> <span className="px-1.5 text-white/40">:</span>
{rightScore} {rightScore}
</span> </span>
) : phase === "live" && live?.score ? (
// 진행 중 실시간 스코어 — flip 시(MLS) 홈 먼저
<span className="whitespace-nowrap font-mono text-[18px] font-extrabold tabular-nums text-white">
{(flip ? live.score.home : live.score.away) ?? 0}
<span className="px-1.5 text-[#FF5B5B]">:</span>
{(flip ? live.score.away : live.score.home) ?? 0}
</span>
) : ( ) : (
<span className="font-impact text-[18px] italic text-[#94FBE0]">VS</span> vsSign ? (
<span
className="font-impact text-[34px] font-extrabold leading-none text-[#94FBE0]"
style={{ textShadow: "0 0 12px rgba(148,251,224,0.55)" }}
title={lang === "en" ? "AI pick lean" : "AI 픽 우세 방향"}
>
{vsSign}
</span>
) : (
<span className="font-impact text-[18px] italic text-[#94FBE0]">VS</span>
)
)} )}
<div className="flex items-center justify-end gap-2"> <div className="flex items-center justify-end gap-2">
{isClub && <RankBadge rank={rightSt?.rank} lang={lang} />}
<span className="truncate text-right text-[15px] font-extrabold">{teamShort(right, lang)}</span> <span className="truncate text-right text-[15px] font-extrabold">{teamShort(right, lang)}</span>
<TeamFlag team={right} className="h-6 w-9 shrink-0" /> <TeamFlag team={right} className={flagCls} />
</div> </div>
</div> </div>
{/* 투표 가능 조만: AI 픽 갈림 + 참여수 + 이동 화살표 */} {/* AI 픽: 각 모델 아이콘을 픽한 팀 아래에 표시 (무승부 픽은 가운데) */}
{match.votable && ( {showAiRow && (
<div className="mt-3 flex items-center justify-between text-[11px] font-bold text-[#F4F3FE]"> <div
<span> className="mt-1.5 grid grid-cols-[1fr_auto_1fr] items-center gap-2"
<span className="font-semibold text-white/55">{t.aiPicks}</span>{" "} aria-label={`${t.aiPicks}: ${aiSplit(match, lang).join(", ")}`}
{aiSplit(match, lang).join(" · ")} >
</span> <div className="flex items-center gap-1">
<AiPickIcons models={leftPicks} />
</div>
<div className="flex items-center justify-center gap-1">
<AiPickIcons models={drawPicks} />
</div>
<div className="flex items-center justify-end gap-1">
<AiPickIcons models={rightPicks} />
</div>
</div>
)}
{/* 야구: 선발 매치업 (프리뷰 캐시 있을 때만) */}
{isBaseball && !match.result && (match.extras?.starterA || match.extras?.starterB) && (
<div className="mt-2 text-center text-[12px] font-semibold text-white/65">
<span className="text-white/50">{lang === "en" ? "SP" : "선발"}</span>{" "}
{match.extras?.starterA?.name ?? "?"}
<span className="px-1 text-white/45">vs</span>
{match.extras?.starterB?.name ?? "?"}
</div>
)}
{/* MLS: 최근 5경기 폼 (프리뷰 캐시 있을 때만) — 홈(왼쪽) 먼저 */}
{isMls && !match.result && (match.extras?.formA || match.extras?.formB) && (
<div className="mt-2 text-center text-[12px] font-semibold text-white/65">
<span className="text-white/50">{lang === "en" ? "Last 5" : "최근 5경기"}</span>{" "}
<FormBadges form={match.extras?.formB} />
<span className="px-1 text-white/45">vs</span>
<FormBadges form={match.extras?.formA} />
</div>
)}
{/* 투표 가능 조만: 참여수 + 이동 화살표 (AI 픽은 위의 아이콘 행이 담당, 취소 경기는 숨김) */}
{match.votable && phase !== "cancelled" && (
<div className="mt-3 flex items-center justify-end text-[12px] font-bold text-[#F4F3FE]">
<span className="flex items-center gap-2"> <span className="flex items-center gap-2">
<span>{t.joined((match.crowd?.total ?? 0).toLocaleString())}</span> <span>{t.joined((match.crowd?.total ?? 0).toLocaleString())}</span>
<span className="text-[#94FBE0]">→</span> <span className="text-[#94FBE0]">→</span>
@@ -314,6 +659,10 @@ function MatchCard({ match, lang }: { match: Match; lang: Lang }) {
); );
const base = "block rounded-2xl border-2 bg-[#171b21] p-4"; const base = "block rounded-2xl border-2 bg-[#171b21] p-4";
// 취소 경기: 클릭 불가·저채도 표시 전용
if (phase === "cancelled") {
return <div className={`${base} border-[var(--line-d)] opacity-60`}>{inner}</div>;
}
if (match.votable && !finished) { if (match.votable && !finished) {
return ( return (
<Link <Link
@@ -343,9 +692,12 @@ function aiSplit(match: Match, lang: Lang): string[] {
else if (p.outcome === "DRAW") tally.d++; else if (p.outcome === "DRAW") tally.d++;
else tally.b++; else tally.b++;
} }
const out: string[] = []; const entA = tally.a ? `${teamShort(match.teamA, lang)} ${tally.a}` : null;
if (tally.a) out.push(`${teamShort(match.teamA, lang)} ${tally.a}`); const entD = tally.d ? `${t.draw} ${tally.d}` : null;
if (tally.d) out.push(`${t.draw} ${tally.d}`); const entB = tally.b ? `${teamShort(match.teamB, lang)} ${tally.b}` : null;
if (tally.b) out.push(`${teamShort(match.teamB, lang)} ${tally.b}`); // MLS 는 홈 팀 먼저 (카드 좌우 표시와 동일 순서)
const out = (match.league === "mls" ? [entB, entD, entA] : [entA, entD, entB]).filter(
(x): x is string => !!x,
);
return out.length ? out : ["-"]; return out.length ? out : ["-"];
} }
+169
View File
@@ -0,0 +1,169 @@
import { useEffect, useState } from "react";
import { getStandings } from "@/lib/api";
import { type Lang, teamShort } from "@/lib/i18n";
import type { StandingRow, StandingsOut } from "@/lib/types";
import TeamFlag from "./TeamFlag";
// 리그 순위표 — KBO: 단일 테이블 · MLB: 디비전 6그룹 · MLS: 컨퍼런스 2그룹(승점제).
// 데이터는 워커가 캐싱한 시즌 순위(/api/standings)로, 하루 수회 갱신된다.
const DIV_LABEL: Record<string, { ko: string; en: string }> = {
ALE: { ko: "AL 동부", en: "AL East" },
ALC: { ko: "AL 중부", en: "AL Central" },
ALW: { ko: "AL 서부", en: "AL West" },
NLE: { ko: "NL 동부", en: "NL East" },
NLC: { ko: "NL 중부", en: "NL Central" },
NLW: { ko: "NL 서부", en: "NL West" },
EAST: { ko: "동부 컨퍼런스", en: "Eastern Conference" },
WEST: { ko: "서부 컨퍼런스", en: "Western Conference" },
};
function fmtWra(v: StandingRow["wra"]): string {
if (v == null || v === "") return "-";
const n = typeof v === "number" ? v : parseFloat(v);
return Number.isNaN(n) ? String(v) : n.toFixed(3);
}
function fmtGb(v: StandingRow["gb"]): string {
if (v == null || v === "" || v === "-") return "-";
const n = Number(v);
return !Number.isNaN(n) && n === 0 ? "-" : String(v);
}
export default function StandingsTable({
league,
lang = "ko",
}: {
league: string;
lang?: Lang;
}) {
const [data, setData] = useState<StandingsOut | null>(null);
const [loaded, setLoaded] = useState(false);
useEffect(() => {
let alive = true;
setLoaded(false);
getStandings(league)
.then((d) => {
if (!alive) return;
setData(d);
setLoaded(true);
})
.catch(() => {
if (!alive) return;
setData(null);
setLoaded(true);
});
return () => {
alive = false;
};
}, [league]);
if (!loaded) {
return (
<p className="py-6 text-center text-[13px] text-white/45">
{lang === "en" ? "Loading…" : "불러오는 중…"}
</p>
);
}
if (!data || data.groups.length === 0) {
return (
<p className="py-6 text-center text-[13px] text-white/45">
{lang === "en" ? "Standings not available yet" : "순위 정보가 아직 없습니다"}
</p>
);
}
const hasDraw = league === "kbo" || league === "mls"; // 무승부 존재 리그
const isPoints = league === "mls"; // 승점제 (승률/게임차 대신 승점/득실차)
return (
<div className="flex flex-col gap-4">
{data.groups.map((g, gi) => (
<div key={g.key ?? gi} className="rounded-2xl border border-[var(--line-d)] bg-[#171b21] px-3 py-2.5">
{g.key && (
<div className="mb-1.5 px-1 text-[13px] font-extrabold text-[#94FBE0]">
{DIV_LABEL[g.key]?.[lang === "en" ? "en" : "ko"] ?? g.key}
</div>
)}
<table className="w-full text-[13px] tabular-nums">
<thead>
<tr className="text-[11px] font-bold text-white/40">
<th className="w-7 py-1 text-center font-bold">{lang === "en" ? "#" : "순위"}</th>
<th className="py-1 text-left font-bold">{lang === "en" ? "Team" : "팀"}</th>
{isPoints && (
<th className="w-8 py-1 text-center font-bold">{lang === "en" ? "GP" : "경기"}</th>
)}
<th className="w-8 py-1 text-center font-bold">{lang === "en" ? "W" : "승"}</th>
{hasDraw && (
<th className="w-8 py-1 text-center font-bold">{lang === "en" ? "D" : "무"}</th>
)}
<th className="w-8 py-1 text-center font-bold">{lang === "en" ? "L" : "패"}</th>
{isPoints ? (
<>
<th className="w-10 py-1 text-center font-bold">{lang === "en" ? "Pts" : "승점"}</th>
<th className="w-10 py-1 text-center font-bold">{lang === "en" ? "GD" : "득실"}</th>
</>
) : (
<>
<th className="w-12 py-1 text-center font-bold">{lang === "en" ? "PCT" : "승률"}</th>
<th className="w-10 py-1 text-center font-bold">{lang === "en" ? "GB" : "게임차"}</th>
</>
)}
</tr>
</thead>
<tbody>
{g.rows.map((r) => (
<tr key={r.code} className="border-t border-white/[0.06]">
<td
className={`py-1.5 text-center font-mono font-extrabold ${
r.rank === 1 ? "text-[#94FBE0]" : "text-white/60"
}`}
>
{r.rank ?? "-"}
</td>
<td className="py-1.5">
<span className="flex items-center gap-1.5">
<TeamFlag team={r} className="h-[18px] w-[18px] shrink-0" />
<span className="truncate font-bold">{teamShort(r, lang)}</span>
</span>
</td>
{isPoints && (
<td className="py-1.5 text-center font-mono text-white/60">{r.gp ?? "-"}</td>
)}
<td className="py-1.5 text-center font-mono text-white/80">{r.w ?? "-"}</td>
{hasDraw && (
<td className="py-1.5 text-center font-mono text-white/50">{r.d ?? "-"}</td>
)}
<td className="py-1.5 text-center font-mono text-white/80">{r.l ?? "-"}</td>
{isPoints ? (
<>
<td className="py-1.5 text-center font-mono font-bold text-white">{r.pts ?? "-"}</td>
<td className="py-1.5 text-center font-mono text-white/60">{r.diff ?? "-"}</td>
</>
) : (
<>
<td className="py-1.5 text-center font-mono font-bold text-white">{fmtWra(r.wra)}</td>
<td className="py-1.5 text-center font-mono text-white/60">{fmtGb(r.gb)}</td>
</>
)}
</tr>
))}
</tbody>
</table>
</div>
))}
{data.updatedAt && (
<p className="-mt-1 text-right text-[11px] text-white/35">
{(() => {
const d = new Date(data.updatedAt);
const hh = String(d.getHours()).padStart(2, "0");
const mm = String(d.getMinutes()).padStart(2, "0");
return lang === "en"
? `As of ${d.getMonth() + 1}/${d.getDate()} ${hh}:${mm}`
: `${d.getMonth() + 1}.${d.getDate()} ${hh}:${mm} 기준`;
})()}
</p>
)}
</div>
);
}
+17 -3
View File
@@ -1,9 +1,10 @@
import { useState } from "react"; import { useState } from "react";
import type { Team } from "@/lib/types"; import type { Team } from "@/lib/types";
// 모든 경기에 일반화된 국기 렌더. // 모든 경기에 일반화된 국기/팀로고 렌더.
// 글로벌 축구 축전 출전 48개국 SVG 자산(/assets/flags/{fifa코드}.svg, 예: kor.svg)을 사용하고, // 야구(KBO/MLB): 백엔드가 flag 필드에 로고 경로/URL 을 실어줌 → 그대로 img.
// 자산이 없는 코드는 이모지 폴백(컨테이너 높이에 비례, 안 잘림). // 축구(월드컵): 48개국 SVG 자산(/assets/flags/{fifa코드}.svg) 사용.
// 없으면 이모지 폴백(컨테이너 높이에 비례, 안 잘림).
export default function TeamFlag({ export default function TeamFlag({
team, team,
className = "", className = "",
@@ -12,6 +13,19 @@ export default function TeamFlag({
className?: string; className?: string;
}) { }) {
const [failed, setFailed] = useState(false); const [failed, setFailed] = useState(false);
const isLogoUrl =
!!team.flag && (team.flag.startsWith("/") || team.flag.startsWith("http"));
if (!failed && isLogoUrl) {
return (
<img
src={team.flag}
alt={team.name}
onError={() => setFailed(true)}
className={`object-contain ${className}`}
/>
);
}
if (!failed && team.code) { if (!failed && team.code) {
return ( return (
+39 -39
View File
@@ -2,83 +2,83 @@ import { useCallback, useEffect, useRef, useState } from "react";
// 페이지 맨 위 파도타기 — 5마리가 순차로 만세(팔 올림)했다 내린다. // 페이지 맨 위 파도타기 — 5마리가 순차로 만세(팔 올림)했다 내린다.
// 5마리는 한 그룹으로 묶여 함께 끌어 옮길 수 있고, 각 캐릭터를 탭하면 // 5마리는 한 그룹으로 묶여 함께 끌어 옮길 수 있고, 각 캐릭터를 탭하면
// 남아공전 응원 말풍선이 뜬다. // 경기 범용 응원 말풍선이 뜬다.
type Animal = { name: string; lines: string[] }; type Animal = { name: string; lines: string[] };
const WAVE: Animal[] = [ const WAVE: Animal[] = [
{ {
name: "bull", name: "bull",
lines: [ lines: [
"한국, 남아공 잡고 16강 가자! 🇰🇷", "오늘 경기 놓치지 마! 🐂",
"남아공 수비를 뚫어라! 🐂", "수비를 뚫어라! ⚽",
"오늘 이기면 16강이 보인다", "오늘 이기면 분위기 탄다",
"대~한민국! 짝짝짝 👏", "골! 골! 짝짝짝 👏",
"투우사도 한국 응원한다 ⚽",
"스페인도 한국 편이다 🇪🇸",
"남아공 골키퍼 긴장해라!",
"한 골이 16강을 가른다",
"투지로 밀어붙여! 💪", "투지로 밀어붙여! 💪",
"끝까지 간다, 대한민국!", "골키퍼 긴장해라!",
"한 골이 승부를 가른다",
"끝까지 간다, 파이팅!",
"오늘 주인공은 누구? 🔥",
"승점 3점 가져오자",
], ],
}, },
{ {
name: "eagle", name: "eagle",
lines: [ lines: [
"남아공전 무조건 이긴다 🦅", "오늘 승부 무조건 잡는다 🦅",
"한국 16강 가즈아 🇰🇷", "골문을 노려라!",
"남아공 골문을 노려라!",
"이 경기 잡으면 토너먼트행 ✈️", "이 경기 잡으면 토너먼트행 ✈️",
"골! 골! 대한민국! ⚽", "골! 골! 골! ⚽",
"아르헨도 한국 편 🇦🇷",
"역습 한 방이면 끝난다", "역습 한 방이면 끝난다",
"오늘 클린시트 가자 🧤", "오늘 클린시트 가자 🧤",
"남아공 수비 흔들어!", "수비 흔들어!",
"16강에서 또 보자 ✈️", "하늘에서 다 보인다 👀",
"끝까지 집중하자",
"다음 라운드에서 또 보자 ✈️",
], ],
}, },
{ {
name: "rooster", name: "rooster",
lines: [ lines: [
"꼬끼오~ 한국 남아공 이겨라! 🐓", "꼬끼오~ 오늘 이겨라! 🐓",
"16강 길목, 오늘이 중요해", "승부의 길목, 오늘이 중요해",
"남아공 막고 골 넣자!", "막고 골 넣자!",
"대한민국 파이팅 🇰🇷", "파이팅! 🙌",
"프랑스도 한국 편이다 🙌",
"전반부터 몰아쳐라 🐓", "전반부터 몰아쳐라 🐓",
"남아공 김빠지게 골 넣자", "김빠지게 골 넣자",
"한국 미드필드 최고지", "미드필드 장악하자",
"오늘 분위기 우리 거야", "오늘 분위기 우리 거야",
"꼬끼오! 승리의 함성 📣", "꼬끼오! 승리의 함성 📣",
"한 점이라도 앞서가자",
], ],
}, },
{ {
name: "parrot", name: "parrot",
lines: [ lines: [
"삼바 응원! 한국 남아공 격파 🥁", "삼바 리듬 타고 골 가자 🥁",
"골 넣고 16강 가자 💃", "골 넣고 앞서가자 💃",
"남아공 수비 흔들어! 🔥", "수비 흔들어! 🔥",
"대한민국 가즈아 🇰🇷", "가즈아 🎶",
"오늘 승점 3점 챙기자 ⚽", "오늘 승점 3점 챙기자 ⚽",
"리듬 타고 골 가자 🎶", "리듬 타고 골! 🎶",
"남아공? 삼바로 제압! 💃", "삼바로 제압! 💃",
"한 골 한 골 쌓아가자 ⚽", "한 골 한 골 쌓아가자 ⚽",
"응원석도 파도타기 🌊", "응원석도 파도타기 🌊",
"오늘 MVP는 대한민국 🏆", "오늘 MVP는 누구? 🏆",
], ],
}, },
{ {
name: "horse", name: "horse",
lines: [ lines: [
"달려라 대한민국, 남아공 잡자! 🏇", "달려라! 끝까지 간다 🏇",
"16강 가는 길, 오늘이 분수령", "승부의 분수령, 오늘!",
"남아공 골문 열어라 ⚽", "골문 열어라 ⚽",
"끝까지 응원! 한국 화이팅 📣", "끝까지 응원! 화이팅 📣",
"호날두도 한국 응원한다 🐴",
"측면 돌파로 무너뜨려!", "측면 돌파로 무너뜨려!",
"스피드로 남아공 제쳐라 🏇", "스피드로 제쳐라 🏇",
"한 점 차도 이기면 돼", "한 점 차도 이기면 돼",
"16강 티켓 가져오자 🎫", "승리 티켓 가져오자 🎫",
"포르투갈도 함께 외친다 🇵🇹", "막판 뒷심 보여주자 💨",
"포기란 없다, 달려! 🐴",
], ],
}, },
]; ];
+2 -2
View File
@@ -42,8 +42,8 @@ body {
body { body {
font-family: font-family:
"Pretendard", -apple-system, BlinkMacSystemFont, system-ui, "Pretendard Variable", "Pretendard", -apple-system, BlinkMacSystemFont,
"Apple SD Gothic Neo", "Malgun Gothic", sans-serif; system-ui, "Apple SD Gothic Neo", "Malgun Gothic", sans-serif;
margin: 0; margin: 0;
} }
+151 -13
View File
@@ -10,6 +10,7 @@ import type {
MyPrediction, MyPrediction,
RankingEntry, RankingEntry,
RankingTab, RankingTab,
StandingsOut,
} from "./types"; } from "./types";
import type { Lang } from "./i18n"; import type { Lang } from "./i18n";
@@ -42,14 +43,142 @@ export class ApiError extends Error {
} }
} }
export function listMatches(lang: Lang): Promise<Match[]> { // ── 오늘의 응원가 ────────────────────────────────────────────
return http<Match[]>(`/matches?lang=${lang}`); export interface SongTrackOut {
title: string;
audioUrl: string;
imageUrl?: string;
duration?: number;
}
export interface SongOut {
matchId: string;
league: string;
teamCode: string;
teamName: string;
title: string;
lyrics?: string;
/** 제작일(경기일 KST, YYYY-MM-DD) — "8월 28일 OO 응원가" 표기용 */
dateKst?: string | null;
tracks: SongTrackOut[];
}
export function getTodaySongs(league = ""): Promise<SongOut[]> {
return http<SongOut[]>(`/songs/today${league ? `?league=${league}` : ""}`);
}
// 경기별 응원가 — 날짜 무관이라 종료된 경기 상세에서도 곡이 나온다
export function getMatchSongs(matchId: string): Promise<SongOut[]> {
return http<SongOut[]>(`/songs/match/${matchId}`);
}
export function listMatches(lang: Lang, league = ""): Promise<Match[]> {
return http<Match[]>(`/matches?lang=${lang}${league ? `&league=${league}` : ""}`);
} }
export function getMatch(matchId: string, lang: Lang): Promise<Match> { export function getMatch(matchId: string, lang: Lang): Promise<Match> {
return http<Match>(`/matches/${matchId}?lang=${lang}`); return http<Match>(`/matches/${matchId}?lang=${lang}`);
} }
// ── 야구 라이브 필드 뷰 ──────────────────────────────────────
export interface LiveBatter {
order?: number | null;
name: string;
pos?: string;
avg?: number | string | null;
sub?: boolean;
}
export interface LiveGoal {
clock: string; // "9'"
team: string; // 팀 코드
player: string;
assist?: string; // 어시스트 선수 (없으면 "")
ownGoal?: boolean;
penalty?: boolean;
}
export interface LiveCard {
clock: string;
team: string; // 팀 코드
player: string;
red?: boolean; // true=레드(퇴장), false=옐로
}
export interface LiveData {
available: boolean;
inn?: number;
half?: "T" | "B";
score?: { away?: number | string; home?: number | string };
bso?: { b?: number | string; s?: number | string; o?: number | string };
bases?: boolean[];
batter?: LiveBatter | null;
pitcher?: { name: string; ballCount?: number | string | null } | null;
vsRecord?: string;
defense?: { pos?: string; name: string }[];
offenseLineup?: LiveBatter[];
relay?: RelayGroup[]; // 야구 문자중계 (KBO=네이버, 최신 타석순)
// MLS(축구) 라이브 — soccer=true 일 때만
soccer?: boolean;
clock?: string; // "45'"
period?: number; // 1=전반 2=후반
state?: string; // pre | in | post
goals?: LiveGoal[];
cards?: LiveCard[];
subs?: LiveSub[];
lineups?: {
away?: SoccerLineup;
home?: SoccerLineup;
} | null;
commentary?: LiveCommentary[]; // 문자중계 (ESPN 영문, 최신순)
}
// 야구 문자중계 — 타석 단위 그룹. events 가 비면 이닝 구분 헤더("7회초 한화 공격").
export interface RelayGroup {
inn?: number;
half?: "T" | "B";
no?: number;
title: string; // "5번타자 노시환"
events: RelayEvent[];
}
export interface RelayEvent {
// pitch=투구 · result=타석결과 · run=주루 · sub=교체 · note=기타 · inning/end=구분
kind: "pitch" | "result" | "run" | "sub" | "note" | "inning" | "batter" | "end";
text: string;
score?: boolean; // 이 이벤트로 점수가 났음
}
export interface LiveCommentary {
clock: string;
text: string;
goal?: boolean;
}
export interface LiveSub {
clock: string;
team: string;
inName: string;
outName: string;
}
export interface SoccerPlayer {
name: string;
pos: string;
jersey: string;
in: boolean; // 교체 투입됨
out: boolean; // 교체 아웃됨
}
export interface SoccerLineup {
formation?: string | null;
starters: SoccerPlayer[];
bench: SoccerPlayer[];
}
export function getLive(matchId: string): Promise<LiveData> {
return http<LiveData>(`/matches/${matchId}/live`);
}
export interface SubmitResult { export interface SubmitResult {
ok: boolean; ok: boolean;
predictionId: string; predictionId: string;
@@ -73,23 +202,28 @@ export function submitPrediction(body: {
}); });
} }
export function getLeaderboard(): Promise<Leaderboard> { export function getLeaderboard(league = ""): Promise<Leaderboard> {
return http<Leaderboard>(`/leaderboard`); return http<Leaderboard>(`/leaderboard${league ? `?league=${league}` : ""}`);
}
// 리그 순위표 (야구 — 워커가 캐싱한 시즌 순위)
export function getStandings(league: string): Promise<StandingsOut> {
return http<StandingsOut>(`/standings?league=${league}`);
} }
// AI 모델 누적 랭킹 (종료 경기 합산 — 서버가 매 조회 시 재계산) // AI 모델 누적 랭킹 (종료 경기 합산 — 서버가 매 조회 시 재계산)
export function getAILeaderboard(): Promise<AILeaderboard> { export function getAILeaderboard(league = ""): Promise<AILeaderboard> {
return http<AILeaderboard>(`/leaderboard/ai`); return http<AILeaderboard>(`/leaderboard/ai${league ? `?league=${league}` : ""}`);
} }
// 랭킹 위젯 공용 — 탭에 맞춰 TOP 10 을 {label, points} 로 정규화해 반환. // 랭킹 위젯 공용 — 탭에 맞춰 TOP 10 을 {label, points} 로 정규화해 반환.
// 경기 종료·채점 때마다 서버 값이 갱신되므로 호출 시점 최신 누적이 내려옴. // league 를 주면 해당 리그 경기만 집계(빈 값 = 전체 통합).
export async function fetchRanking(tab: RankingTab): Promise<RankingEntry[]> { export async function fetchRanking(tab: RankingTab, league = ""): Promise<RankingEntry[]> {
if (tab === "ai") { if (tab === "ai") {
const { standings } = await getAILeaderboard(); const { standings } = await getAILeaderboard(league);
return standings.map((s) => ({ label: s.model, points: s.totalPoints })); return standings.map((s) => ({ label: s.model, points: s.totalPoints }));
} }
const { standings } = await getLeaderboard(); const { standings } = await getLeaderboard(league);
return standings return standings
.slice(0, 10) .slice(0, 10)
.map((s) => ({ label: s.emailMasked, points: s.totalPoints })); .map((s) => ({ label: s.emailMasked, points: s.totalPoints }));
@@ -125,10 +259,14 @@ export function postComment(
// ── 세션 닉네임: 세션당 한 번 발급받아 sessionStorage 에 캐싱 ── // ── 세션 닉네임: 세션당 한 번 발급받아 sessionStorage 에 캐싱 ──
// 탭/창을 닫으면 비워지고(껐다 켜면 새 닉), 시크릿창은 별도 저장소라 새로 발급됨. // 탭/창을 닫으면 비워지고(껐다 켜면 새 닉), 시크릿창은 별도 저장소라 새로 발급됨.
// 종목별(축구/야구) 캐시 분리 — 서버가 리그에 맞는 단어풀로 발급하므로
// 축구 닉이 야구 경기에 재사용되지 않게 키를 나눈다.
const SESSION_NICK_KEY = "tp_session_nick"; const SESSION_NICK_KEY = "tp_session_nick";
const nickKey = (matchId: string) =>
`${SESSION_NICK_KEY}.${/^(KBO|MLB)_/.test(matchId) ? "bb" : "wc"}`;
export async function getSessionNickname(matchId: string): Promise<string> { export async function getSessionNickname(matchId: string): Promise<string> {
try { try {
const cached = sessionStorage.getItem(SESSION_NICK_KEY); const cached = sessionStorage.getItem(nickKey(matchId));
if (cached) return cached; if (cached) return cached;
} catch { } catch {
/* sessionStorage 불가 환경은 매번 발급 */ /* sessionStorage 불가 환경은 매번 발급 */
@@ -137,7 +275,7 @@ export async function getSessionNickname(matchId: string): Promise<string> {
`/matches/${matchId}/comments/nickname`, `/matches/${matchId}/comments/nickname`,
); );
try { try {
sessionStorage.setItem(SESSION_NICK_KEY, nickname); sessionStorage.setItem(nickKey(matchId), nickname);
} catch { } catch {
/* noop */ /* noop */
} }
@@ -150,7 +288,7 @@ export async function rerollSessionNickname(matchId: string): Promise<string> {
`/matches/${matchId}/comments/nickname`, `/matches/${matchId}/comments/nickname`,
); );
try { try {
sessionStorage.setItem(SESSION_NICK_KEY, nickname); sessionStorage.setItem(nickKey(matchId), nickname);
} catch { } catch {
/* noop */ /* noop */
} }
+130
View File
@@ -0,0 +1,130 @@
// 카카오 로그인 클라이언트 (o2o-castad 인증 이식과 짝).
// 토큰은 localStorage 보관, access 만료 시 refresh 로 1회 자동 갱신.
// 콜백은 백엔드가 `/#access_token=..&refresh_token=..` 으로 리다이렉트 — 앱 시작 시 캡처.
import { useEffect, useState } from "react";
const BASE = import.meta.env.VITE_API_BASE || "/api";
const KEY_ACCESS = "tp.auth.access";
const KEY_REFRESH = "tp.auth.refresh";
export interface AuthUser {
userUuid: string;
email: string | null;
nickname: string | null;
profileImageUrl: string | null;
}
// 콜백 해시에서 토큰 캡처 (main.tsx 렌더 전에 호출) — URL 에 토큰이 남지 않게 즉시 제거
export function captureAuthTokens(): void {
const h = window.location.hash;
if (!h.includes("access_token=")) return;
const params = new URLSearchParams(h.slice(1));
const access = params.get("access_token");
const refresh = params.get("refresh_token");
if (access && refresh) {
localStorage.setItem(KEY_ACCESS, access);
localStorage.setItem(KEY_REFRESH, refresh);
userCache = undefined; // 다음 getMe 에서 재조회
}
history.replaceState(null, "", window.location.pathname + window.location.search);
}
export function isLoggedIn(): boolean {
return !!localStorage.getItem(KEY_REFRESH);
}
function clearTokens(): void {
localStorage.removeItem(KEY_ACCESS);
localStorage.removeItem(KEY_REFRESH);
userCache = null;
notify();
}
async function tryRefresh(): Promise<boolean> {
const refresh = localStorage.getItem(KEY_REFRESH);
if (!refresh) return false;
const res = await fetch(`${BASE}/auth/refresh`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ refreshToken: refresh }),
});
if (!res.ok) {
clearTokens(); // 만료/폐기 — 재로그인 필요
return false;
}
const d = await res.json();
localStorage.setItem(KEY_ACCESS, d.access_token);
localStorage.setItem(KEY_REFRESH, d.refresh_token); // rotation — 새 refresh 로 교체
return true;
}
// 인증 헤더로 호출, 401 이면 refresh 후 1회 재시도
async function authFetch(path: string, init?: RequestInit): Promise<Response> {
const call = () =>
fetch(`${BASE}${path}`, {
...init,
headers: {
...(init?.headers || {}),
Authorization: `Bearer ${localStorage.getItem(KEY_ACCESS) || ""}`,
},
});
let res = await call();
if (res.status === 401 && (await tryRefresh())) res = await call();
return res;
}
// /me 는 모듈 레벨 캐시 — 화면 여러 곳(Hero·Arena)에서 써도 1회만 조회
let userCache: AuthUser | null | undefined; // undefined=미조회, null=비로그인
let inflight: Promise<AuthUser | null> | null = null;
const listeners = new Set<() => void>();
const notify = () => listeners.forEach((fn) => fn());
export async function getMe(): Promise<AuthUser | null> {
if (userCache !== undefined) return userCache;
if (!isLoggedIn()) return (userCache = null);
inflight ??= (async () => {
try {
const res = await authFetch("/auth/me");
userCache = res.ok ? ((await res.json()) as AuthUser) : null;
} catch {
userCache = null;
} finally {
inflight = null;
}
notify();
return userCache;
})();
return inflight;
}
export async function startKakaoLogin(): Promise<void> {
const res = await fetch(`${BASE}/auth/kakao/login`);
const d = await res.json();
window.location.href = d.authUrl; // 카카오 인증 페이지로 이동
}
export async function logout(): Promise<void> {
const refresh = localStorage.getItem(KEY_REFRESH);
if (refresh) {
await fetch(`${BASE}/auth/logout`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ refreshToken: refresh }),
}).catch(() => {});
}
clearTokens();
}
// 로그인 상태 훅 — user(null=비로그인) 와 로그인/로그아웃 액션
export function useAuth() {
const [user, setUser] = useState<AuthUser | null>(userCache ?? null);
useEffect(() => {
const sync = () => setUser(userCache ?? null);
listeners.add(sync);
getMe().then(sync);
return () => {
listeners.delete(sync);
};
}, []);
return { user, login: startKakaoLogin, logout };
}
+35 -3
View File
@@ -31,9 +31,20 @@ export function monthEn(m: number): string {
return MONTHS_EN[m - 1]; return MONTHS_EN[m - 1];
} }
// 녹아웃 라운드 라벨(한글) → 영문
const ROUND_EN: Record<string, string> = {
"32강": "Round of 32",
"16강": "Round of 16",
"8강": "Quarter-final",
"4강": "Semi-final",
"3·4위전": "3rd-place",
"결승": "Final",
};
// roundLabel 안의 한국어 토막 번역 // roundLabel 안의 한국어 토막 번역
export function roundLabel(label: string, lang: Lang): string { export function roundLabel(label: string, lang: Lang): string {
if (lang === "ko") return label; if (lang === "ko") return label;
if (ROUND_EN[label]) return ROUND_EN[label];
return label.replace("개막전", "Opener"); return label.replace("개막전", "Opener");
} }
@@ -47,7 +58,14 @@ type Dict = {
prizeLine2: string; prizeLine2: string;
schedTitle: string; schedTitle: string;
schedGuide: string; schedGuide: string;
phase: { open: string; scheduled: string; locked: string; live: string; finished: string }; phase: {
open: string;
scheduled: string;
locked: string;
live: string;
finished: string;
cancelled: string;
};
aiPicks: string; aiPicks: string;
draw: string; draw: string;
joined: (n: string) => string; joined: (n: string) => string;
@@ -79,8 +97,10 @@ type Dict = {
rulesCumulative: string; rulesCumulative: string;
rulesExact: string; rulesExact: string;
rulesCloseGrade: string; rulesCloseGrade: string;
rulesCloseGradeBB: string; // 야구: 득실차 ±1 허용
rulesOutcome: string; rulesOutcome: string;
rulesPartial: string; rulesPartial: string;
rulesPartialBB: string; // 야구: 한 팀 득점 ±1 허용
rulesMiss: string; rulesMiss: string;
rulesEmailRequired: string; rulesEmailRequired: string;
rulesCloseBtn: string; rulesCloseBtn: string;
@@ -96,6 +116,8 @@ type Dict = {
group: (g: string) => string; group: (g: string) => string;
footerNotOfficial: string; footerNotOfficial: string;
footerDisc1: string; footerDisc1: string;
footerNotOfficialBB: string; // 야구(KBO/MLB)용 비제휴 고지
footerDisc1BB: string;
footerDisc2: string; footerDisc2: string;
footerDisc3: string; footerDisc3: string;
hook: (a: string, b: string) => string; hook: (a: string, b: string) => string;
@@ -152,7 +174,7 @@ export const DICT: Record<Lang, Dict> = {
prizeLine2: "최종 우승자에게 100만원 상금", prizeLine2: "최종 우승자에게 100만원 상금",
schedTitle: "전체 일정", schedTitle: "전체 일정",
schedGuide: "투표하고 싶은 경기를 선택해주세요", schedGuide: "투표하고 싶은 경기를 선택해주세요",
phase: { open: "투표 중", scheduled: "오픈 예정", locked: "투표 종료", live: "경기중", finished: "종료" }, phase: { open: "투표 중", scheduled: "오픈 예정", locked: "투표 종료", live: "경기중", finished: "종료", cancelled: "취소" },
aiPicks: "AI 픽", aiPicks: "AI 픽",
draw: "무", draw: "무",
joined: (n) => `${n}명 참여`, joined: (n) => `${n}명 참여`,
@@ -185,8 +207,10 @@ export const DICT: Record<Lang, Dict> = {
rulesCumulative: "경기마다 적중 포인트를 쌓아, 대회 누적 포인트 1위 한 분에게 최종 100만 원을 드립니다.", rulesCumulative: "경기마다 적중 포인트를 쌓아, 대회 누적 포인트 1위 한 분에게 최종 100만 원을 드립니다.",
rulesExact: "정확 스코어 적중", rulesExact: "정확 스코어 적중",
rulesCloseGrade: "근접 (승패 + 득실차 일치)", rulesCloseGrade: "근접 (승패 + 득실차 일치)",
rulesCloseGradeBB: "근접 (승패 + 득실차 ±1)",
rulesOutcome: "승패만 적중", rulesOutcome: "승패만 적중",
rulesPartial: "부분 (한 팀 스코어만 일치)", rulesPartial: "부분 (한 팀 스코어만 일치)",
rulesPartialBB: "부분 (한 팀 득점 ±1)",
rulesMiss: "빗나감", rulesMiss: "빗나감",
rulesEmailRequired: rulesEmailRequired:
"픽 제출 시 입력한 이메일로 챌린지에 참여됩니다. 같은 이메일의 모든 경기 포인트가 합산되어 누적 순위가 매겨집니다.", "픽 제출 시 입력한 이메일로 챌린지에 참여됩니다. 같은 이메일의 모든 경기 포인트가 합산되어 누적 순위가 매겨집니다.",
@@ -204,6 +228,9 @@ export const DICT: Record<Lang, Dict> = {
footerNotOfficial: footerNotOfficial:
"Independent AI prediction game — not affiliated with, endorsed by, or sponsored by FIFA or the official World Cup.", "Independent AI prediction game — not affiliated with, endorsed by, or sponsored by FIFA or the official World Cup.",
footerDisc1: "FIFA 및 공식 월드컵과 무관한 독립 AI 예측 게임입니다 (제휴·후원·운영 아님).", footerDisc1: "FIFA 및 공식 월드컵과 무관한 독립 AI 예측 게임입니다 (제휴·후원·운영 아님).",
footerNotOfficialBB:
"Independent AI prediction game — not affiliated with, endorsed by, or sponsored by KBO, MLB, MLS, or any club.",
footerDisc1BB: "KBO·MLB·MLS 리그 및 각 구단과 무관한 독립 AI 예측 게임입니다 (제휴·후원·운영 아님).",
footerDisc2: "스포츠 분석·엔터테인먼트 목적의 예측 게임이며 베팅·도박을 권유하지 않습니다. AI 예측은 실제 결과를 보장하지 않습니다.", footerDisc2: "스포츠 분석·엔터테인먼트 목적의 예측 게임이며 베팅·도박을 권유하지 않습니다. AI 예측은 실제 결과를 보장하지 않습니다.",
footerDisc3: "100만 원 이벤트는 무료 참여형 챌린지입니다. 지급·동점 처리 조건은 별도 약관에 따릅니다. 이메일은 결과·이벤트 알림 목적으로만 사용됩니다.", footerDisc3: "100만 원 이벤트는 무료 참여형 챌린지입니다. 지급·동점 처리 조건은 별도 약관에 따릅니다. 이메일은 결과·이벤트 알림 목적으로만 사용됩니다.",
hook: (a, b) => `${a} vs ${b}, AI의 선택은 갈렸다`, hook: (a, b) => `${a} vs ${b}, AI의 선택은 갈렸다`,
@@ -255,7 +282,7 @@ export const DICT: Record<Lang, Dict> = {
prizeLine2: "overall winner takes ₩1,000,000", prizeLine2: "overall winner takes ₩1,000,000",
schedTitle: "All Matches", schedTitle: "All Matches",
schedGuide: "Pick a match to predict", schedGuide: "Pick a match to predict",
phase: { open: "Voting", scheduled: "Opens soon", locked: "Closed", live: "Live", finished: "Ended" }, phase: { open: "Voting", scheduled: "Opens soon", locked: "Closed", live: "Live", finished: "Ended", cancelled: "Canceled" },
aiPicks: "AI picks", aiPicks: "AI picks",
draw: "Draw", draw: "Draw",
joined: (n) => `${n} joined`, joined: (n) => `${n} joined`,
@@ -288,8 +315,10 @@ export const DICT: Record<Lang, Dict> = {
rulesCumulative: "Earn points each match — the player with the highest cumulative total wins ₩1,000,000.", rulesCumulative: "Earn points each match — the player with the highest cumulative total wins ₩1,000,000.",
rulesExact: "Exact score", rulesExact: "Exact score",
rulesCloseGrade: "Close (result + goal difference)", rulesCloseGrade: "Close (result + goal difference)",
rulesCloseGradeBB: "Close (result + run diff ±1)",
rulesOutcome: "Correct result only", rulesOutcome: "Correct result only",
rulesPartial: "Partial (one team's score)", rulesPartial: "Partial (one team's score)",
rulesPartialBB: "Partial (one team's runs ±1)",
rulesMiss: "Miss", rulesMiss: "Miss",
rulesEmailRequired: rulesEmailRequired:
"You enter the challenge with the email you provide when submitting a pick. Points from all matches under the same email are summed for the overall ranking.", "You enter the challenge with the email you provide when submitting a pick. Points from all matches under the same email are summed for the overall ranking.",
@@ -307,6 +336,9 @@ export const DICT: Record<Lang, Dict> = {
footerNotOfficial: footerNotOfficial:
"Independent AI prediction game — not affiliated with, endorsed by, or sponsored by FIFA or the official World Cup.", "Independent AI prediction game — not affiliated with, endorsed by, or sponsored by FIFA or the official World Cup.",
footerDisc1: "A fan-run prediction game using public match schedules; all picks are independent.", footerDisc1: "A fan-run prediction game using public match schedules; all picks are independent.",
footerNotOfficialBB:
"Independent AI prediction game — not affiliated with, endorsed by, or sponsored by KBO, MLB, MLS, or any club.",
footerDisc1BB: "A fan-run prediction game using public match schedules; all picks are independent.",
footerDisc2: "A sports-analysis & entertainment prediction game. No betting or gambling. AI predictions do not guarantee real outcomes.", footerDisc2: "A sports-analysis & entertainment prediction game. No betting or gambling. AI predictions do not guarantee real outcomes.",
footerDisc3: "The ₩1,000,000 event is a free-to-enter challenge. Payout & tie-break terms follow separate rules. Email is used only for result & event alerts.", footerDisc3: "The ₩1,000,000 event is a free-to-enter challenge. Payout & tie-break terms follow separate rules. Email is used only for result & event alerts.",
hook: (a, b) => `AI is split on ${a} vs ${b}`, hook: (a, b) => `AI is split on ${a} vs ${b}`,
+63 -19
View File
@@ -7,25 +7,69 @@ export type Track = {
src: string; src: string;
/** 앨범 아트 이미지 경로 또는 URL */ /** 앨범 아트 이미지 경로 또는 URL */
cover?: string; cover?: string;
/** 가사 (오늘의 응원가) — 있으면 플레이어에 '가사 보기' 노출 */
lyrics?: string;
/** 공유 링크·문구 — 있으면 플레이어에 '공유하기' 노출 */
shareUrl?: string;
shareText?: string;
}; };
// 경로별 플레이리스트 — 키가 표시할 경로, 값이 해당 경로의 트랙 목록 // 경로별 정적 플레이리스트 — 월드컵 종료로 비움 (구조는 특설 대비 유지)
// VISIBLE_PATHS는 이 맵의 키에서 자동 생성됩니다. export const PATH_PLAYLISTS: Record<string, Track[]> = {};
export const PATH_PLAYLISTS: Record<string, Track[]> = {
"/match/A_MEX_KOR_20260619": [
{ title: "El Tri vs 붉은 악마", artist: "aio2o", src: "/audio/Mexico vs Korea 2026.mp3", cover: "/thumbnail/Mexico vs Korea 2026.webp" },
{ title: "Red Wave: 멕시코를 넘어", artist: "aio2o", src: "/audio/Red Wave 2026.mp3", cover: "/thumbnail/Red Wave 2026.webp" },
{ title: "붉은 물결", artist: "aio2o", src: "/audio/붉은 물결.mp3", cover: "/thumbnail/붉은 물결.webp" },
{ title: "Triple Pick, We Believe", artist: "aio2o", src: "/audio/Triple Pick, We Believe.mp3", cover: "/thumbnail/Triple Pick, We Believe.webp" },
],
"/match/A_RSA_KOR_20260625": [
{ title: "KOR vs RSA 응원가 #1", artist: "aio2o", src: "/audio/Korea vs South Africa_ TAEGEUK FIRE_Catching.mp3", cover: "/thumbnail/kor_rsa1.webp" },
{ title: "KOR vs RSA 응원가 #2", artist: "aio2o", src: "/audio/Korea vs South Africa_ TAEGEUK FIRE_Emotional.mp3", cover: "/thumbnail/kor_rsa2.webp" },
{ title: "KOR vs RSA 응원가 #3", artist: "aio2o", src: "/audio/Korea vs South Africa_ TAEGEUK FIRE_Energetic.mp3", cover: "/thumbnail/kor_rsa3.webp" },
{ title: "붉은 물결", artist: "aio2o", src: "/audio/붉은 물결.mp3", cover: "/thumbnail/붉은 물결.webp" },
{ title: "Triple Pick, We Believe", artist: "aio2o", src: "/audio/Triple Pick, We Believe.mp3", cover: "/thumbnail/Triple Pick, We Believe.webp" },
],
};
// VISIBLE_PATHS — PATH_PLAYLISTS 키에서 자동 도출 (직접 수정 불필요) // 경로 → 자동 로드 트랙 목록 — 정확일치(PATH_PLAYLISTS, 월드컵 특설)만.
export const VISIBLE_PATHS: string[] = Object.keys(PATH_PLAYLISTS); // KBO 오늘의 응원가는 자동재생하지 않고 상세 페이지의 팀별 '응원가 듣기'
// 버튼(getTeamSongTracks)으로만 재생한다.
export function getTracksForPath(pathname: string): Track[] {
return PATH_PLAYLISTS[pathname] ?? [];
}
// ── 오늘의 응원가 (백엔드 Suno 자동 생성) ─────────────────────
// 경기 단위 조회·캐시 — 날짜 무관이라 종료된 경기 상세에서도 곡이 나온다.
import { getMatchSongs, type SongOut } from "./api";
// 곡은 라인업 반영 재생성으로 당일 중에도 교체되므로 짧은 TTL 로 재조회
const SONGS_TTL_MS = 5 * 60_000;
const matchSongsCache = new Map<string, { at: number; p: Promise<SongOut[]> }>();
function fetchMatchSongsCached(matchId: string): Promise<SongOut[]> {
const hit = matchSongsCache.get(matchId);
if (hit && Date.now() - hit.at <= SONGS_TTL_MS) return hit.p;
const p = getMatchSongs(matchId).catch(() => []);
matchSongsCache.set(matchId, { at: Date.now(), p });
return p;
}
function songToTracks(s: SongOut): Track[] {
const base = s.title || `${s.teamName} 응원가`;
// 제작일 표기 ("8월 28일") — 매일 갱신되는 콘텐츠임을 드러낸다. 날짜 없으면 "오늘의"
const day = s.dateKst
? `${Number(s.dateKst.slice(5, 7))}월 ${Number(s.dateKst.slice(8, 10))}일`
: "오늘의";
// 공유는 응원가 전용 링크 — 크롤러에 "8월 28일 OO 응원가" OG 카드가 나간다
const shareUrl = `${window.location.origin}/song/${s.matchId}/${s.teamCode}`;
const shareText = `${day} ${s.teamName} 응원가 「${base}」 — TriplePick`;
return (s.tracks || [])
.filter((t) => t.audioUrl)
.map((t, i) => ({
title: s.tracks.length > 1 ? `${base} #${i + 1}` : base,
artist: `${day} ${s.teamName} 응원가`,
src: t.audioUrl,
cover: t.imageUrl,
lyrics: s.lyrics || undefined,
shareUrl,
shareText,
}));
}
// 특정 경기·팀의 응원가 트랙 — 상세 페이지 '응원가 듣기' 버튼용.
// 종료된 경기도 그날 생성곡을 그대로 노출한다. 곡이 없으면 빈 배열.
export async function getTeamSongTracks(
matchId: string,
teamCode: string,
): Promise<Track[]> {
const songs = await fetchMatchSongsCached(matchId);
return songs
.filter((s) => s.matchId === matchId && s.teamCode === teamCode)
.flatMap(songToTracks);
}
+69 -1
View File
@@ -2,7 +2,13 @@
export type Outcome = "TEAM_A_WIN" | "DRAW" | "TEAM_B_WIN"; export type Outcome = "TEAM_A_WIN" | "DRAW" | "TEAM_B_WIN";
export type ModelName = "GPT" | "Claude" | "Gemini"; export type ModelName = "GPT" | "Claude" | "Gemini";
export type MatchPhase = "scheduled" | "open" | "locked" | "live" | "finished"; export type MatchPhase =
| "scheduled"
| "open"
| "locked"
| "live"
| "finished"
| "cancelled";
export interface Team { export interface Team {
name: string; name: string;
@@ -36,8 +42,69 @@ export interface CrowdStats {
teamBWin: number; teamBWin: number;
} }
// 리그: wc(월드컵 축구) | kbo | mlb | mls
export type League = "wc" | "kbo" | "mlb" | "mls";
// 야구 부가정보 (프리뷰·순위 캐시 — 없으면 undefined)
export interface StarterInfo {
name: string;
hitType?: string;
era?: string | number | null;
w?: number | null;
l?: number | null;
vsEra?: string | number | null;
}
export interface TeamStanding {
rank?: number | null;
w?: number;
d?: number;
l?: number;
wra?: string | number;
gb?: string | number;
last5?: string | null;
// MLS(승점제) 전용
gp?: number;
pts?: number;
gf?: number;
ga?: number;
diff?: string | null;
}
// /standings 응답 — 팀 정보(Team) + 시즌 성적 한 행
export interface StandingRow extends Team, TeamStanding {
// MLB 디비전(ALE/ALC/ALW/NLE/NLC/NLW) 또는 MLS 컨퍼런스(EAST/WEST) 키
div?: string | null;
}
export interface StandingsOut {
league: string;
updatedAt?: string | null;
groups: { key: string | null; rows: StandingRow[] }[];
}
export interface MatchExtras {
starterA?: StarterInfo | null;
starterB?: StarterInfo | null;
seasonVs?: { aWin?: number; draw?: number; bWin?: number } | null;
standings?: { a?: TeamStanding | null; b?: TeamStanding | null };
// MLS 프리뷰 (ESPN) — 최근5 폼("WWLDW")·시즌 전적("8-2-4")·맞대결
formA?: string | null;
formB?: string | null;
recordA?: string | null;
recordB?: string | null;
h2h?: {
date: string;
home: string;
away: string;
scoreH: number;
scoreA: number;
}[];
}
export interface Match { export interface Match {
matchId: string; matchId: string;
league: League;
roundLabel: string; roundLabel: string;
group: string; group: string;
teamA: Team; teamA: Team;
@@ -54,6 +121,7 @@ export interface Match {
result?: MatchResult | null; result?: MatchResult | null;
predictions: AIPrediction[]; predictions: AIPrediction[];
crowd?: CrowdStats | null; crowd?: CrowdStats | null;
extras?: MatchExtras | null;
} }
export interface UserPick { export interface UserPick {
+20
View File
@@ -0,0 +1,20 @@
import { useSearchParams } from "react-router-dom";
import type { League } from "./types";
// 리그 상태 — URL 쿼리(?league=)가 SSOT. 기본값은 KBO(메인 탭).
// 링크 공유 시에도 리그가 보존되도록 쿼리 파라미터를 쓴다.
export const DEFAULT_LEAGUE: League = "kbo";
export function useLeague(): [League, (l: League) => void] {
const [params, setParams] = useSearchParams();
const raw = params.get("league");
// 월드컵(wc)은 서비스 종료 — 쿼리로 들어와도 KBO 로 강등
const league: League =
raw === "kbo" || raw === "mlb" || raw === "mls" ? raw : DEFAULT_LEAGUE;
const setLeague = (l: League) => {
const next = new URLSearchParams(params);
next.set("league", l);
setParams(next, { replace: false });
};
return [league, setLeague];
}
+3
View File
@@ -2,8 +2,11 @@ import { StrictMode } from "react";
import { createRoot } from "react-dom/client"; import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router-dom"; import { BrowserRouter } from "react-router-dom";
import App from "./App"; import App from "./App";
import { captureAuthTokens } from "./lib/auth";
import "./globals.css"; import "./globals.css";
captureAuthTokens(); // 카카오 콜백 해시(#access_token=..) 캡처 — 라우터 마운트 전에
createRoot(document.getElementById("root")!).render( createRoot(document.getElementById("root")!).render(
<StrictMode> <StrictMode>
<BrowserRouter> <BrowserRouter>
+8 -6
View File
@@ -5,12 +5,14 @@ import Ado2Ad from "@/components/Ado2Ad";
import Footer from "@/components/Footer"; import Footer from "@/components/Footer";
import { dict } from "@/lib/i18n"; import { dict } from "@/lib/i18n";
import { useLang } from "@/lib/useLang"; import { useLang } from "@/lib/useLang";
import { useLeague } from "@/lib/useLeague";
import { listMatches } from "@/lib/api"; import { listMatches } from "@/lib/api";
import type { Match } from "@/lib/types"; import type { Match } from "@/lib/types";
// L1. 전체 일정 대시보드 (랜딩 진입) // L1. 전체 일정 대시보드 (랜딩 진입) — 리그 탭(월드컵/KBO/MLB)별 경기 목록
export default function Dashboard() { export default function Dashboard() {
const lang = useLang(); const lang = useLang();
const [league] = useLeague();
const t = dict(lang); const t = dict(lang);
const [matches, setMatches] = useState<Match[] | null>(null); const [matches, setMatches] = useState<Match[] | null>(null);
const [error, setError] = useState(false); const [error, setError] = useState(false);
@@ -19,17 +21,17 @@ export default function Dashboard() {
let alive = true; let alive = true;
setMatches(null); setMatches(null);
setError(false); setError(false);
listMatches(lang) listMatches(lang, league)
.then((m) => alive && setMatches(m)) .then((m) => alive && setMatches(m))
.catch(() => alive && setError(true)); .catch(() => alive && setError(true));
return () => { return () => {
alive = false; alive = false;
}; };
}, [lang]); }, [lang, league]);
return ( return (
<main className="shell"> <main className="shell">
<Hero lang={lang} /> <Hero lang={lang} league={league} />
{/* 기간 안내 + CTA 영역 */} {/* 기간 안내 + CTA 영역 */}
<div className="mt-5 rounded-2xl border border-[var(--line-d)] bg-[var(--bg2)] p-4 text-center"> <div className="mt-5 rounded-2xl border border-[var(--line-d)] bg-[var(--bg2)] p-4 text-center">
@@ -48,10 +50,10 @@ export default function Dashboard() {
{lang === "en" ? "Failed to load matches." : "경기 정보를 불러오지 못했습니다."} {lang === "en" ? "Failed to load matches." : "경기 정보를 불러오지 못했습니다."}
</p> </p>
)} )}
{matches && <ScheduleBoard matches={matches} lang={lang} />} {matches && <ScheduleBoard matches={matches} lang={lang} league={league} />}
<Ado2Ad lang={lang} /> <Ado2Ad lang={lang} />
<Footer lang={lang} /> <Footer lang={lang} league={league} />
</main> </main>
); );
} }
+24 -10
View File
@@ -2,26 +2,40 @@ import Hero from "@/components/Hero";
import Footer from "@/components/Footer"; import Footer from "@/components/Footer";
import RankingBoard from "@/components/RankingBoard"; import RankingBoard from "@/components/RankingBoard";
import { useLang } from "@/lib/useLang"; import { useLang } from "@/lib/useLang";
import { useLeague } from "@/lib/useLeague";
// L3. 리더보드 — 누적 포인트 랭킹(참가자/AI 탭). 펼친 상태로 전체 표시. // L3. 리더보드 — 누적 포인트 랭킹(참가자/AI 탭). 펼친 상태로 전체 표시.
// 빈 상태·AI 탭·TOP10 렌더는 RankingBoard 위젯이 일괄 처리(매치 페이지와 동일 UI). // ?league= 쿼리에 따라 해당 리그 경기만 집계(기본 KBO).
export default function Leaderboard() { export default function Leaderboard() {
const lang = useLang(); const lang = useLang();
const [league] = useLeague();
// 월드컵 외 리그(KBO/MLB/MLS)는 랭킹 운영 방침(상금 등) 미확정 — 임시 비노출
const isBaseball = league !== "wc";
return ( return (
<main className="shell"> <main className="shell">
<Hero back lang={lang} /> <Hero back lang={lang} league={league} />
<section className="mt-8"> <section className="mt-8">
<div className="font-impact text-[28px] text-[var(--green)]">LEADERBOARD</div> <div className="font-impact text-[28px] text-[var(--green)]">LEADERBOARD</div>
<p className="mt-2 text-[13px] leading-relaxed text-[var(--ink-muted)]"> {isBaseball ? (
{lang === "en" <p className="mt-6 py-10 text-center text-[14px] font-bold text-white/55">
? "Points accumulate each match — the overall #1 wins ₩1,000,000." {lang === "en"
: "매 경기 누적 점수로 순위를 매기고, 끝까지 가장 잘 맞힌 한 분께 최종 100만원을 드립니다."} ? "Rankings are being prepared. Check back soon!"
</p> : "랭킹은 준비 중입니다. 조금만 기다려주세요!"}
{/* 전체 페이지: 펼친 상태(폴딩 토글 숨김) */} </p>
<RankingBoard lang={lang} defaultOpen /> ) : (
<>
<p className="mt-2 text-[13px] leading-relaxed text-[var(--ink-muted)]">
{lang === "en"
? "Points accumulate each match — the overall #1 wins ₩1,000,000."
: "매 경기 누적 점수로 순위를 매기고, 끝까지 가장 잘 맞힌 한 분께 최종 100만원을 드립니다."}
</p>
{/* 전체 페이지: 펼친 상태(폴딩 토글 숨김) */}
<RankingBoard lang={lang} defaultOpen league={league} />
</>
)}
</section> </section>
<Footer lang={lang} /> <Footer lang={lang} league={league} />
</main> </main>
); );
} }
+16 -4
View File
@@ -2,6 +2,8 @@ import { useEffect, useState } from "react";
import { Link, useParams } from "react-router-dom"; import { Link, useParams } from "react-router-dom";
import Hero from "@/components/Hero"; import Hero from "@/components/Hero";
import MatchupHUD from "@/components/MatchupHUD"; import MatchupHUD from "@/components/MatchupHUD";
import LiveField from "@/components/LiveField";
import LiveSoccer from "@/components/LiveSoccer";
import Arena from "@/components/Arena"; import Arena from "@/components/Arena";
import Comments from "@/components/Comments"; import Comments from "@/components/Comments";
import Footer from "@/components/Footer"; import Footer from "@/components/Footer";
@@ -57,11 +59,17 @@ export default function MatchDetail() {
const aShort = teamShort(match.teamA, lang); const aShort = teamShort(match.teamA, lang);
const bShort = teamShort(match.teamB, lang); const bShort = teamShort(match.teamB, lang);
// 한국을 항상 왼쪽에 표시(요청)와 동일하게 공유 제목/후킹 카피도 한국 먼저. // 월드컵: 한국을 항상 왼쪽에. MLS: 홈 팀 먼저(축구 관례) — 제목/후킹 카피 동일 순서.
const flip = match.teamB.code === "KOR" && match.teamA.code !== "KOR"; const isMls = match.league === "mls";
const flip = isMls || (match.teamB.code === "KOR" && match.teamA.code !== "KOR");
const leftShort = flip ? bShort : aShort; const leftShort = flip ? bShort : aShort;
const rightShort = flip ? aShort : bShort; const rightShort = flip ? aShort : bShort;
const hook = lang === "en" ? t.hook(leftShort, rightShort) : match.hookText; const hook =
lang === "en"
? t.hook(leftShort, rightShort)
: isMls
? `${leftShort} vs ${rightShort}` // 저장된 hookText 는 원정-홈 순이라 재구성
: match.hookText;
const url = matchUrl(match.matchId); const url = matchUrl(match.matchId);
return ( return (
@@ -69,6 +77,7 @@ export default function MatchDetail() {
<Hero <Hero
back back
lang={lang} lang={lang}
league={match.league}
share={{ share={{
url, url,
title: `${leftShort} vs ${rightShort} — TriplePick`, title: `${leftShort} vs ${rightShort} — TriplePick`,
@@ -87,6 +96,9 @@ export default function MatchDetail() {
</h1> </h1>
<MatchupHUD match={match} lang={lang} /> <MatchupHUD match={match} lang={lang} />
<LiveField match={match} lang={lang} />
{/* MLS 라이브 (축구) — 경기중에만 렌더, 야구 리그에선 null */}
<LiveSoccer match={match} lang={lang} />
<Arena <Arena
match={match} match={match}
predictions={match.predictions} predictions={match.predictions}
@@ -116,7 +128,7 @@ export default function MatchDetail() {
<span aria-hidden>→</span> <span aria-hidden>→</span>
</Link> </Link>
<Footer lang={lang} /> <Footer lang={lang} league={match.league} />
</main> </main>
); );
} }