Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
98cd620f23 | ||
|
|
5e8e10e2fa | ||
|
|
af0e2fca8a | ||
|
|
11852bf48c | ||
|
|
d4bd508618 |
6
.github/workflows/deploy.yml
vendored
6
.github/workflows/deploy.yml
vendored
@@ -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
1
.gitignore
vendored
@@ -2,3 +2,4 @@
|
|||||||
__pycache__/
|
__pycache__/
|
||||||
*.pyc
|
*.pyc
|
||||||
venv/
|
venv/
|
||||||
|
cookies.txt
|
||||||
|
|||||||
11
CLAUDE.md
11
CLAUDE.md
@@ -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 워크플로우
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|||||||
18
README.md
18
README.md
@@ -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 워크플로우
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -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)
|
||||||
|
|||||||
17
app/main.py
17
app/main.py
@@ -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")
|
||||||
|
|
||||||
video_id = extract_video_id(req.video_url)
|
title = req.title or "제목 없음"
|
||||||
transcript = fetch_transcript(video_id)
|
|
||||||
title = req.title or video_id
|
try:
|
||||||
summary = summarize(transcript, title)
|
video_id = extract_video_id(req.video_url)
|
||||||
await send_to_discord(title, req.video_url, summary)
|
transcript = fetch_transcript(video_id)
|
||||||
|
summary = summarize(transcript, title)
|
||||||
|
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)}
|
||||||
|
|
||||||
|
|||||||
@@ -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,55 @@ 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,
|
||||||
|
"extract_flat": False,
|
||||||
|
"ignore_no_formats_error": 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, download=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)
|
||||||
|
|||||||
@@ -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
|
||||||
|
|
||||||
|
|||||||
@@ -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:**
|
||||||
|
|
||||||
| 헤더 | 값 |
|
| 헤더 | 값 |
|
||||||
|
|||||||
@@ -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` 엔드포인트로 컨테이너 상태 확인
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
Reference in New Issue
Block a user