Fix: [2.0.3] yt-dlp 쿠키 인증 추가, 문서 업데이트, CI/CD .md 스킵
All checks were successful
news-summary-bot-cicd / build_push_deploy (push) Successful in 4m40s

- yt-dlp에 쿠키 파일(/app/cookies.txt) 지원 추가 (YouTube 봇 감지 우회)
- CI/CD에 paths-ignore: **/*.md 추가하여 문서 수정 시 빌드 스킵
- 전체 문서 업데이트: 라우트 변경, 쿠키 인증 방식, n8n Expression 모드 안내
- .gitignore에 cookies.txt 추가

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
sm4640
2026-03-24 15:45:12 +09:00
parent aaf5bd8d05
commit d4bd508618
9 changed files with 104 additions and 16 deletions

View File

@@ -3,6 +3,8 @@ name: news-summary-bot-cicd
on: on:
push: push:
branches: ["main"] branches: ["main"]
paths-ignore:
- "**/*.md"
jobs: jobs:
build_push_deploy: build_push_deploy:

1
.gitignore vendored
View File

@@ -2,3 +2,4 @@
__pycache__/ __pycache__/
*.pyc *.pyc
venv/ venv/
cookies.txt

View File

@@ -25,8 +25,8 @@ docker compose up
n8n(RSS 감지) → `POST /api/news/summarize` → 자막 추출 → Claude 요약 → Discord 웹훅 n8n(RSS 감지) → `POST /api/news/summarize` → 자막 추출 → Claude 요약 → Discord 웹훅
- `app/main.py` — FastAPI 엔드포인트 (`/api/news/summarize`, `/api/news/health`) - `app/main.py` — FastAPI 엔드포인트 (`/summarize`, `/health`) — Nginx가 `/api/news/` prefix를 strip
- `app/transcript.py` — YouTube 자막 추출 (`youtube-transcript-api`) - `app/transcript.py` — YouTube 자막 추출 (`yt-dlp` + 쿠키 인증)
- `app/summarizer.py` — Claude Sonnet 4.6으로 요약 생성 - `app/summarizer.py` — Claude Sonnet 4.6으로 요약 생성
- `app/discord.py` — Discord 웹훅 전송 - `app/discord.py` — Discord 웹훅 전송
- `app/config.py` — 환경변수 설정 (pydantic-settings) - `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 인증용). `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 워크플로우 ## n8n 워크플로우
``` ```

View File

@@ -11,7 +11,7 @@ n8n (RSS 감지) → POST /api/news/summarize → 자막 추출 → Claude 요
| 모듈 | 역할 | | 모듈 | 역할 |
|------|------| |------|------|
| `app/main.py` | FastAPI 엔드포인트 | | `app/main.py` | FastAPI 엔드포인트 |
| `app/transcript.py` | YouTube 자막 추출 (yt-dlp) | | `app/transcript.py` | YouTube 자막 추출 (yt-dlp + 쿠키 인증) |
| `app/summarizer.py` | Claude Sonnet 4.6으로 요약 생성 | | `app/summarizer.py` | Claude Sonnet 4.6으로 요약 생성 |
| `app/discord.py` | Discord 웹훅 전송 | | `app/discord.py` | Discord 웹훅 전송 |
| `app/config.py` | 환경변수 설정 (pydantic-settings) | | `app/config.py` | 환경변수 설정 (pydantic-settings) |
@@ -45,9 +45,19 @@ docker build -t nkey/news-summary-bot .
docker compose up 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 ## API
### `POST /api/news/summarize` ### `POST /api/news/summarize` (외부) / `POST /summarize` (내부)
영상 URL을 받아 자막 추출 → 요약 → Discord 전송을 수행합니다. 영상 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 워크플로우 ## n8n 워크플로우
``` ```

View File

@@ -1,4 +1,5 @@
from youtube_transcript_api import YouTubeTranscriptApi import httpx
import yt_dlp
def extract_video_id(url: str) -> str: 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: def fetch_transcript(video_id: str) -> str:
"""YouTube 자막을 텍스트로 추출.""" """yt-dlp로 YouTube 자동생성 자막을 텍스트로 추출."""
ytt_api = YouTubeTranscriptApi() url = f"https://www.youtube.com/watch?v={video_id}"
transcript = ytt_api.fetch(video_id, languages=["ko", "en"])
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) return " ".join(texts)

