7 Commits
2.0.2 ... 2.0.9

Author SHA1 Message Date
sm4640
0bf38dd2f4 Docs: [2.0.9] 트러블슈팅 가이드 상세화
- Nginx 404, n8n JSON 에러, Docker 쿠키 마운트 이슈 문서화
- YouTube 봇 감지 원인 및 대응 방법 정리
- 쿠키 갱신 절차에 심볼릭 링크 주의사항 추가

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-24 17:48:35 +09:00
sm4640
c8c9c592cf Fix: [2.0.8] process=False로 포맷 처리 건너뛰고 자막만 추출
All checks were successful
news-summary-bot-cicd / build_push_deploy (push) Successful in 15m23s
extract_info에 process=False 적용하여 포맷 선택 단계를 완전히 스킵.
자막 정보는 YouTube extractor에서 직접 반환되므로 포맷 처리 불필요.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-24 17:12:23 +09:00
sm4640
98cd620f23 Fix: [2.0.7] format 에러 해결 - ignore_no_formats_error 사용
All checks were successful
news-summary-bot-cicd / build_push_deploy (push) Successful in 11m7s
format: worst 대신 ignore_no_formats_error: True로 변경하여
포맷 관련 에러 없이 자막만 추출하도록 수정

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-24 16:54:33 +09:00
sm4640
5e8e10e2fa Fix: [2.0.6] Docker 빌드 시 --no-cache 추가
All checks were successful
news-summary-bot-cicd / build_push_deploy (push) Successful in 12m17s
buildx 캐시 참조 에러(no such job) 해결

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-24 16:32:34 +09:00
sm4640
af0e2fca8a Feat: [2.0.5] 에러 발생 시 Discord 알림 전송
Some checks failed
news-summary-bot-cicd / build_push_deploy (push) Failing after 3m42s
- 요약 처리 중 에러 발생 시 Discord에 에러 상세 내용 전송
- 에러 타입, 메시지, 영상 정보를 포함한 embed 형식

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-24 16:27:03 +09:00
sm4640
11852bf48c Fix: [2.0.4] 쿠키 read-only 마운트 및 포맷 에러 해결
Some checks failed
news-summary-bot-cicd / build_push_deploy (push) Has been cancelled
- 쿠키 파일을 임시 파일에 복사하여 yt-dlp 쓰기 가능하도록 처리
- format: worst 추가하여 포맷 선택 에러 방지

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-24 16:23:51 +09:00
sm4640
d4bd508618 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>
2026-03-24 15:45:12 +09:00
11 changed files with 195 additions and 24 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:
@@ -88,10 +90,10 @@ jobs:
IMAGE="${DOCKERHUB_USER}/${IMAGE_NAME}:latest" IMAGE="${DOCKERHUB_USER}/${IMAGE_NAME}:latest"
if [ -n "${VERSION_TAG}" ]; then if [ -n "${VERSION_TAG}" ]; then
VERSIONED_IMAGE="${DOCKERHUB_USER}/${IMAGE_NAME}:${VERSION_TAG}" VERSIONED_IMAGE="${DOCKERHUB_USER}/${IMAGE_NAME}:${VERSION_TAG}"
docker build -t "${IMAGE}" -t "${VERSIONED_IMAGE}" . docker build --no-cache -t "${IMAGE}" -t "${VERSIONED_IMAGE}" .
docker push "${VERSIONED_IMAGE}" docker push "${VERSIONED_IMAGE}"
else else
docker build -t "${IMAGE}" . docker build --no-cache -t "${IMAGE}" .
fi fi
docker push "${IMAGE}" docker push "${IMAGE}"

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

