From d4bd508618e480dd7c6890dbad64fe9b0468f1d4 Mon Sep 17 00:00:00 2001 From: sm4640 Date: Tue, 24 Mar 2026 15:45:12 +0900 Subject: [PATCH] =?UTF-8?q?Fix:=20[2.0.3]=20yt-dlp=20=EC=BF=A0=ED=82=A4=20?= =?UTF-8?q?=EC=9D=B8=EC=A6=9D=20=EC=B6=94=EA=B0=80,=20=EB=AC=B8=EC=84=9C?= =?UTF-8?q?=20=EC=97=85=EB=8D=B0=EC=9D=B4=ED=8A=B8,=20CI/CD=20.md=20?= =?UTF-8?q?=EC=8A=A4=ED=82=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - yt-dlp에 쿠키 파일(/app/cookies.txt) 지원 추가 (YouTube 봇 감지 우회) - CI/CD에 paths-ignore: **/*.md 추가하여 문서 수정 시 빌드 스킵 - 전체 문서 업데이트: 라우트 변경, 쿠키 인증 방식, n8n Expression 모드 안내 - .gitignore에 cookies.txt 추가 Co-Authored-By: Claude Opus 4.6 --- .github/workflows/deploy.yml | 2 ++ .gitignore | 1 + CLAUDE.md | 11 +++++++-- README.md | 18 +++++++++++--- app/transcript.py | 47 ++++++++++++++++++++++++++++++++---- docs/development.md | 6 +++-- docs/n8n-setup.md | 8 ++++-- docs/operations.md | 25 ++++++++++++++++++- requirements.txt | 2 +- 9 files changed, 104 insertions(+), 16 deletions(-) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 57aed3b..95f9dc7 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -3,6 +3,8 @@ name: news-summary-bot-cicd on: push: branches: ["main"] + paths-ignore: + - "**/*.md" jobs: build_push_deploy: diff --git a/.gitignore b/.gitignore index 939f18f..a36f446 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ __pycache__/ *.pyc venv/ +cookies.txt diff --git a/CLAUDE.md b/CLAUDE.md index 45dec83..1bc69a7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -25,8 +25,8 @@ docker compose up n8n(RSS 감지) → `POST /api/news/summarize` → 자막 추출 → Claude 요약 → Discord 웹훅 -- `app/main.py` — FastAPI 엔드포인트 (`/api/news/summarize`, `/api/news/health`) -- `app/transcript.py` — YouTube 자막 추출 (`youtube-transcript-api`) +- `app/main.py` — FastAPI 엔드포인트 (`/summarize`, `/health`) — Nginx가 `/api/news/` prefix를 strip +- `app/transcript.py` — YouTube 자막 추출 (`yt-dlp` + 쿠키 인증) - `app/summarizer.py` — Claude Sonnet 4.6으로 요약 생성 - `app/discord.py` — Discord 웹훅 전송 - `app/config.py` — 환경변수 설정 (pydantic-settings) @@ -35,6 +35,13 @@ n8n(RSS 감지) → `POST /api/news/summarize` → 자막 추출 → Claude 요 `ANTHROPIC_API_KEY`, `DISCORD_WEBHOOK_URL` 필수. `API_SECRET`은 선택(n8n → FastAPI 인증용). +## 쿠키 인증 (YouTube 봇 감지 우회) + +OCI 등 클라우드 서버에서 YouTube 자막 추출 시 봇 감지 차단을 우회하기 위해 쿠키 파일이 필요. +- 브라우저 확장(Get cookies.txt LOCALLY 등)으로 YouTube 쿠키를 `cookies.txt`로 export +- 서버의 `compose.apps.yml`에서 `./news-summary-bot/cookies.txt:/app/cookies.txt:ro`로 마운트 +- 쿠키 만료 시(6개월~1년) 재export 필요 → 500 에러 발생 시 쿠키 갱신 확인 + ## n8n 워크플로우 ``` diff --git a/README.md b/README.md index fde7a1c..c035e77 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ n8n (RSS 감지) → POST /api/news/summarize → 자막 추출 → Claude 요 | 모듈 | 역할 | |------|------| | `app/main.py` | FastAPI 엔드포인트 | -| `app/transcript.py` | YouTube 자막 추출 (yt-dlp) | +| `app/transcript.py` | YouTube 자막 추출 (yt-dlp + 쿠키 인증) | | `app/summarizer.py` | Claude Sonnet 4.6으로 요약 생성 | | `app/discord.py` | Discord 웹훅 전송 | | `app/config.py` | 환경변수 설정 (pydantic-settings) | @@ -45,9 +45,19 @@ docker build -t nkey/news-summary-bot . docker compose up ``` +### 쿠키 파일 (서버 배포 시 필수) + +OCI 등 클라우드 서버에서는 YouTube가 데이터센터 IP를 봇으로 감지하여 자막 추출을 차단합니다. 이를 우회하기 위해 쿠키 파일이 필요합니다. + +1. Chrome 확장 **Get cookies.txt LOCALLY**로 YouTube 쿠키 export +2. 서버에 `cookies.txt` 업로드 +3. `compose.apps.yml`에서 볼륨 마운트: `./news-summary-bot/cookies.txt:/app/cookies.txt:ro` + +> 쿠키는 6개월~1년 후 만료됩니다. 자막 추출 500 에러 발생 시 쿠키 재export가 필요합니다. + ## API -### `POST /api/news/summarize` +### `POST /api/news/summarize` (외부) / `POST /summarize` (내부) 영상 URL을 받아 자막 추출 → 요약 → Discord 전송을 수행합니다. @@ -72,10 +82,12 @@ docker compose up } ``` -### `GET /api/news/health` +### `GET /api/news/health` (외부) / `GET /health` (내부) 헬스 체크 엔드포인트. +> **참고:** Nginx가 `/api/news/` prefix를 strip하므로, FastAPI 내부 라우트는 `/summarize`, `/health`입니다. 외부에서는 `/api/news/summarize`, `/api/news/health`로 접근합니다. + ## n8n 워크플로우 ``` diff --git a/app/transcript.py b/app/transcript.py index 6fb19f8..10f9693 100644 --- a/app/transcript.py +++ b/app/transcript.py @@ -1,4 +1,5 @@ -from youtube_transcript_api import YouTubeTranscriptApi +import httpx +import yt_dlp def extract_video_id(url: str) -> str: @@ -11,9 +12,45 @@ def extract_video_id(url: str) -> str: def fetch_transcript(video_id: str) -> str: - """YouTube 자막을 텍스트로 추출.""" - ytt_api = YouTubeTranscriptApi() - transcript = ytt_api.fetch(video_id, languages=["ko", "en"]) + """yt-dlp로 YouTube 자동생성 자막을 텍스트로 추출.""" + url = f"https://www.youtube.com/watch?v={video_id}" + + ydl_opts = { + "skip_download": True, + "writeautomaticsub": True, + "subtitleslangs": ["ko", "en"], + "subtitlesformat": "json3", + "quiet": True, + "no_warnings": True, + "cookiefile": "/app/cookies.txt", + } + + with yt_dlp.YoutubeDL(ydl_opts) as ydl: + info = ydl.extract_info(url, download=False) + + subs = info.get("automatic_captions", {}) + lang = "ko" if "ko" in subs else "en" if "en" in subs else None + if not lang: + raise ValueError(f"자막을 찾을 수 없습니다: {video_id}") + + sub_url = None + for fmt in subs[lang]: + if fmt["ext"] == "json3": + sub_url = fmt["url"] + break + + if not sub_url: + raise ValueError(f"json3 자막 포맷을 찾을 수 없습니다: {video_id}") + + resp = httpx.get(sub_url) + resp.raise_for_status() + data = resp.json() + + texts = [] + for event in data.get("events", []): + for seg in event.get("segs", []): + text = seg.get("utf8", "").strip() + if text and text != "\n": + texts.append(text) - texts = [entry.text for entry in transcript if entry.text.strip()] return " ".join(texts) diff --git a/docs/development.md b/docs/development.md index 8331fd6..87a1f99 100644 --- a/docs/development.md +++ b/docs/development.md @@ -10,7 +10,7 @@ news-summary-bot/ │ ├── __init__.py │ ├── main.py # FastAPI 엔드포인트 (/summarize, /health) │ ├── config.py # pydantic-settings 환경변수 -│ ├── transcript.py # youtube-transcript-api로 자막 추출 +│ ├── transcript.py # yt-dlp + 쿠키로 자막 추출 │ ├── summarizer.py # Claude Sonnet 4.6 요약 │ └── discord.py # Discord 웹훅 전송 ├── Dockerfile @@ -79,7 +79,9 @@ curl -X POST http://localhost:8000/summarize \ ### transcript.py -YouTube URL에서 video ID를 추출하고 `youtube-transcript-api`를 사용하여 자막을 가져옵니다. 한국어(`ko`) 자막을 우선으로 시도하며, 없을 경우 영어 등 다른 언어 자막을 fallback으로 사용합니다. +YouTube URL에서 video ID를 추출하고 `yt-dlp`를 사용하여 자막을 가져옵니다. 한국어(`ko`) 자막을 우선으로 시도하며, 없을 경우 영어(`en`) 자막을 fallback으로 사용합니다. + +서버 환경에서는 YouTube 봇 감지를 우회하기 위해 `/app/cookies.txt` 쿠키 파일을 사용합니다. 로컬 개발 시에는 가정용 IP라 쿠키 없이도 동작합니다. ### summarizer.py diff --git a/docs/n8n-setup.md b/docs/n8n-setup.md index 680d6de..478fe99 100644 --- a/docs/n8n-setup.md +++ b/docs/n8n-setup.md @@ -48,12 +48,14 @@ FastAPI 서버의 `/api/news/summarize` 엔드포인트를 호출합니다. | 설정 항목 | 값 | |---|---| | Method | `POST` | -| URL | `http://<서버IP>/api/news/summarize` | +| URL | `https://nkeystudy.site/api/news/summarize` | | Body Content Type | JSON | | Body | 아래 참조 | -**Body (JSON):** +**Body 설정:** +- **Specify Body:** `Using JSON` (Expression 모드) +- **JSON:** ```json { "video_url": "{{ $json.link }}", @@ -61,6 +63,8 @@ FastAPI 서버의 `/api/news/summarize` 엔드포인트를 호출합니다. } ``` +> **주의:** 영상 제목에 큰따옴표(`"`)가 포함된 경우 JSON이 깨질 수 있습니다. 반드시 **Expression 모드**를 사용하세요 (Fixed 모드에서는 특수문자 이스케이프가 안 됩니다). + **Headers:** | 헤더 | 값 | diff --git a/docs/operations.md b/docs/operations.md index c89ca7a..69514bc 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -61,7 +61,8 @@ docker compose logs -f news-summary-bot | 증상 | 원인 | 해결 | |------|------|------| -| 자막 추출 실패 | 영상에 자막 없음 | 자동생성 자막이 없는 영상은 스킵됨 | +| 자막 추출 실패 (자막 없음) | 영상에 자막 없음 | 자동생성 자막이 없는 영상은 스킵됨 | +| 자막 추출 실패 (봇 감지) | YouTube 쿠키 만료 | 브라우저에서 쿠키 재export 후 서버에 업로드 (아래 쿠키 갱신 참고) | | Discord 전송 실패 | 웹훅 URL 만료 | Discord에서 웹훅 재생성 후 `.env` 업데이트 | | 401 Unauthorized | API_SECRET 불일치 | n8n 헤더와 `.env` 값 확인 | | Claude API 오류 | API 키 만료 또는 잔액 부족 | Anthropic 콘솔에서 확인 | @@ -69,6 +70,28 @@ docker compose logs -f news-summary-bot --- +## 쿠키 갱신 + +YouTube는 클라우드 서버 IP를 봇으로 감지하여 자막 추출을 차단합니다. 이를 우회하기 위해 브라우저 쿠키를 사용하며, 약 6개월~1년 주기로 만료됩니다. + +**만료 증상:** 자막 추출 시 500 에러 + 로그에 `Sign in to confirm you're not a bot` 메시지 + +**갱신 절차:** + +1. Chrome 확장 **Get cookies.txt LOCALLY**로 YouTube 쿠키 export +2. 서버에 업로드: + ```bash + scp cookies.txt ubuntu@nkeystudy.site:~/nkeysworld/news-summary-bot/cookies.txt + ``` +3. 컨테이너 재시작: + ```bash + docker compose -p nkeys-apps -f /nkeysworld/compose.apps.yml restart news-summary-bot + ``` + +> `compose.apps.yml`에서 `./news-summary-bot/cookies.txt:/app/cookies.txt:ro`로 마운트되어 있어야 합니다. + +--- + ## 모니터링 포인트 - `/health` 엔드포인트로 컨테이너 상태 확인 diff --git a/requirements.txt b/requirements.txt index a233eb2..3076bf0 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,6 +1,6 @@ fastapi==0.115.12 uvicorn==0.34.2 -youtube-transcript-api==1.0.3 +yt-dlp>=2025.3.31 anthropic==0.52.0 httpx==0.28.1 pydantic-settings==2.8.1