View File

@@ -10,7 +10,7 @@ news-summary-bot/
│ ├── __init__.py │ ├── __init__.py
│ ├── main.py # FastAPI 엔드포인트 (/summarize, /health) │ ├── main.py # FastAPI 엔드포인트 (/summarize, /health)
│ ├── config.py # pydantic-settings 환경변수 │ ├── config.py # pydantic-settings 환경변수
│ ├── transcript.py # youtube-transcript-api로 자막 추출 │ ├── transcript.py # yt-dlp + 쿠키로 자막 추출
│ ├── summarizer.py # Claude Sonnet 4.6 요약 │ ├── summarizer.py # Claude Sonnet 4.6 요약
│ └── discord.py # Discord 웹훅 전송 │ └── discord.py # Discord 웹훅 전송
├── Dockerfile ├── Dockerfile
@@ -79,7 +79,9 @@ curl -X POST http://localhost:8000/summarize \
### transcript.py ### 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 ### summarizer.py

View File

@@ -48,12 +48,14 @@ FastAPI 서버의 `/api/news/summarize` 엔드포인트를 호출합니다.
| 설정 항목 | 값 | | 설정 항목 | 값 |
|---|---| |---|---|
| Method | `POST` | | Method | `POST` |
| URL | `http://<서버IP>/api/news/summarize` | | URL | `https://nkeystudy.site/api/news/summarize` |
| Body Content Type | JSON | | Body Content Type | JSON |
| Body | 아래 참조 | | Body | 아래 참조 |
**Body (JSON):** **Body 설정:**
- **Specify Body:** `Using JSON` (Expression 모드)
- **JSON:**
```json ```json
{ {
"video_url": "{{ $json.link }}", "video_url": "{{ $json.link }}",
@@ -61,6 +63,8 @@ FastAPI 서버의 `/api/news/summarize` 엔드포인트를 호출합니다.
} }
``` ```
> **주의:** 영상 제목에 큰따옴표(`"`)가 포함된 경우 JSON이 깨질 수 있습니다. 반드시 **Expression 모드**를 사용하세요 (Fixed 모드에서는 특수문자 이스케이프가 안 됩니다).
**Headers:** **Headers:**
| 헤더 | 값 | | 헤더 | 값 |

View File

@@ -61,7 +61,8 @@ docker compose logs -f news-summary-bot
| 증상 | 원인 | 해결 | | 증상 | 원인 | 해결 |
|------|------|------| |------|------|------|
| 자막 추출 실패 | 영상에 자막 없음 | 자동생성 자막이 없는 영상은 스킵됨 | | 자막 추출 실패 (자막 없음) | 영상에 자막 없음 | 자동생성 자막이 없는 영상은 스킵됨 |
| 자막 추출 실패 (봇 감지) | YouTube 쿠키 만료 | 브라우저에서 쿠키 재export 후 서버에 업로드 (아래 쿠키 갱신 참고) |
| Discord 전송 실패 | 웹훅 URL 만료 | Discord에서 웹훅 재생성 후 `.env` 업데이트 | | Discord 전송 실패 | 웹훅 URL 만료 | Discord에서 웹훅 재생성 후 `.env` 업데이트 |
| 401 Unauthorized | API_SECRET 불일치 | n8n 헤더와 `.env` 값 확인 | | 401 Unauthorized | API_SECRET 불일치 | n8n 헤더와 `.env` 값 확인 |
| Claude API 오류 | API 키 만료 또는 잔액 부족 | Anthropic 콘솔에서 확인 | | 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` 엔드포인트로 컨테이너 상태 확인 - `/health` 엔드포인트로 컨테이너 상태 확인

View File

@@ -1,6 +1,6 @@
fastapi==0.115.12 fastapi==0.115.12
uvicorn==0.34.2 uvicorn==0.34.2
youtube-transcript-api==1.0.3 yt-dlp>=2025.3.31
anthropic==0.52.0 anthropic==0.52.0
httpx==0.28.1 httpx==0.28.1
pydantic-settings==2.8.1 pydantic-settings==2.8.1