@@ -107,3 +107,29 @@ async def send_to_discord(title: str, video_url: str, summary: str) -> None:
async with httpx.AsyncClient() as client: async with httpx.AsyncClient() as client:
resp = await client.post(settings.discord_webhook_url, json=payload) resp = await client.post(settings.discord_webhook_url, json=payload)
resp.raise_for_status() resp.raise_for_status()
async def send_error_to_discord(
title: str, video_url: str, error: Exception
) -> None:
"""에러 발생 시 Discord 웹훅으로 에러 내용 전송."""
error_type = type(error).__name__
error_msg = str(error)[:1024]
embed = {
"title": "❌ 뉴스 요약 실패",
"color": 0xED4245,
"fields": [
{"name": "영상 제목", "value": title or "(제목 없음)", "inline": False},
{"name": "영상 URL", "value": video_url, "inline": False},
{"name": "에러 타입", "value": f"`{error_type}`", "inline": True},
{"name": "에러 내용", "value": f"```\n{error_msg}\n```", "inline": False},
],
"footer": {"text": "YouTube 뉴스 요약 봇 - 에러 알림"},
"timestamp": datetime.now(timezone.utc).isoformat(),
}
payload = {"embeds": [embed]}
async with httpx.AsyncClient() as client:
await client.post(settings.discord_webhook_url, json=payload)

View File

@@ -2,7 +2,7 @@ from fastapi import FastAPI, Header, HTTPException
from pydantic import BaseModel from pydantic import BaseModel
from app.config import settings from app.config import settings
from app.discord import send_to_discord from app.discord import send_error_to_discord, send_to_discord
from app.summarizer import summarize from app.summarizer import summarize
from app.transcript import extract_video_id, fetch_transcript from app.transcript import extract_video_id, fetch_transcript
@@ -22,11 +22,16 @@ async def summarize_video(
if settings.api_secret and x_api_secret != settings.api_secret: if settings.api_secret and x_api_secret != settings.api_secret:
raise HTTPException(status_code=401, detail="Unauthorized") raise HTTPException(status_code=401, detail="Unauthorized")
title = req.title or "제목 없음"
try:
video_id = extract_video_id(req.video_url) video_id = extract_video_id(req.video_url)
transcript = fetch_transcript(video_id) transcript = fetch_transcript(video_id)
title = req.title or video_id
summary = summarize(transcript, title) summary = summarize(transcript, title)
await send_to_discord(title, req.video_url, summary) await send_to_discord(title, req.video_url, summary)
except Exception as e:
await send_error_to_discord(title, req.video_url, e)
raise HTTPException(status_code=500, detail=str(e))
return {"status": "ok", "title": title, "summary_length": len(summary)} return {"status": "ok", "title": title, "summary_length": len(summary)}

View File

@@ -1,4 +1,11 @@
from youtube_transcript_api import YouTubeTranscriptApi import os
import shutil
import tempfile
import httpx
import yt_dlp
COOKIES_SRC = "/app/cookies.txt"
def extract_video_id(url: str) -> str: def extract_video_id(url: str) -> str:
@@ -11,9 +18,50 @@ 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,
"quiet": True,
"no_warnings": True,
}
if os.path.isfile(COOKIES_SRC):
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".txt")
shutil.copy2(COOKIES_SRC, tmp.name)
ydl_opts["cookiefile"] = tmp.name
try:
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(url, ie_key="Youtube", download=False, process=False)
finally:
if "cookiefile" in ydl_opts:
os.unlink(ydl_opts["cookiefile"])
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

