Compare commits

..
33 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
41 changed files with 2754 additions and 201 deletions

No files matched your search

+13
View File
@@ -45,6 +45,15 @@ STATUS_TICK_SECONDS=60
# 관리자 (강한 토큰으로 교체)
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모델 (실연동, 키 없으면 해당 모델 생성 생략) ──
OPENAI_API_KEY=
OPENAI_MODEL=gpt-4o
@@ -72,3 +81,7 @@ SMTP_USER=
SMTP_PASSWORD=
SMTP_FROM=TriplePick <no-reply@triplepick.app>
SMTP_STARTTLS=true
# Suno (sunoapi.org 게이트웨이) — 오늘의 응원가 자동 생성
SUNO_API_KEY=
SONGS_ENABLED=true
+29 -3
View File
@@ -87,9 +87,9 @@ class Settings(BaseSettings):
return "football-data"
return self.schedule_source.lower()
# ── 멀티리그 (wc=월드컵 축구 · kbo · mlb · mls) ──────────
# 활성 리그 (콤마구분). 야구·MLS 리그는 워커가 각자 소스에서 일정·결과를 동기화.
leagues: str = "wc,kbo,mlb,mls"
# ── 멀티리그 (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
@@ -97,6 +97,16 @@ class Settings(BaseSettings):
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"
@@ -163,6 +173,22 @@ class Settings(BaseSettings):
football_refresh_hour: 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.
# AZURE_ACS_SENDER 는 검증된 MailFrom 주소(예: donotreply@triplepick.o2o.kr).
+4
View File
@@ -15,11 +15,13 @@ from .config import settings
from .database import init_db
from .routers import (
admin,
auth,
comments,
leaderboard,
matches,
predictions,
share,
songs,
standings,
visits,
)
@@ -49,6 +51,7 @@ app.add_middleware(
allow_headers=["*"],
)
app.include_router(auth.router)
app.include_router(matches.router)
app.include_router(comments.router)
app.include_router(predictions.router)
@@ -56,6 +59,7 @@ app.include_router(leaderboard.router)
app.include_router(standings.router)
app.include_router(admin.router)
app.include_router(visits.router)
app.include_router(songs.router)
# 공유 미리보기(OG) 프리렌더 — nginx 가 크롤러 UA 의 /match/:id 만 여기로 보낸다.
app.include_router(share.router)
+119
View File
@@ -13,11 +13,13 @@ from datetime import date, datetime
from sqlalchemy import (
JSON,
BigInteger,
Boolean,
Date,
DateTime,
ForeignKey,
Integer,
LargeBinary,
String,
UniqueConstraint,
func,
@@ -250,6 +252,123 @@ class FootballCache(Base):
)
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 프롬프트 조립용.
+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)
+85 -6
View File
@@ -12,10 +12,14 @@ from __future__ import annotations
import html
from fastapi import APIRouter
from fastapi import APIRouter, Depends
from fastapi.responses import HTMLResponse
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from ..config import settings
from ..database import get_db
from ..models import Match, Song
from ..schedule_data import TEAMS
router = APIRouter()
@@ -50,8 +54,68 @@ def _team_label(code: str | None) -> str:
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)
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)
image = DEFAULT_OG
@@ -62,19 +126,34 @@ async def match_share(match_id: str) -> HTMLResponse:
image = OG_DIR + OG_IMAGES[key]
is_custom = True
# 팀명: 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":
la, lb = lb, la
league_ko = {"kbo": "KBO", "mlb": "MLB", "mls": "MLS"}.get(m.league if m else "", "")
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:
title = "TriplePick 2026 — AI 2026 글로벌 축구 축전 승부예측"
desc = "AI 셋이 매 경기를 서로 다르게 예측합니다. 당신의 픽을 찍고 AI와 겨뤄보세요."
title = "TriplePick — AI 스포츠 승부예측 (KBO·MLB·MLS)"
desc = (
"GPT·Claude·Gemini 3대 AI가 이 경기를 서로 다르게 예측합니다. "
"당신의 픽을 찍고 AI와 겨뤄보세요."
)
origin = settings.public_origin.rstrip("/")
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)
d = html.escape(desc)
# 기본 썸네일만 규격이 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}
+20 -50
View File
@@ -34,46 +34,21 @@ class MatchContext:
league: str = "wc" # wc(축구) | kbo | mlb | mls — 프롬프트·스코어 범위 분기
# 모델별 분석 관점(페르소나) — 동일 경기라도 서로 다른 시각으로 보게 해
# 예측이 자연스럽게 갈리도록 한다(강제 분산이 아니라 진짜 판단의 다양화).
PERSONA = {
"GPT": (
"You are a DATA-DRIVEN analyst. Base your call on recent form, head-to-head, "
"FIFA ranking gaps and goals-scored/conceded trends. Be objective and "
"evidence-led; pick the scoreline the numbers most support."
),
"Claude": (
"You are a TACTICAL analyst. Focus on matchups, defensive organization, "
"midfield control and game-state. Take low-scoring games, tight margins and "
"genuine upset potential seriously — do not just rubber-stamp the favorite."
),
"Gemini": (
"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."
),
}
# 공통 페르소나 — 세 모델 모두 동일한 입력(동일 프롬프트+동일 데이터)을 받는다.
# 예측 차이는 모델 자체의 판단 차이에서만 나온다.
ANALYST = (
"You are an expert soccer analyst. Use ALL of the factual match data provided "
"below — recent form, standings, head-to-head and matchup context — and weigh "
"it over your prior knowledge to make the most accurate prediction possible."
)
# 야구용 페르소나 — 축구 페르소나와 같은 3분화(데이터/수비·투수/공격) 구도.
BASEBALL_PERSONA = {
"GPT": (
"You are a DATA-DRIVEN baseball analyst. Base your call on recent form, "
"season standings, head-to-head record and run-scored/allowed trends. "
"Be objective and evidence-led; pick the scoreline the numbers most support."
),
"Claude": (
"You are a PITCHING-AND-DEFENSE analyst. Weigh starting rotation strength, "
"bullpen fatigue, and defensive quality. Take low-scoring games, tight "
"margins and genuine upset potential seriously — do not just rubber-stamp "
"the favorite."
),
"Gemini": (
"You are an OFFENSE-MINDED analyst. Weigh lineup depth, power hitting, "
"momentum and ballpark factors. Lean toward open, higher-scoring scenarios "
"when the bats and conditions justify it."
),
}
BASEBALL_ANALYST = (
"You are an expert baseball analyst. Use ALL of the factual match data provided "
"below — recent form, standings with games-behind, team batting/ERA, "
"head-to-head record, starting pitchers, confirmed lineups and yesterday's "
"results — and weigh it over your prior knowledge to make the most accurate "
"prediction possible."
)
_LEAGUE_LABEL = {
"kbo": "2026 KBO League (Korean professional baseball) regular-season game",
@@ -82,7 +57,7 @@ _LEAGUE_LABEL = {
def _prompt_baseball(ctx: MatchContext, model: str) -> str:
persona = BASEBALL_PERSONA[model]
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 "
@@ -92,9 +67,7 @@ def _prompt_baseball(ctx: MatchContext, model: str) -> str:
)
return (
f"{persona}\n"
f"Predict the result of this {_LEAGUE_LABEL[ctx.league]} using YOUR "
f"perspective above. Judge independently — it is fine to differ from the "
f"obvious consensus pick when your perspective warrants it.\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}"
@@ -115,9 +88,7 @@ def _prompt(ctx: MatchContext, persona: str) -> str:
data = f"\n{ctx.data_block}\n" if ctx.data_block else ""
return (
f"{persona}\n"
f"Predict the result of this 2026 FIFA World Cup match using YOUR perspective "
f"above. Judge independently — it is fine to differ from the obvious consensus "
f"pick when your perspective warrants it.\n"
f"Predict the result of this 2026 FIFA World Cup match.\n"
f"Team A: {ctx.team_a}\nTeam B: {ctx.team_b}\n"
f"Venue: {ctx.venue}\nKickoff: {ctx.kickoff}\n"
f"{data}"
@@ -142,8 +113,7 @@ def _prompt_mls(ctx: MatchContext, persona: str) -> str:
return (
f"{persona}\n"
f"Predict the result of this 2026 MLS (Major League Soccer) regular-season "
f"match using YOUR perspective above. Judge independently — it is fine to "
f"differ from the obvious consensus pick when your perspective warrants it.\n"
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}"
@@ -166,8 +136,8 @@ def _build_prompt(ctx: MatchContext, model: str) -> str:
if ctx.league in ("kbo", "mlb"):
return _prompt_baseball(ctx, model)
if ctx.league == "mls":
return _prompt_mls(ctx, PERSONA[model])
return _prompt(ctx, PERSONA[model])
return _prompt_mls(ctx, ANALYST)
return _prompt(ctx, ANALYST)
# JSON Schema (구조화 출력용 — Anthropic/OpenAI 공통)
+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
+47 -2
View File
@@ -89,17 +89,26 @@ def _starter_line(side: str, s: dict | None) -> str | None:
f" ({s['w']}W-{s['l']}L)"
if s.get("w") is not None and s.get("l") is not None else ""
)
vs = f", ERA vs this opponent {s['vsEra']}" if s.get("vsEra") 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')}){extra}"
f"{st.get('l')}L (pct {st.get('wra')}){gb}{ba}{era}{extra}"
)
@@ -132,6 +141,40 @@ async def _cached_extras(db, match: Match) -> list[str]:
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)
@@ -141,11 +184,13 @@ async def build_baseball_data_block(db, match: Match) -> str | 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,
"===",
])
+24 -9
View File
@@ -95,17 +95,26 @@ async def _fetch_mlb(days_back: int, days_ahead: int) -> list[dict]:
kickoff = (
datetime.fromisoformat(gd.replace("Z", "+00:00")).astimezone(KST)
)
state = (g.get("status") or {}).get("detailedState", "")
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", ""),
"cancelled": state in ("Postponed", "Cancelled", "Suspended"),
# 연기·취소 경기도 abstractGameState 는 "Final" 로 온다(스코어 없음) —
# 취소 여부는 abstract 와 무관하게 detailedState 로만 판정한다.
"cancelled": detailed.startswith(
("Postponed", "Cancelled", "Suspended")
),
"gamePk": g.get("gamePk"), # MLB 라이브 피드 키
}
if state == "Final" and not rec["cancelled"]:
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:
@@ -115,13 +124,19 @@ async def _fetch_mlb(days_back: int, days_ahead: int) -> list[dict]:
# ── 공개 API ────────────────────────────────────────────────────
async def fetch_baseball_schedule(league: str) -> list[dict]:
"""리그 일정+결과 수집 (취소 포함). 실패 시 빈 리스트 — 기존 일정 유지."""
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(settings.result_recheck_days, settings.baseball_days_ahead)
records = await _fetch_kbo(days_back, settings.baseball_days_ahead)
elif league == "mlb":
records = await _fetch_mlb(settings.result_recheck_days, settings.baseball_days_ahead)
records = await _fetch_mlb(days_back, settings.baseball_days_ahead)
else:
return []
# 더블헤더 차수 부여 — sync·정산이 같은 seq 로 경기를 식별한다.
@@ -135,6 +150,6 @@ async def fetch_baseball_schedule(league: str) -> list[dict]:
return []
async def fetch_baseball_results(league: str) -> list[dict]:
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) if "scoreA" in r]
return [r for r in await fetch_baseball_schedule(league, days_back) if "scoreA" in r]
+51 -9
View File
@@ -4,7 +4,8 @@ ESPN site API 는 키 불필요·비공식. 응답 표준 레코드는 야구와
({league, teamA(원정), teamB(홈), dateKst, kickoffKst, venue, cancelled,
[scoreA, scoreB]})라 sync_baseball_schedule/settle 파이프라인을 그대로 탄다.
- 일정: scoreboard?dates=YYYYMMDD-YYYYMMDD (dates 는 미국 동부 기준 날짜라
- 일정: scoreboard?dates=YYYYMMDD 또는 YYYYMM (범위 조회는 ESPN 이 400 반환 →
_fetch_events 가 일/월 단위로 분할. dates 는 미국 동부 기준 날짜라
KST 매칭은 이벤트의 UTC 시각을 KST 로 환산해 산출)
- 순위: 동부/서부 컨퍼런스 → standings:mls 캐시 (승점제)
- 프리뷰: scoreboard 의 form(최근5)·records(시즌 W-D-L)·odds(머니라인)
@@ -18,7 +19,7 @@ import logging
import re
import time
import unicodedata
from datetime import datetime, timedelta, timezone
from datetime import date, datetime, timedelta, timezone
from difflib import SequenceMatcher
from ..config import settings
@@ -89,11 +90,48 @@ def _parse_event(e: dict) -> dict | None:
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]:
r = await client.get(_sb_url(dates))
r.raise_for_status()
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)
@@ -105,14 +143,18 @@ def _clean(rec: dict) -> dict:
return {k: v for k, v in rec.items() if not k.startswith("_")}
async def fetch_mls_schedule() -> list[dict]:
"""일정+결과 수집 (취소 포함). 실패 시 빈 리스트 — 기존 일정 유지."""
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=settings.mls_days_back + 1)
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:
@@ -130,9 +172,9 @@ async def fetch_mls_schedule() -> list[dict]:
return []
async def fetch_mls_results() -> list[dict]:
async def fetch_mls_results(days_back: int | None = None) -> list[dict]:
"""확정 스코어만 → 정산(settle) 입력."""
return [r for r in await fetch_mls_schedule() if "scoreA" in r]
return [r for r in await fetch_mls_schedule(days_back) if "scoreA" in r]
# ── 순위 (동/서부 컨퍼런스, 승점제) ─────────────────────────────
+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
+72 -13
View File
@@ -19,7 +19,7 @@ from __future__ import annotations
import asyncio
import logging
from datetime import timedelta
from datetime import timedelta, timezone
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from sqlalchemy import select
@@ -32,12 +32,13 @@ from .models import AIPrediction, Match, UserPrediction
from .scoring import load_scoring_data
from .services import baseball_data, baseball_details, football_data, mls_espn
from .services.ai import MatchContext, PROVIDERS, ProviderUnavailable
from .services.baseball_fetch import fetch_baseball_results, fetch_baseball_schedule
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.grading import apply_result
from .services.schedule_fetch import fetch_results, fetch_schedule
from .services.schedule_sync import sync_schedule
from .services.songs import tick_songs
logging.basicConfig(level=logging.INFO)
log = logging.getLogger("triplepick.worker")
@@ -327,6 +328,10 @@ async def settle_matches() -> None:
# ── 2.6) 야구·MLS 결과 자동 정산 — (리그, KST 날짜, 팀쌍) 키 매칭 ──
# 킥오프 후 이 시간이 지나도록 소스 일정에 없는 미정산 경기는 취소로 본다.
_VANISHED_GRACE = timedelta(hours=24)
async def settle_baseball() -> None:
_KST = timedelta(hours=9)
now = now_utc()
@@ -343,33 +348,81 @@ async def settle_baseball() -> None:
)
)
).scalars().all()
due = [m.match_id for m in pending if ensure_aware(m.kickoff_at) <= now]
if not due:
due_matches = [m for m in pending if ensure_aware(m.kickoff_at) <= now]
if not due_matches:
continue
results = (
await mls_espn.fetch_mls_results()
if league == "mls"
else await fetch_baseball_results(league)
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]] = {}
for r in results:
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 = 0
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")
sc = by_key.get((d, m.team_a_code, m.team_b_code, match_seq(mid)))
if not sc:
continue
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()
@@ -496,6 +549,12 @@ def build_scheduler() -> AsyncIOScheduler:
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
+2
View File
@@ -10,6 +10,8 @@ aiosmtplib==3.0.2
azure-communication-email==1.0.0
aiohttp==3.10.11
httpx==0.27.2
python-jose[cryptography]==3.5.0
anthropic==0.69.0
openai==1.59.6
google-genai==0.8.0
pillow==11.1.0
+35 -18
View File
@@ -5,23 +5,31 @@
<link rel="icon" href="/icons/profile.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<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
name="description"
content="GPT·Claude·Gemini가 매 경기를 서로 다르게 예측합니다. 당신의 픽을 찍고 AI와 겨뤄보세요. 끝까지 잘 맞히면 100만 원 챌린지."
content="프로야구 승부예측(KBO)부터 해외야구 승부예측(MLB 메이저리그), MLS까지 — GPT·Claude·Gemini 3대 AI가 매 경기를 서로 다르게 예측합니다. 실시간 스코어·문자중계를 보며 당신의 픽을 찍고 AI와 겨뤄보세요. 무료 참여."
/>
<!-- 공유 썸네일 (Open Graph / Twitter) — 카카오톡 등 소셜 미리보기 -->
<meta property="og:type" content="website" />
<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
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:image" 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" />
<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?v=2" />
<meta property="og:image:type" content="image/png" />
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
@@ -29,12 +37,12 @@
<meta property="og:locale" content="ko_KR" />
<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
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" />
@@ -42,7 +50,7 @@
<meta name="naver-site-verification" content="d31508b6376797f7a8c587e4f60b72ffb6c7407c" />
<!-- 검색 키워드 / 색인 지시 -->
<meta name="keywords" content="트리플픽, AI승부예측, 스포츠 승부예측, 축구 승부예측, GPT 예측, 클로드 예측, 제미나이 예측, AI vs 사람, 축구 예측 이벤트, TriplePick" />
<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/" />
@@ -58,7 +66,7 @@
"alternateName": "트리플픽",
"url": "https://triplepick.o2o.kr/",
"logo": "https://triplepick.o2o.kr/assets/bi/og-image.png",
"description": "GPT·Claude·Gemini 3대 AI가 같은 경기 데이터로 승패·스코어·승리확률을 예측·비교하는 참여형 축구 승부예측 서비스.",
"description": "GPT·Claude·Gemini 3대 AI가 같은 경기 데이터로 승패·스코어·승리확률을 예측·비교하는 참여형 스포츠 승부예측 서비스. KBO 프로야구 승부예측·MLB 해외야구 승부예측·MLS 지원.",
"sameAs": [
"https://www.youtube.com/channel/UCIiFvxaahQA-rLP8KpkDM0w",
"https://www.instagram.com/triplepickai"
@@ -78,7 +86,7 @@
"@type": "WebSite",
"@id": "https://triplepick.o2o.kr/#website",
"url": "https://triplepick.o2o.kr/",
"name": "TriplePick — AI 축구 승부예측 아레나",
"name": "TriplePick — AI 스포츠 승부예측 아레나",
"inLanguage": "ko-KR",
"publisher": { "@id": "https://triplepick.o2o.kr/#organization" }
},
@@ -90,7 +98,7 @@
"operatingSystem": "Web",
"inLanguage": "ko-KR",
"offers": { "@type": "Offer", "price": "0", "priceCurrency": "KRW" },
"description": "GPT·Claude·Gemini의 예측을 확인하고 직접 승패와 스코어를 찍어 AI와 겨루는 무료·비로그인 참여형 축구 승부예측 서비스."
"description": "GPT·Claude·Gemini의 예측을 확인하고 직접 승패와 스코어를 찍어 AI와 겨루는 무료 참여형 스포츠 승부예측 서비스. KBO 프로야구·MLB 해외야구·MLS 경기 지원, 실시간 스코어·문자중계 제공."
}
]
}
@@ -101,19 +109,28 @@
<!-- 크롤 가능 본문 폴백(SPA 빈 root 보완). React 마운트 시 실제 앱으로 교체됨.
⚠️ CSS로 숨기지 말 것(클로킹 페널티) — 보이게 두면 React가 즉시 덮음. -->
<div class="seo-fallback">
<h1>트리플픽 — GPT·Claude·Gemini AI 축구 승부예측 대결</h1>
<h1>트리플픽 — GPT·Claude·Gemini AI 스포츠 승부예측 대결</h1>
<p>
트리플픽(TriplePick)은 AI승부예측 서비스입니다. GPT·Claude·Gemini 3대 AI가
같은 경기 데이터로 승패·스코어·승리확률을 서로 다르게 예측하고, 당신은 직접
스포츠 승부예측 픽을 찍어 AI와 겨룹니다. 2026 글로벌 축구 축전 전 경기를 대상으로
무료·비로그인으로 참여할 수 있으며, 끝까지 잘 맞히면 100만 원 챌린지 상금에 도전합니다.
스포츠 승부예측 픽을 찍어 AI와 겨룹니다. KBO 프로야구·MLB·MLS 전 경기를
대상으로 무료로 참여할 수 있습니다.
</p>
<h2>트리플픽은 이런 축구 승부예측 서비스입니다</h2>
<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>
<li>무료 참여 — 카카오 간편 로그인 지원</li>
</ul>
<p>
AI 셋이 갈렸을 때, 당신의 픽은 누구와 같을까요? 트리플픽에서 스포츠 승부예측을
+6
View File
@@ -29,6 +29,12 @@ server {
if ($is_share_crawler) { return 418; }
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 {
proxy_pass http://api:8000;
proxy_set_header Host $host;
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+14 -9
View File
@@ -1,20 +1,25 @@
# TriplePick (트리플픽)
> GPT·Claude·Gemini 3대 AI가 같은 경기 데이터로 승패·스코어·승리확률을 서로 다르게 예측·비교하고, 사용자가 직접 픽을 찍어 AI와 겨루는 참여형 축구 승부예측 서비스. 무료·비로그인 참여, 100만 원 챌린지.
> GPT·Claude·Gemini 3대 AI가 같은 경기 데이터로 승패·스코어·승리확률을 서로 다르게 예측·비교하고, 사용자가 직접 픽을 찍어 AI와 겨루는 참여형 스포츠 승부예측 서비스. 월드컵·KBO 프로야구·MLB·MLS 4개 리그 지원, 무료 참여.
## 핵심 정보
- 서비스명: TriplePick (트리플픽)
- 카테고리: AI승부예측 · 스포츠 승부예측 · 축구 승부예측
- 대상: 2026 글로벌 축구 축전 전 경기
- 카테고리: AI승부예측 · 스포츠 승부예측 · 축구/야구 승부예측
- 대상 리그: 2026 글로벌 축구 축전(월드컵) · KBO 프로야구 · MLB · MLS
- AI 모델: GPT, Claude, Gemini (3종 동시 예측·비교)
- 참여: 무료, 비로그인, 승패·정확 스코어 픽
- 참여: 무료, 승패·정확 스코어 픽 (카카오 간편 로그인 지원)
- 부가 기능: 진행 중 경기 실시간 스코어·문자중계, 팀 순위표, AI 프리뷰
- 운영: AIO2O / ADO2
## 주요 링크
- 홈: https://triplepick.o2o.kr/
- 경기 상세: https://triplepick.o2o.kr/match/{조}_{홈}_{원정}_{YYYYMMDD} (당일 경기별, 예: /match/I_FRA_SEN_20260617)
- 홈(월드컵): 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승부예측 서비스입니다.
- 어떻게 참여하나요? 로그인 없이 홈에서 경기를 고르고 승패·스코어를 찍으면 됩니다.
- 상금이 있나요? 끝까지 잘 맞히면 100만 원 챌린지에 도전할 수 있습니다.
- 트리플픽이 뭔가요? GPT·Claude·Gemini 세 AI의 경기 예측을 비교하고, 내가 직접 픽을 찍어 AI와 적중률을 겨루는 무료 AI승부예측 서비스입니다.
- 어떤 경기를 예측할 수 있나요? 2026 월드컵과 KBO 프로야구·MLB·MLS 경기를 예측할 수 있습니다.
- 어떻게 참여하나요? 홈에서 리그와 경기를 고르고 승패·스코어를 찍으면 됩니다. 카카오 간편 로그인을 지원합니다.
- 경기 중에는 뭘 볼 수 있나요? 실시간 스코어와 문자중계(투구·타석·득점 등 주요 장면)를 볼 수 있습니다.
+11 -4
View File
@@ -1,21 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
<channel>
<title>TriplePick — AI 축구 승부예측</title>
<title>TriplePick — AI 스포츠 승부예측</title>
<link>https://triplepick.o2o.kr/</link>
<description>GPT·Claude·Gemini 3대 AI가 매 경기를 예측·비교하는 참여형 축구 승부예측. 경기별 예측·결과 업데이트.</description>
<description>GPT·Claude·Gemini 3대 AI가 월드컵·KBO·MLB·MLS 매 경기를 예측·비교하는 참여형 스포츠 승부예측. 경기별 예측·결과 업데이트.</description>
<language>ko-KR</language>
<lastBuildDate>Wed, 17 Jun 2026 00:00:00 +0900</lastBuildDate>
<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>
<description>3대 AI의 예측을 비교하고 직접 픽을 찍어 AI와 겨루는 무료 AI승부예측 서비스.</description>
<pubDate>Wed, 17 Jun 2026 00:00:00 +0900</pubDate>
<guid>https://triplepick.o2o.kr/</guid>
</item>
+22 -2
View File
@@ -1,14 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<!-- 홈 (캠페인 1순위 홍보 URL) -->
<!-- 홈 = 월드컵 대시보드 (캠페인 1순위 홍보 URL) -->
<url>
<loc>https://triplepick.o2o.kr/</loc>
<lastmod>2026-06-17</lastmod>
<lastmod>2026-08-20</lastmod>
<changefreq>daily</changefreq>
<priority>1.0</priority>
</url>
<!-- 리그별 대시보드 (2026-08 멀티리그 확장: KBO·MLB·MLS) -->
<url>
<loc>https://triplepick.o2o.kr/?league=kbo</loc>
<lastmod>2026-08-20</lastmod>
<changefreq>daily</changefreq>
<priority>0.9</priority>
</url>
<url>
<loc>https://triplepick.o2o.kr/?league=mlb</loc>
<lastmod>2026-08-20</lastmod>
<changefreq>daily</changefreq>
<priority>0.9</priority>
</url>
<url>
<loc>https://triplepick.o2o.kr/?league=mls</loc>
<lastmod>2026-08-20</lastmod>
<changefreq>daily</changefreq>
<priority>0.9</priority>
</url>
<!--
매치 상세 페이지는 의도적으로 제외했습니다.
라이브 사이트의 매치 URL은 날짜별로 매일 바뀌는 동적 경로이며
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

+9 -1
View File
@@ -1,5 +1,5 @@
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 MatchDetail from "./pages/MatchDetail";
import Leaderboard from "./pages/Leaderboard";
@@ -8,6 +8,13 @@ import { recordVisit } from "./lib/api";
import { PlayerProvider } from "./lib/usePlayer";
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() {
// 접속 시 1회 방문 기록 (하루 1기기 1회 집계는 백엔드가 처리)
useEffect(() => {
@@ -19,6 +26,7 @@ export default function App() {
<Routes>
<Route path="/" element={<Dashboard />} />
<Route path="/match/:matchId" element={<MatchDetail />} />
<Route path="/song/:matchId/:teamCode" element={<SongShareRedirect />} />
<Route path="/leaderboard" element={<Leaderboard />} />
<Route path="*" element={<NotFound />} />
</Routes>
+6
View File
@@ -1,6 +1,7 @@
import { useEffect, useMemo, useState } from "react";
import { outcomeLabel, pctParts, kickoffDisplay, winProb } from "@/lib/format";
import { type Lang, dict, teamShort } from "@/lib/i18n";
import { useAuth } from "@/lib/auth";
import type {
Outcome,
CrowdStats,
@@ -112,6 +113,11 @@ export default function Arena({
const [step, setStep] = useState<Step>("form");
const [recentEmails, setRecentEmails] = useState<string[]>(getRecentEmails);
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 [crowd, setCrowd] = useState<CrowdStats>(initialCrowd);
const [copied, setCopied] = useState(false);
+54 -2
View File
@@ -2,8 +2,54 @@ import { Link, useNavigate } from "react-router-dom";
import ShareButton from "./ShareButton";
import LangSwitch from "./LangSwitch";
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 };
// 브랜드 헤더 (대시보드·상세 공용). 경기별 후킹 카피는 상세 페이지에서 별도 노출.
@@ -31,7 +77,7 @@ export default function Hero({
};
return (
<header className="pt-5 text-center">
{back && (
{back ? (
<div className="mb-3 flex items-center justify-between">
<Link
to={home}
@@ -40,9 +86,16 @@ export default function Hero({
>
{t.back}
</Link>
<span className="flex items-center gap-2">
<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 className="font-impact text-[44px] leading-none tracking-tight">
@@ -80,7 +133,6 @@ export default function Hero({
function LeagueTabs({ lang, current }: { lang: Lang; current: League }) {
const navigate = useNavigate();
const tabs: { key: League; label: string }[] = [
{ key: "wc", label: lang === "en" ? "World Cup" : "월드컵" },
{ key: "kbo", label: "KBO" },
{ key: "mlb", label: "MLB" },
{ key: "mls", label: "MLS" },
+76 -1
View File
@@ -1,11 +1,76 @@
import { useEffect, useRef, useState } from "react";
import type { Match, TeamStanding } from "@/lib/types";
import { kickoffDisplay } from "@/lib/format";
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 { FormBadges } from "./ScheduleBoard";
import TeamFlag from "./TeamFlag";
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,
@@ -103,9 +168,14 @@ export default function MatchupHUD({ match, lang = "ko" }: { match: Match; lang?
</div>
</div>
{/* 국기/로고 + 라이트닝 VS (종료 시 최종 스코어) */}
{/* 국기/로고 + 라이트닝 VS (종료 시 최종 스코어) + 팀별 응원가 버튼(KBO) */}
<div className="mt-5 grid grid-cols-[1fr_auto_1fr] items-center gap-3">
<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="vs-glow absolute h-28 w-28" />
{finished && match.result ? (
@@ -123,7 +193,12 @@ export default function MatchupHUD({ match, lang = "ko" }: { match: Match; lang?
</span>
)}
</div>
<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>
{/* 야구 정보 패널: 선발 매치업 · 순위 · 시즌 상대전적 (캐시 있을 때만) */}
+110 -11
View File
@@ -1,9 +1,9 @@
import { useEffect } from "react";
import { useEffect, useState } from "react";
import { useLocation } from "react-router-dom";
import { usePlayer } from "@/lib/usePlayer";
import { useLang } from "@/lib/useLang";
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>
);
}
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 }) {
if (level === 0) {
return (
@@ -145,20 +166,44 @@ export default function MusicBar() {
loadPlaylist,
} = usePlayer();
// 경로가 바뀌면 해당 경로의 플레이리스트 로드, 없으면 초기화
// 경로가 바뀌면 해당 경로의 자동 플레이리스트 로드(월드컵 특설), 그 외는 초기화.
// KBO 응원가는 상세 페이지 '응원가 듣기' 버튼이 loadPlaylist 로 직접 채운다.
useEffect(() => {
const tracks = PATH_PLAYLISTS[pathname];
loadPlaylist(tracks ?? []);
loadPlaylist(getTracksForPath(pathname));
}, [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 visible = VISIBLE_PATHS.some(
(p: string) => pathname === p || pathname.startsWith(p)
);
if (!visible) return null;
const doShare = async () => {
const tr = currentTrack;
if (!tr?.shareUrl) return;
const text = tr.shareText ?? tr.title;
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 rect = e.currentTarget.getBoundingClientRect();
@@ -233,6 +278,29 @@ export default function MusicBar() {
<div className="relative">
<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
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)" }}
@@ -329,6 +397,37 @@ export default function MusicBar() {
style={{ width: `${displayVolume * 100}%`, background: "rgba(255,255,255,0.85)" }}
/>
</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>
+124 -37
View File
@@ -3,7 +3,7 @@ import { Link } from "react-router-dom";
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 { League, Match, MatchPhase } from "@/lib/types";
import type { League, Match, MatchPhase, ModelName, Outcome } from "@/lib/types";
import TeamFlag from "./TeamFlag";
import StandingsTable from "./StandingsTable";
@@ -18,11 +18,11 @@ function shortDate(iso: string, lang: Lang): string {
const PHASE_CLS: Record<MatchPhase, string> = {
open: "border-[#94FBE0] text-[#94FBE0]",
scheduled: "border-[var(--line-d)] text-[var(--ink-muted)]",
locked: "border-[var(--line-d)] text-white/45",
scheduled: "border-white/20 text-white/60",
locked: "border-white/20 text-white/60",
live: "border-[#FF5B5B] text-[#FF5B5B]",
finished: "border-white/15 text-white/55",
cancelled: "border-white/10 text-white/35",
finished: "border-white/25 text-white/70",
cancelled: "border-white/10 text-white/40",
};
// 토너먼트 탭 라운드 칩 정렬(대진 순서)
@@ -99,13 +99,19 @@ export default function ScheduleBoard({
);
}, [matches, isBaseball, lang]);
// 기본 선택: 오늘(없으면 첫 날짜) / A조 / 현재 진행 라운드.
// 기본 선택: 오늘(경기 없으면 다음 경기일, 시즌 종료면 마지막 날짜) / A조 / 현재 진행 라운드.
// 단, 직전 세션 선택을 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 saved = sessionStorage.getItem("tp.sched.date");
if (saved && dates.includes(saved)) return saved;
return (dates.includes(todayKey) ? todayKey : dates[0]) ?? "";
return defaultDate(dates, todayKey);
});
const [selGroup, setSelGroup] = useState(() => {
const saved = sessionStorage.getItem("tp.sched.group");
@@ -140,7 +146,11 @@ export default function ScheduleBoard({
useEffect(() => {
if (dates.length && !dates.includes(selDate)) {
setSelDate(dates.includes(todayKey) ? todayKey : dates[0]);
// 목록이 비동기 로드될 때도 세션 복원이 동작하게 saved 를 우선 확인
const saved = sessionStorage.getItem("tp.sched.date");
setSelDate(
saved && dates.includes(saved) ? saved : defaultDate(dates, todayKey),
);
}
}, [dates, selDate, todayKey]);
// 리그 전환 시 목록에 없는 팀이면 첫 팀으로
@@ -191,7 +201,7 @@ export default function ScheduleBoard({
<section className="mt-6">
<div className="mb-3 flex items-baseline gap-2.5">
<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>
{/* 탭: 축구 = 날짜별/조별리그/토너먼트 · 야구 = 날짜별/팀별 */}
@@ -203,7 +213,7 @@ export default function ScheduleBoard({
className={`-mb-px border-b-2 pb-2 text-[15px] font-bold transition ${
effTab === k
? "border-[var(--green)] text-white"
: "border-transparent text-white/45"
: "border-transparent text-white/60"
}`}
>
{tabLabel(k)}
@@ -216,7 +226,18 @@ export default function ScheduleBoard({
{/* 칩: 날짜 / 조 / 라운드 — 단일 줄 가로 스크롤 + 양 끝 화살표(PC에서 마우스로 넘김, 끝 도달 시 숨김) */}
{effTab !== "rank" && (
<ChipScroller resetKey={`${league}:${effTab}`}>
<ChipScroller
resetKey={`${league}:${effTab}`}
centerKey={
effTab === "date"
? selDate
: effTab === "team"
? selTeam
: effTab === "group"
? selGroup
: selRound
}
>
{effTab === "date"
? dates.map((d) => (
<Chip key={d} active={d === selDate} onClick={() => setSelDate(d)}>
@@ -250,7 +271,7 @@ export default function ScheduleBoard({
{effTab !== "rank" && (
<div className="flex flex-col gap-2.5">
{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">
{effTab === "tournament"
? lang === "en"
? "Bracket is set after the group stage."
@@ -274,9 +295,11 @@ export default function ScheduleBoard({
function ChipScroller({
children,
resetKey,
centerKey,
}: {
children: React.ReactNode;
resetKey?: string | number;
centerKey?: string; // 현재 선택값 — 바뀔 때마다 선택 칩을 가운데로 (비동기 로드·칩 클릭 포함)
}) {
const ref = useRef<HTMLDivElement>(null);
const [atStart, setAtStart] = useState(true);
@@ -290,7 +313,7 @@ function ChipScroller({
setAtEnd(el.scrollLeft >= max - 1);
};
// 탭/목록 변경 시: 선택된 칩을 가운데로 + 재측정 (레이아웃 확정 후)
// 탭/목록/선택 변경 시: 선택된 칩을 가운데로 + 재측정 (레이아웃 확정 후)
// 선택 칩이 없으면 맨 앞으로 되감는다.
useLayoutEffect(() => {
const el = ref.current;
@@ -301,7 +324,7 @@ function ChipScroller({
: 0;
}
measure();
}, [resetKey]);
}, [resetKey, centerKey]);
useEffect(() => {
measure();
@@ -371,7 +394,7 @@ function Chip({
className={`shrink-0 whitespace-nowrap rounded-full border px-3.5 py-1.5 text-[13px] font-bold transition ${
active
? "border-[#94FBE0] text-[#94FBE0]"
: "border-[var(--line-d)] text-white/55"
: "border-white/20 text-white/70"
}`}
>
{children}
@@ -381,7 +404,7 @@ function Chip({
// MLS 최근 5경기 폼 — "WWLDW" 를 W/D/L 색으로 표시
export function FormBadges({ form }: { form?: string | null }) {
if (!form) return <span className="text-white/35">?</span>;
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) => (
@@ -392,7 +415,7 @@ export function FormBadges({ form }: { form?: string | null }) {
? "text-[#94FBE0]"
: c === "L"
? "text-[#FF5B5B]/80"
: "text-white/45"
: "text-white/60"
}
>
{c}
@@ -406,12 +429,35 @@ export function FormBadges({ form }: { form?: string | null }) {
function RankBadge({ rank, lang = "ko" }: { rank?: number | null; lang?: Lang }) {
if (!rank) return null;
return (
<span className="shrink-0 rounded border border-white/15 px-1 py-px text-[10px] font-bold text-white/45">
<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,
@@ -467,24 +513,41 @@ function MatchCard({
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)는 상세로 이동
const inner = (
<>
<div className="flex items-center justify-between text-[11px]">
<span className="font-mono font-bold text-white/70">
<div className="flex items-center justify-between text-[12px]">
<span className="font-mono font-bold text-white/85">
{showDate && (
<span className="text-white/55">{shortDate(dateKey(match.kickoffKst), lang)} </span>
<span className="text-white/65">{shortDate(dateKey(match.kickoffKst), lang)} </span>
)}
{timeOnly(match.kickoffKst)} <span className="text-white/40">KST</span>
{timeOnly(match.kickoffKst)} <span className="text-white/55">KST</span>
{isClub && match.venue ? (
<span className="text-white/40"> · {match.venue}</span>
<span className="text-white/55"> · {match.venue}</span>
) : match.group && match.roundLabel ? (
<> · {tRound(match.roundLabel, lang)}</>
) : null}
</span>
<span className="flex items-center gap-1.5">
{!isClub && (
<span className="text-[11px] font-bold text-white/45">
<span className="text-[11px] font-bold text-white/60">
{match.group
? lang === "en"
? `Group ${match.group}`
@@ -525,8 +588,18 @@ function MatchCard({
<span className="px-1.5 text-[#FF5B5B]">:</span>
{(flip ? live.score.away : live.score.home) ?? 0}
</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">
{isClub && <RankBadge rank={rightSt?.rank} lang={lang} />}
@@ -535,33 +608,47 @@ function MatchCard({
</div>
</div>
{/* AI 픽: 각 모델 아이콘을 픽한 팀 아래에 표시 (무승부 픽은 가운데) */}
{showAiRow && (
<div
className="mt-1.5 grid grid-cols-[1fr_auto_1fr] items-center gap-2"
aria-label={`${t.aiPicks}: ${aiSplit(match, lang).join(", ")}`}
>
<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-[11px] font-semibold text-white/50">
<span className="text-white/35">{lang === "en" ? "SP" : "선발"}</span>{" "}
<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/30">vs</span>
<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-[11px] font-semibold text-white/50">
<span className="text-white/35">{lang === "en" ? "Last 5" : "최근 5경기"}</span>{" "}
<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/30">vs</span>
<span className="px-1 text-white/45">vs</span>
<FormBadges form={match.extras?.formA} />
</div>
)}
{/* 투표 가능 조만: AI 픽 갈림 + 참여수 + 이동 화살표 (취소 경기는 숨김) */}
{/* 투표 가능 조만: 참여수 + 이동 화살표 (AI 픽은 위의 아이콘 행이 담당, 취소 경기는 숨김) */}
{match.votable && phase !== "cancelled" && (
<div className="mt-3 flex items-center justify-between text-[11px] font-bold text-[#F4F3FE]">
<span>
<span className="font-semibold text-white/55">{t.aiPicks}</span>{" "}
{aiSplit(match, lang).join(" · ")}
</span>
<div className="mt-3 flex items-center justify-end text-[12px] font-bold text-[#F4F3FE]">
<span className="flex items-center gap-2">
<span>{t.joined((match.crowd?.total ?? 0).toLocaleString())}</span>
<span className="text-[#94FBE0]">→</span>
+2 -2
View File
@@ -42,8 +42,8 @@ body {
body {
font-family:
"Pretendard", -apple-system, BlinkMacSystemFont, system-ui,
"Apple SD Gothic Neo", "Malgun Gothic", sans-serif;
"Pretendard Variable", "Pretendard", -apple-system, BlinkMacSystemFont,
system-ui, "Apple SD Gothic Neo", "Malgun Gothic", sans-serif;
margin: 0;
}
+28
View File
@@ -43,6 +43,34 @@ export class ApiError extends Error {
}
}
// ── 오늘의 응원가 ────────────────────────────────────────────
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}` : ""}`);
}
+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 };
}
+63 -19
View File
@@ -7,25 +7,69 @@ export type Track = {
src: string;
/** 앨범 아트 이미지 경로 또는 URL */
cover?: string;
/** 가사 (오늘의 응원가) — 있으면 플레이어에 '가사 보기' 노출 */
lyrics?: string;
/** 공유 링크·문구 — 있으면 플레이어에 '공유하기' 노출 */
shareUrl?: string;
shareText?: string;
};
// 경로별 플레이리스트 — 키가 표시할 경로, 값이 해당 경로의 트랙 목록
// VISIBLE_PATHS는 이 맵의 키에서 자동 생성됩니다.
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" },
],
};
// 경로별 정적 플레이리스트 — 월드컵 종료로 비움 (구조는 특설 대비 유지)
export const PATH_PLAYLISTS: Record<string, Track[]> = {};
// VISIBLE_PATHS — PATH_PLAYLISTS 키에서 자동 도출 (직접 수정 불필요)
export const VISIBLE_PATHS: string[] = Object.keys(PATH_PLAYLISTS);
// 경로 → 자동 로드 트랙 목록 — 정확일치(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);
}
+2 -3
View File
@@ -8,10 +8,9 @@ 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 === "wc" || raw === "kbo" || raw === "mlb" || raw === "mls"
? raw
: DEFAULT_LEAGUE;
raw === "kbo" || raw === "mlb" || raw === "mls" ? raw : DEFAULT_LEAGUE;
const setLeague = (l: League) => {
const next = new URLSearchParams(params);
next.set("league", l);
+3
View File
@@ -2,8 +2,11 @@ import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import App from "./App";
import { captureAuthTokens } from "./lib/auth";
import "./globals.css";
captureAuthTokens(); // 카카오 콜백 해시(#access_token=..) 캡처 — 라우터 마운트 전에
createRoot(document.getElementById("root")!).render(
<StrictMode>
<BrowserRouter>