@@ -59,14 +59,78 @@ 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 콘솔에서 확인 |
| Discord embed 글자 수 초과 | 요약이 4096자 초과 | `summarizer.py``max_tokens` 줄이기 | | Discord embed 글자 수 초과 | 요약이 4096자 초과 | `summarizer.py``max_tokens` 줄이기 |
> 에러 발생 시 FastAPI가 자동으로 Discord에 에러 상세 내용(에러 타입, 메시지, 영상 정보)을 전송합니다.
### Nginx 404 에러
Nginx가 `/api/news/` prefix를 strip하여 FastAPI로 전달합니다. FastAPI 내부 라우트는 `/summarize`, `/health`이며, 외부에서는 `/api/news/summarize`, `/api/news/health`로 접근합니다.
- 404가 발생하면 Nginx 설정에 `/api/news/` location 블록이 있는지 확인
- FastAPI 라우트가 prefix 없이 `/summarize`, `/health`로 되어 있는지 확인
### n8n HTTP Request 에러
| 증상 | 원인 | 해결 |
|------|------|------|
| `JSON parameter needs to be valid JSON` | 영상 제목에 큰따옴표(`"`) 포함 시 JSON 깨짐 | Specify Body를 **Expression 모드**로 설정 (Fixed 모드 사용 금지) |
| 404 Not Found | Nginx → FastAPI 프록시 미설정 또는 라우트 불일치 | Nginx 설정 및 FastAPI 라우트 확인 |
### Docker 쿠키 마운트 관련
| 증상 | 원인 | 해결 |
|------|------|------|
| `Is a directory: '/app/cookies.txt'` | 쿠키 파일이 없는 상태에서 컨테이너 생성 시 Docker가 디렉토리로 자동 생성 | `down` + `up`으로 컨테이너 완전 재생성 (`restart`로는 안 됨) |
| CI/CD 후 쿠키가 디렉토리로 변경됨 | `compose.apps.yml`이 심볼릭 링크일 때 상대경로 볼륨 마운트가 실제 파일 위치 기준으로 해석됨 | 볼륨 마운트에 **절대경로** 사용: `/home/ubuntu/nkeysworld/news-summary-bot/cookies.txt:/app/cookies.txt:ro` |
| `Read-only file system: '/app/cookies.txt'` | `:ro`로 마운트된 쿠키 파일에 yt-dlp가 쓰기 시도 | 코드에서 임시 파일에 복사 후 사용 (현재 적용됨) |
| `Requested format is not available` | yt-dlp가 영상 포맷 선택 단계에서 실패 | `extract_info()``process=False` 옵션으로 포맷 처리 건너뜀 (현재 적용됨) |
### YouTube 봇 감지 (클라우드 서버)
YouTube는 OCI/AWS/GCP 등 **데이터센터 IP를 봇으로 감지**하여 자막 추출을 차단합니다. 도메인 유무와 무관하게 요청 출처 IP 기반으로 판단합니다.
- 로컬(가정용 IP)에서는 쿠키 없이 동작
- 서버(데이터센터 IP)에서는 반드시 YouTube 쿠키 필요
- 로그에 `Sign in to confirm you're not a bot` 메시지가 나타나면 쿠키 만료
---
## 쿠키 갱신
YouTube는 클라우드 서버 IP를 봇으로 감지하여 자막 추출을 차단합니다. 이를 우회하기 위해 브라우저 쿠키를 사용하며, 약 6개월~1년 주기로 만료됩니다.
**만료 증상:** 자막 추출 시 500 에러 + 로그에 `Sign in to confirm you're not a bot` 메시지 + Discord 에러 알림
**갱신 절차:**
1. Chrome 확장 **Get cookies.txt LOCALLY**로 YouTube 쿠키 export (youtube.com에 로그인한 상태에서)
2. 서버에 업로드:
```bash
scp -i <SSH_KEY_PATH> ~/Downloads/cookies.txt ubuntu@nkeystudy.site:~/nkeysworld/news-summary-bot/cookies.txt
```
3. 컨테이너 완전 재생성 (`restart`가 아닌 `down` + `up`):
```bash
docker compose -p nkeys-apps -f /nkeysworld/compose.apps.yml down news-summary-bot
docker compose -p nkeys-apps -f /nkeysworld/compose.apps.yml up -d news-summary-bot
```
4. 마운트 확인:
```bash
docker exec news-summary-bot head -3 /app/cookies.txt
```
> `compose.apps.yml`에서 쿠키 볼륨은 **절대경로**로 마운트해야 합니다: `/home/ubuntu/nkeysworld/news-summary-bot/cookies.txt:/app/cookies.txt:ro`
> (심볼릭 링크된 compose 파일에서 상대경로 사용 시 경로 해석 오류 발생)
--- ---
## 모니터링 포인트 ## 모니터링 포인트

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