Compare commits
13 Commits
feat/insta
...
6922217da6
| Author | SHA1 | Date | |
|---|---|---|---|
| 6922217da6 | |||
| 3a63bfac15 | |||
| 76e045aa82 | |||
| f1a6590f56 | |||
| e14340366c | |||
| c3cf4d70e6 | |||
| 0754e4cab8 | |||
| 8597a9efb7 | |||
| 71e0b6f8db | |||
| 3a828c0f54 | |||
| 07a993fef4 | |||
| 14b4e99bc9 | |||
| 0613400bb7 |
@@ -1,41 +0,0 @@
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Bash(git status:*)",
|
||||
"Bash(git diff:*)",
|
||||
"Bash(git log:*)",
|
||||
"Bash(git show:*)",
|
||||
"Bash(git branch:*)",
|
||||
"Bash(git stash list:*)",
|
||||
"Bash(git remote -v)",
|
||||
"Bash(docker ps:*)",
|
||||
"Bash(docker logs:*)",
|
||||
"Bash(docker compose ps:*)",
|
||||
"Bash(docker compose logs:*)",
|
||||
"Bash(docker compose config:*)",
|
||||
"Bash(docker images:*)",
|
||||
"Bash(pytest:*)",
|
||||
"Bash(python -m pytest:*)",
|
||||
"Bash(python -V)",
|
||||
"Bash(python -c:*)",
|
||||
"Bash(pip list:*)",
|
||||
"Bash(pip show:*)",
|
||||
"Bash(pip freeze:*)",
|
||||
"Bash(uvicorn --version)",
|
||||
"Bash(ls:*)",
|
||||
"Bash(cat docker-compose.yml)"
|
||||
],
|
||||
"deny": [
|
||||
"Read(.env)",
|
||||
"Read(.env.*)",
|
||||
"Read(**/.env)",
|
||||
"Read(**/.env.*)",
|
||||
"Read(**/credentials*)",
|
||||
"Read(**/secrets*)",
|
||||
"Read(**/*.pem)",
|
||||
"Read(**/*.key)",
|
||||
"Read(**/lotto.db)",
|
||||
"Read(**/stock.db)"
|
||||
]
|
||||
}
|
||||
}
|
||||
49
.env.example
49
.env.example
@@ -54,16 +54,8 @@ WINDOWS_AI_SERVER_URL=http://192.168.45.59:8000
|
||||
# Admin API Key (trade/order 등 민감 엔드포인트 보호, 미설정 시 인증 비활성화)
|
||||
ADMIN_API_KEY=
|
||||
|
||||
# Anthropic API Key (AI Coach 프록시 + 뉴스 요약 Claude provider)
|
||||
# Anthropic API Key (AI Coach 프록시, 미설정 시 AI Coach 비활성화)
|
||||
ANTHROPIC_API_KEY=
|
||||
ANTHROPIC_MODEL=claude-haiku-4-5-20251001
|
||||
|
||||
# 뉴스 요약 provider 전환: claude (기본) | ollama
|
||||
LLM_PROVIDER=claude
|
||||
|
||||
# Ollama 서버 (LLM_PROVIDER=ollama 일 때만 사용)
|
||||
OLLAMA_URL=http://192.168.45.59:11435
|
||||
OLLAMA_MODEL=qwen3:14b
|
||||
|
||||
# [BLOG LAB]
|
||||
# Naver Search API (https://developers.naver.com 에서 발급)
|
||||
@@ -82,42 +74,3 @@ SUNO_API_KEY=
|
||||
|
||||
# CORS 허용 도메인 (콤마 구분)
|
||||
CORS_ALLOW_ORIGINS=https://gahusb.synology.me,http://localhost:3007,http://localhost:8080
|
||||
|
||||
# [REALESTATE LAB — agent-office push notify]
|
||||
AGENT_OFFICE_URL=http://agent-office:8000
|
||||
REALESTATE_LAB_URL=http://realestate-lab:8000
|
||||
REALESTATE_DASHBOARD_URL=http://localhost:8080/realestate
|
||||
REALESTATE_NOTIFY_TIMEOUT=15
|
||||
|
||||
# [MUSIC LAB — YouTube Video Generation]
|
||||
PEXELS_API_KEY=
|
||||
YOUTUBE_DATA_API_KEY=
|
||||
# VIDEO_DATA_DIR=/app/data/videos # 기본값, 재정의 필요 시만 설정
|
||||
|
||||
# ─── packs-lab — NAS 자료 다운로드 자동화 ────────────────────────────
|
||||
# Synology DSM 7.x 인증 (공유 링크 발급용)
|
||||
DSM_HOST=https://gahusb.synology.me:5001
|
||||
DSM_USER=
|
||||
DSM_PASS=
|
||||
# LAN IP로 DSM 접근 시 self-signed cert가 IP에 매칭 안 되어 검증 실패. 그 경우 false 설정 (LAN 내부 통신이라 허용 가능). 도메인 + 정상 cert면 true 유지.
|
||||
DSM_VERIFY_SSL=true
|
||||
|
||||
# Vercel SaaS ↔ backend HMAC 시크릿 (양쪽 동일 값)
|
||||
BACKEND_HMAC_SECRET=
|
||||
|
||||
# Supabase pack_files 테이블 접근 (service_role 키, RLS 우회)
|
||||
SUPABASE_URL=https://<project>.supabase.co
|
||||
SUPABASE_SERVICE_KEY=
|
||||
|
||||
# admin upload 토큰 TTL (초). default 1800 = 30분
|
||||
UPLOAD_TOKEN_TTL_SEC=1800
|
||||
|
||||
# 호스트 마운트 경로 (로컬 ./data/packs, NAS /volume1/docker/webpage/media/packs)
|
||||
PACK_DATA_PATH=./data/packs
|
||||
|
||||
# 컨테이너 내부 PACK_BASE_DIR (routes.py가 파일 저장 시 사용. docker-compose volume의 컨테이너 측 경로와 반드시 일치)
|
||||
PACK_BASE_DIR=/app/data/packs
|
||||
|
||||
# DSM·Supabase에 노출되는 NAS 호스트 절대경로 (PACK_DATA_PATH와 같은 디렉토리를 호스트 시점에서 가리킴).
|
||||
# 운영 NAS는 반드시 /volume1/docker/webpage/media/packs 같은 절대경로 설정. 미설정 시 PACK_DATA_PATH로 fallback (로컬 개발용).
|
||||
PACK_HOST_DIR=/volume1/docker/webpage/media/packs
|
||||
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -63,6 +63,3 @@ uploads/
|
||||
################################
|
||||
tmp/
|
||||
temp/
|
||||
|
||||
# Git worktrees
|
||||
.worktrees/
|
||||
|
||||
429
CLAUDE.md
429
CLAUDE.md
@@ -7,9 +7,9 @@
|
||||
## 1. 프로젝트 개요
|
||||
|
||||
Synology NAS 기반의 개인 웹 플랫폼 백엔드 모노레포.
|
||||
- **서비스**: lotto-lab, stock, travel-proxy, music-lab, insta-lab, realestate-lab, agent-office, personal, packs-lab, deployer (10개)
|
||||
- **서비스**: lotto-lab, stock-lab, travel-album, music-lab, blog-lab, realestate-lab, deployer
|
||||
- **프론트엔드**: 별도 레포 (React + Vite SPA), 빌드 산출물만 NAS에 배포
|
||||
- **인프라**: Docker Compose (10컨테이너) + Nginx(리버스 프록시) + Gitea Webhook 자동 배포
|
||||
- **인프라**: Docker Compose + Nginx(리버스 프록시) + Gitea Webhook 자동 배포
|
||||
|
||||
---
|
||||
|
||||
@@ -22,7 +22,7 @@ Synology NAS 기반의 개인 웹 플랫폼 백엔드 모노레포.
|
||||
| 메모리 | 18 GB |
|
||||
| Docker | Synology Container Manager |
|
||||
| Git 서버 | Gitea (self-hosted, NAS 내부) |
|
||||
| AI 서버 | Windows PC (192.168.45.59:8000) — NVIDIA RTX 5070 Ti (16GB VRAM) + Ollama |
|
||||
| AI 서버 | Windows PC (192.168.45.59:8000) — NVIDIA 3070 Ti + Ollama |
|
||||
|
||||
---
|
||||
|
||||
@@ -31,8 +31,8 @@ Synology NAS 기반의 개인 웹 플랫폼 백엔드 모노레포.
|
||||
```
|
||||
/volume1
|
||||
├── docker/webpage/ # 운영 런타임 (Docker Compose 실행 위치)
|
||||
│ ├── lotto/ # lotto 소스 (rsync 동기화)
|
||||
│ ├── stock/ # stock 소스 (rsync 동기화)
|
||||
│ ├── backend/ # lotto-backend 소스 (rsync 동기화)
|
||||
│ ├── stock-lab/ # stock-lab 소스 (rsync 동기화)
|
||||
│ ├── travel-proxy/ # travel-proxy 소스 (rsync 동기화)
|
||||
│ ├── deployer/ # deployer 소스 (rsync 동기화)
|
||||
│ ├── nginx/default.conf # Nginx 설정
|
||||
@@ -53,16 +53,14 @@ Synology NAS 기반의 개인 웹 플랫폼 백엔드 모노레포.
|
||||
|
||||
| 컨테이너 | 포트 | 역할 |
|
||||
|---------|------|------|
|
||||
| `lotto` | 18000 | 로또 데이터 수집·분석·추천 API |
|
||||
| `stock` | 18500 | 주식 뉴스·AI 분석·KIS API 연동 |
|
||||
| `lotto-backend` | 18000 | 로또 데이터 수집·분석·추천 API |
|
||||
| `stock-lab` | 18500 | 주식 뉴스·AI 분석·KIS API 연동 |
|
||||
| `music-lab` | 18600 | AI 음악 생성·라이브러리 관리 API |
|
||||
| `insta-lab` | 18700 | 인스타 카드 피드 자동 생성 (뉴스→키워드→10페이지 카드) |
|
||||
| `blog-lab` | 18700 | 블로그 마케팅 수익화 API |
|
||||
| `realestate-lab` | 18800 | 부동산 청약 자동 수집·매칭 API |
|
||||
| `agent-office` | 18900 | AI 에이전트 오피스 (실시간 WebSocket + 텔레그램 연동) |
|
||||
| `packs-lab` | 18950 | NAS 자료 다운로드 자동화 (DSM 공유 링크 + 5GB 업로드, Vercel SaaS와 HMAC 통신) |
|
||||
| `personal` | 18850 | 개인 서비스 (포트폴리오·블로그·투두 통합) |
|
||||
| `travel-proxy` | 19000 | 여행 사진 API + 썸네일 생성 |
|
||||
| `frontend` (nginx) | 8080 | 정적 SPA 서빙 + API 리버스 프록시 |
|
||||
| `lotto-frontend` (nginx) | 8080 | 정적 SPA 서빙 + API 리버스 프록시 |
|
||||
| `webpage-deployer` | 19010 | Gitea Webhook 수신 → 자동 배포 |
|
||||
|
||||
---
|
||||
@@ -71,22 +69,17 @@ Synology NAS 기반의 개인 웹 플랫폼 백엔드 모노레포.
|
||||
|
||||
| 경로 | 프록시 대상 | 비고 |
|
||||
|------|------------|------|
|
||||
| `/api/` | `lotto:8000` | lotto API (기본) |
|
||||
| `/api/` | `lotto-backend:8000` | lotto API (기본) |
|
||||
| `/api/travel/` | `travel-proxy:8000` | travel API |
|
||||
| `/api/stock/` | `stock:8000` | stock API |
|
||||
| `/api/trade/` | `stock:8000` | KIS 실계좌 API |
|
||||
| `/api/portfolio` | `stock:8000` | trailing slash 유무 모두 매칭 |
|
||||
| `/api/stock/` | `stock-lab:8000` | stock API |
|
||||
| `/api/trade/` | `stock-lab:8000` | KIS 실계좌 API |
|
||||
| `/api/portfolio` | `stock-lab:8000` | trailing slash 유무 모두 매칭 |
|
||||
| `/api/music/` | `music-lab:8000` | AI 음악 생성·라이브러리 API |
|
||||
| `/api/insta/` | `insta-lab:8000` | 인스타 카드 자동 생성 API |
|
||||
| `/api/blog-marketing/` | `blog-lab:8000` | 블로그 마케팅 수익화 API |
|
||||
| `/api/realestate/` | `realestate-lab:8000` | 부동산 청약 API |
|
||||
| `/api/todos` | `personal:8000` | 투두 API |
|
||||
| `/api/blog/` | `personal:8000` | 블로그 API |
|
||||
| `/api/profile/` | `personal:8000` | 포트폴리오 API |
|
||||
| `/api/agent-office/` | `agent-office:8000` | AI 에이전트 오피스 API + WebSocket |
|
||||
| `/api/packs/` | `packs-lab:8000` | 5GB 업로드 대응 (`client_max_body_size 5G`, `proxy_request_buffering off`, 1800s timeout) |
|
||||
| `/webhook`, `/webhook/` | `deployer:9000` | Gitea Webhook |
|
||||
| `/media/music/` | `/data/music/` (파일 직접 서빙) | 생성된 오디오 파일 |
|
||||
| `/media/videos/` | `/data/videos/` (파일 직접 서빙) | YouTube 영상 MP4 |
|
||||
| `/media/travel/.thumb/` | `/data/thumbs/` (파일 직접 서빙) | 썸네일 캐시 |
|
||||
| `/media/travel/` | `/data/travel/` (파일 직접 서빙) | 원본 사진 |
|
||||
| `/assets/` | 정적 파일 (장기 캐시) | Vite 해시 파일 |
|
||||
@@ -135,15 +128,14 @@ docker compose up -d
|
||||
| Lotto Backend | http://localhost:18000 |
|
||||
| Travel API | http://localhost:19000 |
|
||||
| Stock Lab | http://localhost:18500 |
|
||||
| Insta Lab | http://localhost:18700 |
|
||||
| Blog Lab | http://localhost:18700 |
|
||||
| Realestate Lab | http://localhost:18800 |
|
||||
| Packs Lab | http://localhost:18950 |
|
||||
|
||||
---
|
||||
|
||||
## 9. 서비스별 핵심 정보
|
||||
|
||||
### lotto-lab (lotto/)
|
||||
### lotto-lab (backend/)
|
||||
- DB: `/app/data/lotto.db`
|
||||
- 데이터 소스: `smok95.github.io/lotto/results/`
|
||||
- 파일 구조: `main.py`, `db.py`, `recommender.py`, `collector.py`, `checker.py`, `generator.py`, `analyzer.py`, `utils.py`, `purchase_manager.py`, `strategy_evolver.py`
|
||||
@@ -161,9 +153,8 @@ docker compose up -d
|
||||
| `strategy_performance` | 전략별 회차 성과 (EMA 입력 데이터) |
|
||||
| `strategy_weights` | 메타 전략 가중치 (EMA + Softmax) |
|
||||
| `weekly_reports` | 주간 공략 리포트 캐시 |
|
||||
| `lotto_briefings` | AI 큐레이터 주간 브리핑 (5세트 + 내러티브 + 토큰·비용 집계) |
|
||||
| `todos` | 투두리스트 (UUID PK) — personal 서비스로 이전됨, 레거시 테이블 유지 |
|
||||
| `blog_posts` | 블로그 글 (tags: JSON 배열) — personal 서비스로 이전됨, 레거시 테이블 유지 |
|
||||
| `todos` | 투두리스트 (UUID PK) |
|
||||
| `blog_posts` | 블로그 글 (tags: JSON 배열) |
|
||||
|
||||
**스케줄러 job**
|
||||
- 09:10 / 21:10 매일 — 당첨번호 동기화 + 채점 (`sync_latest` → `check_results_for_draw`)
|
||||
@@ -197,22 +188,24 @@ docker compose up -d
|
||||
| GET | `/api/history` | 추천 이력 (limit, offset, favorite, tag, sort) |
|
||||
| PATCH | `/api/history/{id}` | 즐겨찾기·메모·태그 수정 |
|
||||
| DELETE | `/api/history/{id}` | 삭제 |
|
||||
| GET | `/api/lotto/curator/candidates` | 큐레이터용 후보 N세트 + 피처 |
|
||||
| GET | `/api/lotto/curator/context` | 주간 맥락(핫/콜드·직전 회차) |
|
||||
| GET | `/api/lotto/curator/usage` | 큐레이터 토큰·비용 집계 |
|
||||
| POST | `/api/lotto/briefing` | AI 브리핑 저장 |
|
||||
| GET | `/api/lotto/briefing/latest` | 최신 브리핑 |
|
||||
| GET | `/api/lotto/briefing/{draw_no}` | 특정 회차 브리핑 |
|
||||
| GET | `/api/lotto/briefing` | 브리핑 이력 |
|
||||
| GET | `/api/todos` | 투두 전체 목록 |
|
||||
| POST | `/api/todos` | 투두 생성 (status: todo\|in_progress\|done) |
|
||||
| PUT | `/api/todos/{id}` | 투두 수정 |
|
||||
| DELETE | `/api/todos/done` | 완료 항목 일괄 삭제 |
|
||||
| DELETE | `/api/todos/{id}` | 투두 개별 삭제 |
|
||||
| GET | `/api/blog/posts` | 블로그 글 목록 (`{"posts": [...]}`, date DESC) |
|
||||
| POST | `/api/blog/posts` | 블로그 글 생성 (date 미입력 시 오늘) |
|
||||
| PUT | `/api/blog/posts/{id}` | 블로그 글 수정 |
|
||||
| DELETE | `/api/blog/posts/{id}` | 블로그 글 삭제 |
|
||||
|
||||
### stock (stock/)
|
||||
### stock-lab (stock-lab/)
|
||||
- Windows AI 서버 연동: `WINDOWS_AI_SERVER_URL=http://192.168.45.59:8000`
|
||||
- KIS API 연동으로 실계좌 잔고·거래 조회
|
||||
- 뉴스 스크래핑: 네이버 증권 + 해외 사이트
|
||||
- DB: `/app/data/stock.db` (articles, portfolio, broker_cash, asset_snapshots, sell_history 테이블)
|
||||
- 파일 구조: `main.py`, `db.py`, `scraper.py`, `price_fetcher.py`, `holidays.json`
|
||||
|
||||
**stock API 목록**
|
||||
**stock-lab API 목록**
|
||||
|
||||
| 메서드 | 경로 | 설명 |
|
||||
|--------|------|------|
|
||||
@@ -253,11 +246,10 @@ docker compose up -d
|
||||
- 15:40 평일 — 총 자산 스냅샷 저장 (`save_daily_snapshot`)
|
||||
|
||||
### music-lab (music-lab/)
|
||||
- 듀얼 프로바이더 음악 생성 서비스 (Suno API + 로컬 MusicGen) + YouTube 영상 제작 + 시장 조사 트렌드
|
||||
- 듀얼 프로바이더 음악 생성 서비스 (Suno API + 로컬 MusicGen)
|
||||
- 생성된 오디오 파일: `/app/data/music/` (Nginx가 `/media/music/`로 직접 서빙)
|
||||
- 생성된 영상 파일: `/app/data/videos/` (Nginx가 `/media/videos/`로 직접 서빙)
|
||||
- DB: `/app/data/music.db` (music_tasks, music_library, video_projects, revenue_records, market_trends, trend_reports 테이블)
|
||||
- 파일 구조: `main.py`, `db.py`, `suno_provider.py`, `local_provider.py`, `video_producer.py`, `market.py`
|
||||
- DB: `/app/data/music.db` (music_tasks, music_library 테이블)
|
||||
- 파일 구조: `main.py`, `db.py`, `suno_provider.py`, `local_provider.py`
|
||||
- 생성 흐름: POST generate (provider 지정) → task_id 반환 → BackgroundTask → 파일 저장 → 라이브러리 자동 등록
|
||||
|
||||
**Provider 구조**
|
||||
@@ -293,51 +285,12 @@ docker compose up -d
|
||||
| POST | `/api/music/lyrics/library` | 가사 저장 |
|
||||
| PUT | `/api/music/lyrics/library/{id}` | 가사 수정 |
|
||||
| DELETE | `/api/music/lyrics/library/{id}` | 가사 삭제 |
|
||||
| POST | `/api/music/video-project` | 영상 프로젝트 생성 (track_id, format, target_countries) |
|
||||
| GET | `/api/music/video-projects` | 영상 프로젝트 목록 |
|
||||
| GET | `/api/music/video-project/{id}` | 영상 프로젝트 상세 |
|
||||
| POST | `/api/music/video-project/{id}/render` | FFmpeg 렌더링 시작 (BackgroundTask) |
|
||||
| GET | `/api/music/video-project/{id}/export` | 내보내기 패키지 (mp4+thumbnail+metadata.json) |
|
||||
| DELETE | `/api/music/video-project/{id}` | 영상 프로젝트 삭제 |
|
||||
| GET | `/api/music/revenue/dashboard` | 수익 대시보드 (총수익·조회수·가중평균 RPM) |
|
||||
| GET | `/api/music/revenue` | 수익 기록 목록 |
|
||||
| POST | `/api/music/revenue` | 수익 기록 추가 (UNIQUE: yt_video_id+record_month+country) |
|
||||
| PUT | `/api/music/revenue/{id}` | 수익 기록 수정 |
|
||||
| DELETE | `/api/music/revenue/{id}` | 수익 기록 삭제 |
|
||||
| POST | `/api/music/market/ingest` | agent-office 트렌드 수신 + 리포트 생성 |
|
||||
| GET | `/api/music/market/trends` | 트렌드 조회 (country, genre, source, days=7) |
|
||||
| GET | `/api/music/market/report/latest` | 최신 트렌드 리포트 |
|
||||
| GET | `/api/music/market/report` | 트렌드 리포트 목록 (limit=10) |
|
||||
| GET | `/api/music/market/suggest` | Suno 프롬프트 추천 (limit=5) |
|
||||
|
||||
**환경변수**
|
||||
- `SUNO_API_KEY`: Suno API 키 (미설정 시 Suno provider 비활성화)
|
||||
- `MUSIC_AI_SERVER_URL`: 로컬 MusicGen 서버 URL (미설정 시 local provider 비활성화)
|
||||
- `MUSIC_MEDIA_BASE`: 오디오 파일 공개 URL prefix (기본 `/media/music`)
|
||||
- `MUSIC_DATA_PATH`: NAS 오디오 파일 저장 경로 (기본 `./data/music`)
|
||||
- `PEXELS_API_KEY`: Pexels 스톡 이미지 API 키 (미설정 시 슬라이드쇼 Pexels 이미지 비활성화)
|
||||
- `ANTHROPIC_API_KEY`: Claude Haiku — YouTube 메타데이터 생성 + 시장 인사이트 (미설정 시 폴백 텍스트)
|
||||
- `VIDEO_DATA_DIR`: 영상 파일 저장 경로 (기본 `/app/data/videos`)
|
||||
|
||||
**video_projects 테이블**
|
||||
- format: `visualizer` | `slideshow`
|
||||
- status: `pending` → `rendering` → `done` | `failed`
|
||||
- target_countries: JSON 배열 (예: `["BR","US"]`)
|
||||
- render_params: JSON 객체 (FFmpeg 파라미터 캐시)
|
||||
|
||||
**revenue_records 테이블**
|
||||
- UNIQUE(yt_video_id, record_month, country)
|
||||
- avg_rpm 계산: 가중평균 `SUM(revenue_usd)/SUM(views)*1000` (단순 AVG 아님)
|
||||
|
||||
**market_trends 테이블**
|
||||
- source: `youtube` | `google_trends` | `billboard`
|
||||
- metadata: JSON 객체 (원본 API 응답 부분)
|
||||
- 인덱스: `idx_mt_country_source` ON (country, source, collected_at DESC)
|
||||
|
||||
**trend_reports 테이블**
|
||||
- report_date UNIQUE — 같은 날 두 번 ingest 시 upsert
|
||||
- top_genres: JSON 배열 `[{genre, score, countries}]` (최대 10개, score 내림차순)
|
||||
- recommended_styles: JSON 배열 `[{genre, suno_prompt, target_countries, reason}]` (최대 5개)
|
||||
|
||||
**music_library 테이블 (확장 컬럼)**
|
||||
- `provider`: `suno` | `local` — 생성에 사용된 프로바이더
|
||||
@@ -356,64 +309,31 @@ docker compose up -d
|
||||
- 가사 섹션 태그: `[Verse]`, `[Chorus]`, `[Bridge]`, `[Instrumental]` 등
|
||||
|
||||
### realestate-lab (realestate-lab/)
|
||||
- 공공데이터포털 API 연동: 한국부동산원 청약홈 분양정보 조회 + 자치구 5티어 매칭 + agent-office push 알림
|
||||
- 공공데이터포털 API 연동: 한국부동산원 청약홈 분양정보 조회 서비스
|
||||
- DB: `/app/data/realestate.db` (announcements, announcement_models, user_profile, match_results, collect_log 테이블)
|
||||
- 파일 구조: `main.py`, `db.py`, `collector.py`, `matcher.py`, `notifier.py`, `models.py`
|
||||
- 파일 구조: `main.py`, `db.py`, `collector.py`, `matcher.py`, `models.py`
|
||||
|
||||
**환경변수**
|
||||
- `DATA_GO_KR_API_KEY`: 공공데이터포털 API 키 (미설정 시 수동 등록만 가능)
|
||||
- `AGENT_OFFICE_URL`: agent-office 내부 URL (기본 `http://agent-office:8000`) — 신규 매칭 push 대상
|
||||
- `REALESTATE_NOTIFY_TIMEOUT`: agent-office push timeout 초 (기본 15)
|
||||
|
||||
**스케줄러 job (`scheduled_collect` 4단계 흐름)**
|
||||
- 09:00 매일 — `collect → cleanup → match → notify`
|
||||
1. `collect_all()` — 모집공고일 30일 윈도우(`RCRIT_PBLANC_DE_FROM`) 사전 좁힘 + 자치구 추출 + status='완료' skip
|
||||
2. `delete_old_completed_announcements(grace_days=90)` — `winner_date + 90일` 경과한 완료 공고 정리 (FK CASCADE로 match_results도 삭제)
|
||||
3. `run_matching()` — 자치구 5티어 가중치 + 자격 곡선 적용
|
||||
4. `notify_new_matches()` — `notified_at IS NULL AND match_score >= profile.min_match_score AND profile.notify_enabled`인 매칭을 agent-office로 push
|
||||
- 00:00 매일 — 상태 갱신 + 재매칭 (`scheduled_status_update`, notifier 미호출)
|
||||
|
||||
**매칭 점수 모델 (총 100점)**
|
||||
- 지역 35점 — 광역 매칭 시 10점 + 자치구 5티어 가중치(S=25 / A=20 / B=15 / C=10 / D=5)
|
||||
- `preferred_districts`가 모든 티어 비어있으면 광역 매칭만으로 35점 풀 점수 (legacy 호환)
|
||||
- 주택유형 10점 — `preferred_types`에 매칭 (binary)
|
||||
- 면적 15점 — `[min_area, max_area]` 범위 안 모델 1개 이상 (binary)
|
||||
- 가격 15점 — `max_price` 이하 모델 1개 이상 (binary)
|
||||
- 자격 25점 — `_check_eligible_types()` 결과 1개 이상이면 15점 + 추가당 5점, 최대 +10
|
||||
- reasons 텍스트 예시: `"자치구 S티어: 강남구 (+25)"`, `"광역 일치: 서울"`, `"선호 지역 일치: 서울"` (legacy)
|
||||
|
||||
**user_profile 신규 컬럼 (Task 2026-04-28 마이그레이션)**
|
||||
- `preferred_districts` TEXT — JSON `{"S":[...], "A":[...], "B":[...], "C":[...], "D":[...]}`. default `'{}'`
|
||||
- `min_match_score` INTEGER — 알림 임계값. default 70
|
||||
- `notify_enabled` INTEGER — 알림 ON/OFF. default 1
|
||||
|
||||
**announcements / match_results 신규 컬럼**
|
||||
- `announcements.district` TEXT + `idx_ann_district` 인덱스 — collector가 주소/region_name에서 정규식 파싱
|
||||
- `match_results.notified_at` TEXT NULL — agent-office push 성공 시 timestamp 기록 (멱등 마킹)
|
||||
|
||||
**notifier.py 흐름**
|
||||
1. `get_profile()` → `notify_enabled=False`면 skip, `min_match_score` 가져옴
|
||||
2. `get_unnotified_matches(min_score)` — JOIN으로 announcements 정보 포함 (district, status, receipt 등)
|
||||
3. `POST {AGENT_OFFICE_URL}/api/agent-office/realestate/notify` body=`{"matches": [...]}`
|
||||
4. 응답 `{sent_ids: [...]}` → `mark_matches_notified(sent_ids)` (notified_at = now)
|
||||
5. RequestException 시 마킹 안 함 → 다음 사이클 재시도
|
||||
**스케줄러 job**
|
||||
- 09:00 매일 — 청약 공고 수집 + 매칭 (`scheduled_collect`)
|
||||
- 00:00 매일 — 상태 갱신 + 재매칭 (`scheduled_status_update`)
|
||||
|
||||
**realestate-lab API 목록**
|
||||
|
||||
| 메서드 | 경로 | 설명 |
|
||||
|--------|------|------|
|
||||
| GET | `/api/realestate/announcements` | 공고 목록. 응답에 `district`, `match_score`, `match_reasons`, `eligible_types` 포함 |
|
||||
| GET | `/api/realestate/announcements/{id}` | 공고 상세 (주택형별 + district 포함) |
|
||||
| GET | `/api/realestate/announcements` | 공고 목록 (region, status, house_type, matched_only, sort, page, size) |
|
||||
| GET | `/api/realestate/announcements/{id}` | 공고 상세 (주택형별 포함) |
|
||||
| POST | `/api/realestate/announcements` | 수동 공고 등록 |
|
||||
| PUT | `/api/realestate/announcements/{id}` | 공고 수정 |
|
||||
| PATCH | `/api/realestate/announcements/{id}/bookmark` | 북마크 토글 (텔레그램 인라인 키보드 콜백 대상) |
|
||||
| DELETE | `/api/realestate/announcements/{id}` | 공고 삭제 |
|
||||
| DELETE | `/api/realestate/announcements/closed` | status='완료' 공고 일괄 삭제 |
|
||||
| POST | `/api/realestate/collect` | 수동 수집 트리거 (collect → cleanup → match → notify 전체 흐름) |
|
||||
| POST | `/api/realestate/collect` | 수동 수집 트리거 |
|
||||
| GET | `/api/realestate/collect/status` | 마지막 수집 결과 |
|
||||
| GET | `/api/realestate/profile` | 내 프로필 조회 (`preferred_districts`, `min_match_score`, `notify_enabled` 포함) |
|
||||
| PUT | `/api/realestate/profile` | 프로필 수정 (upsert). body에 `preferred_districts: {S:[],...}`, `min_match_score: 0~100`, `notify_enabled: bool` 수용 |
|
||||
| GET | `/api/realestate/matches` | 매칭 결과 목록 (응답에 `district`, `status` 포함) |
|
||||
| GET | `/api/realestate/profile` | 내 프로필 조회 |
|
||||
| PUT | `/api/realestate/profile` | 프로필 수정 (upsert) |
|
||||
| GET | `/api/realestate/matches` | 매칭 결과 목록 |
|
||||
| POST | `/api/realestate/matches/refresh` | 매칭 재계산 |
|
||||
| PATCH | `/api/realestate/matches/{id}/read` | 신규 알림 읽음 처리 |
|
||||
| GET | `/api/realestate/dashboard` | 요약 (진행중 공고수, 신규 매칭수, 다가오는 일정) |
|
||||
@@ -421,146 +341,94 @@ docker compose up -d
|
||||
### travel-proxy (travel-proxy/)
|
||||
- 원본 사진: `/data/travel/` (RO)
|
||||
- 썸네일 캐시: `/data/thumbs/` (RW)
|
||||
- DB: `/data/thumbs/travel.db` (photos, album_covers 테이블)
|
||||
- 메타: `/data/travel/_meta/region_map.json`, `regions.geojson`
|
||||
- 지역 오버라이드: `/data/thumbs/region_map_extra.json` (RW, `_regions_meta` 포함)
|
||||
- 파일 구조: `main.py`, `db.py`, `indexer.py`
|
||||
- 썸네일: 480×480 리사이징 (Pillow), 동기화 시 사전 생성 + 온디맨드 폴백
|
||||
- 데이터 흐름: 수동 sync → 폴더 스캔 → SQLite 인덱싱 + 썸네일 일괄 생성
|
||||
|
||||
**travel.db 테이블**
|
||||
|
||||
| 테이블 | 설명 |
|
||||
|--------|------|
|
||||
| `photos` | 사진 인덱스 (album, filename, mtime, has_thumb) |
|
||||
| `album_covers` | 앨범별 커버 사진 지정 |
|
||||
|
||||
**지역 관리 아키텍처**
|
||||
- `region_map.json` (RO): 원본 지역→앨범 매핑 (`_meta/` 안에 위치)
|
||||
- `region_map_extra.json` (RW): 사용자 수정분 오버라이드 (앨범 이동, 신규 지역)
|
||||
- `_regions_meta`: 커스텀 지역의 이름·좌표 저장 (`{ "region_id": { "name": "...", "coordinates": [lng, lat] } }`)
|
||||
- `regions.geojson` (RO): GeoJSON Polygon 지역 경계
|
||||
- 커스텀 지역: `GET /api/travel/regions`에서 `region_map`에 있지만 GeoJSON에 없는 지역을 자동 추가 (Point geometry 또는 null)
|
||||
- 썸네일: 480×480 리사이징 (Pillow), 온디맨드 생성 후 영구 캐시
|
||||
- 메모리 캐시: TTL 300초 (앨범 스캔 결과)
|
||||
|
||||
**travel-proxy API 목록**
|
||||
|
||||
| 메서드 | 경로 | 설명 |
|
||||
|--------|------|------|
|
||||
| GET | `/api/travel/regions` | 지역 GeoJSON (커스텀 지역 동적 추가 포함) |
|
||||
| GET | `/api/travel/regions` | 지역 GeoJSON |
|
||||
| GET | `/api/travel/photos` | 사진 목록 (region, page=1, size=20) |
|
||||
| POST | `/api/travel/sync` | 폴더 스캔 → DB 동기화 + 썸네일 생성 |
|
||||
| GET | `/api/travel/albums` | 앨범 목록 + 사진 수 + 커버 + region/regionName |
|
||||
| PUT | `/api/travel/albums/{album}/cover` | 앨범 커버 지정 |
|
||||
| PUT | `/api/travel/albums/{album}/region` | 앨범 지역 변경 (region_map_extra 수정) |
|
||||
| PUT | `/api/travel/regions/{region_id}` | 커스텀 지역 이름/좌표 수정 (지도 핀 표시용) |
|
||||
| POST | `/api/travel/reload` | 메모리 캐시 초기화 |
|
||||
|
||||
### insta-lab (insta-lab/)
|
||||
- 인스타그램 카드 피드 자동 생성 — 뉴스 모니터링 → 키워드 추출 → 10페이지 카드 카피 + PNG 렌더 → 텔레그램 푸시 → 사용자 수동 업로드
|
||||
- DB: `/app/data/insta.db` (news_articles, trending_keywords, card_slates, card_assets, generation_tasks, prompt_templates)
|
||||
- 카드 사이즈: 1080×1350 (인스타 4:5 세로)
|
||||
- 카드 렌더: Jinja2 템플릿 → Playwright headless Chromium 스크린샷
|
||||
- 파일 구조: `app/main.py`, `config.py`, `db.py`, `news_collector.py`, `keyword_extractor.py`, `card_writer.py`, `card_renderer.py`, `templates/default/card.html.j2`
|
||||
### blog-lab (blog-lab/)
|
||||
- 블로그 마케팅 수익화 서비스 (키워드 분석 → AI 글 생성 → 마케팅 강화 → 품질 리뷰 → 포스팅 → 수익 추적)
|
||||
- AI 엔진: Claude API (Anthropic, `claude-sonnet-4-20250514`)
|
||||
- 웹 검색: Naver Search API (블로그 + 쇼핑) + 상위 블로그 본문 크롤링
|
||||
- DB: `/app/data/blog_marketing.db`
|
||||
- 파일 구조: `main.py`, `db.py`, `config.py`, `naver_search.py`, `content_generator.py`, `marketer.py`, `quality_reviewer.py`, `web_crawler.py`
|
||||
|
||||
**환경변수**
|
||||
- `NAVER_CLIENT_ID` / `NAVER_CLIENT_SECRET`: 네이버 검색 API
|
||||
- `ANTHROPIC_API_KEY`: Claude API (Haiku=키워드 정제, Sonnet=카드 카피)
|
||||
- `ANTHROPIC_MODEL_HAIKU` / `ANTHROPIC_MODEL_SONNET`: 모델명 오버라이드
|
||||
- `INSTA_DATA_PATH`: SQLite + 카드 PNG 저장 경로 (기본 `/app/data`)
|
||||
- `CARD_TEMPLATE_DIR`: HTML 템플릿 디렉토리 (기본 `/app/app/templates`)
|
||||
- `NEWS_PER_CATEGORY` / `KEYWORDS_PER_CATEGORY`: 수집·추출 limit 튜닝
|
||||
**파이프라인**: 리서치(+크롤링) → 작가(초안) → 마케터(링크 삽입) → 평가자(6기준 60점)
|
||||
**상태 흐름**: `draft` → `marketed` → `reviewed` → `published`
|
||||
|
||||
**카테고리 시드 키워드**
|
||||
- 기본 economy / psychology / celebrity 3종 (config.DEFAULT_CATEGORY_SEEDS)
|
||||
- `prompt_templates.name='category_seeds'`에 JSON으로 오버라이드 가능
|
||||
**blog_marketing.db 테이블**
|
||||
|
||||
**카드 슬레이트 (`card_slates`)**
|
||||
- status: `draft` → `rendered` → `sent` (또는 `failed`)
|
||||
- cover_copy / body_copies (8개) / cta_copy / suggested_caption / hashtags JSON 컬럼
|
||||
- accent_color는 카테고리별 기본값 (economy=#0F62FE, psychology=#A66CFF, celebrity=#FF5C8A)
|
||||
| 테이블 | 설명 |
|
||||
|--------|------|
|
||||
| `keyword_analyses` | 키워드 분석 결과 (네이버 검색 데이터 + 경쟁도/기회 점수 + 크롤링 본문) |
|
||||
| `blog_posts` | 블로그 글 (draft → marketed → reviewed → published) |
|
||||
| `brand_links` | 브랜드커넥트 제휴 링크 (post_id/keyword_id FK) |
|
||||
| `commissions` | 포스트별 월간 클릭/구매/수익 |
|
||||
| `generation_tasks` | 비동기 작업 상태 (research/generate/market/review) |
|
||||
| `prompt_templates` | AI 프롬프트 템플릿 (DB 저장, 코드 배포 없이 수정 가능) |
|
||||
|
||||
**스케줄러 job (agent-office)**
|
||||
- 09:30 매일 — `_run_insta_schedule` (insta_pipeline) → 뉴스 수집 → 키워드 추출 → 텔레그램 후보 푸시
|
||||
- `agent_config.custom_config.auto_select=True`이면 카테고리당 1위 키워드 자동 슬레이트 생성·발송
|
||||
|
||||
**insta-lab API 목록**
|
||||
**blog-lab API 목록**
|
||||
|
||||
| 메서드 | 경로 | 설명 |
|
||||
|--------|------|------|
|
||||
| GET | `/api/insta/status` | 서비스 상태 (NAVER/ANTHROPIC 키 여부) |
|
||||
| POST | `/api/insta/news/collect` | 뉴스 수집 트리거 (BackgroundTask) |
|
||||
| GET | `/api/insta/news/articles` | 수집 기사 목록 (category, days) |
|
||||
| POST | `/api/insta/keywords/extract` | 키워드 추출 트리거 (BackgroundTask) |
|
||||
| GET | `/api/insta/keywords` | 트렌딩 키워드 목록 (category, used) |
|
||||
| POST | `/api/insta/slates` | 슬레이트 생성 (keyword, category) |
|
||||
| GET | `/api/insta/slates` | 슬레이트 목록 |
|
||||
| GET | `/api/insta/slates/{id}` | 슬레이트 상세 + 자산 |
|
||||
| POST | `/api/insta/slates/{id}/render` | 카드 렌더 재시도 |
|
||||
| GET | `/api/insta/slates/{id}/assets/{page}` | 카드 PNG 다운로드 (1~10) |
|
||||
| DELETE | `/api/insta/slates/{id}` | 슬레이트 삭제 (자산 파일 포함) |
|
||||
| GET | `/api/insta/tasks/{task_id}` | BackgroundTask 상태 폴링 |
|
||||
| GET/PUT | `/api/insta/templates/prompts/{name}` | 프롬프트 템플릿 CRUD |
|
||||
| GET | `/api/blog-marketing/status` | 서비스 상태 (API 키 설정 현황) |
|
||||
| POST | `/api/blog-marketing/research` | 키워드 분석 시작 (+ 상위 블로그 크롤링) |
|
||||
| GET | `/api/blog-marketing/research/history` | 분석 이력 조회 |
|
||||
| GET | `/api/blog-marketing/research/{id}` | 분석 상세 조회 |
|
||||
| DELETE | `/api/blog-marketing/research/{id}` | 분석 삭제 |
|
||||
| GET | `/api/blog-marketing/task/{task_id}` | 작업 상태 폴링 |
|
||||
| POST | `/api/blog-marketing/generate` | 작가 단계: AI 글 생성 (크롤링 참고 + 링크 반영) |
|
||||
| POST | `/api/blog-marketing/market/{post_id}` | 마케터 단계: 전환율 강화 + 링크 삽입 |
|
||||
| POST | `/api/blog-marketing/review/{post_id}` | 평가자 단계: 품질 리뷰 (6기준 × 10점, 42/60 통과) |
|
||||
| POST | `/api/blog-marketing/regenerate/{post_id}` | 피드백 기반 재생성 |
|
||||
| POST | `/api/blog-marketing/links` | 브랜드커넥트 링크 등록 |
|
||||
| GET | `/api/blog-marketing/links` | 링크 조회 (post_id, keyword_id 필터) |
|
||||
| PUT | `/api/blog-marketing/links/{id}` | 링크 수정 |
|
||||
| DELETE | `/api/blog-marketing/links/{id}` | 링크 삭제 |
|
||||
| GET | `/api/blog-marketing/posts` | 포스트 목록 (status 필터) |
|
||||
| GET | `/api/blog-marketing/posts/{id}` | 포스트 상세 |
|
||||
| PUT | `/api/blog-marketing/posts/{id}` | 포스트 수정 |
|
||||
| DELETE | `/api/blog-marketing/posts/{id}` | 포스트 삭제 |
|
||||
| POST | `/api/blog-marketing/posts/{id}/publish` | 발행 (네이버 URL 등록) |
|
||||
| GET | `/api/blog-marketing/commissions` | 수익 내역 조회 |
|
||||
| POST | `/api/blog-marketing/commissions` | 수익 기록 추가 |
|
||||
| PUT | `/api/blog-marketing/commissions/{id}` | 수익 기록 수정 |
|
||||
| DELETE | `/api/blog-marketing/commissions/{id}` | 수익 기록 삭제 |
|
||||
| GET | `/api/blog-marketing/dashboard` | 대시보드 집계 |
|
||||
|
||||
**환경변수**
|
||||
- `ANTHROPIC_API_KEY`: Claude API 키 (미설정 시 AI 생성 비활성화)
|
||||
- `NAVER_CLIENT_ID`: 네이버 검색 API 클라이언트 ID
|
||||
- `NAVER_CLIENT_SECRET`: 네이버 검색 API 시크릿
|
||||
- `BLOG_DATA_PATH`: SQLite DB 저장 경로 (기본 `./data/blog`)
|
||||
|
||||
### agent-office (agent-office/)
|
||||
- AI 에이전트 가상 오피스 — 2D 픽셀아트 사무실에서 에이전트가 실제 작업 수행
|
||||
- stock/music-lab/realestate-lab 기존 API를 서비스 프록시로 호출 (직접 DB 접근 없음)
|
||||
- stock-lab/music-lab 기존 API를 서비스 프록시로 호출 (직접 DB 접근 없음)
|
||||
- 실시간 상태 동기화: WebSocket (`/api/agent-office/ws`)
|
||||
- 텔레그램 봇: 양방향 알림 + 승인 (인라인 키보드)
|
||||
- 청약 매칭 알림: realestate-lab이 신규 매칭 발견 시 push → `RealestateAgent.on_new_matches()` → 텔레그램 1통(인라인 [🔖 북마크]/[📄 공고] 또는 [전체 보기] 버튼)
|
||||
- DB: `/app/data/agent_office.db` (agent_config, agent_tasks, agent_logs, telegram_state 테이블)
|
||||
- 파일 구조: `main.py`, `db.py`, `config.py`, `models.py`, `websocket_manager.py`, `service_proxy.py`, `telegram_bot.py`, `scheduler.py`, `agents/base.py`, `agents/stock.py`, `agents/music.py`, `agents/realestate.py`, `telegram/realestate_message.py`
|
||||
- 파일 구조: `main.py`, `db.py`, `config.py`, `models.py`, `websocket_manager.py`, `service_proxy.py`, `telegram_bot.py`, `scheduler.py`, `agents/base.py`, `agents/stock.py`, `agents/music.py`
|
||||
|
||||
**에이전트 FSM 상태**: idle → working → waiting (승인 대기) → reporting → break (휴식)
|
||||
|
||||
**환경변수**
|
||||
- `STOCK_URL`: stock 내부 URL (기본 `http://stock:8000`)
|
||||
- `STOCK_LAB_URL`: stock-lab 내부 URL (기본 `http://stock-lab:8000`)
|
||||
- `MUSIC_LAB_URL`: music-lab 내부 URL (기본 `http://music-lab:8000`)
|
||||
- `REALESTATE_LAB_URL`: realestate-lab 내부 URL (기본 `http://realestate-lab:8000`) — 북마크 콜백 프록시 대상
|
||||
- `REALESTATE_DASHBOARD_URL`: 텔레그램 [전체 보기] 버튼 URL (기본 `http://localhost:8080/realestate`)
|
||||
- `TELEGRAM_BOT_TOKEN`: 텔레그램 봇 토큰 (미설정 시 알림 비활성화)
|
||||
- `TELEGRAM_CHAT_ID`: 텔레그램 채팅 ID
|
||||
- `TELEGRAM_WEBHOOK_URL`: 텔레그램 Webhook URL
|
||||
- `TELEGRAM_WIFE_CHAT_ID`: 아내 chat.id (브리핑 공유 + 대화 허용)
|
||||
- `ANTHROPIC_API_KEY`: 자연어 대화용 Claude API 키 (미설정 시 대화 비활성)
|
||||
- `CONVERSATION_MODEL`: 대화 모델 (기본 `claude-haiku-4-5-20251001`)
|
||||
- `CONVERSATION_HISTORY_LIMIT`: 이력 주입 수 (기본 20)
|
||||
- `CONVERSATION_RATE_PER_MIN`: 채팅당 분당 최대 메시지 (기본 6)
|
||||
- `LOTTO_BACKEND_URL`: 기본 `http://lotto:8000`
|
||||
- `LOTTO_CURATOR_MODEL`: 기본 `claude-sonnet-4-5`
|
||||
- `YOUTUBE_DATA_API_KEY`: YouTube Data API v3 키 (미설정 시 YouTube trending 수집 skip)
|
||||
|
||||
**YouTubeResearchAgent (`agents/youtube.py`)**
|
||||
- `agent_id = "youtube"` — AGENT_REGISTRY에 등록
|
||||
- 09:00 매일 `on_schedule()` → 국가별 YouTube 트렌딩 + Google Trends + Billboard Top20 수집 → music-lab push
|
||||
- `on_command("research", {countries: []})` → 수동 트리거 (백그라운드 asyncio.create_task)
|
||||
- 수집 소스: `youtube_researcher.py` (fetch_youtube_trending, fetch_google_trends, fetch_billboard_top20)
|
||||
- DB: `youtube_research_jobs` 테이블에 실행 이력 기록
|
||||
- 동시실행 방지: `self.state == "working"` 체크 후 거부
|
||||
- 월요일 08:00 `send_weekly_report()` → music-lab 최신 리포트 → 텔레그램 발송
|
||||
|
||||
**텔레그램 자연어 대화 (옵션 B)**
|
||||
- 슬래시 명령이 아닌 일반 문장을 보내면 Claude Haiku 4.5가 응답
|
||||
- 프롬프트 캐싱: `system` 블록 + 히스토리 마지막 블록에 `cache_control: ephemeral` → 5분 TTL
|
||||
- 허용 chat_id 화이트리스트: `TELEGRAM_CHAT_ID`, `TELEGRAM_WIFE_CHAT_ID`
|
||||
- 평가 지표: `conversation_messages` 테이블에 tokens / cache_read / cache_write / latency 기록
|
||||
- 조회: `GET /api/agent-office/conversation/stats?days=7`
|
||||
|
||||
**스케줄러 job**
|
||||
- 07:30 매일 — 주식 뉴스 요약 (`stock_news_job`)
|
||||
- 매주 월요일 07:00 — 로또 큐레이터 브리핑 (`lotto_curate`)
|
||||
- 08:00 매일 — 주식 뉴스 요약 (`stock_news_job`)
|
||||
- 60초 간격 — 유휴 에이전트 휴식 체크 (`idle_check_job`)
|
||||
- ~~09:15 매일 — 청약 매칭 데일리 리포트~~ (Task 2026-04-28에서 폐기. realestate-lab의 push 트리거로 전환)
|
||||
- 09:00 매일 — YouTube 트렌드 수집 (`youtube_research`) → music-lab `/api/music/market/ingest` push
|
||||
- 매주 월요일 08:00 — YouTube 주간 리포트 텔레그램 발송 (`youtube_weekly_report`)
|
||||
|
||||
**RealestateAgent (`agents/realestate.py`)**
|
||||
- 진입점: `on_new_matches(matches: list[dict]) -> {sent, sent_ids, message_id}`
|
||||
- realestate-lab의 push에서 트리거 → `format_realestate_matches()` + `build_match_keyboard()` → `messaging.send_raw()`
|
||||
- 1~2건이면 풀 카드 + [🔖 북마크]/[📄 공고 보기] 행씩, 3건 이상이면 묶음 카드 + [📋 전체 보기] 단일 URL 버튼
|
||||
- 인라인 키보드 콜백 `realestate_bookmark_{id}` → `webhook.py`의 `_handle_realestate_bookmark` → `service_proxy.realestate_bookmark_toggle()` → realestate-lab의 `PATCH /announcements/{id}/bookmark`
|
||||
- 송신 성공 시 sent_ids 반환 → realestate-lab이 match_results.notified_at 마킹 (멱등)
|
||||
- 실패 시 sent=0/sent_ids=[]/error 반환 → 마킹 안 됨 → 다음 사이클 재시도
|
||||
- `on_command("fetch_matches")`: 수동 트리거 — service_proxy로 매치 가져와 `on_new_matches` 호출
|
||||
- `on_schedule`: 폐기 (cron 등록 제거됨)
|
||||
|
||||
**agent-office API 목록**
|
||||
|
||||
@@ -576,100 +444,8 @@ docker compose up -d
|
||||
| GET | `/api/agent-office/tasks/{id}` | 작업 상세 |
|
||||
| POST | `/api/agent-office/command` | 에이전트에 명령 전송 |
|
||||
| POST | `/api/agent-office/approve` | 작업 승인/거부 |
|
||||
| POST | `/api/agent-office/telegram/webhook` | 텔레그램 Webhook 수신 (realestate_bookmark_* 콜백 포함) |
|
||||
| POST | `/api/agent-office/realestate/notify` | realestate-lab 전용 push 수신 → 텔레그램 송신 |
|
||||
| POST | `/api/agent-office/telegram/webhook` | 텔레그램 Webhook 수신 |
|
||||
| GET | `/api/agent-office/states` | 전체 에이전트 상태 조회 |
|
||||
| GET | `/api/agent-office/conversation/stats` | 텔레그램 자연어 대화 토큰·캐시 통계 (`days` 필터) |
|
||||
| POST | `/api/agent-office/youtube/research` | YouTube 트렌드 수집 수동 트리거 (body: `{countries: []}`) |
|
||||
| GET | `/api/agent-office/youtube/research/status` | 마지막 수집 작업 상태 |
|
||||
|
||||
### personal (personal/)
|
||||
- 개인 서비스 (포트폴리오 + 블로그 + 투두 통합)
|
||||
- DB: `/app/data/personal.db` (profile, careers, projects, skills, introductions, todos, blog_posts 테이블)
|
||||
- 편집 인증: `PORTFOLIO_EDIT_PASSWORD` 환경변수, Bearer 토큰 (24시간 TTL)
|
||||
- 파일 구조: `main.py`, `db.py`, `models.py`, `auth.py`
|
||||
|
||||
**환경변수**
|
||||
- `PORTFOLIO_EDIT_PASSWORD`: 편집 모드 비밀번호 (미설정 시 편집 불가)
|
||||
|
||||
**personal API 목록**
|
||||
|
||||
| 메서드 | 경로 | 설명 |
|
||||
|--------|------|------|
|
||||
| GET | `/api/profile/public` | 공개 데이터 일괄 조회 |
|
||||
| POST | `/api/profile/auth` | 비밀번호 인증 → 토큰 |
|
||||
| GET | `/api/profile/profile` | 프로필 조회 (인증) |
|
||||
| PUT | `/api/profile/profile` | 프로필 수정 (인증) |
|
||||
| GET | `/api/profile/careers` | 경력 목록 (인증) |
|
||||
| POST | `/api/profile/careers` | 경력 추가 (인증) |
|
||||
| PUT | `/api/profile/careers/{id}` | 경력 수정 (인증) |
|
||||
| DELETE | `/api/profile/careers/{id}` | 경력 삭제 (인증) |
|
||||
| GET | `/api/profile/projects` | 프로젝트 목록 (인증) |
|
||||
| POST | `/api/profile/projects` | 프로젝트 추가 (인증) |
|
||||
| PUT | `/api/profile/projects/{id}` | 프로젝트 수정 (인증) |
|
||||
| DELETE | `/api/profile/projects/{id}` | 프로젝트 삭제 (인증) |
|
||||
| GET | `/api/profile/skills` | 기술 목록 (인증) |
|
||||
| POST | `/api/profile/skills` | 기술 추가 (인증) |
|
||||
| PUT | `/api/profile/skills/{id}` | 기술 수정 (인증) |
|
||||
| DELETE | `/api/profile/skills/{id}` | 기술 삭제 (인증) |
|
||||
| GET | `/api/profile/introductions` | 자기소개 목록 (인증) |
|
||||
| POST | `/api/profile/introductions` | 자기소개 추가 (인증) |
|
||||
| PUT | `/api/profile/introductions/{id}` | 자기소개 수정 (인증) |
|
||||
| DELETE | `/api/profile/introductions/{id}` | 자기소개 삭제 (인증) |
|
||||
| PATCH | `/api/profile/introductions/{id}/main` | 메인 자기소개 지정 (인증) |
|
||||
| GET | `/api/todos` | 투두 전체 목록 |
|
||||
| POST | `/api/todos` | 투두 생성 |
|
||||
| PUT | `/api/todos/{id}` | 투두 수정 |
|
||||
| DELETE | `/api/todos/done` | 완료 항목 일괄 삭제 |
|
||||
| DELETE | `/api/todos/{id}` | 투두 개별 삭제 |
|
||||
| GET | `/api/blog/posts` | 블로그 글 목록 |
|
||||
| POST | `/api/blog/posts` | 블로그 글 생성 |
|
||||
| PUT | `/api/blog/posts/{id}` | 블로그 글 수정 |
|
||||
| DELETE | `/api/blog/posts/{id}` | 블로그 글 삭제 |
|
||||
|
||||
### packs-lab (packs-lab/)
|
||||
- NAS 자료 다운로드 자동화 — Synology DSM 공유링크 발급 + 5GB 멀티파트 업로드 수신
|
||||
- Vercel SaaS와 HMAC 인증으로 통신, 사용자 인증은 Vercel이 Supabase로 처리 (본 서비스는 외부 인증 없음)
|
||||
- DB: 외부 Supabase `pack_files` 테이블 (DDL: `packs-lab/supabase/pack_files.sql`)
|
||||
- 파일 구조: `app/main.py`, `app/auth.py`, `app/dsm_client.py`, `app/routes.py`, `app/models.py`
|
||||
- 경로 3분리: `PACK_DATA_PATH`(호스트 OS path, docker volume 좌측) → `PACK_BASE_DIR`(컨테이너 내부, upload 저장 target) → `PACK_HOST_DIR`(DSM API path, Supabase에 저장). 운영 NAS에서 `PACK_HOST_DIR` 미설정 시 sign-link가 컨테이너 경로를 DSM에 전달해 파일을 못 찾음.
|
||||
- ⚠️ **DSM API path 형식**: Synology DSM API는 일반 사용자 권한일 때 `/<shared_folder>/...` 형식만 인식하고 `/volume1/...` 절대경로는 거부(error 408). 운영 NAS는 반드시 `PACK_HOST_DIR=/docker/webpage/media/packs` (shared folder 시점) 설정. admin 사용자만 `/volume1/...` 사용 가능하나 보안상 권장 안 함.
|
||||
|
||||
**환경변수**
|
||||
- `DSM_HOST` / `DSM_USER` / `DSM_PASS`: Synology DSM 7.x 인증 (공유 링크 발급용)
|
||||
- `DSM_VERIFY_SSL`: SSL 검증 (default `true`). LAN IP + self-signed cert 환경에서 IP mismatch 시 `false` 설정 (LAN 내부 통신이라 허용)
|
||||
- `BACKEND_HMAC_SECRET`: Vercel SaaS와 양쪽 공유 시크릿 (HMAC SHA256)
|
||||
- `SUPABASE_URL` / `SUPABASE_SERVICE_KEY`: Supabase pack_files 테이블 접근 (service_role, RLS 우회)
|
||||
- `UPLOAD_TOKEN_TTL_SEC`: admin upload 토큰 TTL (기본 1800초 = 30분)
|
||||
- `PACK_BASE_DIR`: 컨테이너 내부 저장 경로 (기본 `/app/data/packs`)
|
||||
- `PACK_HOST_DIR`: DSM API용 path. **운영 NAS는 `/docker/webpage/media/packs` (shared folder 시점)**. 미설정 시 `PACK_BASE_DIR`로 fallback (DSM 호출 X 환경에서만 안전)
|
||||
- `PACK_DATA_PATH`: docker-compose volume 마운트의 호스트 측 OS 경로 (로컬 `./data/packs`, NAS `/volume1/docker/webpage/media/packs`)
|
||||
|
||||
**HMAC 인증 패턴**
|
||||
- Vercel → backend 요청: `X-Timestamp` (UNIX 초) + `X-Signature` (HMAC_SHA256(timestamp + "." + body, secret))
|
||||
- Replay 방어: 타임스탬프 ±5분 윈도우
|
||||
- admin browser → backend upload: `Authorization: Bearer <token>` (jti 단발성)
|
||||
|
||||
**packs-lab API 목록**
|
||||
|
||||
| 메서드 | 경로 | 설명 |
|
||||
|--------|------|------|
|
||||
| POST | `/api/packs/sign-link` | Vercel HMAC → DSM Sharing.create로 4시간 유효 다운로드 URL 발급 |
|
||||
| POST | `/api/packs/admin/mint-token` | Vercel HMAC → 일회성 upload 토큰 발급 (기본 30분 TTL) |
|
||||
| POST | `/api/packs/upload` | Bearer token (single-shot) → multipart 5GB 저장 + Supabase INSERT |
|
||||
| POST | `/api/packs/upload/init` | Bearer token → chunked upload 세션 초기화 (`session_id = jti`, `chunk_max_size` 반환). init만 jti consume |
|
||||
| PUT | `/api/packs/upload/{session_id}/chunk?offset=N` | 동일 Bearer token → 부분파일 append (offset 불일치 시 409 + `X-Current-Offset` 헤더) |
|
||||
| GET | `/api/packs/upload/{session_id}/status` | 동일 Bearer token → `{written, expected_size}` 조회 (재개용) |
|
||||
| POST | `/api/packs/upload/{session_id}/complete` | 동일 Bearer token → 부분파일 rename + Supabase INSERT |
|
||||
| DELETE | `/api/packs/upload/{session_id}` | 동일 Bearer token → 세션 중단 + 부분파일 정리 |
|
||||
| GET | `/api/packs/list` | Vercel HMAC → 활성 pack_files 목록 (deleted_at IS NULL) |
|
||||
| DELETE | `/api/packs/{file_id}` | Vercel HMAC → soft delete (DSM 공유는 자동 만료) |
|
||||
|
||||
**Chunked upload 흐름 (5GB+ 안정성)**
|
||||
- 같은 mint-token을 init·chunk·status·complete·abort 전체에서 Bearer로 재사용 (jti consume은 init에서만)
|
||||
- 세션 state: 컨테이너 내부 `PACK_BASE_DIR/.uploads/{jti}/meta.json + data.part`
|
||||
- chunk 재시도: 클라이언트는 PUT 응답 헤더 `X-Current-Offset` 또는 `GET /status`로 재개 지점 확인
|
||||
- 환경변수 `PACK_CHUNK_MAX_SIZE` (기본 64MB) — 너무 크면 nginx buffering 부담, 너무 작으면 RTT 비용
|
||||
|
||||
### deployer (deployer/)
|
||||
- Webhook 검증: `X-Gitea-Signature` (HMAC SHA256, `compare_digest` 사용)
|
||||
@@ -682,13 +458,12 @@ docker compose up -d
|
||||
## 10. 주의사항
|
||||
|
||||
- **Nginx trailing slash**: `/api/portfolio`는 trailing slash 없이도 매칭되도록 두 location 블록으로 처리
|
||||
- **라우트 순서**: `DELETE /api/todos/done`은 `DELETE /api/todos/{id}` 보다 **반드시 먼저** 등록 (personal 서비스, FastAPI prefix 매칭 순서)
|
||||
- **라우트 순서**: `DELETE /api/todos/done`은 `DELETE /api/todos/{id}` 보다 **반드시 먼저** 등록 (FastAPI prefix 매칭 순서)
|
||||
- **PUID/PGID**: travel-proxy는 NAS 파일 권한을 위해 PUID/PGID를 환경변수로 주입
|
||||
- **캐시 전략**: `index.html`은 `no-store`, `assets/`는 1년 장기 캐시(immutable)
|
||||
- **Frontend 배포**: git push로 자동 배포되지 않음. 로컬 빌드 후 NAS에 수동 업로드
|
||||
- **.env 파일**: 절대 커밋 금지. `.env.example`만 레포에 포함
|
||||
- **공휴일 목록**: `stock/app/holidays.json` 매년 수동 갱신 필요 (KRX 기준)
|
||||
- **공휴일 목록**: `stock-lab/app/holidays.json` 매년 수동 갱신 필요 (KRX 기준)
|
||||
- **Windows AI 서버 IP**: `192.168.45.59` — 공유기 DHCP 고정 예약으로 고정. Tailscale은 Synology에서 TCP 불가(userspace 모드)라 로컬 IP 사용
|
||||
- **현재가 조회**: 네이버 모바일 API → HTML 파싱 폴백, 3분 TTL 캐시 (`price_fetcher.py`)
|
||||
- **시뮬레이션 교체 방식**: `best_picks`는 교체형 — 새 시뮬레이션 실행 시 `is_active=0`으로 비활성화 후 신규 입력
|
||||
- **insta-lab Playwright**: NAS에서 chromium 빌드는 가능하지만 +500MB 이미지. 메모리 부족 시 카드 렌더 실패 가능 — 한 번에 1슬레이트만 렌더하도록 직렬화됨
|
||||
|
||||
379
README.md
379
README.md
@@ -1,40 +1,31 @@
|
||||
# web-backend
|
||||
|
||||
Synology NAS 기반 개인 웹 플랫폼 백엔드 모노레포.
|
||||
로또 분석, 주식 포트폴리오, AI 음악 생성, 블로그 마케팅, 부동산 청약, AI 에이전트 오피스, 여행 앨범을 하나의 Docker Compose 스택으로 운영한다.
|
||||
로또 분석, 주식 포트폴리오, 여행 앨범, 블로그, 투두리스트를 하나의 서비스로 운영한다.
|
||||
|
||||
---
|
||||
|
||||
## 서비스 구성
|
||||
|
||||
```
|
||||
┌──────────────────────────────────────────────────────────────────────┐
|
||||
│ lotto-frontend (Nginx:8080) │
|
||||
│ ├── 정적 SPA 서빙 (React + Vite) │
|
||||
│ └── API 리버스 프록시 │
|
||||
│ ├── /api/ → lotto-backend:8000 (로또·블로그·투두)│
|
||||
│ ├── /api/stock/, /trade/ → stock:8000 │
|
||||
│ ├── /api/portfolio → stock:8000 │
|
||||
│ ├── /api/music/ → music-lab:8000 │
|
||||
│ ├── /api/blog-marketing/ → blog-lab:8000 │
|
||||
│ ├── /api/realestate/ → realestate-lab:8000 │
|
||||
│ ├── /api/agent-office/ → agent-office:8000 (+ WebSocket) │
|
||||
│ ├── /api/travel/ → travel-proxy:8000 │
|
||||
│ ├── /media/music/… (nginx 직접 서빙, 생성 오디오) │
|
||||
│ ├── /media/travel/… (nginx 직접 서빙, 사진/썸네일) │
|
||||
│ └── /webhook → deployer:9000 │
|
||||
└──────────────────────────────────────────────────────────────────────┘
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ lotto-frontend (Nginx:8080) │
|
||||
│ ├── 정적 SPA 서빙 (React + Vite) │
|
||||
│ └── API 리버스 프록시 │
|
||||
│ ├── /api/ → lotto-backend:8000 │
|
||||
│ ├── /api/stock/ → stock-lab:8000 │
|
||||
│ ├── /api/trade/ → stock-lab:8000 │
|
||||
│ ├── /api/portfolio → stock-lab:8000 │
|
||||
│ ├── /api/travel/ → travel-proxy:8000 │
|
||||
│ └── /webhook → deployer:9000 │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
| 컨테이너 | 포트 | 역할 |
|
||||
|---------|------|------|
|
||||
| `lotto-backend` | 18000 | 로또 데이터 수집·분석·추천 + 블로그·투두 API |
|
||||
| `stock` | 18500 | 주식 뉴스·AI 요약·KIS 실계좌·포트폴리오·자산 추적 |
|
||||
| `music-lab` | 18600 | AI 음악 생성 (Suno + 로컬 MusicGen 듀얼 프로바이더) |
|
||||
| `blog-lab` | 18700 | 블로그 마케팅 수익화 (키워드→글 생성→리뷰→발행) |
|
||||
| `realestate-lab` | 18800 | 청약 공고 자동 수집·프로필 매칭 |
|
||||
| `agent-office` | 18900 | AI 에이전트 가상 오피스 (WebSocket + 텔레그램 봇) |
|
||||
| `travel-proxy` | 19000 | 여행 사진 API + 온디맨드 썸네일 |
|
||||
| `lotto-backend` | 18000 | 로또·블로그·투두 API |
|
||||
| `stock-lab` | 18500 | 주식 뉴스·포트폴리오·자산 추적 |
|
||||
| `travel-proxy` | 19000 | 여행 사진 API + 썸네일 생성 |
|
||||
| `lotto-frontend` | 8080 | SPA 서빙 + 리버스 프록시 |
|
||||
| `webpage-deployer` | 19010 | Gitea Webhook → 자동 배포 |
|
||||
|
||||
@@ -44,19 +35,47 @@ Synology NAS 기반 개인 웹 플랫폼 백엔드 모노레포.
|
||||
|
||||
```
|
||||
web-backend/
|
||||
├── backend/ # lotto-backend (로또·블로그·투두)
|
||||
├── stock/ # 주식·포트폴리오
|
||||
├── music-lab/ # AI 음악 생성
|
||||
├── blog-lab/ # 블로그 마케팅 파이프라인
|
||||
├── realestate-lab/ # 청약 자동 수집·매칭
|
||||
├── agent-office/ # AI 에이전트 오피스 (WS + 텔레그램)
|
||||
├── travel-proxy/ # 여행 사진 + 썸네일
|
||||
├── deployer/ # Gitea Webhook 수신 → 자동 배포
|
||||
├── nginx/default.conf # 리버스 프록시 + SPA + 캐시
|
||||
├── scripts/ # deploy.sh, deploy-nas.sh, healthcheck.sh
|
||||
├── backend/ # lotto-backend 서비스 (Python/FastAPI)
|
||||
│ ├── app/
|
||||
│ │ ├── main.py # 라우터, 스케줄러
|
||||
│ │ ├── db.py # SQLite CRUD (7개 테이블)
|
||||
│ │ ├── generator.py # 몬테카를로 시뮬레이션 엔진
|
||||
│ │ ├── analyzer.py # 5가지 통계 분석
|
||||
│ │ ├── checker.py # 당첨 결과 채점
|
||||
│ │ ├── collector.py # 로또 데이터 수집
|
||||
│ │ ├── recommender.py # 추천 알고리즘
|
||||
│ │ └── utils.py # 메트릭 계산
|
||||
│ └── Dockerfile
|
||||
│
|
||||
├── stock-lab/ # stock-lab 서비스 (Python/FastAPI)
|
||||
│ ├── app/
|
||||
│ │ ├── main.py # 라우터, 스케줄러
|
||||
│ │ ├── db.py # SQLite CRUD (4개 테이블)
|
||||
│ │ ├── scraper.py # 네이버 금융 뉴스 크롤링
|
||||
│ │ ├── price_fetcher.py # 현재가 조회 (3분 캐시)
|
||||
│ │ └── holidays.json # 한국 주식시장 휴장일
|
||||
│ └── Dockerfile
|
||||
│
|
||||
├── travel-proxy/ # travel-proxy 서비스 (Python/FastAPI)
|
||||
│ ├── app/
|
||||
│ │ └── main.py # 사진 API, 썸네일 생성 (Pillow)
|
||||
│ └── Dockerfile
|
||||
│
|
||||
├── deployer/ # Gitea Webhook 수신 → 자동 배포
|
||||
│ ├── app.py # HMAC SHA256 검증 + 배포 트리거
|
||||
│ └── Dockerfile
|
||||
│
|
||||
├── nginx/
|
||||
│ └── default.conf # 리버스 프록시 + SPA + 캐시
|
||||
│
|
||||
├── scripts/
|
||||
│ ├── deploy.sh # 운영 배포 (git pull → rsync → compose up)
|
||||
│ ├── deploy-nas.sh # rsync 전용 스크립트
|
||||
│ └── healthcheck.sh # 전체 서비스 헬스 체크
|
||||
│
|
||||
├── docker-compose.yml
|
||||
├── .env.example
|
||||
└── CLAUDE.md # Claude Code 작업용 상세 컨텍스트
|
||||
└── CLAUDE.md
|
||||
```
|
||||
|
||||
---
|
||||
@@ -64,9 +83,13 @@ web-backend/
|
||||
## 빠른 시작 (로컬 개발)
|
||||
|
||||
```bash
|
||||
# 1. 환경변수 설정
|
||||
cp .env.example .env
|
||||
|
||||
# 2. 컨테이너 실행 (.env 기본값으로 즉시 실행 가능)
|
||||
docker compose up -d
|
||||
|
||||
# 3. 확인
|
||||
curl http://localhost:18000/health
|
||||
curl http://localhost:18500/health
|
||||
```
|
||||
@@ -75,133 +98,107 @@ curl http://localhost:18500/health
|
||||
|--------|----------|
|
||||
| Frontend + API | http://localhost:8080 |
|
||||
| lotto-backend | http://localhost:18000 |
|
||||
| stock | http://localhost:18500 |
|
||||
| music-lab | http://localhost:18600 |
|
||||
| blog-lab | http://localhost:18700 |
|
||||
| realestate-lab | http://localhost:18800 |
|
||||
| agent-office | http://localhost:18900 |
|
||||
| stock-lab | http://localhost:18500 |
|
||||
| travel-proxy | http://localhost:19000 |
|
||||
|
||||
---
|
||||
|
||||
## 서비스별 기능
|
||||
## API 목록
|
||||
|
||||
### 1. lotto-backend (`/api/`)
|
||||
### lotto-backend (`/api/`)
|
||||
|
||||
로또 당첨번호 수집·통계 분석·몬테카를로 시뮬레이션 기반 추천 + 투두·블로그 CRUD.
|
||||
#### 로또
|
||||
|
||||
- **로또**: 당첨번호 조회, 5종 통계 분석, 시뮬레이션 최적 번호(`best_picks` 20쌍), 통계/히트맵/스마트/배치 추천, 전략 가중치(EMA+Softmax), 구매 이력 관리
|
||||
- **추천 이력**: 즐겨찾기·태그·메모 관리
|
||||
- **투두리스트**: UUID PK, 상태(todo/in_progress/done)
|
||||
- **블로그**: 일기형 포스트 (tags JSON 배열, date DESC)
|
||||
| 메서드 | 경로 | 설명 |
|
||||
|--------|------|------|
|
||||
| GET | `/api/lotto/latest` | 최신 당첨번호 |
|
||||
| GET | `/api/lotto/{drw_no}` | 특정 회차 |
|
||||
| GET | `/api/lotto/stats` | 번호 빈도 통계 |
|
||||
| GET | `/api/lotto/analysis` | 5가지 통계 분석 리포트 |
|
||||
| GET | `/api/lotto/best` | 시뮬레이션 최적 번호 (기본 20쌍) |
|
||||
| GET | `/api/lotto/simulation` | 시뮬레이션 상세 결과 |
|
||||
| GET | `/api/lotto/recommend` | 통계 기반 추천 |
|
||||
| GET | `/api/lotto/recommend/heatmap` | 히트맵 기반 추천 |
|
||||
| GET | `/api/lotto/recommend/batch` | 배치 추천 |
|
||||
| POST | `/api/admin/simulate` | 시뮬레이션 수동 실행 |
|
||||
| POST | `/api/admin/sync_latest` | 당첨번호 수동 동기화 |
|
||||
|
||||
**스케줄러**
|
||||
- 09:10 / 21:10 — 당첨번호 동기화 + 추천 채점
|
||||
- 00:05, 04:05, 08:05, 12:05, 16:05, 20:05 — 몬테카를로 시뮬레이션 (후보 20,000 → 상위 100 → best_picks 20쌍 교체)
|
||||
#### 추천 이력
|
||||
|
||||
### 2. stock (`/api/stock/`, `/api/trade/`, `/api/portfolio`)
|
||||
| 메서드 | 경로 | 설명 |
|
||||
|--------|------|------|
|
||||
| GET | `/api/history` | 목록 (limit, offset, favorite, tag, sort) |
|
||||
| PATCH | `/api/history/{id}` | 즐겨찾기·메모·태그 수정 |
|
||||
| DELETE | `/api/history/{id}` | 삭제 |
|
||||
|
||||
주식 뉴스 스크래핑 + LLM 요약 + KIS 실계좌 연동 + 포트폴리오·자산 스냅샷.
|
||||
#### 투두리스트
|
||||
|
||||
- **뉴스**: 네이버 증권 + 해외 사이트 크롤링, LLM 기반 한국어 요약
|
||||
- **실계좌**: Windows AI 서버(192.168.45.59:8000) 프록시 → KIS Open API (잔고/주문)
|
||||
- **포트폴리오**: 종목·예수금·매도 히스토리 관리, 현재가 자동 조회
|
||||
- **자산 스냅샷**: 평일 15:40 자동 저장 (KRX 공휴일 판별, `holidays.json` 매년 갱신)
|
||||
| 메서드 | 경로 | 설명 |
|
||||
|--------|------|------|
|
||||
| GET | `/api/todos` | 전체 목록 |
|
||||
| POST | `/api/todos` | 생성 (status: todo\|in_progress\|done) |
|
||||
| PUT | `/api/todos/{id}` | 수정 |
|
||||
| DELETE | `/api/todos/done` | 완료 항목 일괄 삭제 |
|
||||
| DELETE | `/api/todos/{id}` | 개별 삭제 |
|
||||
|
||||
**LLM provider 전환** — `LLM_PROVIDER` 환경변수
|
||||
- `claude` (기본): Anthropic Messages API (`claude-haiku-4-5`)
|
||||
- `ollama`: Windows AI 서버 Ollama (`qwen3:14b`)
|
||||
> ⚠️ `/done` 라우트는 반드시 `/{id}` 보다 먼저 등록해야 함
|
||||
|
||||
**현재가 조회**: 네이버 모바일 API → HTML 파싱 폴백, 3분 TTL 메모리 캐시
|
||||
#### 블로그
|
||||
|
||||
### 3. music-lab (`/api/music/`)
|
||||
| 메서드 | 경로 | 설명 |
|
||||
|--------|------|------|
|
||||
| GET | `/api/blog/posts` | 글 목록 (`{"posts": [...]}`, date DESC) |
|
||||
| POST | `/api/blog/posts` | 글 생성 (date 미입력 시 오늘 날짜) |
|
||||
| PUT | `/api/blog/posts/{id}` | 글 수정 |
|
||||
| DELETE | `/api/blog/posts/{id}` | 글 삭제 |
|
||||
|
||||
듀얼 프로바이더 AI 음악 생성.
|
||||
블로그 포스트 구조: `{ id, title, tags[], body, date, excerpt, created_at, updated_at }`
|
||||
|
||||
- **Suno** (`suno`): REST API 연동, 보컬·가사·인스트루멘탈. 1회 요청 시 2개 variation 생성, 곡 연장, 보컬 분리, WAV 변환, 12스템 분리, 뮤직비디오, AI Cover 등 풀 스위트 지원
|
||||
- **로컬 MusicGen** (`local`): Windows AI PC(RTX 5070 Ti, 16GB VRAM) 인스트루멘탈 전용
|
||||
- **라이브러리**: 생성 파일은 `/app/data/music/`에 저장되고 Nginx가 `/media/music/`으로 직접 서빙
|
||||
- **가사 도구**: 저장·편집·타임스탬프 기반 가라오케 동기
|
||||
---
|
||||
|
||||
### 4. blog-lab (`/api/blog-marketing/`)
|
||||
### stock-lab (`/api/stock/`, `/api/trade/`, `/api/portfolio`)
|
||||
|
||||
블로그 마케팅 수익화 4단계 파이프라인 (`draft → marketed → reviewed → published`).
|
||||
#### 뉴스 & 지표
|
||||
|
||||
```
|
||||
리서치(Naver Search + 상위 블로그 본문 크롤링)
|
||||
→ 작가(AI 초안 생성)
|
||||
→ 마케터(전환율 강화 + 브랜드 링크 삽입)
|
||||
→ 평가자(6기준×10점, 42/60 통과 시 published)
|
||||
```
|
||||
| 메서드 | 경로 | 설명 |
|
||||
|--------|------|------|
|
||||
| GET | `/api/stock/news` | 뉴스 목록 (limit, category) |
|
||||
| GET | `/api/stock/indices` | 주요 지표 (KOSPI 등) |
|
||||
| POST | `/api/stock/scrap` | 뉴스 수동 스크랩 |
|
||||
|
||||
- **AI 엔진**: Claude API (`claude-sonnet-4-20250514`)
|
||||
- **키워드 분석**: 네이버 검색(블로그+쇼핑) API + 경쟁도/기회 점수
|
||||
- **수익 추적**: 포스트별 월간 클릭/구매/수익 기록
|
||||
- **프롬프트 템플릿**: DB에 저장 → 코드 배포 없이 수정 가능
|
||||
#### 실계좌 (Windows AI 서버 프록시)
|
||||
|
||||
### 5. realestate-lab (`/api/realestate/`)
|
||||
| 메서드 | 경로 | 설명 |
|
||||
|--------|------|------|
|
||||
| GET | `/api/trade/balance` | 실계좌 잔고 조회 |
|
||||
| POST | `/api/trade/order` | 주문 (BUY\|SELL, price=0이면 시장가) |
|
||||
|
||||
공공데이터포털 청약홈 API 연동 + 프로필 기반 자동 매칭.
|
||||
#### 포트폴리오
|
||||
|
||||
- **공고 수집**: 09:00 매일 자동 (`DATA_GO_KR_API_KEY` 필요)
|
||||
- **상태 갱신 + 재매칭**: 00:00 매일 자동
|
||||
- **프로필 매칭**: 지역·주택형·소득·부양가족 등으로 점수화, 신규 매칭 알림
|
||||
- **대시보드**: 진행 중 공고수, 신규 매칭수, 다가오는 일정 요약
|
||||
| 메서드 | 경로 | 설명 |
|
||||
|--------|------|------|
|
||||
| GET | `/api/portfolio` | 전체 조회 (현재가·손익·예수금 포함) |
|
||||
| POST | `/api/portfolio` | 종목 추가 |
|
||||
| PUT | `/api/portfolio/{id}` | 종목 수정 |
|
||||
| DELETE | `/api/portfolio/{id}` | 종목 삭제 |
|
||||
| GET | `/api/portfolio/cash` | 예수금 전체 조회 |
|
||||
| PUT | `/api/portfolio/cash` | 예수금 upsert |
|
||||
| DELETE | `/api/portfolio/cash/{broker}` | 예수금 삭제 |
|
||||
| POST | `/api/portfolio/snapshot` | 총 자산 스냅샷 수동 저장 |
|
||||
| GET | `/api/portfolio/snapshot/history` | 자산 변화 이력 (days=0: 전체) |
|
||||
|
||||
### 6. agent-office (`/api/agent-office/`)
|
||||
---
|
||||
|
||||
AI 에이전트 가상 오피스 — 2D 픽셀아트 사무실에서 4명의 에이전트가 실제 작업을 수행한다.
|
||||
### travel-proxy (`/api/travel/`)
|
||||
|
||||
- **아키텍처**: stock / music-lab / blog-lab / realestate-lab 기존 API를 서비스 프록시로 호출 (직접 DB 접근 없음)
|
||||
- **FSM 상태**: `idle → working → waiting(승인 대기) → reporting → break`
|
||||
- **실시간 동기화**: WebSocket `/api/agent-office/ws` (init, agent_state, task_complete, command_result)
|
||||
- **텔레그램 연동**: 양방향 알림 + 인라인 키보드 승인
|
||||
- 봇이 작업 결과를 텔레그램으로 푸시, 명령은 텔레그램에서 바로 에이전트에 전달
|
||||
- Webhook 검증 후 `chat.id` 기준 라우팅
|
||||
| 메서드 | 경로 | 설명 |
|
||||
|--------|------|------|
|
||||
| GET | `/api/travel/regions` | 지역 GeoJSON |
|
||||
| GET | `/api/travel/photos` | 사진 목록 (region, page, size) |
|
||||
| POST | `/api/travel/reload` | 캐시 초기화 |
|
||||
|
||||
#### 에이전트 구성
|
||||
|
||||
| 에이전트 | 스케줄 | 승인 | 주요 기능 |
|
||||
|---------|--------|-----|----------|
|
||||
| 📈 **주식 트레이더** (`stock`) | 08:00 매일 | — | 뉴스 요약 (LLM) → 텔레그램 아침 브리핑, 종목 알람 등록 |
|
||||
| 🎵 **음악 프로듀서** (`music`) | 수동 트리거 | ✅ 작곡 | 프롬프트 수신 → 승인 → Suno API 작곡 → 트랙 푸시 |
|
||||
| ✍️ **블로그 마케터** (`blog`) | 10:00 매일 | ✅ 발행 | 트렌드 키워드 1개 선택 → 리서치→작가→마케터→평가 자동 실행 → 점수·본문을 텔레그램 승인 요청 → 승인 시 `published` 전환, 거절 시 재생성 |
|
||||
| 🏢 **청약 애널리스트** (`realestate`) | 09:15 매일 | — | realestate-lab 수집 트리거 → 신규 매칭 상위 5건 + 대시보드 요약을 텔레그램 리포트 (읽음 처리 자동) |
|
||||
|
||||
#### 에이전트별 명령
|
||||
|
||||
**Stock** — `fetch_news`, `list_alerts`, `add_alert`, `test_telegram`
|
||||
**Music** — `compose` (승인 필요), `credits`
|
||||
**Blog** — `research {keyword}`, `add_trend_keyword`, `list_trend_keywords`
|
||||
**Realestate** — `fetch_matches`, `dashboard`
|
||||
|
||||
#### 스케줄러 잡
|
||||
|
||||
- 07:00 월요일 — Lotto: AI 큐레이터 브리핑 (5세트 + 내러티브)
|
||||
- 07:30 — Stock: 뉴스 요약
|
||||
- 09:15 — Realestate: 매칭 리포트
|
||||
- 10:00 — Blog: 자동 파이프라인 (리서치→생성→리뷰→승인 대기)
|
||||
- 60초 interval — 유휴 에이전트 휴식 체크
|
||||
|
||||
### 7. travel-proxy (`/api/travel/`)
|
||||
|
||||
여행 사진 API + SQLite 인덱스 + 온디맨드 썸네일 + 지역 관리.
|
||||
|
||||
- 원본: `/data/travel/` (RO 마운트)
|
||||
- 썸네일: 480×480 Pillow 리사이징, `/data/thumbs/` 영구 캐시 (tmp → rename 원자성 보장)
|
||||
- DB: `/data/thumbs/travel.db` (photos, album_covers 테이블)
|
||||
- 메타: `region_map.json` (RO) + `region_map_extra.json` (RW 오버라이드) + `regions.geojson`
|
||||
- 지역 관리: 앨범 지역 변경, 커스텀 지역 생성, 지도 핀 좌표 지정
|
||||
- 데이터 흐름: 수동 sync → 폴더 스캔 → SQLite 인덱싱 + 썸네일 일괄 생성
|
||||
|
||||
### 8. deployer (`/webhook`)
|
||||
|
||||
Gitea Webhook 수신 → NAS 자동 배포.
|
||||
|
||||
- HMAC SHA256 서명 검증 (`compare_digest`, `WEBHOOK_SECRET`)
|
||||
- 수신 즉시 200 응답 후 BackgroundTask로 배포
|
||||
- 배포 스크립트: `git pull` → `.releases/` 백업 → `rsync` → `docker compose up -d --build` → `chown PUID:PGID`
|
||||
- 타임아웃 10분
|
||||
- 썸네일: `/media/travel/.thumb/{album}/{file}` (nginx 직접 서빙, 30일 캐시)
|
||||
- 원본: `/media/travel/{album}/{file}` (nginx 직접 서빙, 7일 캐시)
|
||||
|
||||
---
|
||||
|
||||
@@ -216,6 +213,8 @@ Gitea Webhook 수신 → NAS 자동 배포.
|
||||
→ 상위 100개 DB 저장 → best_picks 20개 교체
|
||||
```
|
||||
|
||||
**5가지 채점 기법:**
|
||||
|
||||
| 기법 | 가중치 | 내용 |
|
||||
|------|--------|------|
|
||||
| 빈도 Z-score | 25% | 번호 출현 빈도의 표준편차 |
|
||||
@@ -224,21 +223,28 @@ Gitea Webhook 수신 → NAS 자동 배포.
|
||||
| 공동 출현 | 15% | 번호 쌍 동시 출현 빈도 |
|
||||
| 다양성 | 10% | 연속번호·범위·구간 커버리지 |
|
||||
|
||||
### LLM 요약 provider 추상화 (stock)
|
||||
**스케줄:** 매일 0, 4, 8, 12, 16, 20시 (하루 6회, 각 5분)
|
||||
|
||||
`ai_summarizer.py`는 provider 분리 구조. `summarize_news(articles)` 시그니처는 provider와 무관하게 고정.
|
||||
### 총 자산 스냅샷 (stock-lab)
|
||||
|
||||
- `_summarize_with_claude`: Anthropic Messages API 직접 호출 (httpx, SDK 의존성 없음)
|
||||
- `_summarize_with_ollama`: Ollama `/api/generate` (타임아웃 180s, qwen3:14b 첫 로드 대응)
|
||||
- 실패 시 `LLMError` (구 `OllamaError` alias 유지)
|
||||
```
|
||||
평일 15:40 자동 실행 → holidays.json으로 공휴일 스킵
|
||||
→ 포트폴리오 현재가 조회 → total_eval
|
||||
→ 예수금 합계 → total_cash
|
||||
→ asset_snapshots upsert (date UNIQUE, 같은 날 중복 시 덮어씀)
|
||||
```
|
||||
|
||||
### 총 자산 스냅샷 (stock)
|
||||
### 현재가 조회 (stock-lab)
|
||||
|
||||
평일 15:40 자동 실행 → `holidays.json`으로 공휴일 스킵 → 포트폴리오 현재가 조회 + 예수금 합계 → `asset_snapshots` upsert (date UNIQUE).
|
||||
- 네이버 모바일 API 우선 (`m.stock.naver.com/api/stock/{ticker}/basic`)
|
||||
- 실패 시 네이버 금융 HTML 파싱 폴백
|
||||
- 3분 TTL 메모리 캐시
|
||||
|
||||
### 에이전트 FSM + WS 동기화 (agent-office)
|
||||
### 여행 사진 썸네일 (travel-proxy)
|
||||
|
||||
DB에 저장된 에이전트 상태가 바뀔 때마다 `websocket_manager`가 전체 클라이언트에 브로드캐스트. 텔레그램 봇은 `waiting` 상태 작업에 인라인 키보드를 붙여 승인 요청. 승인/거부 결과가 DB → WS → 프론트로 전파.
|
||||
- 480×480 리사이징 (Pillow), 확장자 유지 (JPEG/PNG/WEBP)
|
||||
- 온디맨드 생성 후 `/data/thumbs/` 영구 캐시
|
||||
- 원자성 보장: tmp 파일 작성 후 rename
|
||||
|
||||
---
|
||||
|
||||
@@ -246,7 +252,7 @@ DB에 저장된 에이전트 상태가 바뀔 때마다 `websocket_manager`가
|
||||
|
||||
```
|
||||
git push → Gitea → X-Gitea-Signature (HMAC SHA256)
|
||||
→ deployer:9000/webhook (서명 검증, compare_digest)
|
||||
→ deployer:9000/webhook (서명 검증, compare_digest 사용)
|
||||
→ BackgroundTask: scripts/deploy.sh (10분 타임아웃)
|
||||
1. git pull
|
||||
2. .releases/{timestamp}/ 백업
|
||||
@@ -255,30 +261,39 @@ git push → Gitea → X-Gitea-Signature (HMAC SHA256)
|
||||
5. chown PUID:PGID
|
||||
```
|
||||
|
||||
> 프론트엔드는 **자동 배포 안 됨** — 로컬 빌드 후 NAS에 수동 업로드 (`scripts/deploy.bat --frontend`)
|
||||
> 프론트엔드는 **자동 배포 안 됨** — 로컬 빌드 후 NAS에 수동 업로드
|
||||
|
||||
---
|
||||
|
||||
## 데이터베이스
|
||||
|
||||
각 서비스는 독립 SQLite DB를 `/app/data/` 볼륨에 저장.
|
||||
### lotto.db (`/app/data/lotto.db`)
|
||||
|
||||
| DB | 소유 서비스 | 주요 테이블 |
|
||||
|----|------------|-----------|
|
||||
| `lotto.db` | lotto-backend | draws, recommendations, simulation_runs/candidates, best_picks, purchase_history, strategy_performance/weights, weekly_reports, lotto_briefings, todos, blog_posts |
|
||||
| `stock.db` | stock | articles, portfolio, broker_cash, asset_snapshots, sell_history |
|
||||
| `music.db` | music-lab | music_tasks, music_library (provider, lyrics, image_url, suno_id, file_hash, cover_images, wav_url, video_url, stem_urls) |
|
||||
| `blog_marketing.db` | blog-lab | keyword_analyses, blog_posts, brand_links, commissions, generation_tasks, prompt_templates |
|
||||
| `realestate.db` | realestate-lab | announcements, announcement_models, user_profile, match_results, collect_log |
|
||||
| `agent_office.db` | agent-office | agent_config, agent_tasks, agent_logs, telegram_state, conversation_messages |
|
||||
| `travel.db` | travel-proxy | photos (album, filename, mtime, has_thumb), album_covers |
|
||||
| 테이블 | 설명 |
|
||||
|--------|------|
|
||||
| `draws` | 로또 당첨번호 |
|
||||
| `recommendations` | 추천 이력 (즐겨찾기·태그·채점 포함) |
|
||||
| `simulation_runs` | 시뮬레이션 실행 기록 |
|
||||
| `simulation_candidates` | 시뮬레이션 후보 (점수 5종) |
|
||||
| `best_picks` | 현재 활성 최적 번호 20개 (is_active 플래그) |
|
||||
| `todos` | 투두리스트 (UUID PK) |
|
||||
| `blog_posts` | 블로그 글 (tags: JSON 배열) |
|
||||
|
||||
### stock.db (`/app/data/stock.db`)
|
||||
|
||||
| 테이블 | 설명 |
|
||||
|--------|------|
|
||||
| `articles` | 뉴스 기사 (hash UNIQUE, category: domestic\|overseas) |
|
||||
| `portfolio` | 보유 종목 (broker, ticker, quantity, avg_price) |
|
||||
| `broker_cash` | 증권사별 예수금 (broker UNIQUE) |
|
||||
| `asset_snapshots` | 일별 총 자산 스냅샷 (date UNIQUE) |
|
||||
|
||||
---
|
||||
|
||||
## 환경변수
|
||||
|
||||
```env
|
||||
# 경로
|
||||
# 경로 설정
|
||||
RUNTIME_PATH=.
|
||||
REPO_PATH=.
|
||||
FRONTEND_PATH=./frontend/dist
|
||||
@@ -291,34 +306,6 @@ PGID=1000
|
||||
# 외부 서비스
|
||||
WINDOWS_AI_SERVER_URL=http://192.168.45.59:8000
|
||||
WEBHOOK_SECRET=your_secret_here
|
||||
|
||||
# LLM (stock, blog-lab, agent-office 공통)
|
||||
ANTHROPIC_API_KEY=sk-ant-...
|
||||
ANTHROPIC_MODEL=claude-haiku-4-5-20251001
|
||||
LLM_PROVIDER=claude # claude | ollama
|
||||
OLLAMA_URL=http://192.168.45.59:11435
|
||||
OLLAMA_MODEL=qwen3:14b
|
||||
|
||||
# music-lab
|
||||
SUNO_API_KEY=
|
||||
MUSIC_AI_SERVER_URL=
|
||||
MUSIC_MEDIA_BASE=/media/music
|
||||
|
||||
# blog-lab
|
||||
NAVER_CLIENT_ID=
|
||||
NAVER_CLIENT_SECRET=
|
||||
|
||||
# realestate-lab
|
||||
DATA_GO_KR_API_KEY=
|
||||
|
||||
# agent-office
|
||||
TELEGRAM_BOT_TOKEN=
|
||||
TELEGRAM_CHAT_ID=
|
||||
TELEGRAM_WEBHOOK_URL=
|
||||
STOCK_URL=http://stock:8000
|
||||
MUSIC_LAB_URL=http://music-lab:8000
|
||||
BLOG_LAB_URL=http://blog-lab:8000
|
||||
REALESTATE_LAB_URL=http://realestate-lab:8000
|
||||
```
|
||||
|
||||
---
|
||||
@@ -329,9 +316,9 @@ REALESTATE_LAB_URL=http://realestate-lab:8000
|
||||
|------|----|
|
||||
| 장비 | Synology NAS (Intel Celeron J4025, 18GB RAM) |
|
||||
| Docker | Synology Container Manager |
|
||||
| Git 서버 | Gitea (NAS 내부 self-hosted, `gahusb.synology.me`) |
|
||||
| AI 서버 | Windows PC (192.168.45.59) — RTX 5070 Ti (16GB VRAM) + Ollama + MusicGen |
|
||||
| Python | 3.12 (`slim` 기반 이미지) |
|
||||
| Git 서버 | Gitea (NAS 내부 self-hosted) |
|
||||
| AI 서버 | Windows PC (192.168.45.59:8000) — RTX 3070 Ti + Ollama |
|
||||
| Python | 3.12 (`slim` / `alpine` 기반 이미지) |
|
||||
| DB | SQLite (볼륨 마운트로 영속 저장) |
|
||||
|
||||
---
|
||||
@@ -340,18 +327,8 @@ REALESTATE_LAB_URL=http://realestate-lab:8000
|
||||
|
||||
- **`.env` 파일** — 절대 커밋 금지. `.env.example`만 레포에 포함
|
||||
- **Nginx trailing slash** — `/api/portfolio`는 두 location 블록으로 처리 (trailing slash 유무 모두 매칭)
|
||||
- **라우트 순서** — `DELETE /api/todos/done`은 `/api/todos/{id}` 보다 먼저 등록 필수 (FastAPI prefix 매칭)
|
||||
- **라우트 순서** — `/api/todos/done`은 `/api/todos/{id}` 보다 먼저 등록 필수
|
||||
- **캐시 전략** — `index.html`: no-store / `assets/`: 1년 immutable
|
||||
- **PUID/PGID** — travel-proxy는 NAS 파일 권한을 위해 환경변수 주입 필수
|
||||
- **공휴일 목록** — `stock/app/holidays.json` 매년 수동 갱신 (KRX 기준)
|
||||
- **Windows AI 서버 IP** — `192.168.45.59` 공유기 DHCP 고정 예약. Synology Tailscale은 userspace 모드라 TCP 불가 → 로컬 IP 사용
|
||||
- **Suno CDN** — `cdn1.suno.ai` URL은 임시 만료 → 생성 즉시 로컬 다운로드 필수
|
||||
- **LLM provider 롤백** — Claude API 장애 시 `.env`의 `LLM_PROVIDER=ollama`로 전환 후 `docker compose up -d`
|
||||
- **시뮬레이션 교체 방식** — `best_picks`는 교체형 (`is_active=0` 비활성화 후 신규 입력)
|
||||
|
||||
---
|
||||
|
||||
## 참고 문서
|
||||
|
||||
- `CLAUDE.md` — Claude Code 작업용 상세 컨텍스트 (API 전체 목록, 테이블 스키마 등)
|
||||
- `docs/` — 서비스별 기획·설계 문서
|
||||
- **공휴일 목록** — `stock-lab/app/holidays.json` 매년 수동 갱신 필요 (KRX 기준)
|
||||
- **Windows AI 서버** — IP 192.168.45.59 (공유기 DHCP 고정 예약)
|
||||
|
||||
109
STATUS.md
109
STATUS.md
@@ -1,109 +0,0 @@
|
||||
# web-backend — 구현 현황 & 로드맵
|
||||
|
||||
> 최종 갱신: 2026-05-07
|
||||
> 자세한 서비스·환경변수·DB 표는 [CLAUDE.md](./CLAUDE.md), 설계는 `docs/superpowers/specs/`, 실행 계획은 `docs/superpowers/plans/` 참조.
|
||||
|
||||
---
|
||||
|
||||
## 1. 서비스 구현 현황
|
||||
|
||||
### 1-1. 운영 중인 컨테이너 (10개)
|
||||
|
||||
| 서비스 | 포트 | 상태 | 핵심 기능 |
|
||||
|--------|------|------|-----------|
|
||||
| `lotto-backend` | 18000 | ✅ | 로또 추천·통계·리포트·구매내역 + 블로그·투두 |
|
||||
| `stock` | 18500 | ✅ | 주식 뉴스·지수·트레이딩·포트폴리오·자산 스냅샷 |
|
||||
| `music-lab` | 18600 | ✅ | Suno + MusicGen + YouTube 수익화 + 컴파일 |
|
||||
| `blog-lab` | 18700 | ✅ | 블로그 마케팅 수익화 파이프라인 |
|
||||
| `realestate-lab` | 18800 | ✅ | 청약 수집·5티어 매칭·매칭 알림 |
|
||||
| `agent-office` | 18900 | ✅ | AI 에이전트 (WebSocket + 텔레그램 + YouTubeResearcher) |
|
||||
| `packs-lab` | 18950 | ✅ | NAS 자료 다운로드 자동화 (HMAC + Supabase) — 2026-05-05 |
|
||||
| `travel-proxy` | 19000 | ✅ | 여행 사진 API + 썸네일 + 지역 관리 |
|
||||
| `nginx` | 8080 | ✅ | SPA + 리버스 프록시 (5GB body limit) |
|
||||
| `webpage-deployer` | 19010 | ✅ | Gitea Webhook 자동 배포 |
|
||||
|
||||
### 1-2. 최근 큰 작업 (2026-04 ~ 05)
|
||||
|
||||
| 시기 | 영역 | 핵심 |
|
||||
|------|------|------|
|
||||
| 2026-05-05 | packs-lab | sign-link / upload / list / delete + admin mint-token + 5GB nginx body limit + Supabase DDL |
|
||||
| 2026-05-01~06 | music-lab | YouTube 수익화 백엔드 (market_trends·trend_reports DB + 5개 API) + 다중 트랙 FFmpeg concat MP4 |
|
||||
| 2026-04-28 | realestate-lab | targeting enhancement (5티어 매칭·5축 점수·알림 대상 카운트) |
|
||||
| 2026-04-27 | personal | personal 서비스 분리 마이그레이션 (블로그·투두·포트폴리오 인증) |
|
||||
| 2026-04-27 | agent-office | v2 — youtube_researcher (YouTube API + pytrends + Billboard) + 알림 |
|
||||
| 2026-04-24 | travel-proxy | 갤러리 리디자인 + 성능 개선 (썸네일/페이지네이션) |
|
||||
| 2026-04-15 | lotto-backend | AI 큐레이터 (Claude 기반 주간 브리핑 자동 생성) |
|
||||
| 2026-04-08 | music-lab | Suno enhancement + MusicGen 통합 |
|
||||
| 2026-04-06 | blog-lab | 마케팅 파이프라인 (research → generate → market → review) |
|
||||
|
||||
### 1-3. 인프라 / DX
|
||||
|
||||
| 항목 | 상태 |
|
||||
|------|------|
|
||||
| docker-compose 통합 (10 서비스) | ✅ |
|
||||
| Gitea Webhook → deployer rsync 자동 배포 | ✅ |
|
||||
| nginx 라우팅 표 (/api/* 서비스별) | ✅ |
|
||||
| 배포 환경변수 (PEXELS·YOUTUBE_DATA·VIDEO_DATA_DIR 등) | ✅ |
|
||||
|
||||
---
|
||||
|
||||
## 2. 진행 중 / 향후 계획
|
||||
|
||||
### 2-1. 로또 프리미엄 (Phase 3) — 구독 모델
|
||||
> 출처: [docs/lotto-premium-roadmap.md](./docs/lotto-premium-roadmap.md)
|
||||
|
||||
- [ ] 회원 시스템 (JWT 인증, `users` 테이블)
|
||||
- [ ] 구독 플랜 (`subscription_plans`, `user_subscriptions`)
|
||||
- [ ] 결제 연동 (Toss Payments 또는 Stripe)
|
||||
- [ ] 이메일 발송 자동화 (SendGrid)
|
||||
- [ ] 소셜 증거 데이터 집계 API (가장 많이 선택된 번호 TOP 10 등)
|
||||
|
||||
Phase 1·2 (성과 통계 / 회차별 공략 리포트 / 개인 분석 / 구매 추적)는 이미 완료.
|
||||
|
||||
### 2-2. Pet Lab (신규 서비스) — 설계 단계
|
||||
> 출처: `docs/superpowers/specs/2026-04-07-pet-lab-design.md`, `plans/2026-04-07-pet-lab.md`
|
||||
|
||||
- [ ] 컨테이너 추가 + 포트 배정
|
||||
- [ ] 핵심 도메인 모델 (반려동물 등록·기록·일정)
|
||||
- [ ] 프론트 페이지 신설
|
||||
|
||||
### 2-3. Music YouTube 자동화 후속
|
||||
|
||||
- [ ] VideoProjects 실제 렌더링 잡 큐 (현재 스켈레톤)
|
||||
- [ ] 시장 트렌드 → 자동 음악 생성 트리거 연결
|
||||
- [ ] Revenue 트래킹 정확도 개선 (YouTube Analytics API)
|
||||
|
||||
### 2-4. Travel 영상 지원
|
||||
|
||||
- [ ] `travel-proxy`에 영상 메타·썸네일 API 추가
|
||||
- [ ] `/media/travel/.video-thumb/` 처리
|
||||
- [ ] `/api/travel/videos` 엔드포인트
|
||||
|
||||
### 2-5. 청약 (realestate-lab) 후속
|
||||
|
||||
- [ ] 알림 dry-run API (사용자가 사전 시뮬레이션 가능)
|
||||
- [ ] 신규 매칭 텔레그램 알림 노이즈 필터링 (이미 본 공고 제외)
|
||||
- [ ] 백오피스용 공고 수동 보정 API
|
||||
|
||||
### 2-6. packs-lab 후속
|
||||
|
||||
- [ ] 사용자별 다운로드 쿼터 제어
|
||||
- [ ] 만료된 토큰/링크 정리 스케줄러
|
||||
- [ ] Vercel SaaS 측 UI 연결 검증
|
||||
|
||||
### 2-7. 인프라 일반
|
||||
|
||||
- [ ] APScheduler 잡 모니터링 대시보드 (현재 로그 의존)
|
||||
- [ ] 백업 자동화 (lotto.db / stock.db / 사진 메타)
|
||||
- [ ] OpenAPI 스펙 통합 (서비스별 자동 수집)
|
||||
|
||||
---
|
||||
|
||||
## 3. 참고 문서
|
||||
|
||||
- 서비스·포트·API 전체 표: [CLAUDE.md](./CLAUDE.md)
|
||||
- 워크스페이스 통합 가이드: `../CLAUDE.md`
|
||||
- 프론트엔드 상태: `../web-ui/STATUS.md`
|
||||
- 설계 스펙: `docs/superpowers/specs/`
|
||||
- 실행 계획: `docs/superpowers/plans/`
|
||||
- 로또 프리미엄 로드맵: `docs/lotto-premium-roadmap.md`
|
||||
@@ -1,21 +1,11 @@
|
||||
from .stock import StockAgent
|
||||
from .music import MusicAgent
|
||||
from .insta import InstaAgent
|
||||
from .realestate import RealestateAgent
|
||||
from .lotto import LottoAgent
|
||||
from .youtube import YouTubeResearchAgent
|
||||
from .youtube_publisher import YoutubePublisherAgent
|
||||
|
||||
AGENT_REGISTRY = {}
|
||||
|
||||
def init_agents():
|
||||
AGENT_REGISTRY["stock"] = StockAgent()
|
||||
AGENT_REGISTRY["music"] = MusicAgent()
|
||||
AGENT_REGISTRY["insta"] = InstaAgent()
|
||||
AGENT_REGISTRY["realestate"] = RealestateAgent()
|
||||
AGENT_REGISTRY["lotto"] = LottoAgent()
|
||||
AGENT_REGISTRY["youtube"] = YouTubeResearchAgent()
|
||||
AGENT_REGISTRY["youtube_publisher"] = YoutubePublisherAgent()
|
||||
|
||||
def get_agent(agent_id: str):
|
||||
return AGENT_REGISTRY.get(agent_id)
|
||||
|
||||
@@ -40,14 +40,6 @@ class BaseAgent:
|
||||
|
||||
if self._ws_manager:
|
||||
await self._ws_manager.send_agent_state(self.agent_id, new_state, detail, task_id)
|
||||
if new_state == "working" and old != "working":
|
||||
await self._ws_manager.send_notification(
|
||||
self.agent_id, "task_assigned", task_id, detail or "새 작업 시작"
|
||||
)
|
||||
elif new_state == "idle" and old in ("working", "reporting"):
|
||||
await self._ws_manager.send_notification(
|
||||
self.agent_id, "task_completed", task_id, detail or "작업 완료"
|
||||
)
|
||||
if new_state == "break":
|
||||
await self._ws_manager.send_agent_move(self.agent_id, "break_room")
|
||||
elif old == "break" and new_state == "idle":
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
"""텔레그램 사용자 응답 자연어 분류 — 화이트리스트 우선, 모호 시 LLM."""
|
||||
import os
|
||||
import json
|
||||
import logging
|
||||
import httpx
|
||||
|
||||
logger = logging.getLogger("agent-office.classify_intent")
|
||||
|
||||
CLAUDE_HAIKU_DEFAULT = "claude-haiku-4-5-20251001"
|
||||
|
||||
APPROVE_WORDS = {
|
||||
"승인", "시작", "진행", "ok", "okay", "agree",
|
||||
"네", "예", "좋아", "좋아요", "go", "yes", "y",
|
||||
}
|
||||
REJECT_WORDS = {"반려", "거절", "취소", "no", "nope", "n"}
|
||||
|
||||
|
||||
def _get_api_key() -> str:
|
||||
return os.getenv("ANTHROPIC_API_KEY", "")
|
||||
|
||||
|
||||
def _get_model() -> str:
|
||||
return os.getenv("CLAUDE_HAIKU_MODEL", CLAUDE_HAIKU_DEFAULT)
|
||||
|
||||
|
||||
def classify(text: str) -> tuple[str, str | None]:
|
||||
"""returns (intent, feedback) — intent ∈ {approve, reject, unclear}"""
|
||||
if not text:
|
||||
return ("unclear", None)
|
||||
t = text.strip().lower()
|
||||
if t in APPROVE_WORDS:
|
||||
return ("approve", None)
|
||||
if t in REJECT_WORDS:
|
||||
return ("reject", None)
|
||||
# 반려 단어로 시작 + 추가 텍스트
|
||||
for w in REJECT_WORDS:
|
||||
if t.startswith(w):
|
||||
rest = text.strip()[len(w):].lstrip(" ,.-:").strip()
|
||||
if rest:
|
||||
return ("reject", rest)
|
||||
# 승인 단어로 시작 (긍정 의도면 추가 텍스트 무시)
|
||||
for w in APPROVE_WORDS:
|
||||
if t.startswith(w + " ") or t == w:
|
||||
return ("approve", None)
|
||||
return _llm_classify(text)
|
||||
|
||||
|
||||
def _llm_classify(text: str) -> tuple[str, str | None]:
|
||||
api_key = _get_api_key()
|
||||
if not api_key:
|
||||
return ("unclear", None)
|
||||
prompt = (
|
||||
"사용자 응답을 분류하세요. JSON으로만 응답.\n"
|
||||
f'응답: "{text}"\n\n'
|
||||
'출력: {"intent":"approve|reject|unclear","feedback":"반려면 수정 방향, 아니면 빈 문자열"}'
|
||||
)
|
||||
try:
|
||||
resp = httpx.post(
|
||||
"https://api.anthropic.com/v1/messages",
|
||||
headers={"x-api-key": api_key, "anthropic-version": "2023-06-01"},
|
||||
json={"model": _get_model(), "max_tokens": 200,
|
||||
"messages": [{"role": "user", "content": prompt}]},
|
||||
timeout=15,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
text_out = resp.json()["content"][0]["text"]
|
||||
start = text_out.find("{")
|
||||
end = text_out.rfind("}") + 1
|
||||
if start < 0 or end <= start:
|
||||
return ("unclear", None)
|
||||
data = json.loads(text_out[start:end])
|
||||
return (data.get("intent", "unclear"), data.get("feedback") or None)
|
||||
except (httpx.HTTPError, httpx.TimeoutException, KeyError, ValueError, json.JSONDecodeError) as e:
|
||||
logger.warning("LLM 분류 실패: %s", e)
|
||||
return ("unclear", None)
|
||||
@@ -1,162 +0,0 @@
|
||||
"""인스타 카드 에이전트 — 매일 09:30 뉴스 수집·키워드 추출 → 텔레그램 후보 푸시.
|
||||
사용자가 키워드 버튼을 누르면 카드 슬레이트 생성 + 10장 미디어 그룹 발송."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
import httpx
|
||||
|
||||
from .base import BaseAgent
|
||||
from ..db import (
|
||||
create_task, update_task_status, add_log, get_agent_config,
|
||||
)
|
||||
from ..config import TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_ID
|
||||
from .. import service_proxy
|
||||
from ..telegram import messaging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def _send_media_group(media: List[Dict[str, Any]], caption: str = "") -> Dict[str, Any]:
|
||||
"""텔레그램 sendMediaGroup. media는 InputMediaPhoto dicts.
|
||||
각 항목에는 임시 키 '_bytes'로 PNG 바이트가 담겨 있어 attach:// 형식으로 multipart 업로드."""
|
||||
if not TELEGRAM_BOT_TOKEN:
|
||||
return {"ok": False, "reason": "TELEGRAM_BOT_TOKEN missing"}
|
||||
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMediaGroup"
|
||||
files: Dict[str, tuple] = {}
|
||||
for i, m in enumerate(media):
|
||||
attach_key = f"photo{i+1}"
|
||||
files[attach_key] = (f"{i+1}.png", m["_bytes"], "image/png")
|
||||
m["media"] = f"attach://{attach_key}"
|
||||
m.pop("_bytes", None)
|
||||
if caption and media:
|
||||
media[0]["caption"] = caption[:1024]
|
||||
payload = {"chat_id": TELEGRAM_CHAT_ID, "media": json.dumps(media, ensure_ascii=False)}
|
||||
async with httpx.AsyncClient(timeout=60) as client:
|
||||
resp = await client.post(url, data=payload, files=files)
|
||||
return resp.json()
|
||||
|
||||
|
||||
class InstaAgent(BaseAgent):
|
||||
agent_id = "insta"
|
||||
display_name = "인스타 큐레이터"
|
||||
|
||||
async def on_schedule(self) -> None:
|
||||
"""09:30 매일: 뉴스 수집 → 키워드 추출 → 텔레그램 후보 푸시.
|
||||
custom_config.auto_select=True면 카테고리당 1위 키워드 자동 슬레이트 생성."""
|
||||
if self.state not in ("idle", "break"):
|
||||
return
|
||||
config = get_agent_config(self.agent_id) or {}
|
||||
custom = config.get("custom_config", {}) or {}
|
||||
auto_select = bool(custom.get("auto_select", False))
|
||||
|
||||
task_id = create_task(self.agent_id, "insta_daily", {"auto_select": auto_select},
|
||||
requires_approval=False)
|
||||
await self.transition("working", "뉴스 수집·키워드 추출", task_id)
|
||||
try:
|
||||
await self._run_collect_and_extract()
|
||||
kws = await service_proxy.insta_list_keywords(used=False)
|
||||
if auto_select:
|
||||
await self._auto_render(kws)
|
||||
else:
|
||||
await self._push_keyword_candidates(kws)
|
||||
update_task_status(task_id, "succeeded", {"keywords": len(kws)})
|
||||
await self.transition("idle", "후보 푸시 완료")
|
||||
except Exception as e:
|
||||
add_log(self.agent_id, f"insta daily failed: {e}", "error", task_id)
|
||||
update_task_status(task_id, "failed", {"error": str(e)})
|
||||
await self.transition("idle", f"오류: {e}")
|
||||
|
||||
async def _run_collect_and_extract(self) -> None:
|
||||
col = await service_proxy.insta_collect()
|
||||
await self._wait_task(col["task_id"], step="collect", timeout_sec=300)
|
||||
ext = await service_proxy.insta_extract()
|
||||
await self._wait_task(ext["task_id"], step="extract", timeout_sec=300)
|
||||
|
||||
async def _wait_task(self, task_id: str, step: str, timeout_sec: int = 300) -> Dict[str, Any]:
|
||||
attempts = max(1, timeout_sec // 5)
|
||||
for _ in range(attempts):
|
||||
await asyncio.sleep(5)
|
||||
st = await service_proxy.insta_task_status(task_id)
|
||||
if st["status"] == "succeeded":
|
||||
return st
|
||||
if st["status"] == "failed":
|
||||
raise RuntimeError(f"{step} failed: {st.get('error')}")
|
||||
raise TimeoutError(f"{step} timeout {timeout_sec}s")
|
||||
|
||||
async def _push_keyword_candidates(self, keywords: List[Dict[str, Any]]) -> None:
|
||||
by_cat: Dict[str, List[Dict[str, Any]]] = {}
|
||||
for k in keywords:
|
||||
by_cat.setdefault(k["category"], []).append(k)
|
||||
if not by_cat:
|
||||
await messaging.send_raw("📰 [인스타 큐레이터] 오늘은 추천할 키워드가 없습니다.")
|
||||
return
|
||||
rows: List[List[Dict[str, Any]]] = []
|
||||
text_lines = ["📰 <b>[인스타 큐레이터]</b> 오늘의 키워드 후보"]
|
||||
for cat, items in by_cat.items():
|
||||
text_lines.append(f"\n<b>{cat}</b>")
|
||||
for k in items[:5]:
|
||||
text_lines.append(f" · {k['keyword']} (score {k['score']:.2f})")
|
||||
rows.append([{
|
||||
"text": f"🎴 {k['keyword']}",
|
||||
"callback_data": f"render_{k['id']}",
|
||||
}])
|
||||
await messaging.send_raw("\n".join(text_lines), reply_markup={"inline_keyboard": rows})
|
||||
|
||||
async def _auto_render(self, keywords: List[Dict[str, Any]]) -> None:
|
||||
by_cat: Dict[str, Dict[str, Any]] = {}
|
||||
for k in keywords:
|
||||
cat = k["category"]
|
||||
if cat not in by_cat or k["score"] > by_cat[cat]["score"]:
|
||||
by_cat[cat] = k
|
||||
for kw in by_cat.values():
|
||||
await self._render_and_push(kw["id"])
|
||||
|
||||
async def _render_and_push(self, keyword_id: int) -> None:
|
||||
kw = await service_proxy.insta_get_keyword(keyword_id)
|
||||
if not kw:
|
||||
await messaging.send_raw(f"⚠️ 키워드 {keyword_id} 없음")
|
||||
return
|
||||
await messaging.send_raw(f"🎨 카드 생성 중: <b>{kw['keyword']}</b>")
|
||||
created = await service_proxy.insta_create_slate(
|
||||
keyword=kw["keyword"], category=kw["category"], keyword_id=kw["id"],
|
||||
)
|
||||
st = await self._wait_task(created["task_id"], step="slate", timeout_sec=600)
|
||||
slate_id = st["result_id"]
|
||||
slate = await service_proxy.insta_get_slate(slate_id)
|
||||
media = []
|
||||
for a in slate["assets"][:10]:
|
||||
data = await service_proxy.insta_get_asset_bytes(slate_id, a["page_index"])
|
||||
media.append({"type": "photo", "_bytes": data})
|
||||
caption = slate.get("suggested_caption", "")
|
||||
hashtags = " ".join(slate.get("hashtags", []) or [])
|
||||
full_caption = f"{caption}\n\n{hashtags}".strip()
|
||||
await _send_media_group(media, caption=full_caption)
|
||||
|
||||
async def on_command(self, command: str, params: dict) -> dict:
|
||||
if command == "extract":
|
||||
await self._run_collect_and_extract()
|
||||
kws = await service_proxy.insta_list_keywords(used=False)
|
||||
await self._push_keyword_candidates(kws)
|
||||
return {"ok": True, "count": len(kws)}
|
||||
if command == "render":
|
||||
kid = int(params.get("keyword_id") or 0)
|
||||
if not kid:
|
||||
return {"ok": False, "message": "keyword_id 필수"}
|
||||
await self._render_and_push(kid)
|
||||
return {"ok": True}
|
||||
return {"ok": False, "message": f"Unknown command: {command}"}
|
||||
|
||||
async def on_callback(self, action: str, params: dict) -> dict:
|
||||
if action == "render":
|
||||
kid = int(params.get("keyword_id") or 0)
|
||||
if not kid:
|
||||
return {"ok": False}
|
||||
await self._render_and_push(kid)
|
||||
return {"ok": True}
|
||||
return {"ok": False}
|
||||
|
||||
async def on_approval(self, task_id: str, approved: bool, feedback: str = "") -> None:
|
||||
return
|
||||
@@ -1,54 +0,0 @@
|
||||
from .base import BaseAgent
|
||||
from ..db import create_task, update_task_status, add_log
|
||||
from ..curator.pipeline import curate_weekly, CuratorError
|
||||
|
||||
|
||||
class LottoAgent(BaseAgent):
|
||||
agent_id = "lotto"
|
||||
display_name = "로또 큐레이터"
|
||||
|
||||
async def on_schedule(self) -> None:
|
||||
if self.state not in ("idle", "break"):
|
||||
return
|
||||
await self._run(source="auto")
|
||||
|
||||
async def on_command(self, action: str, params: dict) -> dict:
|
||||
if action in ("curate_now", "curate_weekly"):
|
||||
return await self._run(source="manual")
|
||||
if action == "status":
|
||||
return {"ok": True, "message": f"{self.state}: {self.state_detail}"}
|
||||
return {"ok": False, "message": f"unknown action: {action}"}
|
||||
|
||||
async def on_approval(self, task_id: str, approved: bool, feedback: str = "") -> None:
|
||||
pass
|
||||
|
||||
async def _run(self, source: str) -> dict:
|
||||
task_id = create_task(self.agent_id, "curate_weekly", {"source": source})
|
||||
await self.transition("working", "후보 수집 및 AI 큐레이션 중...", task_id)
|
||||
try:
|
||||
result = await curate_weekly(source=source)
|
||||
update_task_status(task_id, "succeeded", result_data={
|
||||
k: v for k, v in result.items() if k != "payload"
|
||||
})
|
||||
await self.transition("reporting", f"#{result['draw_no']} 브리핑 저장 완료")
|
||||
add_log(self.agent_id, f"큐레이션 완료: #{result['draw_no']} conf={result['confidence']}", task_id=task_id)
|
||||
|
||||
# 텔레그램 헤드라인 푸시 (실패해도 큐레이션은 성공으로 마감)
|
||||
try:
|
||||
from ..notifiers.telegram_lotto import send_curator_briefing
|
||||
await send_curator_briefing(result["payload"])
|
||||
except Exception as e:
|
||||
add_log(self.agent_id, f"텔레그램 알림 실패: {e}", level="warning", task_id=task_id)
|
||||
|
||||
await self.transition("idle", "대기 중")
|
||||
return {"ok": True, **{k: v for k, v in result.items() if k != "payload"}}
|
||||
except CuratorError as e:
|
||||
update_task_status(task_id, "failed", result_data={"error": str(e)})
|
||||
add_log(self.agent_id, f"큐레이션 실패: {e}", level="error", task_id=task_id)
|
||||
await self.transition("idle", "오류")
|
||||
return {"ok": False, "message": str(e)}
|
||||
except Exception as e:
|
||||
update_task_status(task_id, "failed", result_data={"error": str(e)})
|
||||
add_log(self.agent_id, f"큐레이션 예외: {e}", level="error", task_id=task_id)
|
||||
await self.transition("idle", "오류")
|
||||
return {"ok": False, "message": f"{type(e).__name__}: {e}"}
|
||||
@@ -1,77 +0,0 @@
|
||||
from .base import BaseAgent
|
||||
from ..db import create_task, update_task_status, add_log
|
||||
from .. import service_proxy
|
||||
from ..telegram import messaging
|
||||
from ..telegram.realestate_message import format_realestate_matches, build_match_keyboard
|
||||
|
||||
|
||||
class RealestateAgent(BaseAgent):
|
||||
"""부동산 청약 에이전트.
|
||||
|
||||
realestate-lab이 신규 매칭 발견 시 /realestate/notify로 push해 트리거됨.
|
||||
on_new_matches가 메인 진입점. on_schedule은 사용하지 않음(cron 폐기).
|
||||
"""
|
||||
|
||||
agent_id = "realestate"
|
||||
display_name = "청약 애널리스트"
|
||||
|
||||
async def on_new_matches(self, matches: list[dict]) -> dict:
|
||||
"""신규 매칭 N건을 텔레그램 1통으로 푸시.
|
||||
성공 시 sent_ids 반환 → realestate-lab이 notified_at 마킹.
|
||||
실패 시 sent=0, sent_ids=[] 반환 → 다음 사이클 재시도.
|
||||
"""
|
||||
if not matches:
|
||||
return {"sent": 0, "sent_ids": []}
|
||||
|
||||
task_id = create_task(self.agent_id, "notify_matches", {"count": len(matches)})
|
||||
|
||||
try:
|
||||
text = format_realestate_matches(matches)
|
||||
keyboard = build_match_keyboard(matches)
|
||||
await self.transition("reporting", f"매칭 {len(matches)}건 알림", task_id)
|
||||
|
||||
tg = await messaging.send_raw(text, reply_markup=keyboard)
|
||||
if not tg.get("ok"):
|
||||
update_task_status(task_id, "failed", {"error": tg.get("description")})
|
||||
await self.transition("idle", "알림 실패")
|
||||
return {"sent": 0, "sent_ids": [], "error": tg.get("description")}
|
||||
|
||||
sent_ids = [m["id"] for m in matches if "id" in m]
|
||||
update_task_status(task_id, "succeeded", {
|
||||
"sent": len(matches),
|
||||
"telegram_message_id": tg.get("message_id"),
|
||||
})
|
||||
await self.transition("idle", f"매칭 {len(matches)}건 알림 완료")
|
||||
return {
|
||||
"sent": len(matches),
|
||||
"sent_ids": sent_ids,
|
||||
"message_id": tg.get("message_id"),
|
||||
}
|
||||
except Exception as e:
|
||||
add_log(self.agent_id, f"on_new_matches failed: {e}", "error", task_id)
|
||||
update_task_status(task_id, "failed", {"error": str(e)})
|
||||
await self.transition("idle", f"오류: {e}")
|
||||
return {"sent": 0, "sent_ids": [], "error": str(e)}
|
||||
|
||||
async def on_command(self, command: str, params: dict) -> dict:
|
||||
if command == "fetch_matches":
|
||||
try:
|
||||
matches = await service_proxy.realestate_matches(limit=20)
|
||||
if not matches:
|
||||
return {"ok": True, "message": "매칭 없음"}
|
||||
result = await self.on_new_matches(matches)
|
||||
return {"ok": True, "result": result}
|
||||
except Exception as e:
|
||||
return {"ok": False, "message": str(e)}
|
||||
|
||||
if command == "dashboard":
|
||||
try:
|
||||
data = await service_proxy.realestate_dashboard()
|
||||
return {"ok": True, "dashboard": data}
|
||||
except Exception as e:
|
||||
return {"ok": False, "message": str(e)}
|
||||
|
||||
return {"ok": False, "message": f"Unknown command: {command}"}
|
||||
|
||||
async def on_approval(self, task_id: str, approved: bool, feedback: str = "") -> None:
|
||||
pass
|
||||
@@ -1,44 +1,10 @@
|
||||
import asyncio
|
||||
import html
|
||||
from typing import Optional
|
||||
|
||||
from .base import BaseAgent
|
||||
from ..db import create_task, update_task_status, get_agent_config, add_log
|
||||
from .. import service_proxy
|
||||
|
||||
|
||||
def _build_briefing_body(result: dict, max_headlines: int = 5) -> str:
|
||||
"""아침 시장 브리핑 본문 조립.
|
||||
|
||||
LLM 요약 + 주요 뉴스 헤드라인(링크) 섹션을 합친다.
|
||||
향후 본문 고도화 시 이 함수만 수정하면 됨 (텔레그램 HTML parse_mode).
|
||||
"""
|
||||
summary = (result.get("summary") or "").strip()
|
||||
articles = result.get("articles") or []
|
||||
|
||||
# body_is_html=True 로 보낼 예정이므로 LLM 요약(plain text)도 escape
|
||||
parts = [html.escape(summary)] if summary else []
|
||||
|
||||
headlines = []
|
||||
for a in articles[:max_headlines]:
|
||||
title = (a.get("title") or "").strip()
|
||||
if not title:
|
||||
continue
|
||||
title_esc = html.escape(title)
|
||||
link = (a.get("link") or "").strip()
|
||||
press = (a.get("press") or "").strip()
|
||||
press_suffix = f" — {html.escape(press)}" if press else ""
|
||||
if link:
|
||||
headlines.append(f'• <a href="{html.escape(link, quote=True)}">{title_esc}</a>{press_suffix}')
|
||||
else:
|
||||
headlines.append(f"• {title_esc}{press_suffix}")
|
||||
|
||||
if headlines:
|
||||
parts.append("📰 <b>주요 뉴스</b>\n" + "\n".join(headlines))
|
||||
|
||||
return "\n\n".join(parts)
|
||||
|
||||
|
||||
class StockAgent(BaseAgent):
|
||||
agent_id = "stock"
|
||||
display_name = "주식 트레이더"
|
||||
@@ -48,69 +14,23 @@ class StockAgent(BaseAgent):
|
||||
return
|
||||
|
||||
task_id = create_task(self.agent_id, "news_summary", {"limit": 15})
|
||||
await self.transition("working", "최신 뉴스 수집 중...", task_id)
|
||||
await self.transition("working", "뉴스 수집 중...", task_id)
|
||||
|
||||
try:
|
||||
# stock cron(매일 8:00)이 7:30 브리핑보다 늦게 돌아 어제 뉴스가
|
||||
# 요약되던 문제 방지 — 요약 직전에 동기 스크랩으로 DB를 갱신한다.
|
||||
try:
|
||||
await service_proxy.scrape_stock_news()
|
||||
except Exception as e:
|
||||
add_log(self.agent_id, f"뉴스 스크랩 실패 (이전 데이터로 진행): {e}", "warning", task_id)
|
||||
news = await service_proxy.fetch_stock_news(limit=15)
|
||||
indices = await service_proxy.fetch_stock_indices()
|
||||
|
||||
await self.transition("working", "AI 뉴스 요약 생성 중...")
|
||||
summary = self._format_news_summary(news, indices)
|
||||
|
||||
# AI 요약 호출 (LLM 처리는 stock이 담당)
|
||||
result = await service_proxy.summarize_stock_news(limit=15)
|
||||
update_task_status(task_id, "succeeded", {
|
||||
"summary": summary,
|
||||
"news_count": len(news) if isinstance(news, list) else 0,
|
||||
})
|
||||
|
||||
await self.transition("reporting", "뉴스 요약 전송 중...")
|
||||
|
||||
body = _build_briefing_body(result)
|
||||
|
||||
# 새 통합 텔레그램 API 사용
|
||||
from ..telegram import send_agent_message
|
||||
tg_result = await send_agent_message(
|
||||
agent_id=self.agent_id,
|
||||
kind="report",
|
||||
title="아침 시장 브리핑",
|
||||
body=body,
|
||||
body_is_html=True,
|
||||
task_id=task_id,
|
||||
metadata={
|
||||
"tokens": result["tokens"]["total"],
|
||||
"duration_ms": result["duration_ms"],
|
||||
"model": result["model"],
|
||||
},
|
||||
)
|
||||
|
||||
# 아내 chat 추가 전송 (설정된 경우) — 제목 + 본문만 간결하게
|
||||
from ..config import TELEGRAM_WIFE_CHAT_ID
|
||||
if TELEGRAM_WIFE_CHAT_ID:
|
||||
from ..telegram.messaging import send_raw
|
||||
wife_text = f"📈 <b>아침 시장 브리핑</b>\n\n{body}"
|
||||
wife_result = await send_raw(wife_text, chat_id=TELEGRAM_WIFE_CHAT_ID)
|
||||
if not wife_result.get("ok"):
|
||||
desc = wife_result.get("description") or "unknown"
|
||||
add_log(self.agent_id, f"Wife telegram send failed: {desc}", "warning", task_id)
|
||||
|
||||
update_task_status(task_id, "succeeded", {
|
||||
"summary": result["summary"],
|
||||
"article_count": result.get("article_count", 0),
|
||||
"tokens": result["tokens"],
|
||||
"model": result["model"],
|
||||
"duration_ms": result["duration_ms"],
|
||||
"telegram_sent": tg_result.get("ok", False),
|
||||
"telegram_message_id": tg_result.get("message_id"),
|
||||
})
|
||||
|
||||
if not tg_result.get("ok"):
|
||||
desc = tg_result.get("description") or "unknown"
|
||||
code = tg_result.get("error_code")
|
||||
add_log(self.agent_id, f"Telegram send failed: [{code}] {desc}", "warning", task_id)
|
||||
if self._ws_manager:
|
||||
await self._ws_manager.send_notification(
|
||||
self.agent_id, "telegram_failed", task_id, "텔레그램 전송 실패"
|
||||
)
|
||||
from ..telegram_bot import send_stock_summary
|
||||
await send_stock_summary(summary)
|
||||
|
||||
await self.transition("idle", "뉴스 요약 완료")
|
||||
|
||||
@@ -119,246 +39,7 @@ class StockAgent(BaseAgent):
|
||||
update_task_status(task_id, "failed", {"error": str(e)})
|
||||
await self.transition("idle", f"오류: {e}")
|
||||
|
||||
async def on_screener_schedule(self) -> None:
|
||||
"""KRX 강세주 스크리너 자동 잡 (평일 16:30 KST).
|
||||
|
||||
흐름:
|
||||
1) snapshot/refresh — 일봉 갱신 (실패해도 진행, 경고 로그)
|
||||
2) screener/run mode='auto' — 실행 + 결과 영구화 + telegram_payload 응답
|
||||
3) status=='skipped_holiday' → 종료 (텔레그램 미발신)
|
||||
4) status=='success' → telegram_payload.text 를 parse_mode 그대로 전송
|
||||
5) 예외/실패 → 운영자에게 별도 텔레그램 알림 (HTML)
|
||||
"""
|
||||
if self.state not in ("idle", "break"):
|
||||
return
|
||||
|
||||
task_id = create_task(self.agent_id, "screener_run", {"mode": "auto"})
|
||||
await self.transition("working", "스크리너 스냅샷 갱신 중...", task_id)
|
||||
|
||||
try:
|
||||
# 1) 스냅샷 갱신 — 실패해도 기존 일봉 데이터로 진행
|
||||
try:
|
||||
snap = await service_proxy.refresh_screener_snapshot()
|
||||
add_log(
|
||||
self.agent_id,
|
||||
f"snapshot refreshed: status={snap.get('status', '?')}",
|
||||
"info", task_id,
|
||||
)
|
||||
except Exception as e:
|
||||
add_log(
|
||||
self.agent_id,
|
||||
f"스냅샷 갱신 실패 (기존 데이터로 진행): {e}",
|
||||
"warning", task_id,
|
||||
)
|
||||
|
||||
await self.transition("working", "스크리너 실행 중...")
|
||||
|
||||
# 2) 스크리너 실행
|
||||
body = await service_proxy.run_stock_screener(mode="auto")
|
||||
status = body.get("status")
|
||||
asof = body.get("asof")
|
||||
|
||||
# 3) 공휴일 — 종료
|
||||
if status == "skipped_holiday":
|
||||
update_task_status(task_id, "succeeded", {
|
||||
"status": status,
|
||||
"asof": asof,
|
||||
"telegram_sent": False,
|
||||
})
|
||||
add_log(self.agent_id, f"스크리너 건너뜀 (휴일): {asof}", "info", task_id)
|
||||
await self.transition("idle", "휴일 — 스크리너 건너뜀")
|
||||
return
|
||||
|
||||
# 4) 성공 → 텔레그램 전송
|
||||
if status == "success":
|
||||
payload = body.get("telegram_payload") or {}
|
||||
text = payload.get("text") or ""
|
||||
parse_mode = payload.get("parse_mode", "MarkdownV2")
|
||||
|
||||
if not text:
|
||||
raise RuntimeError("telegram_payload.text 누락")
|
||||
|
||||
await self.transition("reporting", "스크리너 결과 전송 중...")
|
||||
|
||||
from ..telegram.messaging import send_raw
|
||||
tg = await send_raw(text, parse_mode=parse_mode)
|
||||
|
||||
update_task_status(task_id, "succeeded", {
|
||||
"status": status,
|
||||
"asof": asof,
|
||||
"run_id": body.get("run_id"),
|
||||
"survivors_count": body.get("survivors_count"),
|
||||
"telegram_sent": tg.get("ok", False),
|
||||
"telegram_message_id": tg.get("message_id"),
|
||||
})
|
||||
|
||||
if not tg.get("ok"):
|
||||
desc = tg.get("description") or "unknown"
|
||||
code = tg.get("error_code")
|
||||
add_log(
|
||||
self.agent_id,
|
||||
f"Screener telegram send failed: [{code}] {desc}",
|
||||
"warning", task_id,
|
||||
)
|
||||
if self._ws_manager:
|
||||
await self._ws_manager.send_notification(
|
||||
self.agent_id, "telegram_failed", task_id,
|
||||
"스크리너 텔레그램 전송 실패",
|
||||
)
|
||||
|
||||
await self.transition("idle", "스크리너 완료")
|
||||
return
|
||||
|
||||
# 5) 기타 status — failed 취급
|
||||
raise RuntimeError(f"unexpected screener status: {status}")
|
||||
|
||||
except Exception as e:
|
||||
err_msg = str(e)
|
||||
add_log(self.agent_id, f"Screener job failed: {err_msg}", "error", task_id)
|
||||
update_task_status(task_id, "failed", {"error": err_msg})
|
||||
|
||||
# 운영자 알림 — 기본 HTML parse_mode 사용
|
||||
try:
|
||||
from ..telegram.messaging import send_raw
|
||||
await send_raw(
|
||||
f"⚠️ <b>KRX 스크리너 실패</b>\n"
|
||||
f"<code>{html.escape(err_msg)[:500]}</code>"
|
||||
)
|
||||
except Exception as notify_err:
|
||||
add_log(
|
||||
self.agent_id,
|
||||
f"operator notify failed: {notify_err}",
|
||||
"warning", task_id,
|
||||
)
|
||||
|
||||
await self.transition("idle", f"스크리너 오류: {err_msg[:80]}")
|
||||
|
||||
async def on_ai_news_schedule(self) -> None:
|
||||
"""AI 뉴스 sentiment 분석 자동 잡 (평일 08:00 KST).
|
||||
|
||||
흐름:
|
||||
1) stock /snapshot/refresh-news-sentiment 호출
|
||||
2) status='skipped_weekend'/'skipped_holiday' → 종료 (텔레그램 미발신)
|
||||
3) updated=0 → 운영자 알림 (HTML)
|
||||
4) failures > 30% → 경고 알림 후 메인 메시지 발송
|
||||
5) 정상 → Top 5 호재/악재 메시지 발송 (MarkdownV2)
|
||||
"""
|
||||
if self.state not in ("idle", "break"):
|
||||
return
|
||||
|
||||
task_id = create_task(self.agent_id, "ai_news_sentiment", {})
|
||||
await self.transition("working", "AI 뉴스 분석 중...", task_id)
|
||||
|
||||
try:
|
||||
result = await service_proxy.refresh_ai_news_sentiment()
|
||||
except Exception as e:
|
||||
err_msg = str(e)
|
||||
add_log(self.agent_id, f"AI 뉴스 분석 실패: {err_msg}", "error", task_id)
|
||||
update_task_status(task_id, "failed", {"error": err_msg})
|
||||
try:
|
||||
from ..telegram.messaging import send_raw
|
||||
await send_raw(
|
||||
f"⚠️ <b>AI 뉴스 분석 실패</b>\n"
|
||||
f"<code>{html.escape(err_msg)[:500]}</code>"
|
||||
)
|
||||
except Exception as notify_err:
|
||||
add_log(
|
||||
self.agent_id,
|
||||
f"operator notify failed: {notify_err}",
|
||||
"warning", task_id,
|
||||
)
|
||||
await self.transition("idle", f"AI 뉴스 오류: {err_msg[:80]}")
|
||||
return
|
||||
|
||||
status = result.get("status")
|
||||
if status in ("skipped_weekend", "skipped_holiday"):
|
||||
update_task_status(task_id, "succeeded", {"status": status})
|
||||
add_log(self.agent_id, f"AI 뉴스 건너뜀: {status}", "info", task_id)
|
||||
await self.transition("idle", "휴일/주말 — 건너뜀")
|
||||
return
|
||||
|
||||
updated = int(result.get("updated", 0))
|
||||
failures = result.get("failures", []) or []
|
||||
if updated == 0:
|
||||
update_task_status(task_id, "failed", {"reason": "0 tickers updated"})
|
||||
try:
|
||||
from ..telegram.messaging import send_raw
|
||||
await send_raw(
|
||||
"⚠️ <b>AI 뉴스 분석 0종목</b>\n"
|
||||
"스크래핑/LLM 전체 실패 — 어제 데이터 사용"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
await self.transition("idle", "AI 뉴스 0건")
|
||||
return
|
||||
|
||||
# 실패율 경고 (별도 알림, 본 메시지는 계속 발송)
|
||||
failure_rate = len(failures) / max(1, updated + len(failures))
|
||||
if failure_rate > 0.3:
|
||||
try:
|
||||
from ..telegram.messaging import send_raw
|
||||
await send_raw(
|
||||
f"⚠️ <b>AI 뉴스 실패율 {failure_rate:.0%}</b>\n"
|
||||
f"updated={updated}, failures={len(failures)}"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 정상 — Top 5 메시지 (stock이 빌드해서 응답에 telegram_text 동봉)
|
||||
text = result.get("telegram_text") or ""
|
||||
if not text:
|
||||
add_log(self.agent_id, "telegram_text 누락 — stock 응답 결함", "error", task_id)
|
||||
update_task_status(task_id, "failed", {"error": "telegram_text 누락"})
|
||||
await self.transition("idle", "AI 뉴스 응답 결함")
|
||||
return
|
||||
|
||||
await self.transition("reporting", "AI 뉴스 알림 전송 중...")
|
||||
from ..telegram.messaging import send_raw
|
||||
tg = await send_raw(text, parse_mode="MarkdownV2")
|
||||
|
||||
update_task_status(task_id, "succeeded", {
|
||||
"asof": result["asof"],
|
||||
"updated": updated,
|
||||
"failures": len(failures),
|
||||
"tokens_input": int(result.get("tokens_input", 0)),
|
||||
"tokens_output": int(result.get("tokens_output", 0)),
|
||||
"telegram_sent": tg.get("ok", False),
|
||||
})
|
||||
|
||||
if not tg.get("ok"):
|
||||
desc = tg.get("description") or "unknown"
|
||||
code = tg.get("error_code")
|
||||
add_log(
|
||||
self.agent_id,
|
||||
f"AI news telegram send failed: [{code}] {desc}",
|
||||
"warning", task_id,
|
||||
)
|
||||
|
||||
await self.transition("idle", "AI 뉴스 완료")
|
||||
|
||||
async def on_command(self, command: str, params: dict) -> dict:
|
||||
if command == "run_screener":
|
||||
await self.on_screener_schedule()
|
||||
return {"ok": True, "message": "스크리너 실행 트리거 완료"}
|
||||
|
||||
if command == "run_ai_news":
|
||||
await self.on_ai_news_schedule()
|
||||
return {"ok": True, "message": "AI 뉴스 분석 트리거 완료"}
|
||||
|
||||
if command == "test_telegram":
|
||||
from ..telegram import send_agent_message
|
||||
result = await send_agent_message(
|
||||
agent_id=self.agent_id,
|
||||
kind="info",
|
||||
title="연결 테스트",
|
||||
body="텔레그램 연동이 정상적으로 동작합니다.",
|
||||
)
|
||||
return {
|
||||
"ok": result.get("ok", False),
|
||||
"message": "텔레그램 전송 성공" if result.get("ok") else "텔레그램 전송 실패",
|
||||
"telegram_message_id": result.get("message_id"),
|
||||
}
|
||||
|
||||
if command == "fetch_news":
|
||||
await self.on_schedule()
|
||||
return {"ok": True, "message": "뉴스 수집 시작"}
|
||||
@@ -389,3 +70,30 @@ class StockAgent(BaseAgent):
|
||||
|
||||
async def on_approval(self, task_id: str, approved: bool, feedback: str = "") -> None:
|
||||
pass
|
||||
|
||||
def _format_news_summary(self, news, indices) -> str:
|
||||
lines = ["📈 [주식 에이전트] 아침 뉴스 요약", "━" * 20]
|
||||
|
||||
if isinstance(news, list):
|
||||
for item in news[:10]:
|
||||
title = item.get("title", "")
|
||||
if title:
|
||||
lines.append(f"• {title}")
|
||||
elif isinstance(news, dict) and "articles" in news:
|
||||
for item in news["articles"][:10]:
|
||||
title = item.get("title", "")
|
||||
if title:
|
||||
lines.append(f"• {title}")
|
||||
|
||||
if indices:
|
||||
lines.append("")
|
||||
lines.append("📊 주요 지수")
|
||||
if isinstance(indices, dict):
|
||||
for key, val in indices.items():
|
||||
if isinstance(val, dict):
|
||||
name = val.get("name", key)
|
||||
price = val.get("price", "")
|
||||
change = val.get("change", "")
|
||||
lines.append(f"{name}: {price} ({change})")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
@@ -1,93 +0,0 @@
|
||||
# agent-office/app/agents/youtube.py
|
||||
import asyncio
|
||||
import logging
|
||||
from datetime import date
|
||||
|
||||
import httpx
|
||||
|
||||
from .base import BaseAgent
|
||||
from ..db import add_youtube_research_job, update_youtube_research_job, add_log
|
||||
from ..youtube_researcher import (
|
||||
TARGET_COUNTRIES, TREND_KEYWORDS, MUSIC_LAB_URL,
|
||||
fetch_youtube_trending, fetch_google_trends, fetch_billboard_top20,
|
||||
push_to_music_lab,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class YouTubeResearchAgent(BaseAgent):
|
||||
agent_id = "youtube"
|
||||
display_name = "YouTube 리서치"
|
||||
|
||||
async def on_schedule(self) -> None:
|
||||
await self._run_research(TARGET_COUNTRIES)
|
||||
|
||||
async def on_command(self, command: str, params: dict) -> dict:
|
||||
if command == "research":
|
||||
if self.state == "working":
|
||||
return {"ok": False, "message": "이미 수집 중"}
|
||||
countries = params.get("countries", TARGET_COUNTRIES)
|
||||
asyncio.create_task(self._run_research(countries))
|
||||
return {"ok": True, "message": f"리서치 시작: {countries}"}
|
||||
return {"ok": False, "message": f"Unknown command: {command}"}
|
||||
|
||||
async def on_approval(self, task_id: str, approved: bool, feedback: str = "") -> None:
|
||||
pass
|
||||
|
||||
async def _run_research(self, countries: list) -> None:
|
||||
job_id = add_youtube_research_job(countries)
|
||||
await self.transition("working", f"트렌드 수집 중 ({','.join(countries)})", str(job_id))
|
||||
|
||||
all_trends = []
|
||||
try:
|
||||
for country in countries:
|
||||
trends = await fetch_youtube_trending(country)
|
||||
all_trends.extend(trends)
|
||||
|
||||
gt = await fetch_google_trends(TREND_KEYWORDS, countries)
|
||||
all_trends.extend(gt)
|
||||
|
||||
bb = await fetch_billboard_top20()
|
||||
all_trends.extend(bb)
|
||||
|
||||
ok = await push_to_music_lab(all_trends, date.today().isoformat())
|
||||
if not ok:
|
||||
raise RuntimeError("music-lab push 실패")
|
||||
|
||||
update_youtube_research_job(job_id, "completed", len(all_trends))
|
||||
await self.transition("reporting", f"수집 완료: {len(all_trends)}건", str(job_id))
|
||||
except Exception as e:
|
||||
update_youtube_research_job(job_id, "failed", len(all_trends), str(e))
|
||||
await self.transition("idle", f"수집 실패: {e}")
|
||||
return
|
||||
|
||||
await self.transition("idle", "리서치 완료")
|
||||
|
||||
async def send_weekly_report(self) -> None:
|
||||
"""매주 월요일 08:00 — 주간 인사이트 텔레그램 발송."""
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=10.0) as client:
|
||||
resp = await client.get(f"{MUSIC_LAB_URL}/api/music/market/report/latest")
|
||||
if resp.status_code != 200:
|
||||
return
|
||||
report = resp.json()
|
||||
except Exception as e:
|
||||
add_log(self.agent_id, f"주간 리포트 조회 실패: {e}", level="error")
|
||||
logger.error("send_weekly_report: music-lab 조회 실패: %s", e)
|
||||
return
|
||||
|
||||
top = report.get("top_genres", [])[:3]
|
||||
insights = report.get("insights", "")
|
||||
text = "📊 *YouTube 시장 주간 리포트*\n\n🔥 인기 장르:\n"
|
||||
for g in top:
|
||||
text += f" • {g['genre']} (score: {g['score']:.2f})\n"
|
||||
if insights:
|
||||
text += f"\n💡 {insights[:300]}"
|
||||
|
||||
try:
|
||||
from ..telegram_bot import send_message
|
||||
await send_message(text)
|
||||
except (ImportError, Exception) as e:
|
||||
add_log(self.agent_id, f"주간 리포트 텔레그램 발송 실패: {e}", level="error")
|
||||
logger.error("send_weekly_report: 텔레그램 발송 실패: %s", e)
|
||||
@@ -1,112 +0,0 @@
|
||||
"""텔레그램 단일 채널로 단계별 승인 인터랙션 오케스트레이션."""
|
||||
import logging
|
||||
|
||||
from .base import BaseAgent
|
||||
from . import classify_intent
|
||||
from .. import service_proxy
|
||||
from ..db import add_log
|
||||
from ..telegram.messaging import send_raw
|
||||
|
||||
logger = logging.getLogger("agent-office.youtube_publisher")
|
||||
|
||||
|
||||
_STEP_TITLES = {
|
||||
"cover_pending": ("커버 아트", "cover"),
|
||||
"video_pending": ("영상 비주얼", "video"),
|
||||
"thumb_pending": ("썸네일", "thumb"),
|
||||
"meta_pending": ("메타데이터", "meta"),
|
||||
"publish_pending": ("최종 검토 + 발행", "publish"),
|
||||
}
|
||||
|
||||
|
||||
class YoutubePublisherAgent(BaseAgent):
|
||||
agent_id = "youtube_publisher"
|
||||
display_name = "YouTube 퍼블리셔"
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self._notified_state_per_pipeline: dict[int, tuple] = {}
|
||||
|
||||
async def poll_state_changes(self) -> None:
|
||||
"""주기적으로 호출되어 *_pending 신규 진입 시 텔레그램 발송."""
|
||||
try:
|
||||
pipelines = await service_proxy.list_active_pipelines()
|
||||
except Exception as e:
|
||||
logger.warning("폴링 실패: %s", e)
|
||||
return
|
||||
|
||||
for p in pipelines:
|
||||
state = p.get("state")
|
||||
pid = p.get("id")
|
||||
if pid is None:
|
||||
continue
|
||||
if state in _STEP_TITLES:
|
||||
_, step = _STEP_TITLES[state]
|
||||
fb_count = (p.get("feedback_count_per_step") or {}).get(step, 0)
|
||||
key = (state, fb_count)
|
||||
if self._notified_state_per_pipeline.get(pid) != key:
|
||||
await self._notify_step(p)
|
||||
self._notified_state_per_pipeline[pid] = key
|
||||
|
||||
async def _notify_step(self, pipeline: dict) -> None:
|
||||
state = pipeline["state"]
|
||||
title_name, step = _STEP_TITLES[state]
|
||||
body = self._format_body(pipeline, step)
|
||||
track_title = pipeline.get("track_title") or f"Pipeline #{pipeline['id']}"
|
||||
text = (
|
||||
f"🎵 [{track_title}] {title_name} 검토\n\n"
|
||||
f"{body}\n\n"
|
||||
f"➡️ 답장으로 알려주세요: '승인' 또는 '반려 + 수정 방향'"
|
||||
)
|
||||
sent = await send_raw(text=text)
|
||||
if sent.get("ok"):
|
||||
msg_id = sent.get("message_id")
|
||||
try:
|
||||
await service_proxy.save_pipeline_telegram_msg(pipeline["id"], step, msg_id)
|
||||
except Exception as e:
|
||||
logger.warning("telegram-msg 저장 실패: %s", e)
|
||||
add_log(self.agent_id, f"pipeline {pipeline['id']} {step} 알림 전송", "info")
|
||||
|
||||
def _format_body(self, p: dict, step: str) -> str:
|
||||
if step == "cover":
|
||||
return f"🖼️ 커버: {p.get('cover_url', '-')}"
|
||||
if step == "video":
|
||||
return f"🎬 영상: {p.get('video_url', '-')}"
|
||||
if step == "thumb":
|
||||
return f"🎴 썸네일: {p.get('thumbnail_url', '-')}"
|
||||
if step == "meta":
|
||||
m = p.get("metadata", {}) or {}
|
||||
tags = m.get("tags", []) or []
|
||||
description = (m.get("description", "") or "")
|
||||
return (
|
||||
f"📝 제목: {m.get('title', '')}\n"
|
||||
f"🏷️ 태그: {', '.join(tags[:8])}\n"
|
||||
f"📄 설명(앞부분): {description[:200]}"
|
||||
)
|
||||
if step == "publish":
|
||||
r = p.get("review", {}) or {}
|
||||
return (
|
||||
f"AI 검토 결과: {r.get('verdict', '?')} "
|
||||
f"(가중 {r.get('weighted_total', '?')}/100)\n"
|
||||
f"{r.get('summary', '')}"
|
||||
)
|
||||
return ""
|
||||
|
||||
async def on_telegram_reply(self, pipeline_id: int, step: str, user_text: str) -> None:
|
||||
intent, feedback = classify_intent.classify(user_text)
|
||||
if intent == "unclear":
|
||||
await send_raw("다시 입력해주세요. 예: '승인' 또는 '반려, 제목 짧게'")
|
||||
return
|
||||
try:
|
||||
await service_proxy.post_pipeline_feedback(pipeline_id, step, intent, feedback)
|
||||
except Exception as e:
|
||||
await send_raw(f"⚠️ 처리 실패: {e}")
|
||||
|
||||
async def on_schedule(self) -> None:
|
||||
await self.poll_state_changes()
|
||||
|
||||
async def on_command(self, command: str, params: dict) -> dict:
|
||||
return {"ok": False, "message": f"Unknown command: {command}"}
|
||||
|
||||
async def on_approval(self, task_id: str, approved: bool, feedback: str = "") -> None:
|
||||
pass
|
||||
@@ -1,22 +1,13 @@
|
||||
import os
|
||||
|
||||
# Service URLs (Docker internal network)
|
||||
STOCK_URL = os.getenv("STOCK_URL", "http://localhost:18500")
|
||||
STOCK_LAB_URL = os.getenv("STOCK_LAB_URL", "http://localhost:18500")
|
||||
MUSIC_LAB_URL = os.getenv("MUSIC_LAB_URL", "http://localhost:18600")
|
||||
INSTA_LAB_URL = os.getenv("INSTA_LAB_URL", "http://localhost:18700")
|
||||
REALESTATE_LAB_URL = os.getenv("REALESTATE_LAB_URL", "http://localhost:18800")
|
||||
|
||||
# Telegram
|
||||
TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN", "")
|
||||
TELEGRAM_CHAT_ID = os.getenv("TELEGRAM_CHAT_ID", "")
|
||||
TELEGRAM_WEBHOOK_URL = os.getenv("TELEGRAM_WEBHOOK_URL", "")
|
||||
TELEGRAM_WIFE_CHAT_ID = os.getenv("TELEGRAM_WIFE_CHAT_ID", "")
|
||||
|
||||
# Anthropic (conversational)
|
||||
ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY", "")
|
||||
CONVERSATION_MODEL = os.getenv("CONVERSATION_MODEL", "claude-haiku-4-5-20251001")
|
||||
CONVERSATION_HISTORY_LIMIT = int(os.getenv("CONVERSATION_HISTORY_LIMIT", "20"))
|
||||
CONVERSATION_RATE_PER_MIN = int(os.getenv("CONVERSATION_RATE_PER_MIN", "6"))
|
||||
|
||||
# Database
|
||||
DB_PATH = os.getenv("AGENT_OFFICE_DB_PATH", "/app/data/agent_office.db")
|
||||
@@ -30,7 +21,3 @@ CORS_ALLOW_ORIGINS = os.getenv(
|
||||
IDLE_BREAK_THRESHOLD = int(os.getenv("IDLE_BREAK_THRESHOLD", "300")) # 5 min
|
||||
BREAK_DURATION_MIN = int(os.getenv("BREAK_DURATION_MIN", "60")) # 1 min
|
||||
BREAK_DURATION_MAX = int(os.getenv("BREAK_DURATION_MAX", "180")) # 3 min
|
||||
|
||||
# Lotto Curator
|
||||
LOTTO_BACKEND_URL = os.getenv("LOTTO_BACKEND_URL", "http://lotto:8000")
|
||||
LOTTO_CURATOR_MODEL = os.getenv("LOTTO_CURATOR_MODEL", "claude-sonnet-4-5")
|
||||
|
||||
@@ -1,132 +0,0 @@
|
||||
"""큐레이터 파이프라인 — fetch → claude → validate → save."""
|
||||
import json
|
||||
import time
|
||||
from typing import Any, Dict
|
||||
|
||||
import httpx
|
||||
|
||||
from ..config import ANTHROPIC_API_KEY, LOTTO_CURATOR_MODEL
|
||||
from .. import service_proxy
|
||||
from .prompt import SYSTEM_PROMPT, build_user_message
|
||||
from .schema import validate_response
|
||||
from .retrospective import build_retrospective
|
||||
|
||||
|
||||
API_URL = "https://api.anthropic.com/v1/messages"
|
||||
|
||||
|
||||
class CuratorError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
async def _call_claude(user_text: str, feedback: str = "") -> tuple[dict, dict]:
|
||||
if not ANTHROPIC_API_KEY:
|
||||
raise CuratorError("ANTHROPIC_API_KEY missing")
|
||||
headers = {
|
||||
"x-api-key": ANTHROPIC_API_KEY,
|
||||
"anthropic-version": "2023-06-01",
|
||||
"anthropic-beta": "prompt-caching-2024-07-31",
|
||||
"content-type": "application/json",
|
||||
}
|
||||
system_blocks = [{
|
||||
"type": "text",
|
||||
"text": SYSTEM_PROMPT,
|
||||
"cache_control": {"type": "ephemeral"},
|
||||
}]
|
||||
if feedback:
|
||||
user_text = f"이전 응답이 다음 이유로 거절됨: {feedback}\n올바른 스키마로 다시 응답.\n\n{user_text}"
|
||||
payload = {
|
||||
"model": LOTTO_CURATOR_MODEL,
|
||||
"max_tokens": 8192, # 4계층 20세트 + narrative + retrospective 수용
|
||||
"system": system_blocks,
|
||||
"messages": [{"role": "user", "content": [{"type": "text", "text": user_text}]}],
|
||||
}
|
||||
started = time.monotonic()
|
||||
async with httpx.AsyncClient(timeout=180) as client: # 큰 응답 → 시간 여유
|
||||
r = await client.post(API_URL, headers=headers, json=payload)
|
||||
r.raise_for_status()
|
||||
resp = r.json()
|
||||
latency_ms = int((time.monotonic() - started) * 1000)
|
||||
|
||||
text = "".join(
|
||||
b.get("text", "") for b in resp.get("content", []) if b.get("type") == "text"
|
||||
).strip()
|
||||
if text.startswith("```"):
|
||||
text = text.strip("`")
|
||||
if text.startswith("json"):
|
||||
text = text[4:]
|
||||
text = text.strip()
|
||||
parsed = json.loads(text)
|
||||
|
||||
usage = resp.get("usage", {}) or {}
|
||||
return parsed, {
|
||||
"input": int(usage.get("input_tokens", 0) or 0),
|
||||
"output": int(usage.get("output_tokens", 0) or 0),
|
||||
"cache_read": int(usage.get("cache_read_input_tokens", 0) or 0),
|
||||
"cache_write": int(usage.get("cache_creation_input_tokens", 0) or 0),
|
||||
"latency_ms": latency_ms,
|
||||
}
|
||||
|
||||
|
||||
async def curate_weekly(source: str = "auto") -> Dict[str, Any]:
|
||||
cand_resp = await service_proxy.lotto_candidates(n=30) # ← 30 으로 확장
|
||||
draw_no = cand_resp["draw_no"]
|
||||
candidates = cand_resp["candidates"]
|
||||
context = await service_proxy.lotto_context()
|
||||
|
||||
retrospective = await build_retrospective(draw_no)
|
||||
|
||||
user_text = build_user_message(draw_no, candidates, {
|
||||
"hot_numbers": context.get("hot_numbers", []),
|
||||
"cold_numbers": context.get("cold_numbers", []),
|
||||
"last_draw_summary": context.get("last_draw_summary", ""),
|
||||
"my_recent_performance": context.get("my_recent_performance", []),
|
||||
"retrospective": retrospective,
|
||||
})
|
||||
|
||||
candidate_numbers = [c["numbers"] for c in candidates]
|
||||
|
||||
usage_total = {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "latency_ms": 0}
|
||||
last_error = None
|
||||
validated = None
|
||||
|
||||
for attempt in (0, 1):
|
||||
try:
|
||||
raw, usage = await _call_claude(user_text, feedback=last_error or "")
|
||||
for k in usage_total:
|
||||
usage_total[k] += usage[k]
|
||||
validated = validate_response(raw, candidate_numbers)
|
||||
break
|
||||
except Exception as e:
|
||||
last_error = f"{type(e).__name__}: {e}"
|
||||
|
||||
if validated is None:
|
||||
raise CuratorError(f"schema validation failed after retry: {last_error}")
|
||||
|
||||
payload = {
|
||||
"draw_no": draw_no,
|
||||
"picks": {
|
||||
"core": [p.model_dump() for p in validated.core_picks],
|
||||
"bonus": [p.model_dump() for p in validated.bonus_picks],
|
||||
"extended": [p.model_dump() for p in validated.extended_picks],
|
||||
"pool": [p.model_dump() for p in validated.pool_picks],
|
||||
},
|
||||
"narrative": validated.narrative.model_dump(),
|
||||
"tier_rationale": validated.tier_rationale.model_dump(),
|
||||
"confidence": validated.confidence,
|
||||
"model": LOTTO_CURATOR_MODEL,
|
||||
"tokens_input": usage_total["input"],
|
||||
"tokens_output": usage_total["output"],
|
||||
"cache_read": usage_total["cache_read"],
|
||||
"cache_write": usage_total["cache_write"],
|
||||
"latency_ms": usage_total["latency_ms"],
|
||||
"source": source,
|
||||
}
|
||||
await service_proxy.lotto_save_briefing(payload)
|
||||
return {
|
||||
"ok": True,
|
||||
"draw_no": draw_no,
|
||||
"confidence": validated.confidence,
|
||||
"tokens": {"input": usage_total["input"], "output": usage_total["output"]},
|
||||
"payload": payload, # 텔레그램 알림용
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
"""큐레이터 system/user 프롬프트. system은 정적이므로 캐시 대상."""
|
||||
import json
|
||||
|
||||
|
||||
SYSTEM_PROMPT = """당신은 로또 번호 큐레이터입니다.
|
||||
주어진 후보 30세트 중 4계층(코어 5, 보너스 5, 확장 5, 풀 5) 총 20세트를 선별합니다.
|
||||
|
||||
계층별 큐레이션 규칙:
|
||||
- core_picks (5): 안정 2 / 균형 2 / 공격 1. 그 주 주축. 홀짝·저고·구간 분포가 세트끼리 겹치지 않게.
|
||||
- bonus_picks (5): 코어 분배의 공백을 메우는 5세트. 코어가 공격 1뿐이면 보너스에 공격 +2 식.
|
||||
- extended_picks (5): 코어·보너스에 없는 시각 — 합계 극단(80↓ / 180↑) / 콜드 4주 누적 / 4주 미등장 번호 노출.
|
||||
- pool_picks (5): 이번 주 한 번도 누르지 않은 패턴 — 연속 3개 / 동일 끝자리 / 5수 균등(각 끝자리 5개씩) 등.
|
||||
- tier_rationale 의 3개 키(bonus·extended·pool)에 각각 30자 이내 한국어 사유.
|
||||
|
||||
공통 규칙:
|
||||
- 후보에 없는 번호 조합은 절대 사용 금지. 모든 픽은 candidates 중 하나와 정확히 일치해야 함.
|
||||
- 4계층 사이에 중복 픽 금지 (총 20세트는 모두 서로 달라야 함).
|
||||
- 각 픽 reason 은 한국어 40자 이내. 해당 픽의 features 와 context 만 근거로.
|
||||
- 중립형(hot_number_count=0 이고 cold_number_count=0) 세트를 코어에 최소 1개 포함.
|
||||
|
||||
회고 규칙:
|
||||
- context.retrospective 가 있으면 narrative.retrospective 에 한 줄(60자 이내)로 작성.
|
||||
- 회고는 큐레이터 자기 결과(curator_avg, best_tier) + 사용자 결과(user_avg, pattern_delta) 둘 다 짚을 것.
|
||||
- 이번 주 코어 분배는 회고에 근거해 조정. 조정 사유는 narrative.headline 에 한 줄로.
|
||||
예: "지난 주 너 저번호 편향 → 보너스 고번호 보강"
|
||||
- context.retrospective 가 없으면 narrative.retrospective 는 빈 문자열.
|
||||
|
||||
narrative 규칙:
|
||||
- headline: 한 줄, 이번 주 추첨 전망 + 조정 사유.
|
||||
- summary_3lines: 정확히 3개 항목.
|
||||
- hot_cold_comment: hot/cold 번호 한 줄 논평.
|
||||
- warnings: 주의사항 없으면 빈 문자열.
|
||||
- retrospective: 회고 한 줄 또는 빈 문자열.
|
||||
|
||||
출력은 반드시 JSON 하나, 그 외 어떤 텍스트도 금지. 스키마:
|
||||
{
|
||||
"core_picks": [{"numbers":[...], "risk_tag":"안정"|"균형"|"공격", "reason": str}, ...5개],
|
||||
"bonus_picks": [...5개],
|
||||
"extended_picks": [...5개],
|
||||
"pool_picks": [...5개],
|
||||
"tier_rationale": {"bonus": str, "extended": str, "pool": str},
|
||||
"narrative": {
|
||||
"headline": str,
|
||||
"summary_3lines": [str, str, str],
|
||||
"hot_cold_comment": str,
|
||||
"warnings": str,
|
||||
"retrospective": str
|
||||
},
|
||||
"confidence": int (0~100)
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def build_user_message(draw_no: int, candidates: list, context: dict) -> str:
|
||||
payload = {
|
||||
"draw_no": draw_no,
|
||||
"context": context, # hot_numbers, cold_numbers, last_draw_summary, my_recent_performance, retrospective
|
||||
"candidates": candidates,
|
||||
}
|
||||
return (
|
||||
f"이번 회차: {draw_no}\n"
|
||||
f"아래 데이터로 4계층 20세트를 큐레이션하고 위 스키마로만 응답하세요.\n\n"
|
||||
f"```json\n{json.dumps(payload, ensure_ascii=False)}\n```"
|
||||
)
|
||||
@@ -1,50 +0,0 @@
|
||||
"""큐레이션 직전 호출 — review 1건 + 추세 3건 → 컨텍스트 dict."""
|
||||
import json
|
||||
from typing import Optional, Dict, Any
|
||||
from .. import service_proxy
|
||||
|
||||
|
||||
def _detect_bias(reviews: list) -> str:
|
||||
"""3주↑ 같은 방향 패턴 편향이 유지되면 한 줄로."""
|
||||
deltas = [r.get("pattern_delta") or "" for r in reviews if r.get("pattern_delta")]
|
||||
if len(deltas) < 2:
|
||||
return ""
|
||||
# 단순 휴리스틱 — 같은 키워드("저번호" 등)가 2회 이상이면 지속 편향
|
||||
keywords = ["저번호", "고번호", "합계", "홀짝"]
|
||||
persistent = []
|
||||
for kw in keywords:
|
||||
cnt = sum(1 for d in deltas if kw in d)
|
||||
if cnt >= max(2, len(deltas) - 1):
|
||||
persistent.append(kw)
|
||||
return " · ".join(persistent)
|
||||
|
||||
|
||||
async def build_retrospective(target_draw_no: int) -> Optional[Dict[str, Any]]:
|
||||
"""target_draw_no(이번 주) 직전 회차의 review + 그 앞 3회 추세."""
|
||||
last = await service_proxy.lotto_review_by_draw(target_draw_no - 1)
|
||||
if not last:
|
||||
return None
|
||||
|
||||
history = await service_proxy.lotto_reviews_history(limit=4)
|
||||
# history 는 desc 정렬 → last 와 그 이전 3건 분리
|
||||
others = [r for r in history if r["draw_no"] < target_draw_no - 1][:3]
|
||||
series = [last] + others
|
||||
|
||||
cur_avgs = [r["curator_avg_match"] for r in series if r.get("curator_avg_match") is not None]
|
||||
usr_avgs = [r["user_avg_match"] for r in series if r.get("user_avg_match") is not None]
|
||||
|
||||
return {
|
||||
"last_draw": {
|
||||
"draw_no": last["draw_no"],
|
||||
"curator_avg": last.get("curator_avg_match"),
|
||||
"curator_best_tier": last.get("curator_best_tier"),
|
||||
"user_avg": last.get("user_avg_match"),
|
||||
"user_5plus": last.get("user_5plus_prizes"),
|
||||
"pattern_delta": last.get("pattern_delta") or "",
|
||||
},
|
||||
"trend_4w": {
|
||||
"curator_avg_4w": round(sum(cur_avgs) / len(cur_avgs), 2) if cur_avgs else None,
|
||||
"user_avg_4w": round(sum(usr_avgs) / len(usr_avgs), 2) if usr_avgs else None,
|
||||
"user_persistent_bias": _detect_bias(series),
|
||||
},
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
from typing import List, Literal
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
|
||||
class Pick(BaseModel):
|
||||
numbers: List[int] = Field(min_length=6, max_length=6)
|
||||
risk_tag: Literal["안정", "균형", "공격"]
|
||||
reason: str = Field(max_length=80)
|
||||
|
||||
@field_validator("numbers")
|
||||
@classmethod
|
||||
def _check_numbers(cls, v):
|
||||
if len(set(v)) != 6:
|
||||
raise ValueError("numbers must be 6 unique integers")
|
||||
if any(n < 1 or n > 45 for n in v):
|
||||
raise ValueError("numbers must be within 1..45")
|
||||
return sorted(v)
|
||||
|
||||
|
||||
class TierRationale(BaseModel):
|
||||
bonus: str = Field(max_length=40)
|
||||
extended: str = Field(max_length=40)
|
||||
pool: str = Field(max_length=40)
|
||||
|
||||
|
||||
class Narrative(BaseModel):
|
||||
headline: str
|
||||
summary_3lines: List[str] = Field(min_length=3, max_length=3)
|
||||
hot_cold_comment: str = ""
|
||||
warnings: str = ""
|
||||
retrospective: str = Field(default="", max_length=80)
|
||||
|
||||
|
||||
class CuratorOutput(BaseModel):
|
||||
core_picks: List[Pick] = Field(min_length=5, max_length=5)
|
||||
bonus_picks: List[Pick] = Field(min_length=5, max_length=5)
|
||||
extended_picks: List[Pick] = Field(min_length=5, max_length=5)
|
||||
pool_picks: List[Pick] = Field(min_length=5, max_length=5)
|
||||
tier_rationale: TierRationale
|
||||
narrative: Narrative
|
||||
confidence: int = Field(ge=0, le=100)
|
||||
|
||||
|
||||
def validate_response(data: dict, candidate_numbers: List[List[int]]) -> CuratorOutput:
|
||||
out = CuratorOutput.model_validate(data)
|
||||
candidate_set = {tuple(sorted(c)) for c in candidate_numbers}
|
||||
all_picks = (
|
||||
out.core_picks + out.bonus_picks + out.extended_picks + out.pool_picks
|
||||
)
|
||||
# 중복 픽 검증
|
||||
pick_keys = [tuple(p.numbers) for p in all_picks]
|
||||
if len(pick_keys) != len(set(pick_keys)):
|
||||
raise ValueError("duplicate picks across tiers")
|
||||
# 후보에 없는 번호 조합 금지
|
||||
for p in all_picks:
|
||||
if tuple(p.numbers) not in candidate_set:
|
||||
raise ValueError(f"pick {p.numbers} not in candidates")
|
||||
return out
|
||||
@@ -9,10 +9,9 @@ from .config import DB_PATH
|
||||
|
||||
def _conn() -> sqlite3.Connection:
|
||||
os.makedirs(os.path.dirname(DB_PATH), exist_ok=True)
|
||||
conn = sqlite3.connect(DB_PATH, timeout=120.0)
|
||||
conn = sqlite3.connect(DB_PATH, timeout=10)
|
||||
conn.row_factory = sqlite3.Row
|
||||
conn.execute("PRAGMA journal_mode=WAL")
|
||||
conn.execute("PRAGMA busy_timeout=120000")
|
||||
return conn
|
||||
|
||||
|
||||
@@ -68,45 +67,8 @@ def init_db() -> None:
|
||||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
|
||||
)
|
||||
""")
|
||||
conn.execute("""
|
||||
CREATE TABLE IF NOT EXISTS conversation_messages (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
chat_id TEXT NOT NULL,
|
||||
role TEXT NOT NULL,
|
||||
content TEXT NOT NULL,
|
||||
model TEXT,
|
||||
tokens_input INTEGER DEFAULT 0,
|
||||
tokens_output INTEGER DEFAULT 0,
|
||||
cache_read INTEGER DEFAULT 0,
|
||||
cache_write INTEGER DEFAULT 0,
|
||||
latency_ms INTEGER DEFAULT 0,
|
||||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
|
||||
)
|
||||
""")
|
||||
conn.execute("""
|
||||
CREATE INDEX IF NOT EXISTS idx_conv_chat
|
||||
ON conversation_messages(chat_id, created_at DESC)
|
||||
""")
|
||||
conn.execute("""
|
||||
CREATE TABLE IF NOT EXISTS youtube_research_jobs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
status TEXT NOT NULL DEFAULT 'running',
|
||||
countries TEXT NOT NULL DEFAULT '[]',
|
||||
trends_collected INTEGER NOT NULL DEFAULT 0,
|
||||
error TEXT,
|
||||
started_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
|
||||
completed_at TEXT
|
||||
)
|
||||
""")
|
||||
# Seed default agent configs
|
||||
for agent_id, name in [
|
||||
("stock", "주식 트레이더"),
|
||||
("music", "음악 프로듀서"),
|
||||
("blog", "블로그 마케터"),
|
||||
("realestate", "청약 애널리스트"),
|
||||
("lotto", "로또 큐레이터"),
|
||||
("youtube", "YouTube 리서치"),
|
||||
]:
|
||||
for agent_id, name in [("stock", "주식 트레이더"), ("music", "음악 프로듀서")]:
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO agent_config(agent_id, display_name) VALUES(?,?)",
|
||||
(agent_id, name),
|
||||
@@ -297,262 +259,3 @@ def mark_telegram_responded(callback_id: str, action: str) -> None:
|
||||
"UPDATE telegram_state SET responded=1, action=? WHERE callback_id=?",
|
||||
(action, callback_id),
|
||||
)
|
||||
|
||||
|
||||
def get_token_usage_stats(agent_id: str, days: int = 1) -> dict:
|
||||
"""지정 에이전트의 최근 N일 토큰 사용량 집계.
|
||||
|
||||
agent_tasks 테이블의 result_data JSON에서 tokens.total을 합산.
|
||||
반환: {"total_tokens": int, "task_count": int, "by_day": [{"date": "YYYY-MM-DD", "tokens": int}]}
|
||||
"""
|
||||
with _conn() as conn:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT completed_at, result_data
|
||||
FROM agent_tasks
|
||||
WHERE agent_id = ?
|
||||
AND status = 'succeeded'
|
||||
AND completed_at IS NOT NULL
|
||||
AND completed_at >= strftime('%Y-%m-%dT%H:%M:%fZ','now', ?)
|
||||
""",
|
||||
(agent_id, f"-{int(days)} days"),
|
||||
).fetchall()
|
||||
|
||||
total_tokens = 0
|
||||
task_count = 0
|
||||
by_day_map: Dict[str, int] = {}
|
||||
for r in rows:
|
||||
result_data = r["result_data"]
|
||||
if not result_data:
|
||||
continue
|
||||
try:
|
||||
parsed = json.loads(result_data)
|
||||
except Exception:
|
||||
continue
|
||||
tokens = parsed.get("tokens") if isinstance(parsed, dict) else None
|
||||
total = 0
|
||||
if isinstance(tokens, dict):
|
||||
total = int(tokens.get("total", 0) or 0)
|
||||
if total <= 0:
|
||||
continue
|
||||
total_tokens += total
|
||||
task_count += 1
|
||||
completed_at = r["completed_at"] or ""
|
||||
day = completed_at[:10] if completed_at else "unknown"
|
||||
by_day_map[day] = by_day_map.get(day, 0) + total
|
||||
|
||||
by_day = [
|
||||
{"date": d, "tokens": t}
|
||||
for d, t in sorted(by_day_map.items())
|
||||
]
|
||||
return {
|
||||
"total_tokens": total_tokens,
|
||||
"task_count": task_count,
|
||||
"by_day": by_day,
|
||||
}
|
||||
|
||||
|
||||
def save_conversation_message(
|
||||
chat_id: str,
|
||||
role: str,
|
||||
content: str,
|
||||
model: Optional[str] = None,
|
||||
tokens_input: int = 0,
|
||||
tokens_output: int = 0,
|
||||
cache_read: int = 0,
|
||||
cache_write: int = 0,
|
||||
latency_ms: int = 0,
|
||||
) -> None:
|
||||
with _conn() as conn:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO conversation_messages
|
||||
(chat_id, role, content, model, tokens_input, tokens_output,
|
||||
cache_read, cache_write, latency_ms)
|
||||
VALUES (?,?,?,?,?,?,?,?,?)
|
||||
""",
|
||||
(str(chat_id), role, content, model, tokens_input, tokens_output,
|
||||
cache_read, cache_write, latency_ms),
|
||||
)
|
||||
|
||||
|
||||
def get_conversation_history(chat_id: str, limit: int = 20) -> List[Dict[str, Any]]:
|
||||
"""최근 N개를 시간순(오래된 → 최신)으로 반환."""
|
||||
with _conn() as conn:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT role, content FROM conversation_messages
|
||||
WHERE chat_id=? ORDER BY id DESC LIMIT ?
|
||||
""",
|
||||
(str(chat_id), limit),
|
||||
).fetchall()
|
||||
return [{"role": r["role"], "content": r["content"]} for r in reversed(rows)]
|
||||
|
||||
|
||||
def count_recent_user_messages(chat_id: str, seconds: int = 60) -> int:
|
||||
with _conn() as conn:
|
||||
r = conn.execute(
|
||||
"""
|
||||
SELECT COUNT(*) AS c FROM conversation_messages
|
||||
WHERE chat_id=? AND role='user'
|
||||
AND created_at >= strftime('%Y-%m-%dT%H:%M:%fZ','now', ?)
|
||||
""",
|
||||
(str(chat_id), f"-{int(seconds)} seconds"),
|
||||
).fetchone()
|
||||
return r["c"] if r else 0
|
||||
|
||||
|
||||
def get_conversation_stats(days: int = 7) -> Dict[str, Any]:
|
||||
with _conn() as conn:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT chat_id,
|
||||
COUNT(*) AS msg_count,
|
||||
SUM(tokens_input) AS in_tokens,
|
||||
SUM(tokens_output) AS out_tokens,
|
||||
SUM(cache_read) AS cache_read,
|
||||
SUM(cache_write) AS cache_write,
|
||||
AVG(latency_ms) AS avg_latency
|
||||
FROM conversation_messages
|
||||
WHERE role='assistant'
|
||||
AND created_at >= strftime('%Y-%m-%dT%H:%M:%fZ','now', ?)
|
||||
GROUP BY chat_id
|
||||
""",
|
||||
(f"-{int(days)} days",),
|
||||
).fetchall()
|
||||
|
||||
by_chat = []
|
||||
tot_in = tot_out = tot_r = tot_w = tot_msgs = 0
|
||||
for r in rows:
|
||||
ci = int(r["in_tokens"] or 0)
|
||||
co = int(r["out_tokens"] or 0)
|
||||
cr = int(r["cache_read"] or 0)
|
||||
cw = int(r["cache_write"] or 0)
|
||||
mc = int(r["msg_count"] or 0)
|
||||
hit_rate = (cr / (cr + cw)) if (cr + cw) > 0 else 0.0
|
||||
by_chat.append({
|
||||
"chat_id": r["chat_id"],
|
||||
"message_count": mc,
|
||||
"tokens_input": ci,
|
||||
"tokens_output": co,
|
||||
"cache_read": cr,
|
||||
"cache_write": cw,
|
||||
"cache_hit_rate": round(hit_rate, 3),
|
||||
"avg_latency_ms": round(float(r["avg_latency"] or 0), 1),
|
||||
})
|
||||
tot_in += ci; tot_out += co; tot_r += cr; tot_w += cw; tot_msgs += mc
|
||||
|
||||
overall_hit = (tot_r / (tot_r + tot_w)) if (tot_r + tot_w) > 0 else 0.0
|
||||
return {
|
||||
"days": days,
|
||||
"total_messages": tot_msgs,
|
||||
"tokens_input": tot_in,
|
||||
"tokens_output": tot_out,
|
||||
"cache_read": tot_r,
|
||||
"cache_write": tot_w,
|
||||
"cache_hit_rate": round(overall_hit, 3),
|
||||
"by_chat": by_chat,
|
||||
}
|
||||
|
||||
|
||||
def get_activity_feed(limit: int = 50, offset: int = 0) -> dict:
|
||||
with _conn() as conn:
|
||||
total_row = conn.execute("""
|
||||
SELECT (SELECT COUNT(*) FROM agent_tasks) + (SELECT COUNT(*) FROM agent_logs) AS total
|
||||
""").fetchone()
|
||||
total = total_row["total"] if total_row else 0
|
||||
|
||||
rows = conn.execute("""
|
||||
SELECT 'task' AS type, agent_id, id AS task_id, task_type,
|
||||
status, NULL AS level,
|
||||
COALESCE(
|
||||
json_extract(result_data, '$.summary'),
|
||||
task_type
|
||||
) AS message,
|
||||
created_at, completed_at,
|
||||
result_data
|
||||
FROM agent_tasks
|
||||
UNION ALL
|
||||
SELECT 'log' AS type, agent_id, task_id, NULL AS task_type,
|
||||
NULL AS status, level,
|
||||
message,
|
||||
created_at, NULL AS completed_at,
|
||||
NULL AS result_data
|
||||
FROM agent_logs
|
||||
ORDER BY created_at DESC
|
||||
LIMIT ? OFFSET ?
|
||||
""", (limit, offset)).fetchall()
|
||||
|
||||
items = []
|
||||
for r in rows:
|
||||
item = {
|
||||
"type": r["type"],
|
||||
"agent_id": r["agent_id"],
|
||||
"task_id": r["task_id"],
|
||||
"message": r["message"],
|
||||
"created_at": r["created_at"],
|
||||
}
|
||||
if r["type"] == "task":
|
||||
item["task_type"] = r["task_type"]
|
||||
item["status"] = r["status"]
|
||||
item["completed_at"] = r["completed_at"]
|
||||
if r["created_at"] and r["completed_at"]:
|
||||
try:
|
||||
from datetime import datetime
|
||||
start = datetime.fromisoformat(r["created_at"].replace("Z", "+00:00"))
|
||||
end = datetime.fromisoformat(r["completed_at"].replace("Z", "+00:00"))
|
||||
item["duration_seconds"] = round((end - start).total_seconds())
|
||||
except Exception:
|
||||
item["duration_seconds"] = None
|
||||
else:
|
||||
item["duration_seconds"] = None
|
||||
result_data = json.loads(r["result_data"]) if r["result_data"] else None
|
||||
if result_data and "telegram_sent" in result_data:
|
||||
item["telegram_sent"] = result_data["telegram_sent"]
|
||||
else:
|
||||
item["level"] = r["level"]
|
||||
items.append(item)
|
||||
|
||||
return {"items": items, "total": total}
|
||||
|
||||
|
||||
# ── youtube_research_jobs CRUD ────────────────────────────────────────────────
|
||||
|
||||
def add_youtube_research_job(countries: list) -> int:
|
||||
with _conn() as conn:
|
||||
conn.execute(
|
||||
"INSERT INTO youtube_research_jobs (countries) VALUES (?)",
|
||||
(json.dumps(countries),),
|
||||
)
|
||||
return conn.execute("SELECT last_insert_rowid()").fetchone()[0]
|
||||
|
||||
|
||||
def update_youtube_research_job(
|
||||
job_id: int, status: str, trends_collected: int, error: Optional[str] = None
|
||||
) -> None:
|
||||
with _conn() as conn:
|
||||
conn.execute(
|
||||
"""UPDATE youtube_research_jobs
|
||||
SET status=?, trends_collected=?, error=?,
|
||||
completed_at=strftime('%Y-%m-%dT%H:%M:%fZ','now')
|
||||
WHERE id=?""",
|
||||
(status, trends_collected, error, job_id),
|
||||
)
|
||||
|
||||
|
||||
def get_latest_youtube_research_job() -> Optional[Dict[str, Any]]:
|
||||
with _conn() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT * FROM youtube_research_jobs ORDER BY id DESC LIMIT 1"
|
||||
).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
return {
|
||||
"id": row["id"],
|
||||
"status": row["status"],
|
||||
"countries": json.loads(row["countries"]),
|
||||
"trends_collected": row["trends_collected"],
|
||||
"error": row["error"],
|
||||
"started_at": row["started_at"],
|
||||
"completed_at": row["completed_at"],
|
||||
}
|
||||
|
||||
@@ -4,16 +4,14 @@ from fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnect
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from .config import CORS_ALLOW_ORIGINS
|
||||
from .db import init_db, get_all_agents, get_agent_config, update_agent_config, get_agent_tasks, get_pending_approvals, get_task, get_logs, get_activity_feed, get_latest_youtube_research_job
|
||||
from .db import init_db, get_all_agents, get_agent_config, update_agent_config, get_agent_tasks, get_pending_approvals, get_task, get_logs
|
||||
from .models import CommandRequest, ApprovalRequest, AgentConfigUpdate
|
||||
from .websocket_manager import ws_manager
|
||||
from .agents import init_agents, get_agent, get_all_agent_states, AGENT_REGISTRY
|
||||
from .scheduler import init_scheduler
|
||||
from . import telegram_bot
|
||||
from .routers import notify as notify_router
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(notify_router.router)
|
||||
|
||||
_cors_origins = CORS_ALLOW_ORIGINS.split(",")
|
||||
app.add_middleware(
|
||||
@@ -140,26 +138,10 @@ async def approve(body: ApprovalRequest):
|
||||
|
||||
# --- Telegram Webhook ---
|
||||
|
||||
async def _agent_dispatcher(agent_id: str, command: str, params: dict) -> dict:
|
||||
"""텔레그램 라우터가 호출하는 에이전트 디스패처."""
|
||||
# 전역 상태 조회
|
||||
if agent_id == "__global__" and command == "status":
|
||||
result = {}
|
||||
for aid, agent in AGENT_REGISTRY.items():
|
||||
result[aid] = {"state": agent.state, "detail": agent.state_detail}
|
||||
return result
|
||||
|
||||
agent = AGENT_REGISTRY.get(agent_id)
|
||||
if agent is None:
|
||||
return {"ok": False, "message": f"Unknown agent: {agent_id}"}
|
||||
return await agent.on_command(command, params or {})
|
||||
|
||||
|
||||
@app.post("/api/agent-office/telegram/webhook")
|
||||
async def telegram_webhook(data: dict):
|
||||
result = await telegram_bot.handle_webhook(data, agent_dispatcher=_agent_dispatcher)
|
||||
# callback_query (승인/거절) → 기존 승인 흐름
|
||||
if result and "approved" in result:
|
||||
result = await telegram_bot.handle_webhook(data)
|
||||
if result:
|
||||
agent = get_agent(result["agent_id"])
|
||||
if agent:
|
||||
await agent.on_approval(result["task_id"], result["approved"])
|
||||
@@ -168,62 +150,3 @@ async def telegram_webhook(data: dict):
|
||||
@app.get("/api/agent-office/states")
|
||||
def all_states():
|
||||
return {"agents": get_all_agent_states()}
|
||||
|
||||
@app.get("/api/agent-office/agents/{agent_id}/token-usage")
|
||||
def agent_token_usage(agent_id: str, days: int = 1):
|
||||
from .db import get_token_usage_stats
|
||||
return get_token_usage_stats(agent_id, days)
|
||||
|
||||
@app.get("/api/agent-office/conversation/stats")
|
||||
def conversation_stats(days: int = 7):
|
||||
from .db import get_conversation_stats
|
||||
return get_conversation_stats(days)
|
||||
|
||||
@app.get("/api/agent-office/activity")
|
||||
def activity_feed(limit: int = 50, offset: int = 0):
|
||||
return get_activity_feed(limit, offset)
|
||||
|
||||
|
||||
# --- Realestate Agent Push Endpoint ---
|
||||
|
||||
from pydantic import BaseModel
|
||||
from typing import List, Dict, Any, Optional
|
||||
|
||||
|
||||
class RealestateNotifyBody(BaseModel):
|
||||
matches: List[Dict[str, Any]]
|
||||
|
||||
|
||||
@app.post("/api/agent-office/realestate/notify")
|
||||
async def realestate_notify(body: RealestateNotifyBody):
|
||||
agent = get_agent("realestate")
|
||||
if agent is None:
|
||||
from fastapi import HTTPException
|
||||
raise HTTPException(status_code=503, detail="RealestateAgent not initialized")
|
||||
return await agent.on_new_matches(body.matches)
|
||||
|
||||
|
||||
# --- YouTube Research Agent Endpoints ---
|
||||
|
||||
class YouTubeResearchBody(BaseModel):
|
||||
countries: List[str] = []
|
||||
|
||||
|
||||
@app.post("/api/agent-office/youtube/research")
|
||||
async def trigger_youtube_research(body: Optional[YouTubeResearchBody] = None):
|
||||
agent = get_agent("youtube")
|
||||
if not agent:
|
||||
raise HTTPException(status_code=503, detail="YouTubeResearchAgent 없음")
|
||||
params = {}
|
||||
if body and body.countries:
|
||||
params["countries"] = body.countries
|
||||
result = await agent.on_command("research", params)
|
||||
return result
|
||||
|
||||
|
||||
@app.get("/api/agent-office/youtube/research/status")
|
||||
def youtube_research_status():
|
||||
job = get_latest_youtube_research_job()
|
||||
if not job:
|
||||
return {"status": "never_run"}
|
||||
return job
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
"""로또 큐레이션·당첨 알림 — 텔레그램 푸시."""
|
||||
import logging
|
||||
from typing import Dict, Any
|
||||
|
||||
# 기존 에이전트들과 동일한 패턴: send_raw(text, reply_markup=None, chat_id=None)
|
||||
# chat_id 생략 시 기본 TELEGRAM_CHAT_ID로 자동 발송.
|
||||
from ..telegram.messaging import send_raw
|
||||
|
||||
logger = logging.getLogger("agent-office")
|
||||
|
||||
LOTTO_URL = "https://gahusb.synology.me/lotto"
|
||||
|
||||
|
||||
def _format_briefing(payload: Dict[str, Any]) -> str:
|
||||
draw_no = payload["draw_no"]
|
||||
nar = payload["narrative"]
|
||||
conf = payload["confidence"]
|
||||
|
||||
# 분배 칩 — core 5세트의 risk_tag 빈도
|
||||
core = payload["picks"]["core"]
|
||||
role_count = {"안정": 0, "균형": 0, "공격": 0}
|
||||
for p in core:
|
||||
role_count[p["risk_tag"]] = role_count.get(p["risk_tag"], 0) + 1
|
||||
chip = " · ".join(f"{k} {v}" for k, v in role_count.items() if v)
|
||||
|
||||
msg = [
|
||||
f"🎟 {draw_no}회 · 큐레이션 떴음",
|
||||
"",
|
||||
f"\"{nar['headline']}\"",
|
||||
f"신뢰도 {conf} · 분배 {chip}",
|
||||
]
|
||||
retro = nar.get("retrospective") or ""
|
||||
if retro:
|
||||
msg += ["", f"▸ 회고: {retro}"]
|
||||
msg += ["", f"👉 결정 카드 보러가기 ({LOTTO_URL})"]
|
||||
return "\n".join(msg)
|
||||
|
||||
|
||||
def _format_prize_alert(event: Dict[str, Any]) -> str:
|
||||
return (
|
||||
"🚨 로또 당첨 가능성!\n"
|
||||
f"{event['draw_no']}회 — {event['match_count']}개 일치\n"
|
||||
f"번호: {', '.join(str(n) for n in event['numbers'])}\n"
|
||||
"동행복권에서 즉시 확인하세요."
|
||||
)
|
||||
|
||||
|
||||
async def send_curator_briefing(payload: Dict[str, Any]) -> None:
|
||||
text = _format_briefing(payload)
|
||||
try:
|
||||
await send_raw(text)
|
||||
except Exception as e:
|
||||
logger.warning(f"[telegram_lotto] briefing send failed: {e}")
|
||||
|
||||
|
||||
async def send_prize_alert(event: Dict[str, Any]) -> None:
|
||||
text = _format_prize_alert(event)
|
||||
try:
|
||||
await send_raw(text)
|
||||
except Exception as e:
|
||||
logger.warning(f"[telegram_lotto] prize alert send failed: {e}")
|
||||
@@ -1,20 +0,0 @@
|
||||
"""다른 서비스가 트리거하는 웹훅 — 현재 lotto-backend → 텔레그램 푸시."""
|
||||
from typing import List
|
||||
from fastapi import APIRouter
|
||||
from pydantic import BaseModel
|
||||
from ..notifiers.telegram_lotto import send_prize_alert
|
||||
|
||||
router = APIRouter(prefix="/api/agent-office/notify")
|
||||
|
||||
|
||||
class LottoPrizeEvent(BaseModel):
|
||||
draw_no: int
|
||||
match_count: int
|
||||
numbers: List[int]
|
||||
purchase_id: int
|
||||
|
||||
|
||||
@router.post("/lotto-prize")
|
||||
async def lotto_prize(body: LottoPrizeEvent):
|
||||
await send_prize_alert(body.model_dump())
|
||||
return {"ok": True}
|
||||
@@ -14,63 +14,7 @@ async def _run_stock_schedule():
|
||||
if agent:
|
||||
await agent.on_schedule()
|
||||
|
||||
async def _run_stock_screener():
|
||||
agent = AGENT_REGISTRY.get("stock")
|
||||
if agent:
|
||||
await agent.on_screener_schedule()
|
||||
|
||||
async def _run_stock_ai_news():
|
||||
agent = AGENT_REGISTRY.get("stock")
|
||||
if agent:
|
||||
await agent.on_ai_news_schedule()
|
||||
|
||||
async def _run_insta_schedule():
|
||||
agent = AGENT_REGISTRY.get("insta")
|
||||
if agent:
|
||||
await agent.on_schedule()
|
||||
|
||||
async def _run_lotto_schedule():
|
||||
agent = AGENT_REGISTRY.get("lotto")
|
||||
if agent:
|
||||
await agent.on_schedule()
|
||||
|
||||
async def _run_youtube_research():
|
||||
agent = AGENT_REGISTRY.get("youtube")
|
||||
if agent:
|
||||
await agent.on_schedule()
|
||||
|
||||
async def _send_youtube_weekly_report():
|
||||
agent = AGENT_REGISTRY.get("youtube")
|
||||
if agent:
|
||||
await agent.send_weekly_report()
|
||||
|
||||
async def _poll_pipelines():
|
||||
agent = AGENT_REGISTRY.get("youtube_publisher")
|
||||
if agent:
|
||||
await agent.poll_state_changes()
|
||||
|
||||
def init_scheduler():
|
||||
scheduler.add_job(_run_stock_schedule, "cron", hour=7, minute=30, id="stock_news")
|
||||
scheduler.add_job(
|
||||
_run_stock_screener,
|
||||
"cron",
|
||||
day_of_week="mon-fri",
|
||||
hour=16,
|
||||
minute=30,
|
||||
id="stock_screener",
|
||||
)
|
||||
scheduler.add_job(
|
||||
_run_stock_ai_news,
|
||||
"cron",
|
||||
day_of_week="mon-fri",
|
||||
hour=8,
|
||||
minute=0,
|
||||
id="stock_ai_news_sentiment",
|
||||
)
|
||||
scheduler.add_job(_run_insta_schedule, "cron", hour=9, minute=30, id="insta_pipeline")
|
||||
scheduler.add_job(_run_lotto_schedule, "cron", day_of_week="mon", hour=9, minute=0, id="lotto_curate")
|
||||
scheduler.add_job(_run_youtube_research, "cron", hour=9, minute=0, id="youtube_research")
|
||||
scheduler.add_job(_send_youtube_weekly_report, "cron", day_of_week="mon", hour=8, minute=0, id="youtube_weekly_report")
|
||||
scheduler.add_job(_run_stock_schedule, "cron", hour=8, minute=0, id="stock_news")
|
||||
scheduler.add_job(_check_idle_breaks, "interval", seconds=60, id="idle_check")
|
||||
scheduler.add_job(_poll_pipelines, "interval", seconds=30, id="pipeline_poll")
|
||||
scheduler.start()
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import httpx
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from .config import STOCK_URL, MUSIC_LAB_URL, INSTA_LAB_URL, REALESTATE_LAB_URL
|
||||
from .config import STOCK_LAB_URL, MUSIC_LAB_URL
|
||||
|
||||
_client = httpx.AsyncClient(timeout=30.0)
|
||||
|
||||
@@ -9,82 +9,15 @@ async def fetch_stock_news(limit: int = 10, category: str = None) -> List[Dict[s
|
||||
params = {"limit": limit}
|
||||
if category:
|
||||
params["category"] = category
|
||||
resp = await _client.get(f"{STOCK_URL}/api/stock/news", params=params)
|
||||
resp = await _client.get(f"{STOCK_LAB_URL}/api/stock/news", params=params)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
async def fetch_stock_indices() -> Dict[str, Any]:
|
||||
resp = await _client.get(f"{STOCK_URL}/api/stock/indices")
|
||||
resp = await _client.get(f"{STOCK_LAB_URL}/api/stock/indices")
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
async def summarize_stock_news(limit: int = 15) -> Dict[str, Any]:
|
||||
"""stock의 AI 요약 엔드포인트 호출.
|
||||
반환: {"summary": str, "tokens": {...}, "model": str, "duration_ms": int, "article_count": int}
|
||||
"""
|
||||
# stock 내부 Ollama 호출이 180s까지 가능하므로 여유있게 200s
|
||||
async with httpx.AsyncClient(timeout=200.0) as client:
|
||||
resp = await client.post(
|
||||
f"{STOCK_URL}/api/stock/news/summarize",
|
||||
json={"limit": limit},
|
||||
)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
|
||||
async def refresh_screener_snapshot() -> Dict[str, Any]:
|
||||
"""stock의 KRX 일봉 스냅샷 갱신 (스크리너 실행 전 호출).
|
||||
|
||||
네이버 금융 일괄 다운로드라 보통 30~120s, 여유있게 180s.
|
||||
"""
|
||||
async with httpx.AsyncClient(timeout=180.0) as client:
|
||||
resp = await client.post(f"{STOCK_URL}/api/stock/screener/snapshot/refresh")
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
|
||||
async def refresh_ai_news_sentiment() -> Dict[str, Any]:
|
||||
"""stock의 AI 뉴스 sentiment 분석 트리거 (08:00 cron).
|
||||
|
||||
네이버 100종목 스크래핑 + Claude Haiku 100콜 병렬 = 약 30-60초.
|
||||
여유있게 240s timeout.
|
||||
"""
|
||||
async with httpx.AsyncClient(timeout=240.0) as client:
|
||||
resp = await client.post(
|
||||
f"{STOCK_URL}/api/stock/screener/snapshot/refresh-news-sentiment"
|
||||
)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
|
||||
async def run_stock_screener(mode: str = "auto") -> Dict[str, Any]:
|
||||
"""stock의 스크리너 실행.
|
||||
|
||||
반환 status:
|
||||
- 'skipped_holiday': 공휴일/주말 — telegram_payload 없음
|
||||
- 'success': telegram_payload 동봉
|
||||
엔진 자체는 수 초 내 끝나지만, 컨텍스트 로드+200종목 처리 여유 180s.
|
||||
"""
|
||||
async with httpx.AsyncClient(timeout=180.0) as client:
|
||||
resp = await client.post(
|
||||
f"{STOCK_URL}/api/stock/screener/run",
|
||||
json={"mode": mode},
|
||||
)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
|
||||
async def scrape_stock_news() -> Dict[str, Any]:
|
||||
"""stock의 수동 뉴스 스크랩 트리거 — DB에 최신 뉴스 저장.
|
||||
|
||||
아침 브리핑 직전 호출하여 어제 데이터가 아닌 오늘 새벽 뉴스를 보장한다.
|
||||
네이버 금융 단일 요청이라 보통 수 초 내 완료, 여유있게 60s.
|
||||
"""
|
||||
async with httpx.AsyncClient(timeout=60.0) as client:
|
||||
resp = await client.post(f"{STOCK_URL}/api/stock/scrap")
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
async def generate_music(payload: dict) -> Dict[str, Any]:
|
||||
resp = await _client.post(f"{MUSIC_LAB_URL}/api/music/generate", json=payload)
|
||||
resp.raise_for_status()
|
||||
@@ -99,207 +32,3 @@ async def get_music_credits() -> Dict[str, Any]:
|
||||
resp = await _client.get(f"{MUSIC_LAB_URL}/api/music/credits")
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
|
||||
# --- insta-lab ---
|
||||
|
||||
async def insta_collect(categories: Optional[list] = None) -> Dict[str, Any]:
|
||||
"""뉴스 수집 트리거 → task_id 반환."""
|
||||
payload = {"categories": categories} if categories else {}
|
||||
resp = await _client.post(f"{INSTA_LAB_URL}/api/insta/news/collect", json=payload)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
|
||||
async def insta_extract(categories: Optional[list] = None) -> Dict[str, Any]:
|
||||
payload = {"categories": categories} if categories else {}
|
||||
resp = await _client.post(f"{INSTA_LAB_URL}/api/insta/keywords/extract", json=payload)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
|
||||
async def insta_list_keywords(category: Optional[str] = None,
|
||||
used: Optional[bool] = None) -> List[Dict[str, Any]]:
|
||||
params: Dict[str, Any] = {}
|
||||
if category:
|
||||
params["category"] = category
|
||||
if used is not None:
|
||||
params["used"] = "true" if used else "false"
|
||||
resp = await _client.get(f"{INSTA_LAB_URL}/api/insta/keywords", params=params)
|
||||
resp.raise_for_status()
|
||||
return resp.json().get("items", [])
|
||||
|
||||
|
||||
async def insta_get_keyword(keyword_id: int) -> Optional[Dict[str, Any]]:
|
||||
items = await insta_list_keywords()
|
||||
for it in items:
|
||||
if it["id"] == keyword_id:
|
||||
return it
|
||||
return None
|
||||
|
||||
|
||||
async def insta_create_slate(keyword: str, category: str, keyword_id: Optional[int] = None) -> Dict[str, Any]:
|
||||
resp = await _client.post(
|
||||
f"{INSTA_LAB_URL}/api/insta/slates",
|
||||
json={"keyword": keyword, "category": category, "keyword_id": keyword_id},
|
||||
)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
|
||||
async def insta_task_status(task_id: str) -> Dict[str, Any]:
|
||||
resp = await _client.get(f"{INSTA_LAB_URL}/api/insta/tasks/{task_id}")
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
|
||||
async def insta_get_slate(slate_id: int) -> Dict[str, Any]:
|
||||
resp = await _client.get(f"{INSTA_LAB_URL}/api/insta/slates/{slate_id}")
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
|
||||
async def insta_get_asset_bytes(slate_id: int, page: int) -> bytes:
|
||||
"""카드 PNG 바이트를 가져와 텔레그램 미디어 그룹에 첨부."""
|
||||
async with httpx.AsyncClient(timeout=30) as client:
|
||||
resp = await client.get(f"{INSTA_LAB_URL}/api/insta/slates/{slate_id}/assets/{page}")
|
||||
resp.raise_for_status()
|
||||
return resp.content
|
||||
|
||||
|
||||
# --- realestate-lab ---
|
||||
|
||||
async def realestate_collect() -> Dict[str, Any]:
|
||||
"""청약 공고 수동 수집 트리거"""
|
||||
async with httpx.AsyncClient(timeout=120.0) as client:
|
||||
resp = await client.post(f"{REALESTATE_LAB_URL}/api/realestate/collect")
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
|
||||
async def realestate_matches(limit: int = 20) -> List[Dict[str, Any]]:
|
||||
"""realestate-lab의 GET /api/realestate/matches 호출."""
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
resp = await client.get(
|
||||
f"{REALESTATE_LAB_URL}/api/realestate/matches",
|
||||
params={"size": limit},
|
||||
)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
return data.get("items", [])
|
||||
|
||||
|
||||
async def realestate_dashboard() -> Dict[str, Any]:
|
||||
resp = await _client.get(f"{REALESTATE_LAB_URL}/api/realestate/dashboard")
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
|
||||
async def realestate_mark_read(match_id: int) -> Dict[str, Any]:
|
||||
resp = await _client.patch(f"{REALESTATE_LAB_URL}/api/realestate/matches/{match_id}/read")
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
|
||||
async def realestate_bookmark_toggle(announcement_id: int) -> Dict[str, Any]:
|
||||
"""realestate-lab의 PATCH /api/realestate/announcements/{id}/bookmark 호출."""
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
resp = await client.patch(
|
||||
f"{REALESTATE_LAB_URL}/api/realestate/announcements/{announcement_id}/bookmark"
|
||||
)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
|
||||
# --- lotto-backend ---
|
||||
|
||||
async def lotto_candidates(n: int = 20) -> Dict[str, Any]:
|
||||
from .config import LOTTO_BACKEND_URL
|
||||
resp = await _client.get(f"{LOTTO_BACKEND_URL}/api/lotto/curator/candidates", params={"n": n})
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
|
||||
async def lotto_context() -> Dict[str, Any]:
|
||||
from .config import LOTTO_BACKEND_URL
|
||||
resp = await _client.get(f"{LOTTO_BACKEND_URL}/api/lotto/curator/context")
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
|
||||
async def lotto_save_briefing(payload: dict) -> Dict[str, Any]:
|
||||
from .config import LOTTO_BACKEND_URL
|
||||
resp = await _client.post(f"{LOTTO_BACKEND_URL}/api/lotto/briefing", json=payload)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
|
||||
async def lotto_review_latest() -> Optional[Dict[str, Any]]:
|
||||
from .config import LOTTO_BACKEND_URL
|
||||
resp = await _client.get(f"{LOTTO_BACKEND_URL}/api/lotto/review/latest")
|
||||
if resp.status_code == 404:
|
||||
return None
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
|
||||
async def lotto_review_by_draw(draw_no: int) -> Optional[Dict[str, Any]]:
|
||||
from .config import LOTTO_BACKEND_URL
|
||||
resp = await _client.get(f"{LOTTO_BACKEND_URL}/api/lotto/review/{draw_no}")
|
||||
if resp.status_code == 404:
|
||||
return None
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
|
||||
async def lotto_reviews_history(limit: int = 10) -> List[Dict[str, Any]]:
|
||||
from .config import LOTTO_BACKEND_URL
|
||||
resp = await _client.get(
|
||||
f"{LOTTO_BACKEND_URL}/api/lotto/review/history",
|
||||
params={"limit": limit},
|
||||
)
|
||||
resp.raise_for_status()
|
||||
return resp.json().get("reviews", [])
|
||||
|
||||
|
||||
# --- music-lab pipeline (YouTube publisher orchestration) ---
|
||||
|
||||
async def list_active_pipelines() -> list[dict]:
|
||||
async with httpx.AsyncClient(timeout=15) as client:
|
||||
resp = await client.get(f"{MUSIC_LAB_URL}/api/music/pipeline?status=active")
|
||||
resp.raise_for_status()
|
||||
return resp.json().get("pipelines", [])
|
||||
|
||||
|
||||
async def get_pipeline(pid: int) -> dict:
|
||||
async with httpx.AsyncClient(timeout=15) as client:
|
||||
resp = await client.get(f"{MUSIC_LAB_URL}/api/music/pipeline/{pid}")
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
|
||||
async def post_pipeline_feedback(pid: int, step: str, intent: str,
|
||||
feedback_text: Optional[str] = None) -> dict:
|
||||
async with httpx.AsyncClient(timeout=15) as client:
|
||||
resp = await client.post(
|
||||
f"{MUSIC_LAB_URL}/api/music/pipeline/{pid}/feedback",
|
||||
json={"step": step, "intent": intent, "feedback_text": feedback_text},
|
||||
)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
|
||||
async def save_pipeline_telegram_msg(pid: int, step: str, msg_id: int) -> None:
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
await client.patch(
|
||||
f"{MUSIC_LAB_URL}/api/music/pipeline/{pid}/telegram-msg",
|
||||
json={"step": step, "message_id": msg_id},
|
||||
)
|
||||
|
||||
|
||||
async def lookup_pipeline_by_msg(msg_id: int) -> Optional[dict]:
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
resp = await client.get(f"{MUSIC_LAB_URL}/api/music/pipeline/lookup-by-msg/{msg_id}")
|
||||
if resp.status_code == 200:
|
||||
return resp.json()
|
||||
return None
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
"""Telegram 통합 메시지 패키지."""
|
||||
from .agent_registry import AGENT_META, get_agent_meta, register_agent
|
||||
from .messaging import send_agent_message, send_approval_request, send_raw
|
||||
from .router import parse_command, resolve_agent_command, HELP_TEXT
|
||||
from .webhook import handle_webhook, setup_webhook
|
||||
|
||||
__all__ = [
|
||||
"send_agent_message",
|
||||
"send_approval_request",
|
||||
"send_raw",
|
||||
"handle_webhook",
|
||||
"setup_webhook",
|
||||
"get_agent_meta",
|
||||
"register_agent",
|
||||
"AGENT_META",
|
||||
"parse_command",
|
||||
"resolve_agent_command",
|
||||
"HELP_TEXT",
|
||||
]
|
||||
@@ -1,39 +0,0 @@
|
||||
"""에이전트 메타 등록소."""
|
||||
|
||||
AGENT_META = {
|
||||
"stock": {
|
||||
"display_name": "주식 트레이더",
|
||||
"emoji": "📈",
|
||||
"color": "#4488cc",
|
||||
},
|
||||
"music": {
|
||||
"display_name": "음악 프로듀서",
|
||||
"emoji": "🎵",
|
||||
"color": "#44aa88",
|
||||
},
|
||||
"lotto": {
|
||||
"emoji": "🎱",
|
||||
"display_name": "로또 큐레이터",
|
||||
},
|
||||
"realestate": {
|
||||
"display_name": "청약 애널리스트",
|
||||
"emoji": "🏢",
|
||||
"color": "#f43f5e",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def get_agent_meta(agent_id: str) -> dict:
|
||||
return AGENT_META.get(
|
||||
agent_id,
|
||||
{"display_name": agent_id, "emoji": "🤖", "color": "#888"},
|
||||
)
|
||||
|
||||
|
||||
def register_agent(agent_id: str, display_name: str, emoji: str, color: str = "#888"):
|
||||
"""향후 에이전트 동적 등록용"""
|
||||
AGENT_META[agent_id] = {
|
||||
"display_name": display_name,
|
||||
"emoji": emoji,
|
||||
"color": color,
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
"""Telegram Bot API 저수준 래퍼."""
|
||||
import httpx
|
||||
|
||||
from ..config import TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_ID, TELEGRAM_WEBHOOK_URL
|
||||
|
||||
_BASE = "https://api.telegram.org/bot"
|
||||
|
||||
|
||||
def _enabled() -> bool:
|
||||
return bool(TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID)
|
||||
|
||||
|
||||
async def api_call(method: str, payload: dict) -> dict:
|
||||
if not _enabled():
|
||||
return {"ok": False, "description": "Telegram not configured"}
|
||||
async with httpx.AsyncClient(timeout=10.0) as client:
|
||||
resp = await client.post(f"{_BASE}{TELEGRAM_BOT_TOKEN}/{method}", json=payload)
|
||||
return resp.json()
|
||||
@@ -1,182 +0,0 @@
|
||||
"""텔레그램 자연어 대화 핸들러 — Claude + 프롬프트 캐싱.
|
||||
|
||||
구조:
|
||||
- system prompt(정적) + 최근 대화 이력 + 마지막 user turn
|
||||
- system과 history 끝 블록에 cache_control=ephemeral 적용 → 5분 TTL 프롬프트 캐시
|
||||
- 평가를 위해 토큰·캐시·latency를 DB에 기록
|
||||
"""
|
||||
import asyncio
|
||||
import time
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
|
||||
from ..config import (
|
||||
ANTHROPIC_API_KEY,
|
||||
CONVERSATION_MODEL,
|
||||
CONVERSATION_HISTORY_LIMIT,
|
||||
CONVERSATION_RATE_PER_MIN,
|
||||
TELEGRAM_CHAT_ID,
|
||||
TELEGRAM_WIFE_CHAT_ID,
|
||||
)
|
||||
from ..db import (
|
||||
save_conversation_message,
|
||||
get_conversation_history,
|
||||
count_recent_user_messages,
|
||||
)
|
||||
|
||||
API_URL = "https://api.anthropic.com/v1/messages"
|
||||
|
||||
SYSTEM_PROMPT = """당신은 'gahusb' 개인 웹 플랫폼의 AI 비서입니다. 텔레그램을 통해 CEO(주인)와 그의 가족과 대화합니다.
|
||||
|
||||
역할과 성격:
|
||||
- 따뜻하지만 간결합니다. 텔레그램에서 읽기 쉽게 2~5문장 위주로 답합니다.
|
||||
- 농담과 위트를 섞되 공손하게. 이모지는 상황에 맞게 1~2개만.
|
||||
- 모르는 것은 솔직히 모른다고 하고, 추측은 명시합니다.
|
||||
|
||||
플랫폼 컨텍스트(대답에 자연스럽게 참고):
|
||||
- 주식 에이전트: 뉴스 요약·시장 브리핑·포트폴리오 관리
|
||||
- 음악 에이전트: AI 음악 생성(Suno/MusicGen)
|
||||
- 블로그 에이전트: 키워드 리서치·포스트 생성·품질 리뷰
|
||||
- 청약 에이전트: 부동산 청약 공고 수집·매칭
|
||||
- 명령은 `/help`, `/agents`, `/status`, `/stock.brief` 같은 슬래시 형식이 있습니다. 사용자가 요청을 설명만 하면 해당 명령을 안내해 주세요.
|
||||
|
||||
응답 규칙:
|
||||
- 장문 설명 금지. 스크롤을 넘기지 않을 분량.
|
||||
- 에이전트 실행을 부탁받으면 지금 이 채널은 '대화'만 가능함을 알리고, 정확한 슬래시 명령을 한 줄로 제시하세요.
|
||||
- HTML·마크다운 태그 없이 평문으로 답합니다."""
|
||||
|
||||
|
||||
_rate_lock = asyncio.Lock()
|
||||
|
||||
|
||||
def is_whitelisted(chat_id: str) -> bool:
|
||||
allowed = {str(x) for x in (TELEGRAM_CHAT_ID, TELEGRAM_WIFE_CHAT_ID) if x}
|
||||
return str(chat_id) in allowed
|
||||
|
||||
|
||||
async def _check_rate_limit(chat_id: str) -> bool:
|
||||
async with _rate_lock:
|
||||
count = count_recent_user_messages(chat_id, seconds=60)
|
||||
return count < CONVERSATION_RATE_PER_MIN
|
||||
|
||||
|
||||
async def _call_claude(messages: list) -> dict:
|
||||
"""Anthropic Messages API 호출 (prompt caching beta)."""
|
||||
headers = {
|
||||
"x-api-key": ANTHROPIC_API_KEY,
|
||||
"anthropic-version": "2023-06-01",
|
||||
"anthropic-beta": "prompt-caching-2024-07-31",
|
||||
"content-type": "application/json",
|
||||
}
|
||||
# system: cache_control 적용하여 정적 프롬프트 캐싱
|
||||
system_blocks = [
|
||||
{
|
||||
"type": "text",
|
||||
"text": SYSTEM_PROMPT,
|
||||
"cache_control": {"type": "ephemeral"},
|
||||
}
|
||||
]
|
||||
payload = {
|
||||
"model": CONVERSATION_MODEL,
|
||||
"max_tokens": 1024,
|
||||
"system": system_blocks,
|
||||
"messages": messages,
|
||||
}
|
||||
async with httpx.AsyncClient(timeout=60) as client:
|
||||
r = await client.post(API_URL, headers=headers, json=payload)
|
||||
r.raise_for_status()
|
||||
return r.json()
|
||||
|
||||
|
||||
def _build_messages(history: list, user_text: str) -> list:
|
||||
"""history: [{role, content(str)}, ...]. 가장 오래된 턴을 제외한 나머지 히스토리 끝 블록에
|
||||
cache_control을 추가하여 누적 이력을 캐시한다."""
|
||||
msgs: list = []
|
||||
for h in history:
|
||||
msgs.append({"role": h["role"], "content": [{"type": "text", "text": h["content"]}]})
|
||||
# 히스토리 마지막 블록에 cache_control → 이전 대화를 캐시
|
||||
if msgs:
|
||||
last = msgs[-1]["content"][-1]
|
||||
last["cache_control"] = {"type": "ephemeral"}
|
||||
msgs.append({"role": "user", "content": [{"type": "text", "text": user_text}]})
|
||||
return msgs
|
||||
|
||||
|
||||
async def maybe_route_to_pipeline(message: dict) -> bool:
|
||||
"""파이프라인 텔레그램 메시지에 대한 reply 인 경우 youtube_publisher 로 라우팅.
|
||||
|
||||
Returns True if message was routed (caller should stop further processing).
|
||||
"""
|
||||
reply_to = message.get("reply_to_message") or {}
|
||||
msg_id = reply_to.get("message_id")
|
||||
if not msg_id:
|
||||
return False
|
||||
from .. import service_proxy
|
||||
try:
|
||||
link = await service_proxy.lookup_pipeline_by_msg(msg_id)
|
||||
except Exception:
|
||||
return False
|
||||
if not link:
|
||||
return False
|
||||
from ..agents import AGENT_REGISTRY
|
||||
agent = AGENT_REGISTRY.get("youtube_publisher")
|
||||
if not agent:
|
||||
return False
|
||||
pipeline_id = link.get("pipeline_id")
|
||||
step = link.get("step")
|
||||
if pipeline_id is None or not step:
|
||||
return False
|
||||
await agent.on_telegram_reply(pipeline_id, step, message.get("text", ""))
|
||||
return True
|
||||
|
||||
|
||||
async def respond_to_message(chat_id: str, user_text: str) -> Optional[str]:
|
||||
"""자연어 메시지에 응답. 실패 시 사용자에게 돌려줄 문자열 반환(또는 None = 무시)."""
|
||||
if not ANTHROPIC_API_KEY:
|
||||
return None # 기능 비활성
|
||||
|
||||
if not is_whitelisted(chat_id):
|
||||
return None # 모르는 사용자 무시
|
||||
|
||||
if not await _check_rate_limit(chat_id):
|
||||
return "⏳ 잠시만요, 너무 빠릅니다. 분당 몇 번만 대화해 주세요."
|
||||
|
||||
history = get_conversation_history(chat_id, limit=CONVERSATION_HISTORY_LIMIT)
|
||||
messages = _build_messages(history, user_text)
|
||||
|
||||
started = time.monotonic()
|
||||
try:
|
||||
resp = await _call_claude(messages)
|
||||
except httpx.HTTPStatusError as e:
|
||||
body = e.response.text[:200] if e.response is not None else ""
|
||||
return f"⚠️ Claude 호출 실패: {e.response.status_code} {body}"
|
||||
except Exception as e:
|
||||
return f"⚠️ 응답 생성 중 오류: {type(e).__name__}"
|
||||
latency_ms = int((time.monotonic() - started) * 1000)
|
||||
|
||||
try:
|
||||
reply = "".join(
|
||||
blk.get("text", "") for blk in resp.get("content", []) if blk.get("type") == "text"
|
||||
).strip()
|
||||
except Exception:
|
||||
reply = ""
|
||||
if not reply:
|
||||
reply = "(빈 응답)"
|
||||
|
||||
usage = resp.get("usage", {}) or {}
|
||||
t_in = int(usage.get("input_tokens", 0) or 0)
|
||||
t_out = int(usage.get("output_tokens", 0) or 0)
|
||||
c_read = int(usage.get("cache_read_input_tokens", 0) or 0)
|
||||
c_write = int(usage.get("cache_creation_input_tokens", 0) or 0)
|
||||
|
||||
# 기록: user 먼저, assistant 나중 (순서 보존)
|
||||
save_conversation_message(chat_id, "user", user_text)
|
||||
save_conversation_message(
|
||||
chat_id, "assistant", reply,
|
||||
model=CONVERSATION_MODEL,
|
||||
tokens_input=t_in, tokens_output=t_out,
|
||||
cache_read=c_read, cache_write=c_write,
|
||||
latency_ms=latency_ms,
|
||||
)
|
||||
return reply
|
||||
@@ -1,51 +0,0 @@
|
||||
"""에이전트 메시지 포맷팅."""
|
||||
from html import escape as _h
|
||||
from typing import Literal, Optional
|
||||
|
||||
from .agent_registry import get_agent_meta
|
||||
|
||||
MessageKind = Literal["report", "alert", "approval", "error", "info"]
|
||||
|
||||
KIND_ICONS = {
|
||||
"report": "📊",
|
||||
"alert": "🔔",
|
||||
"approval": "✋",
|
||||
"error": "⚠️",
|
||||
"info": "ℹ️",
|
||||
}
|
||||
|
||||
|
||||
def format_agent_message(
|
||||
agent_id: str,
|
||||
kind: MessageKind,
|
||||
title: str,
|
||||
body: str,
|
||||
metadata: Optional[dict] = None,
|
||||
body_is_html: bool = False,
|
||||
) -> str:
|
||||
meta = get_agent_meta(agent_id)
|
||||
icon = KIND_ICONS.get(kind, "")
|
||||
header = f"{icon} <b>[{_h(meta['emoji'])} {_h(meta['display_name'])}]</b> {_h(title)}"
|
||||
|
||||
# Telegram 단일 메시지 4096자 제한 대응 (헤더/푸터 여유 512자 확보)
|
||||
# body_is_html=True 면 호출자가 이미 HTML-safe하게 구성한 것으로 간주 (예: <a> 링크 포함)
|
||||
safe_body = body if body_is_html else _h(body)
|
||||
if len(safe_body) > 3500:
|
||||
safe_body = safe_body[:3500] + "\n…(생략)"
|
||||
|
||||
lines = [header, "━" * 20, safe_body]
|
||||
|
||||
if metadata:
|
||||
footer_parts = []
|
||||
if "tokens" in metadata:
|
||||
footer_parts.append(f"🧮 {metadata['tokens']:,} tokens")
|
||||
if "duration_ms" in metadata:
|
||||
seconds = metadata["duration_ms"] / 1000
|
||||
footer_parts.append(f"⏱ {seconds:.1f}s")
|
||||
if "model" in metadata:
|
||||
footer_parts.append(f"🤖 {metadata['model']}")
|
||||
if footer_parts:
|
||||
lines.append("")
|
||||
lines.append(f"<i>{_h(' · '.join(footer_parts))}</i>")
|
||||
|
||||
return "\n".join(lines)
|
||||
@@ -1,83 +0,0 @@
|
||||
"""고수준 메시지 전송 API."""
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
from ..config import TELEGRAM_CHAT_ID
|
||||
from ..db import save_telegram_callback
|
||||
from .client import _enabled, api_call
|
||||
from .formatter import MessageKind, format_agent_message
|
||||
|
||||
|
||||
async def send_raw(
|
||||
text: str,
|
||||
reply_markup: Optional[dict] = None,
|
||||
chat_id: Optional[str] = None,
|
||||
parse_mode: str = "HTML",
|
||||
) -> dict:
|
||||
"""가장 저수준. 원문 텍스트 그대로 전송. chat_id 생략 시 기본 TELEGRAM_CHAT_ID로.
|
||||
|
||||
parse_mode: 기본 'HTML'. MarkdownV2 페이로드(예: 스크리너) 전송 시 명시 지정.
|
||||
"""
|
||||
if not _enabled():
|
||||
return {"ok": False, "message_id": None}
|
||||
payload = {
|
||||
"chat_id": chat_id or TELEGRAM_CHAT_ID,
|
||||
"text": text,
|
||||
"parse_mode": parse_mode,
|
||||
}
|
||||
if reply_markup:
|
||||
payload["reply_markup"] = reply_markup
|
||||
result = await api_call("sendMessage", payload)
|
||||
ok = result.get("ok", False)
|
||||
return {
|
||||
"ok": ok,
|
||||
"message_id": result.get("result", {}).get("message_id") if ok else None,
|
||||
"description": result.get("description") if not ok else None,
|
||||
"error_code": result.get("error_code") if not ok else None,
|
||||
}
|
||||
|
||||
|
||||
async def send_agent_message(
|
||||
agent_id: str,
|
||||
kind: MessageKind,
|
||||
title: str,
|
||||
body: str,
|
||||
task_id: Optional[str] = None,
|
||||
actions: Optional[list] = None,
|
||||
metadata: Optional[dict] = None,
|
||||
body_is_html: bool = False,
|
||||
) -> dict:
|
||||
"""통합 에이전트 메시지 API. 모든 에이전트가 이걸 씀.
|
||||
|
||||
body_is_html=True: 호출자가 이미 HTML-safe 포맷(링크 <a> 등) 구성한 경우.
|
||||
"""
|
||||
text = format_agent_message(agent_id, kind, title, body, metadata, body_is_html=body_is_html)
|
||||
reply_markup = None
|
||||
if actions:
|
||||
buttons = []
|
||||
for action in actions:
|
||||
cb_id = f"{action['action']}_{uuid.uuid4().hex[:8]}"
|
||||
save_telegram_callback(cb_id, task_id or "", agent_id)
|
||||
buttons.append({"text": action["label"], "callback_data": cb_id})
|
||||
reply_markup = {"inline_keyboard": [buttons]}
|
||||
return await send_raw(text, reply_markup)
|
||||
|
||||
|
||||
async def send_approval_request(
|
||||
agent_id: str,
|
||||
task_id: str,
|
||||
title: str,
|
||||
detail: str,
|
||||
) -> dict:
|
||||
"""승인/거절 단축 헬퍼."""
|
||||
return await send_agent_message(
|
||||
agent_id=agent_id,
|
||||
kind="approval",
|
||||
title=title,
|
||||
body=detail,
|
||||
task_id=task_id,
|
||||
actions=[
|
||||
{"label": "✅ 승인", "action": "approve"},
|
||||
{"label": "❌ 거절", "action": "reject"},
|
||||
],
|
||||
)
|
||||
@@ -1,93 +0,0 @@
|
||||
"""청약 매칭 알림 — 텔레그램 메시지 포맷터 + 인라인 키보드 빌더."""
|
||||
import os
|
||||
from html import escape as _h
|
||||
from typing import Optional
|
||||
|
||||
DASHBOARD_URL = os.getenv("REALESTATE_DASHBOARD_URL", "https://example.com/realestate")
|
||||
|
||||
|
||||
def _format_one_compact(m: dict) -> str:
|
||||
score = m.get("match_score", 0)
|
||||
name = _h(m.get("house_nm") or "(제목 없음)")
|
||||
district = m.get("district") or ""
|
||||
region = m.get("region_name") or ""
|
||||
where = f"{region.split()[0] if region else ''} {district}".strip() or "위치 미상"
|
||||
rstart = m.get("receipt_start") or ""
|
||||
rend = m.get("receipt_end") or ""
|
||||
return (
|
||||
f"⭐ {score}점 — <b>{name}</b>\n"
|
||||
f"📍 {_h(where)} 📅 {_h(rstart)} ~ {_h(rend)}"
|
||||
)
|
||||
|
||||
|
||||
def _format_one_full(m: dict) -> str:
|
||||
score = m.get("match_score", 0)
|
||||
name = _h(m.get("house_nm") or "(제목 없음)")
|
||||
district = m.get("district") or ""
|
||||
region = m.get("region_name") or ""
|
||||
flags = []
|
||||
if m.get("is_speculative_area") == "Y":
|
||||
flags.append("투기과열")
|
||||
if m.get("is_price_cap") == "Y":
|
||||
flags.append("분양가상한제")
|
||||
flag_str = f" ({', '.join(flags)})" if flags else ""
|
||||
|
||||
rstart = m.get("receipt_start") or ""
|
||||
rend = m.get("receipt_end") or ""
|
||||
elig = m.get("eligible_types") or []
|
||||
reasons = m.get("match_reasons") or []
|
||||
|
||||
where = f"{region.split()[0] if region else ''} {district}".strip() or "위치 미상"
|
||||
|
||||
lines = [
|
||||
f"⭐ {score}점 — <b>{name}</b>",
|
||||
f"📍 {_h(where)}{_h(flag_str)}",
|
||||
f"📅 청약 {_h(rstart)} ~ {_h(rend)}",
|
||||
]
|
||||
if elig:
|
||||
lines.append(f"✓ 자격: {_h(', '.join(elig))}")
|
||||
if reasons:
|
||||
lines.append(f"💡 {_h(' / '.join(reasons[:4]))}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def format_realestate_matches(matches: list[dict]) -> str:
|
||||
"""매칭 목록을 텔레그램 HTML 메시지로 변환.
|
||||
1~2건은 풀 카드, 3건 이상은 묶음 카드(상위 5건).
|
||||
"""
|
||||
if not matches:
|
||||
return "🏢 새 청약 매칭이 없습니다."
|
||||
|
||||
if len(matches) <= 2:
|
||||
body = "\n\n".join(_format_one_full(m) for m in matches)
|
||||
return f"🏢 <b>새 청약 매칭 {len(matches)}건</b>\n━━━━━━━━━━\n\n{body}"
|
||||
|
||||
top = matches[:5]
|
||||
body = "\n\n".join(_format_one_compact(m) for m in top)
|
||||
suffix = f"\n\n…외 {len(matches) - 5}건" if len(matches) > 5 else ""
|
||||
return f"🏢 <b>새 청약 매칭 {len(matches)}건</b>\n━━━━━━━━━━\n\n{body}{suffix}"
|
||||
|
||||
|
||||
def build_match_keyboard(matches: list[dict]) -> Optional[dict]:
|
||||
"""1~2건: 매치별 [북마크][공고 보기] 행. 3건 이상: [전체 보기] 단일 행."""
|
||||
if not matches:
|
||||
return None
|
||||
|
||||
if len(matches) <= 2:
|
||||
rows = []
|
||||
for m in matches:
|
||||
buttons = [{
|
||||
"text": "🔖 북마크",
|
||||
"callback_data": f"realestate_bookmark_{m['id']}",
|
||||
}]
|
||||
url = m.get("pblanc_url")
|
||||
if url:
|
||||
buttons.append({"text": "📄 공고 보기", "url": url})
|
||||
rows.append(buttons)
|
||||
return {"inline_keyboard": rows}
|
||||
|
||||
return {
|
||||
"inline_keyboard": [[
|
||||
{"text": "📋 전체 보기", "url": DASHBOARD_URL},
|
||||
]],
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
"""텔레그램 메시지 명령 → 에이전트 라우팅.
|
||||
새 명령을 추가하려면 AGENT_COMMAND_MAP에 등록만 하면 됨."""
|
||||
from typing import Optional
|
||||
|
||||
|
||||
def parse_command(text: str) -> Optional[tuple]:
|
||||
"""슬래시 명령 파싱.
|
||||
|
||||
반환: (agent_id_or_None, command, args_list) 또는 None
|
||||
|
||||
예시:
|
||||
/stock news -> ("stock", "news", [])
|
||||
/status -> (None, "status", [])
|
||||
/music compose 잔잔한 피아노 -> ("music", "compose", ["잔잔한 피아노"])
|
||||
"""
|
||||
if not text:
|
||||
return None
|
||||
text = text.strip()
|
||||
if not text.startswith("/"):
|
||||
return None
|
||||
parts = text[1:].split(maxsplit=2)
|
||||
if not parts:
|
||||
return None
|
||||
|
||||
first = parts[0].lower()
|
||||
|
||||
# 전역 명령
|
||||
if first in ("status", "agents", "help"):
|
||||
return (None, first, parts[1:] if len(parts) > 1 else [])
|
||||
|
||||
# 에이전트 명령: /<agent> <command> [args...]
|
||||
if len(parts) < 2:
|
||||
return None
|
||||
|
||||
agent_id = first
|
||||
command = parts[1].lower()
|
||||
args = [parts[2]] if len(parts) > 2 else []
|
||||
return (agent_id, command, args)
|
||||
|
||||
|
||||
# 에이전트별 텔레그램 → 내부 command 매핑
|
||||
# 텔레그램에서 친숙한 이름 -> (실제 on_command의 command, 기본 params)
|
||||
AGENT_COMMAND_MAP = {
|
||||
"stock": {
|
||||
"news": ("fetch_news", {}),
|
||||
"alerts": ("list_alerts", {}),
|
||||
"test": ("test_telegram", {}),
|
||||
},
|
||||
"music": {
|
||||
"credits": ("credits", {}),
|
||||
# compose는 인자 필요 — 아래 특수 케이스에서 처리
|
||||
},
|
||||
"realestate": {
|
||||
"matches": ("fetch_matches", {}),
|
||||
"dashboard": ("dashboard", {}),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def resolve_agent_command(agent_id: str, command: str, args: list) -> Optional[tuple]:
|
||||
"""(internal_command, params) 반환. 매핑 없으면 None."""
|
||||
mapping = AGENT_COMMAND_MAP.get(agent_id, {}).get(command)
|
||||
if mapping is None:
|
||||
# 특수 케이스: music compose <prompt>
|
||||
if agent_id == "music" and command == "compose" and args:
|
||||
return ("compose", {"prompt": " ".join(args)})
|
||||
return None
|
||||
internal_cmd, base_params = mapping
|
||||
params = dict(base_params)
|
||||
if args:
|
||||
# args가 있으면 첫 번째(합쳐진 나머지)를 message로 자동 주입
|
||||
params["message"] = " ".join(args)
|
||||
return (internal_cmd, params)
|
||||
|
||||
|
||||
HELP_TEXT = """<b>🤖 Agent Office 텔레그램 명령</b>
|
||||
|
||||
<b>전역</b>
|
||||
/status — 모든 에이전트 상태
|
||||
/agents — 에이전트 목록
|
||||
/help — 이 도움말
|
||||
|
||||
<b>📈 주식 트레이더</b>
|
||||
/stock news — 뉴스 AI 요약 실행
|
||||
/stock alerts — 알람 목록
|
||||
/stock test — 텔레그램 테스트
|
||||
|
||||
<b>🎵 음악 프로듀서</b>
|
||||
/music credits — Suno 크레딧 조회
|
||||
/music compose <프롬프트> — 작곡 시작
|
||||
|
||||
<b>🏢 청약 애널리스트</b>
|
||||
/realestate matches — 신규 매칭 조회 후 알림 전송
|
||||
/realestate dashboard — 청약 현황 요약
|
||||
"""
|
||||
@@ -1,239 +0,0 @@
|
||||
"""텔레그램 Webhook 이벤트 처리."""
|
||||
from typing import Optional
|
||||
|
||||
from ..db import get_telegram_callback, mark_telegram_responded
|
||||
from .client import _enabled, api_call
|
||||
|
||||
|
||||
async def handle_webhook(data: dict, agent_dispatcher=None) -> Optional[dict]:
|
||||
"""텔레그램에서 들어오는 이벤트 처리.
|
||||
|
||||
- callback_query(인라인 버튼)는 항상 처리 → 승인/거절 dict 반환
|
||||
- message(텍스트 슬래시 명령)는 `agent_dispatcher`가 주입된 경우에만 처리
|
||||
|
||||
agent_dispatcher: async (agent_id, command, params) -> dict
|
||||
- agent_id == "__global__", command == "status" 특수 케이스는
|
||||
{agent_id: {state, detail}} dict를 반환해야 함.
|
||||
"""
|
||||
callback_query = data.get("callback_query")
|
||||
if callback_query:
|
||||
return await _handle_callback(callback_query)
|
||||
|
||||
message = data.get("message")
|
||||
if message:
|
||||
chat = message.get("chat", {})
|
||||
print(f"[TG-WEBHOOK] chat.id={chat.get('id')} type={chat.get('type')} text={message.get('text')!r}", flush=True)
|
||||
if message and message.get("text") and agent_dispatcher is not None:
|
||||
return await _handle_message(message, agent_dispatcher)
|
||||
|
||||
return None
|
||||
|
||||
|
||||
async def _handle_callback(callback_query: dict) -> Optional[dict]:
|
||||
"""승인/거절 및 realestate 북마크 콜백 처리."""
|
||||
callback_id = callback_query.get("data", "")
|
||||
|
||||
# realestate 북마크 토글 콜백 — DB 조회 없이 직접 처리
|
||||
if callback_id.startswith("realestate_bookmark_"):
|
||||
return await _handle_realestate_bookmark(callback_query, callback_id)
|
||||
|
||||
if callback_id.startswith("render_"):
|
||||
return await _handle_insta_render(callback_query, callback_id)
|
||||
|
||||
cb = get_telegram_callback(callback_id)
|
||||
if not cb:
|
||||
return None
|
||||
|
||||
action = callback_id.split("_")[0]
|
||||
mark_telegram_responded(callback_id, action)
|
||||
|
||||
feedback_text = {
|
||||
"approve": "승인됨 ✅",
|
||||
"reject": "거절됨 ❌",
|
||||
}.get(action, f"처리됨: {action}")
|
||||
|
||||
await api_call(
|
||||
"answerCallbackQuery",
|
||||
{
|
||||
"callback_query_id": callback_query["id"],
|
||||
"text": feedback_text,
|
||||
},
|
||||
)
|
||||
|
||||
return {
|
||||
"task_id": cb["task_id"],
|
||||
"agent_id": cb["agent_id"],
|
||||
"action": action,
|
||||
"approved": action == "approve",
|
||||
}
|
||||
|
||||
|
||||
async def _handle_realestate_bookmark(callback_query: dict, callback_id: str) -> dict:
|
||||
"""realestate_bookmark_{announcement_id} 콜백 처리."""
|
||||
from .. import service_proxy
|
||||
from .messaging import send_raw
|
||||
|
||||
# answerCallbackQuery 먼저 — 텔레그램 로딩 스피너 해제
|
||||
await api_call(
|
||||
"answerCallbackQuery",
|
||||
{"callback_query_id": callback_query["id"], "text": "처리 중..."},
|
||||
)
|
||||
|
||||
try:
|
||||
ann_id = int(callback_id.removeprefix("realestate_bookmark_"))
|
||||
except ValueError:
|
||||
await send_raw("⚠️ 잘못된 북마크 콜백 데이터")
|
||||
return {"ok": False, "error": "invalid_callback_data"}
|
||||
|
||||
try:
|
||||
result = await service_proxy.realestate_bookmark_toggle(ann_id)
|
||||
is_on = result.get("is_bookmarked")
|
||||
if is_on == 1:
|
||||
await send_raw(f"🔖 북마크 추가 완료 (#{ann_id})")
|
||||
elif is_on == 0:
|
||||
await send_raw(f"🔖 북마크 해제 완료 (#{ann_id})")
|
||||
else:
|
||||
await send_raw(f"🔖 북마크 토글 완료 (#{ann_id})")
|
||||
return {"ok": True, "announcement_id": ann_id}
|
||||
except Exception as e:
|
||||
await send_raw(f"⚠️ 북마크 처리 실패: {e}")
|
||||
return {"ok": False, "error": str(e)}
|
||||
|
||||
|
||||
async def _handle_insta_render(callback_query: dict, callback_id: str) -> dict:
|
||||
"""render_{keyword_id} 콜백 → InstaAgent.on_callback('render', ...).
|
||||
|
||||
텔레그램 인라인 버튼이 보낸 callback_data가 `render_<keyword_id>` 형식.
|
||||
InstaAgent._push_keyword_candidates가 callback_data를 그대로 박아 보내며,
|
||||
별도 DB lookup 없이 keyword_id를 파싱해 dispatch한다."""
|
||||
from .messaging import send_raw
|
||||
from ..agents import AGENT_REGISTRY
|
||||
|
||||
await api_call(
|
||||
"answerCallbackQuery",
|
||||
{"callback_query_id": callback_query["id"], "text": "카드 생성 시작"},
|
||||
)
|
||||
|
||||
try:
|
||||
keyword_id = int(callback_id.removeprefix("render_"))
|
||||
except ValueError:
|
||||
await send_raw("⚠️ 잘못된 render 콜백 데이터")
|
||||
return {"ok": False, "error": "invalid_callback_data"}
|
||||
|
||||
agent = AGENT_REGISTRY.get("insta")
|
||||
if not agent:
|
||||
await send_raw("⚠️ insta agent 미등록")
|
||||
return {"ok": False, "error": "agent_missing"}
|
||||
|
||||
try:
|
||||
return await agent.on_callback("render", {"keyword_id": keyword_id})
|
||||
except Exception as e:
|
||||
await send_raw(f"⚠️ 카드 생성 실패: {e}")
|
||||
return {"ok": False, "error": str(e)}
|
||||
|
||||
|
||||
async def _handle_message(message: dict, agent_dispatcher) -> Optional[dict]:
|
||||
"""슬래시 명령 메시지 처리."""
|
||||
from .router import parse_command, resolve_agent_command, HELP_TEXT
|
||||
from .messaging import send_raw, send_agent_message
|
||||
from .agent_registry import AGENT_META
|
||||
from .conversational import maybe_route_to_pipeline
|
||||
|
||||
# 파이프라인 메시지에 대한 reply라면 youtube_publisher 로 라우팅
|
||||
if await maybe_route_to_pipeline(message):
|
||||
return {"handled": "pipeline_reply"}
|
||||
|
||||
text = message.get("text", "")
|
||||
parsed = parse_command(text)
|
||||
if not parsed:
|
||||
# 슬래시 명령이 아니면 자연어 대화로 라우팅
|
||||
chat_id = str(message.get("chat", {}).get("id", ""))
|
||||
if not chat_id:
|
||||
return None
|
||||
from .conversational import respond_to_message
|
||||
reply = await respond_to_message(chat_id, text)
|
||||
if reply:
|
||||
import html as _html
|
||||
await send_raw(_html.escape(reply), chat_id=chat_id)
|
||||
return {"handled": "chat"}
|
||||
return None
|
||||
|
||||
agent_id, command, args = parsed
|
||||
|
||||
# 전역 명령
|
||||
if agent_id is None:
|
||||
if command == "help":
|
||||
await send_raw(HELP_TEXT)
|
||||
return {"handled": "help"}
|
||||
|
||||
if command == "agents":
|
||||
lines = ["<b>📋 등록된 에이전트</b>", ""]
|
||||
for aid, meta in AGENT_META.items():
|
||||
lines.append(
|
||||
f"{meta['emoji']} <b>{meta['display_name']}</b> <code>/{aid}</code>"
|
||||
)
|
||||
await send_raw("\n".join(lines))
|
||||
return {"handled": "agents"}
|
||||
|
||||
if command == "status":
|
||||
try:
|
||||
result = await agent_dispatcher("__global__", "status", {})
|
||||
body_lines = []
|
||||
if isinstance(result, dict):
|
||||
for aid, info in result.items():
|
||||
meta = AGENT_META.get(
|
||||
aid, {"emoji": "🤖", "display_name": aid}
|
||||
)
|
||||
state = info.get("state", "unknown") if isinstance(info, dict) else "unknown"
|
||||
body_lines.append(
|
||||
f"{meta['emoji']} <b>{meta['display_name']}</b>: <code>{state}</code>"
|
||||
)
|
||||
detail = info.get("detail") if isinstance(info, dict) else None
|
||||
if detail:
|
||||
body_lines.append(f" └ {detail}")
|
||||
await send_raw("<b>📊 전체 상태</b>\n\n" + "\n".join(body_lines))
|
||||
except Exception as e:
|
||||
await send_raw(f"⚠️ 상태 조회 실패: {e}")
|
||||
return {"handled": "status"}
|
||||
|
||||
return None
|
||||
|
||||
# 에이전트 명령
|
||||
if agent_id not in AGENT_META:
|
||||
await send_raw(
|
||||
f"⚠️ 알 수 없는 에이전트: <code>{agent_id}</code>\n/help 로 사용 가능한 명령 확인"
|
||||
)
|
||||
return {"handled": "unknown_agent"}
|
||||
|
||||
resolved = resolve_agent_command(agent_id, command, args)
|
||||
if resolved is None:
|
||||
await send_raw(
|
||||
f"⚠️ <code>{agent_id}</code>에서 <code>{command}</code> 명령은 지원하지 않습니다."
|
||||
)
|
||||
return {"handled": "unknown_command"}
|
||||
|
||||
internal_cmd, params = resolved
|
||||
|
||||
try:
|
||||
result = await agent_dispatcher(agent_id, internal_cmd, params)
|
||||
ok = result.get("ok", False) if isinstance(result, dict) else False
|
||||
msg = result.get("message", "") if isinstance(result, dict) else str(result)
|
||||
|
||||
await send_agent_message(
|
||||
agent_id=agent_id,
|
||||
kind="info" if ok else "error",
|
||||
title=f"{internal_cmd} 실행 결과",
|
||||
body=msg or str(result),
|
||||
)
|
||||
except Exception as e:
|
||||
await send_raw(f"⚠️ 명령 실행 실패: {e}")
|
||||
|
||||
return {"handled": "command", "agent_id": agent_id, "command": internal_cmd}
|
||||
|
||||
|
||||
async def setup_webhook() -> dict:
|
||||
from ..config import TELEGRAM_WEBHOOK_URL
|
||||
|
||||
if not _enabled() or not TELEGRAM_WEBHOOK_URL:
|
||||
return {"ok": False, "description": "Webhook URL not configured"}
|
||||
return await api_call("setWebhook", {"url": TELEGRAM_WEBHOOK_URL})
|
||||
@@ -1,27 +1,82 @@
|
||||
"""Deprecated: app.telegram 패키지 사용 권장. 하위 호환용 re-export."""
|
||||
from .telegram import handle_webhook, send_approval_request, send_raw, setup_webhook
|
||||
from .telegram.messaging import send_agent_message
|
||||
import json
|
||||
import uuid
|
||||
import httpx
|
||||
from typing import Optional
|
||||
|
||||
from .config import TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_ID, TELEGRAM_WEBHOOK_URL
|
||||
from .db import save_telegram_callback, get_telegram_callback, mark_telegram_responded
|
||||
|
||||
_BASE = "https://api.telegram.org/bot"
|
||||
|
||||
def _enabled() -> bool:
|
||||
return bool(TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID)
|
||||
|
||||
async def _api(method: str, payload: dict) -> dict:
|
||||
if not _enabled():
|
||||
return {"ok": False, "description": "Telegram not configured"}
|
||||
async with httpx.AsyncClient(timeout=10.0) as client:
|
||||
resp = await client.post(f"{_BASE}{TELEGRAM_BOT_TOKEN}/{method}", json=payload)
|
||||
return resp.json()
|
||||
|
||||
# 기존 호출자가 쓰던 이름들
|
||||
async def send_message(text: str, reply_markup: dict = None) -> dict:
|
||||
return await send_raw(text, reply_markup)
|
||||
|
||||
payload = {
|
||||
"chat_id": TELEGRAM_CHAT_ID,
|
||||
"text": text,
|
||||
"parse_mode": "HTML",
|
||||
}
|
||||
if reply_markup:
|
||||
payload["reply_markup"] = reply_markup
|
||||
return await _api("sendMessage", payload)
|
||||
|
||||
async def send_stock_summary(summary: str) -> dict:
|
||||
return await send_raw(summary)
|
||||
return await send_message(summary)
|
||||
|
||||
async def send_approval_request(agent_id: str, task_id: str, title: str, detail: str) -> dict:
|
||||
approve_id = f"approve_{uuid.uuid4().hex[:8]}"
|
||||
reject_id = f"reject_{uuid.uuid4().hex[:8]}"
|
||||
|
||||
save_telegram_callback(approve_id, task_id, agent_id)
|
||||
save_telegram_callback(reject_id, task_id, agent_id)
|
||||
|
||||
text = f"{title}\n{'━' * 20}\n{detail}"
|
||||
reply_markup = {
|
||||
"inline_keyboard": [[
|
||||
{"text": "✅ 승인", "callback_data": approve_id},
|
||||
{"text": "❌ 거절", "callback_data": reject_id},
|
||||
]]
|
||||
}
|
||||
return await send_message(text, reply_markup)
|
||||
|
||||
async def send_task_result(agent_id: str, title: str, result: str) -> dict:
|
||||
return await send_agent_message(agent_id, "report", title, result)
|
||||
text = f"{title}\n{'━' * 20}\n{result}"
|
||||
return await send_message(text)
|
||||
|
||||
async def handle_webhook(data: dict) -> Optional[dict]:
|
||||
callback_query = data.get("callback_query")
|
||||
if not callback_query:
|
||||
return None
|
||||
|
||||
__all__ = [
|
||||
"send_message",
|
||||
"send_stock_summary",
|
||||
"send_task_result",
|
||||
"send_approval_request",
|
||||
"send_agent_message",
|
||||
"handle_webhook",
|
||||
"setup_webhook",
|
||||
]
|
||||
callback_id = callback_query.get("data", "")
|
||||
cb = get_telegram_callback(callback_id)
|
||||
if not cb:
|
||||
return None
|
||||
|
||||
action = "approve" if callback_id.startswith("approve_") else "reject"
|
||||
mark_telegram_responded(callback_id, action)
|
||||
|
||||
await _api("answerCallbackQuery", {
|
||||
"callback_query_id": callback_query["id"],
|
||||
"text": "승인됨 ✅" if action == "approve" else "거절됨 ❌",
|
||||
})
|
||||
|
||||
return {
|
||||
"task_id": cb["task_id"],
|
||||
"agent_id": cb["agent_id"],
|
||||
"action": action,
|
||||
"approved": action == "approve",
|
||||
}
|
||||
|
||||
async def setup_webhook() -> dict:
|
||||
if not _enabled() or not TELEGRAM_WEBHOOK_URL:
|
||||
return {"ok": False, "description": "Webhook URL not configured"}
|
||||
return await _api("setWebhook", {"url": TELEGRAM_WEBHOOK_URL})
|
||||
|
||||
@@ -43,13 +43,4 @@ class WebSocketManager:
|
||||
async def send_agent_move(self, agent_id: str, target: str) -> None:
|
||||
await self.broadcast({"type": "agent_move", "agent": agent_id, "target": target})
|
||||
|
||||
async def send_notification(self, agent_id: str, event: str, task_id: str = None, message: str = "") -> None:
|
||||
await self.broadcast({
|
||||
"type": "notification",
|
||||
"agent": agent_id,
|
||||
"event": event,
|
||||
"task_id": task_id,
|
||||
"message": message,
|
||||
})
|
||||
|
||||
ws_manager = WebSocketManager()
|
||||
|
||||
@@ -1,142 +0,0 @@
|
||||
import os
|
||||
import re
|
||||
import asyncio
|
||||
from typing import List, Dict, Any
|
||||
|
||||
import httpx
|
||||
|
||||
YOUTUBE_DATA_API_KEY = os.getenv("YOUTUBE_DATA_API_KEY", "")
|
||||
MUSIC_LAB_URL = os.getenv("MUSIC_LAB_URL", "http://music-lab:8000")
|
||||
TARGET_COUNTRIES = ["BR", "ID", "MX", "US", "KR"]
|
||||
TREND_KEYWORDS = ["lofi music", "phonk", "ambient music", "chill beats", "study music"]
|
||||
YOUTUBE_MUSIC_CAT = "10"
|
||||
|
||||
GENRE_TAGS = {
|
||||
"lo-fi": ["lofi", "lo-fi", "lo fi", "chill", "study"],
|
||||
"phonk": ["phonk", "drift", "memphis"],
|
||||
"ambient": ["ambient", "relaxing", "meditation"],
|
||||
"pop": ["pop", "kpop", "k-pop"],
|
||||
"funk": ["funk", "baile funk"],
|
||||
"latin": ["latin", "reggaeton", "sertanejo"],
|
||||
}
|
||||
|
||||
|
||||
def _tags_to_genre(tags: list) -> str:
|
||||
joined = " ".join(t.lower() for t in tags)
|
||||
for genre, kws in GENRE_TAGS.items():
|
||||
if any(kw in joined for kw in kws):
|
||||
return genre
|
||||
return "general"
|
||||
|
||||
|
||||
async def fetch_youtube_trending(country: str, max_results: int = 50) -> List[Dict[str, Any]]:
|
||||
"""YouTube Data API v3 — 국가별 트렌딩 음악 영상 (categoryId=10)."""
|
||||
if not YOUTUBE_DATA_API_KEY:
|
||||
return []
|
||||
async with httpx.AsyncClient(timeout=10.0) as client:
|
||||
try:
|
||||
resp = await client.get(
|
||||
"https://www.googleapis.com/youtube/v3/videos",
|
||||
params={
|
||||
"part": "snippet,statistics",
|
||||
"chart": "mostPopular",
|
||||
"regionCode": country,
|
||||
"videoCategoryId": YOUTUBE_MUSIC_CAT,
|
||||
"maxResults": max_results,
|
||||
"key": YOUTUBE_DATA_API_KEY,
|
||||
},
|
||||
)
|
||||
if resp.status_code != 200:
|
||||
return []
|
||||
items = resp.json().get("items", [])
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
results = []
|
||||
for i, item in enumerate(items):
|
||||
snippet = item.get("snippet", {})
|
||||
stats = item.get("statistics", {})
|
||||
genre = _tags_to_genre(snippet.get("tags") or [])
|
||||
results.append({
|
||||
"source": "youtube",
|
||||
"country": country,
|
||||
"genre": genre,
|
||||
"keyword": snippet.get("title", "")[:100],
|
||||
"score": round(1.0 - i / max_results, 3),
|
||||
"rank": i + 1,
|
||||
"metadata": {
|
||||
"video_id": item["id"],
|
||||
"view_count": int(stats.get("viewCount", 0)),
|
||||
"channel": snippet.get("channelTitle", ""),
|
||||
},
|
||||
})
|
||||
return results
|
||||
|
||||
|
||||
async def fetch_google_trends(keywords: List[str], countries: List[str]) -> List[Dict[str, Any]]:
|
||||
"""pytrends — 키워드별 Google 관심도 (sync → threadpool)."""
|
||||
try:
|
||||
from pytrends.request import TrendReq
|
||||
except ImportError:
|
||||
return []
|
||||
|
||||
def _sync_fetch(kw: str) -> List[Dict[str, Any]]:
|
||||
try:
|
||||
pt = TrendReq(hl="en-US", tz=0, timeout=(5, 15))
|
||||
pt.build_payload([kw], timeframe="now 7-d")
|
||||
df = pt.interest_over_time()
|
||||
if df.empty or kw not in df.columns:
|
||||
return []
|
||||
score = round(float(df[kw].mean()) / 100.0, 3)
|
||||
return [
|
||||
{"source": "google_trends", "country": c, "genre": "",
|
||||
"keyword": kw, "score": score, "rank": None, "metadata": {}}
|
||||
for c in countries
|
||||
]
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
loop = asyncio.get_running_loop()
|
||||
results = []
|
||||
for kw in keywords[:5]:
|
||||
rows = await loop.run_in_executor(None, _sync_fetch, kw)
|
||||
results.extend(rows)
|
||||
await asyncio.sleep(1.0)
|
||||
return results
|
||||
|
||||
|
||||
async def fetch_billboard_top20() -> List[Dict[str, Any]]:
|
||||
"""Billboard Hot 100 스크래핑 — 상위 20위."""
|
||||
async with httpx.AsyncClient(
|
||||
timeout=10.0,
|
||||
headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"},
|
||||
follow_redirects=True,
|
||||
) as client:
|
||||
try:
|
||||
resp = await client.get("https://www.billboard.com/charts/hot-100/")
|
||||
if resp.status_code != 200:
|
||||
return []
|
||||
titles = re.findall(
|
||||
r'class="c-title[^"]*"[^>]*>\s*([^<\n]{3,80})\s*<', resp.text
|
||||
)[:20]
|
||||
return [
|
||||
{"source": "billboard", "country": "US", "genre": "pop",
|
||||
"keyword": t.strip(), "score": round(1.0 - i / 20, 3),
|
||||
"rank": i + 1, "metadata": {}}
|
||||
for i, t in enumerate(titles) if t.strip()
|
||||
]
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
|
||||
async def push_to_music_lab(trends: List[Dict[str, Any]], report_date: str) -> bool:
|
||||
"""수집한 트렌드를 music-lab /api/music/market/ingest로 push."""
|
||||
async with httpx.AsyncClient(timeout=15.0) as client:
|
||||
try:
|
||||
resp = await client.post(
|
||||
f"{MUSIC_LAB_URL}/api/music/market/ingest",
|
||||
json={"trends": trends, "report_date": report_date},
|
||||
)
|
||||
return resp.status_code == 200
|
||||
except Exception:
|
||||
return False
|
||||
@@ -3,6 +3,3 @@ uvicorn[standard]==0.30.6
|
||||
apscheduler==3.10.4
|
||||
websockets>=12.0
|
||||
httpx>=0.27
|
||||
respx>=0.21
|
||||
google-api-python-client>=2.100.0
|
||||
pytrends>=4.9.2
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
import pytest
|
||||
import respx
|
||||
from httpx import Response
|
||||
from app.agents import classify_intent as ci
|
||||
|
||||
|
||||
def test_clear_approve_no_llm(monkeypatch):
|
||||
# Patch _llm_classify so we can assert it wasn't called
|
||||
called = {"n": 0}
|
||||
def fake(text):
|
||||
called["n"] += 1
|
||||
return ("unclear", None)
|
||||
monkeypatch.setattr(ci, "_llm_classify", fake)
|
||||
assert ci.classify("승인") == ("approve", None)
|
||||
assert ci.classify("OK") == ("approve", None)
|
||||
assert ci.classify("진행") == ("approve", None)
|
||||
assert ci.classify("agree") == ("approve", None)
|
||||
assert called["n"] == 0
|
||||
|
||||
|
||||
def test_clear_reject_only_no_llm(monkeypatch):
|
||||
monkeypatch.setattr(ci, "_llm_classify", lambda t: ("unclear", None))
|
||||
assert ci.classify("반려") == ("reject", None)
|
||||
assert ci.classify("거절") == ("reject", None)
|
||||
|
||||
|
||||
def test_reject_with_text_split(monkeypatch):
|
||||
monkeypatch.setattr(ci, "_llm_classify", lambda t: ("unclear", None))
|
||||
intent, fb = ci.classify("반려, 제목 짧게")
|
||||
assert intent == "reject"
|
||||
assert "제목 짧게" in fb
|
||||
|
||||
|
||||
@respx.mock
|
||||
def test_ambiguous_calls_llm(monkeypatch):
|
||||
monkeypatch.setenv("ANTHROPIC_API_KEY", "k")
|
||||
respx.post("https://api.anthropic.com/v1/messages").mock(
|
||||
return_value=Response(200, json={"content": [{"type": "text",
|
||||
"text": '{"intent":"reject","feedback":"좀 더 화려하게"}'}]})
|
||||
)
|
||||
intent, fb = ci.classify("음... 좀 더 화려한 분위기가 좋겠어")
|
||||
assert intent == "reject"
|
||||
assert "화려하게" in fb
|
||||
|
||||
|
||||
def test_empty_text_returns_unclear():
|
||||
assert ci.classify("") == ("unclear", None)
|
||||
assert ci.classify(None) == ("unclear", None)
|
||||
@@ -1,55 +0,0 @@
|
||||
import sys, os
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
|
||||
|
||||
import pytest
|
||||
from app.curator.schema import validate_response
|
||||
|
||||
|
||||
def _pick(nums, role="안정"):
|
||||
return {"numbers": nums, "risk_tag": role, "reason": "x"}
|
||||
|
||||
|
||||
def _make_payload(core, bonus, ext, pool):
|
||||
return {
|
||||
"core_picks": core, "bonus_picks": bonus,
|
||||
"extended_picks": ext, "pool_picks": pool,
|
||||
"tier_rationale": {"bonus": "a", "extended": "b", "pool": "c"},
|
||||
"narrative": {
|
||||
"headline": "h",
|
||||
"summary_3lines": ["1", "2", "3"],
|
||||
"retrospective": "지난주 평균 1.8",
|
||||
},
|
||||
"confidence": 70,
|
||||
}
|
||||
|
||||
|
||||
def test_valid_4tier():
|
||||
pool = [[i, i+1, i+2, i+3, i+4, i+5] for i in range(1, 21)]
|
||||
cores = [_pick(pool[i]) for i in range(5)]
|
||||
bonus = [_pick(pool[i]) for i in range(5, 10)]
|
||||
ext = [_pick(pool[i]) for i in range(10, 15)]
|
||||
pl = [_pick(pool[i]) for i in range(15, 20)]
|
||||
out = validate_response(_make_payload(cores, bonus, ext, pl), pool)
|
||||
assert len(out.core_picks) == 5
|
||||
assert out.narrative.retrospective.startswith("지난주")
|
||||
|
||||
|
||||
def test_duplicate_pick_rejected():
|
||||
pool = [[i, i+1, i+2, i+3, i+4, i+5] for i in range(1, 21)]
|
||||
cores = [_pick(pool[0])] * 5 # 중복
|
||||
bonus = [_pick(pool[i]) for i in range(5, 10)]
|
||||
ext = [_pick(pool[i]) for i in range(10, 15)]
|
||||
pl = [_pick(pool[i]) for i in range(15, 20)]
|
||||
with pytest.raises(ValueError, match="duplicate"):
|
||||
validate_response(_make_payload(cores, bonus, ext, pl), pool)
|
||||
|
||||
|
||||
def test_pick_not_in_candidates_rejected():
|
||||
pool = [[i, i+1, i+2, i+3, i+4, i+5] for i in range(1, 21)]
|
||||
foreign = [40, 41, 42, 43, 44, 45]
|
||||
cores = [_pick(foreign)] + [_pick(pool[i]) for i in range(1, 5)]
|
||||
bonus = [_pick(pool[i]) for i in range(5, 10)]
|
||||
ext = [_pick(pool[i]) for i in range(10, 15)]
|
||||
pl = [_pick(pool[i]) for i in range(15, 20)]
|
||||
with pytest.raises(ValueError, match="not in candidates"):
|
||||
validate_response(_make_payload(cores, bonus, ext, pl), pool)
|
||||
@@ -1,85 +0,0 @@
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
_fd, _TMP = tempfile.mkstemp(suffix=".db")
|
||||
os.close(_fd)
|
||||
os.unlink(_TMP)
|
||||
os.environ["AGENT_OFFICE_DB_PATH"] = _TMP
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from unittest.mock import patch, AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from app.agents.insta import InstaAgent
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _init_db():
|
||||
import gc
|
||||
gc.collect()
|
||||
if os.path.exists(_TMP):
|
||||
os.remove(_TMP)
|
||||
from app.db import init_db
|
||||
init_db()
|
||||
yield
|
||||
gc.collect()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_on_command_extract_dispatches(monkeypatch):
|
||||
agent = InstaAgent()
|
||||
fake_collect = AsyncMock(return_value={"task_id": "tcollect"})
|
||||
fake_extract = AsyncMock(return_value={"task_id": "textract"})
|
||||
fake_status = AsyncMock(side_effect=[
|
||||
{"status": "succeeded", "result_id": 0},
|
||||
{"status": "succeeded", "result_id": 0},
|
||||
])
|
||||
fake_keywords = AsyncMock(return_value=[
|
||||
{"id": 1, "keyword": "K1", "category": "economy", "score": 0.9},
|
||||
{"id": 2, "keyword": "K2", "category": "psychology", "score": 0.8},
|
||||
])
|
||||
|
||||
monkeypatch.setattr("app.agents.insta.service_proxy.insta_collect", fake_collect)
|
||||
monkeypatch.setattr("app.agents.insta.service_proxy.insta_extract", fake_extract)
|
||||
monkeypatch.setattr("app.agents.insta.service_proxy.insta_task_status", fake_status)
|
||||
monkeypatch.setattr("app.agents.insta.service_proxy.insta_list_keywords", fake_keywords)
|
||||
monkeypatch.setattr("app.agents.insta.messaging.send_raw", AsyncMock(return_value={"ok": True}))
|
||||
|
||||
result = await agent.on_command("extract", {})
|
||||
assert result["ok"] is True
|
||||
fake_collect.assert_awaited()
|
||||
fake_extract.assert_awaited()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_on_callback_render_kicks_pipeline(monkeypatch):
|
||||
agent = InstaAgent()
|
||||
fake_kw = AsyncMock(return_value={"id": 7, "keyword": "테스트", "category": "economy"})
|
||||
fake_create = AsyncMock(return_value={"task_id": "tslate"})
|
||||
fake_status = AsyncMock(side_effect=[
|
||||
{"status": "processing"},
|
||||
{"status": "succeeded", "result_id": 42},
|
||||
])
|
||||
fake_slate = AsyncMock(return_value={
|
||||
"id": 42, "status": "rendered",
|
||||
"suggested_caption": "캡션", "hashtags": ["#a", "#b"],
|
||||
"assets": [{"page_index": i, "file_path": f"/x/{i}.png"} for i in range(1, 11)],
|
||||
})
|
||||
fake_bytes = AsyncMock(side_effect=[b"PNG"] * 10)
|
||||
fake_send_media = AsyncMock(return_value={"ok": True})
|
||||
|
||||
monkeypatch.setattr("app.agents.insta.service_proxy.insta_get_keyword", fake_kw)
|
||||
monkeypatch.setattr("app.agents.insta.service_proxy.insta_create_slate", fake_create)
|
||||
monkeypatch.setattr("app.agents.insta.service_proxy.insta_task_status", fake_status)
|
||||
monkeypatch.setattr("app.agents.insta.service_proxy.insta_get_slate", fake_slate)
|
||||
monkeypatch.setattr("app.agents.insta.service_proxy.insta_get_asset_bytes", fake_bytes)
|
||||
monkeypatch.setattr("app.agents.insta._send_media_group", fake_send_media)
|
||||
monkeypatch.setattr("app.agents.insta.messaging.send_raw", AsyncMock(return_value={"ok": True}))
|
||||
|
||||
out = await agent.on_callback("render", {"keyword_id": 7})
|
||||
assert out["ok"] is True
|
||||
fake_create.assert_awaited()
|
||||
fake_send_media.assert_awaited()
|
||||
@@ -1,132 +0,0 @@
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
_fd, _TMP = tempfile.mkstemp(suffix=".db")
|
||||
os.close(_fd)
|
||||
os.unlink(_TMP)
|
||||
os.environ["AGENT_OFFICE_DB_PATH"] = _TMP
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
|
||||
import pytest
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _init_db():
|
||||
import gc
|
||||
gc.collect()
|
||||
if os.path.exists(_TMP):
|
||||
os.remove(_TMP)
|
||||
from app.db import init_db
|
||||
init_db()
|
||||
yield
|
||||
gc.collect()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_poll_notifies_once_per_state():
|
||||
from app.agents.youtube_publisher import YoutubePublisherAgent
|
||||
|
||||
pipelines = [{
|
||||
"id": 1,
|
||||
"state": "cover_pending",
|
||||
"cover_url": "/x.jpg",
|
||||
"track_title": "Test",
|
||||
"feedback_count_per_step": {},
|
||||
}]
|
||||
with patch(
|
||||
"app.agents.youtube_publisher.service_proxy.list_active_pipelines",
|
||||
new=AsyncMock(return_value=pipelines),
|
||||
), patch(
|
||||
"app.agents.youtube_publisher.send_raw",
|
||||
new=AsyncMock(return_value={"ok": True, "message_id": 99}),
|
||||
) as mock_send, patch(
|
||||
"app.agents.youtube_publisher.service_proxy.save_pipeline_telegram_msg",
|
||||
new=AsyncMock(),
|
||||
):
|
||||
a = YoutubePublisherAgent()
|
||||
await a.poll_state_changes()
|
||||
await a.poll_state_changes() # 같은 상태 — 두 번째는 알림 안 함
|
||||
assert mock_send.call_count == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_poll_renotifies_on_reject_regen(monkeypatch):
|
||||
from app.agents.youtube_publisher import YoutubePublisherAgent
|
||||
|
||||
pipelines_v1 = [{"id": 1, "state": "cover_pending", "cover_url": "/x.jpg",
|
||||
"track_title": "Test", "feedback_count_per_step": {}}]
|
||||
pipelines_v2 = [{"id": 1, "state": "cover_pending", "cover_url": "/x2.jpg",
|
||||
"track_title": "Test", "feedback_count_per_step": {"cover": 1}}]
|
||||
list_mock = AsyncMock(side_effect=[pipelines_v1, pipelines_v2])
|
||||
with patch("app.agents.youtube_publisher.service_proxy.list_active_pipelines", list_mock), \
|
||||
patch("app.agents.youtube_publisher.send_raw",
|
||||
new=AsyncMock(return_value={"ok": True, "message_id": 99})), \
|
||||
patch("app.agents.youtube_publisher.service_proxy.save_pipeline_telegram_msg",
|
||||
new=AsyncMock()):
|
||||
a = YoutubePublisherAgent()
|
||||
await a.poll_state_changes() # 1st: notify
|
||||
await a.poll_state_changes() # 2nd: feedback count differs → notify again
|
||||
from app.agents.youtube_publisher import send_raw as sr
|
||||
assert sr.call_count == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_on_telegram_reply_approve_calls_feedback():
|
||||
from app.agents.youtube_publisher import YoutubePublisherAgent
|
||||
|
||||
with patch(
|
||||
"app.agents.youtube_publisher.service_proxy.post_pipeline_feedback",
|
||||
new=AsyncMock(),
|
||||
) as mock_fb, patch(
|
||||
"app.agents.youtube_publisher.send_raw",
|
||||
new=AsyncMock(),
|
||||
):
|
||||
a = YoutubePublisherAgent()
|
||||
await a.on_telegram_reply(pipeline_id=42, step="cover", user_text="승인")
|
||||
mock_fb.assert_called_once_with(42, "cover", "approve", None)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_on_telegram_reply_reject_with_feedback():
|
||||
from app.agents.youtube_publisher import YoutubePublisherAgent
|
||||
|
||||
with patch(
|
||||
"app.agents.youtube_publisher.service_proxy.post_pipeline_feedback",
|
||||
new=AsyncMock(),
|
||||
) as mock_fb, patch(
|
||||
"app.agents.youtube_publisher.send_raw",
|
||||
new=AsyncMock(),
|
||||
):
|
||||
a = YoutubePublisherAgent()
|
||||
await a.on_telegram_reply(pipeline_id=43, step="meta", user_text="반려, 제목 짧게")
|
||||
args = mock_fb.call_args[0]
|
||||
assert args[0] == 43
|
||||
assert args[1] == "meta"
|
||||
assert args[2] == "reject"
|
||||
assert "제목 짧게" in (args[3] or "")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_on_telegram_reply_unclear_asks_again():
|
||||
from app.agents.youtube_publisher import YoutubePublisherAgent
|
||||
|
||||
sent = []
|
||||
|
||||
async def mock_send(text=None, **kw):
|
||||
sent.append(text)
|
||||
return {"ok": True, "message_id": 1}
|
||||
|
||||
with patch(
|
||||
"app.agents.youtube_publisher.send_raw",
|
||||
new=mock_send,
|
||||
), patch(
|
||||
"app.agents.youtube_publisher.classify_intent.classify",
|
||||
return_value=("unclear", None),
|
||||
):
|
||||
a = YoutubePublisherAgent()
|
||||
await a.on_telegram_reply(pipeline_id=44, step="cover", user_text="huh?")
|
||||
assert any("다시 입력" in (s or "") for s in sent)
|
||||
@@ -1,99 +0,0 @@
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
_fd, _TMP = tempfile.mkstemp(suffix=".db")
|
||||
os.close(_fd)
|
||||
os.unlink(_TMP)
|
||||
os.environ["AGENT_OFFICE_DB_PATH"] = _TMP
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
|
||||
import asyncio
|
||||
from unittest.mock import AsyncMock, patch
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _init_db():
|
||||
import gc
|
||||
gc.collect()
|
||||
if os.path.exists(_TMP):
|
||||
os.remove(_TMP)
|
||||
from app.db import init_db
|
||||
init_db()
|
||||
yield
|
||||
gc.collect()
|
||||
|
||||
|
||||
def test_on_new_matches_returns_empty_when_no_matches():
|
||||
from app.agents.realestate import RealestateAgent
|
||||
|
||||
agent = RealestateAgent()
|
||||
result = asyncio.run(agent.on_new_matches([]))
|
||||
assert result == {"sent": 0, "sent_ids": []}
|
||||
|
||||
|
||||
def test_on_new_matches_sends_telegram_and_returns_ids():
|
||||
from app.agents.realestate import RealestateAgent
|
||||
from app.telegram import messaging
|
||||
|
||||
matches = [{
|
||||
"id": 7, "match_score": 80, "house_nm": "단지A",
|
||||
"region_name": "서울특별시", "district": "강남구",
|
||||
"receipt_start": "2026-05-01", "receipt_end": "2026-05-05",
|
||||
"match_reasons": [], "eligible_types": [], "pblanc_url": "https://x.test/7",
|
||||
}]
|
||||
|
||||
fake_send = AsyncMock(return_value={"ok": True, "message_id": 123})
|
||||
with patch.object(messaging, "send_raw", fake_send):
|
||||
agent = RealestateAgent()
|
||||
result = asyncio.run(agent.on_new_matches(matches))
|
||||
|
||||
assert result["sent"] == 1
|
||||
assert result["sent_ids"] == [7]
|
||||
assert result["message_id"] == 123
|
||||
fake_send.assert_awaited_once()
|
||||
args, kwargs = fake_send.call_args
|
||||
text = args[0]
|
||||
assert "단지A" in text
|
||||
|
||||
|
||||
def test_on_new_matches_telegram_failure_returns_zero():
|
||||
from app.agents.realestate import RealestateAgent
|
||||
from app.telegram import messaging
|
||||
|
||||
matches = [{
|
||||
"id": 8, "match_score": 80, "house_nm": "단지B",
|
||||
"region_name": "서울", "district": "송파구",
|
||||
"receipt_start": "", "receipt_end": "",
|
||||
"match_reasons": [], "eligible_types": [], "pblanc_url": "",
|
||||
}]
|
||||
|
||||
fake_send = AsyncMock(return_value={"ok": False, "description": "401"})
|
||||
with patch.object(messaging, "send_raw", fake_send):
|
||||
agent = RealestateAgent()
|
||||
result = asyncio.run(agent.on_new_matches(matches))
|
||||
|
||||
assert result["sent"] == 0
|
||||
assert result["sent_ids"] == []
|
||||
assert "error" in result
|
||||
|
||||
|
||||
def test_endpoint_calls_agent_on_new_matches():
|
||||
from fastapi.testclient import TestClient
|
||||
from app.main import app
|
||||
from app.agents.realestate import RealestateAgent
|
||||
|
||||
fake = AsyncMock(return_value={"sent": 1, "sent_ids": [99], "message_id": 1})
|
||||
with patch.object(RealestateAgent, "on_new_matches", fake):
|
||||
with TestClient(app) as client:
|
||||
resp = client.post(
|
||||
"/api/agent-office/realestate/notify",
|
||||
json={"matches": [{"id": 99, "match_score": 80}]},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
body = resp.json()
|
||||
assert body["sent"] == 1
|
||||
assert body["sent_ids"] == [99]
|
||||
@@ -1,133 +0,0 @@
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import gc
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
_fd, _TMP = tempfile.mkstemp(suffix=".db")
|
||||
os.close(_fd)
|
||||
os.unlink(_TMP)
|
||||
os.environ["AGENT_OFFICE_DB_PATH"] = _TMP
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
import asyncio
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _init_db():
|
||||
gc.collect()
|
||||
if os.path.exists(_TMP):
|
||||
try:
|
||||
os.remove(_TMP)
|
||||
except PermissionError:
|
||||
pass
|
||||
from app.db import init_db
|
||||
init_db()
|
||||
yield
|
||||
|
||||
|
||||
def test_callback_realestate_bookmark_calls_proxy():
|
||||
"""callback_data 'realestate_bookmark_42' 가 service_proxy.realestate_bookmark_toggle(42) 를 호출하고
|
||||
is_bookmarked=1 이면 '추가 완료' 메시지를 전송한다."""
|
||||
from app import service_proxy
|
||||
from app.telegram import webhook
|
||||
|
||||
fake_toggle = AsyncMock(return_value={"is_bookmarked": 1})
|
||||
fake_send = AsyncMock(return_value={"ok": True})
|
||||
fake_api_call = AsyncMock(return_value={"ok": True})
|
||||
|
||||
update = {
|
||||
"callback_query": {
|
||||
"id": "cb1",
|
||||
"from": {"id": 1},
|
||||
"data": "realestate_bookmark_42",
|
||||
}
|
||||
}
|
||||
|
||||
with patch.object(service_proxy, "realestate_bookmark_toggle", fake_toggle), \
|
||||
patch("app.telegram.messaging.send_raw", fake_send), \
|
||||
patch("app.telegram.webhook.api_call", fake_api_call):
|
||||
result = asyncio.run(webhook.handle_webhook(update))
|
||||
|
||||
fake_toggle.assert_awaited_once_with(42)
|
||||
assert result == {"ok": True, "announcement_id": 42}
|
||||
args, _ = fake_send.call_args
|
||||
assert "추가" in args[0]
|
||||
|
||||
|
||||
def test_callback_realestate_bookmark_invalid_id():
|
||||
"""callback_data 'realestate_bookmark_abc' 는 ValueError를 처리하고 에러 응답 반환."""
|
||||
from app import service_proxy
|
||||
from app.telegram import webhook
|
||||
|
||||
fake_toggle = AsyncMock(return_value={"bookmarked": True})
|
||||
fake_send = AsyncMock(return_value={"ok": True})
|
||||
fake_api_call = AsyncMock(return_value={"ok": True})
|
||||
|
||||
update = {
|
||||
"callback_query": {
|
||||
"id": "cb2",
|
||||
"from": {"id": 1},
|
||||
"data": "realestate_bookmark_abc",
|
||||
}
|
||||
}
|
||||
|
||||
with patch.object(service_proxy, "realestate_bookmark_toggle", fake_toggle), \
|
||||
patch("app.telegram.messaging.send_raw", fake_send), \
|
||||
patch("app.telegram.webhook.api_call", fake_api_call):
|
||||
result = asyncio.run(webhook.handle_webhook(update))
|
||||
|
||||
fake_toggle.assert_not_awaited()
|
||||
assert result is not None
|
||||
assert result.get("ok") is False
|
||||
assert result.get("error") == "invalid_callback_data"
|
||||
|
||||
|
||||
def test_callback_realestate_bookmark_proxy_error():
|
||||
"""service_proxy 가 예외를 던질 때 에러 응답 반환."""
|
||||
from app import service_proxy
|
||||
from app.telegram import webhook
|
||||
|
||||
fake_toggle = AsyncMock(side_effect=Exception("connection refused"))
|
||||
fake_send = AsyncMock(return_value={"ok": True})
|
||||
fake_api_call = AsyncMock(return_value={"ok": True})
|
||||
|
||||
update = {
|
||||
"callback_query": {
|
||||
"id": "cb3",
|
||||
"from": {"id": 1},
|
||||
"data": "realestate_bookmark_99",
|
||||
}
|
||||
}
|
||||
|
||||
with patch.object(service_proxy, "realestate_bookmark_toggle", fake_toggle), \
|
||||
patch("app.telegram.messaging.send_raw", fake_send), \
|
||||
patch("app.telegram.webhook.api_call", fake_api_call):
|
||||
result = asyncio.run(webhook.handle_webhook(update))
|
||||
|
||||
fake_toggle.assert_awaited_once_with(99)
|
||||
assert result is not None
|
||||
assert result.get("ok") is False
|
||||
assert "connection refused" in result.get("error", "")
|
||||
|
||||
|
||||
def test_non_realestate_callback_uses_db_path():
|
||||
"""approve_*/reject_* 콜백은 기존 DB 조회 경로를 사용 (realestate 분기를 타지 않음)."""
|
||||
from app.telegram import webhook
|
||||
|
||||
fake_api_call = AsyncMock(return_value={"ok": True})
|
||||
|
||||
update = {
|
||||
"callback_query": {
|
||||
"id": "cb4",
|
||||
"from": {"id": 1},
|
||||
"data": "approve_abcd1234",
|
||||
}
|
||||
}
|
||||
|
||||
# DB에 등록되지 않은 콜백이므로 None 반환 — 기존 로직 진입 확인
|
||||
with patch("app.telegram.webhook.api_call", fake_api_call):
|
||||
result = asyncio.run(webhook.handle_webhook(update))
|
||||
|
||||
assert result is None # DB에 없으면 None 반환 (기존 동작 유지)
|
||||
@@ -1,59 +0,0 @@
|
||||
def test_format_realestate_match_full_card_single():
|
||||
from app.telegram.realestate_message import format_realestate_matches
|
||||
matches = [{
|
||||
"id": 1,
|
||||
"match_score": 90,
|
||||
"house_nm": "디에이치 강남",
|
||||
"region_name": "서울특별시",
|
||||
"district": "강남구",
|
||||
"is_speculative_area": "Y",
|
||||
"is_price_cap": "Y",
|
||||
"receipt_start": "2026-05-15",
|
||||
"receipt_end": "2026-05-19",
|
||||
"match_reasons": ["광역 일치", "자치구 S티어: 강남구 (+25)", "예산 범위"],
|
||||
"eligible_types": ["일반1순위", "특별-신혼부부"],
|
||||
"pblanc_url": "https://example.com/p/1",
|
||||
}]
|
||||
text = format_realestate_matches(matches)
|
||||
assert "디에이치 강남" in text
|
||||
assert "90점" in text
|
||||
assert "강남구" in text
|
||||
assert "2026-05-15" in text
|
||||
|
||||
|
||||
def test_format_realestate_match_compact_when_three_or_more():
|
||||
from app.telegram.realestate_message import format_realestate_matches
|
||||
matches = [
|
||||
{"id": i, "match_score": 90 - i, "house_nm": f"단지{i}", "district": "강남구",
|
||||
"region_name": "서울특별시", "receipt_start": "2026-05-15", "receipt_end": "2026-05-19",
|
||||
"match_reasons": [], "eligible_types": [], "pblanc_url": ""}
|
||||
for i in range(3)
|
||||
]
|
||||
text = format_realestate_matches(matches)
|
||||
assert "3건" in text or "3" in text
|
||||
for i in range(3):
|
||||
assert f"단지{i}" in text
|
||||
|
||||
|
||||
def test_build_keyboard_single_match_has_bookmark_and_url():
|
||||
from app.telegram.realestate_message import build_match_keyboard
|
||||
matches = [{"id": 42, "pblanc_url": "https://example.com/p/42"}]
|
||||
kb = build_match_keyboard(matches)
|
||||
rows = kb["inline_keyboard"]
|
||||
flat = [b for row in rows for b in row]
|
||||
assert any(b.get("callback_data", "").startswith("realestate_bookmark_42") for b in flat)
|
||||
assert any(b.get("url") == "https://example.com/p/42" for b in flat)
|
||||
|
||||
|
||||
def test_build_keyboard_multi_matches_uses_dashboard_link():
|
||||
from app.telegram.realestate_message import build_match_keyboard
|
||||
matches = [{"id": i, "pblanc_url": ""} for i in range(3)]
|
||||
kb = build_match_keyboard(matches)
|
||||
flat = [b for row in kb["inline_keyboard"] for b in row]
|
||||
# 3건 이상이면 [전체 보기] 단일 URL 버튼
|
||||
assert any("전체" in b.get("text", "") for b in flat)
|
||||
|
||||
|
||||
def test_build_keyboard_empty_returns_none():
|
||||
from app.telegram.realestate_message import build_match_keyboard
|
||||
assert build_match_keyboard([]) is None
|
||||
@@ -1,47 +0,0 @@
|
||||
import sys, os
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
|
||||
|
||||
import pytest
|
||||
from unittest.mock import AsyncMock, patch
|
||||
from app.curator.retrospective import build_retrospective, _detect_bias
|
||||
|
||||
|
||||
def test_detect_bias_persistent_low():
|
||||
reviews = [
|
||||
{"pattern_delta": "저번호 편향 +1.2 / 합계 -18"},
|
||||
{"pattern_delta": "저번호 편향 +0.8"},
|
||||
{"pattern_delta": "저번호 편향 +1.0 / 홀짝 +0.5"},
|
||||
]
|
||||
assert "저번호" in _detect_bias(reviews)
|
||||
|
||||
|
||||
def test_detect_bias_no_persistence():
|
||||
reviews = [
|
||||
{"pattern_delta": "저번호 편향 +1.2"},
|
||||
{"pattern_delta": "고번호 편향 +0.8"},
|
||||
]
|
||||
assert _detect_bias(reviews) == ""
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_build_retrospective_with_data():
|
||||
with patch("app.service_proxy.lotto_review_by_draw", new=AsyncMock(return_value={
|
||||
"draw_no": 1153, "curator_avg_match": 1.8, "curator_best_tier": "안정",
|
||||
"user_avg_match": 2.0, "user_5plus_prizes": 1, "pattern_delta": "저번호 편향 +1.2",
|
||||
})), patch("app.service_proxy.lotto_reviews_history", new=AsyncMock(return_value=[
|
||||
{"draw_no": 1153, "curator_avg_match": 1.8, "user_avg_match": 2.0, "pattern_delta": "저번호 편향 +1.2"},
|
||||
{"draw_no": 1152, "curator_avg_match": 1.6, "user_avg_match": 1.5, "pattern_delta": "저번호 편향 +0.8"},
|
||||
{"draw_no": 1151, "curator_avg_match": 1.7, "user_avg_match": 1.8, "pattern_delta": "저번호 편향 +1.0"},
|
||||
{"draw_no": 1150, "curator_avg_match": 1.9, "user_avg_match": 2.2, "pattern_delta": ""},
|
||||
])):
|
||||
out = await build_retrospective(1154)
|
||||
assert out["last_draw"]["draw_no"] == 1153
|
||||
assert out["trend_4w"]["curator_avg_4w"] == round((1.8+1.6+1.7+1.9)/4, 2)
|
||||
assert "저번호" in out["trend_4w"]["user_persistent_bias"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_build_retrospective_no_review():
|
||||
with patch("app.service_proxy.lotto_review_by_draw", new=AsyncMock(return_value=None)):
|
||||
out = await build_retrospective(1154)
|
||||
assert out is None
|
||||
@@ -1,177 +0,0 @@
|
||||
"""StockAgent.on_screener_schedule — 평일 16:30 KST 자동 잡 단위 테스트.
|
||||
|
||||
stock HTTP 호출은 service_proxy mock, 텔레그램은 messaging.send_raw mock.
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
_fd, _TMP = tempfile.mkstemp(suffix=".db")
|
||||
os.close(_fd)
|
||||
os.unlink(_TMP)
|
||||
os.environ["AGENT_OFFICE_DB_PATH"] = _TMP
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
|
||||
import asyncio
|
||||
from unittest.mock import AsyncMock, patch
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _init_db():
|
||||
import gc
|
||||
gc.collect()
|
||||
if os.path.exists(_TMP):
|
||||
os.remove(_TMP)
|
||||
from app.db import init_db
|
||||
init_db()
|
||||
yield
|
||||
gc.collect()
|
||||
|
||||
|
||||
def _success_body(asof="2026-05-12"):
|
||||
return {
|
||||
"asof": asof,
|
||||
"mode": "auto",
|
||||
"status": "success",
|
||||
"run_id": 42,
|
||||
"survivors_count": 600,
|
||||
"top_n": 20,
|
||||
"results": [],
|
||||
"telegram_payload": {
|
||||
"chat_target": "default",
|
||||
"parse_mode": "MarkdownV2",
|
||||
"text": "*KRX 강세주 스크리너* test body",
|
||||
},
|
||||
"warnings": [],
|
||||
}
|
||||
|
||||
|
||||
def _holiday_body(asof="2026-05-05"):
|
||||
return {
|
||||
"asof": asof,
|
||||
"mode": "auto",
|
||||
"status": "skipped_holiday",
|
||||
"run_id": None,
|
||||
"survivors_count": None,
|
||||
"top_n": 0,
|
||||
"results": [],
|
||||
"telegram_payload": None,
|
||||
"warnings": [f"{asof} is a holiday — skipped"],
|
||||
}
|
||||
|
||||
|
||||
def test_screener_success_sends_markdownv2_telegram():
|
||||
from app.agents.stock import StockAgent
|
||||
from app import service_proxy
|
||||
from app.telegram import messaging
|
||||
|
||||
fake_snap = AsyncMock(return_value={"status": "ok"})
|
||||
fake_run = AsyncMock(return_value=_success_body())
|
||||
fake_send = AsyncMock(return_value={"ok": True, "message_id": 7777})
|
||||
|
||||
with patch.object(service_proxy, "refresh_screener_snapshot", fake_snap), \
|
||||
patch.object(service_proxy, "run_stock_screener", fake_run), \
|
||||
patch.object(messaging, "send_raw", fake_send):
|
||||
agent = StockAgent()
|
||||
asyncio.run(agent.on_screener_schedule())
|
||||
|
||||
fake_snap.assert_awaited_once()
|
||||
fake_run.assert_awaited_once_with(mode="auto")
|
||||
fake_send.assert_awaited_once()
|
||||
args, kwargs = fake_send.call_args
|
||||
# 첫 인자(text) 또는 kwargs로 전달
|
||||
text = args[0] if args else kwargs.get("text")
|
||||
assert "KRX 강세주 스크리너" in text
|
||||
assert kwargs.get("parse_mode") == "MarkdownV2"
|
||||
assert agent.state == "idle"
|
||||
|
||||
|
||||
def test_screener_holiday_skips_telegram():
|
||||
from app.agents.stock import StockAgent
|
||||
from app import service_proxy
|
||||
from app.telegram import messaging
|
||||
|
||||
fake_snap = AsyncMock(return_value={"status": "skipped_weekend"})
|
||||
fake_run = AsyncMock(return_value=_holiday_body())
|
||||
fake_send = AsyncMock(return_value={"ok": True, "message_id": 1})
|
||||
|
||||
with patch.object(service_proxy, "refresh_screener_snapshot", fake_snap), \
|
||||
patch.object(service_proxy, "run_stock_screener", fake_run), \
|
||||
patch.object(messaging, "send_raw", fake_send):
|
||||
agent = StockAgent()
|
||||
asyncio.run(agent.on_screener_schedule())
|
||||
|
||||
fake_run.assert_awaited_once()
|
||||
# 휴일이면 텔레그램 미발신
|
||||
fake_send.assert_not_awaited()
|
||||
assert agent.state == "idle"
|
||||
|
||||
|
||||
def test_screener_snapshot_failure_still_runs_screener():
|
||||
"""스냅샷 실패는 경고만 남기고 screener 호출은 계속됨."""
|
||||
from app.agents.stock import StockAgent
|
||||
from app import service_proxy
|
||||
from app.telegram import messaging
|
||||
|
||||
fake_snap = AsyncMock(side_effect=RuntimeError("snapshot upstream down"))
|
||||
fake_run = AsyncMock(return_value=_success_body())
|
||||
fake_send = AsyncMock(return_value={"ok": True, "message_id": 8888})
|
||||
|
||||
with patch.object(service_proxy, "refresh_screener_snapshot", fake_snap), \
|
||||
patch.object(service_proxy, "run_stock_screener", fake_run), \
|
||||
patch.object(messaging, "send_raw", fake_send):
|
||||
agent = StockAgent()
|
||||
asyncio.run(agent.on_screener_schedule())
|
||||
|
||||
fake_snap.assert_awaited_once()
|
||||
fake_run.assert_awaited_once_with(mode="auto")
|
||||
fake_send.assert_awaited_once()
|
||||
|
||||
|
||||
def test_screener_run_failure_notifies_operator():
|
||||
"""screener/run 실패 시 운영자 알림 텔레그램 발송."""
|
||||
from app.agents.stock import StockAgent
|
||||
from app import service_proxy
|
||||
from app.telegram import messaging
|
||||
|
||||
fake_snap = AsyncMock(return_value={"status": "ok"})
|
||||
fake_run = AsyncMock(side_effect=RuntimeError("stock 500"))
|
||||
fake_send = AsyncMock(return_value={"ok": True, "message_id": 1})
|
||||
|
||||
with patch.object(service_proxy, "refresh_screener_snapshot", fake_snap), \
|
||||
patch.object(service_proxy, "run_stock_screener", fake_run), \
|
||||
patch.object(messaging, "send_raw", fake_send):
|
||||
agent = StockAgent()
|
||||
asyncio.run(agent.on_screener_schedule())
|
||||
|
||||
# 운영자 알림 1회는 호출
|
||||
assert fake_send.await_count == 1
|
||||
args, kwargs = fake_send.call_args
|
||||
text = args[0] if args else kwargs.get("text")
|
||||
assert "스크리너 실패" in text
|
||||
assert agent.state == "idle"
|
||||
|
||||
|
||||
def test_screener_unexpected_status_treated_as_failure():
|
||||
from app.agents.stock import StockAgent
|
||||
from app import service_proxy
|
||||
from app.telegram import messaging
|
||||
|
||||
fake_snap = AsyncMock(return_value={"status": "ok"})
|
||||
fake_run = AsyncMock(return_value={"status": "weird", "asof": "2026-05-12"})
|
||||
fake_send = AsyncMock(return_value={"ok": True, "message_id": 1})
|
||||
|
||||
with patch.object(service_proxy, "refresh_screener_snapshot", fake_snap), \
|
||||
patch.object(service_proxy, "run_stock_screener", fake_run), \
|
||||
patch.object(messaging, "send_raw", fake_send):
|
||||
agent = StockAgent()
|
||||
asyncio.run(agent.on_screener_schedule())
|
||||
|
||||
# 운영자 알림 1회 + screener payload 미발송
|
||||
assert fake_send.await_count == 1
|
||||
args, kwargs = fake_send.call_args
|
||||
text = args[0] if args else kwargs.get("text")
|
||||
assert "스크리너 실패" in text
|
||||
@@ -1,44 +0,0 @@
|
||||
import sys, os
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
|
||||
|
||||
from app.notifiers.telegram_lotto import _format_briefing, _format_prize_alert
|
||||
|
||||
|
||||
def test_briefing_with_retrospective():
|
||||
payload = {
|
||||
"draw_no": 1154,
|
||||
"confidence": 72,
|
||||
"narrative": {
|
||||
"headline": "안정 +1, 콜드 누적 보강",
|
||||
"summary_3lines": ["a", "b", "c"],
|
||||
"retrospective": "너 2.0 / 나 1.8 — 저번호 편향",
|
||||
},
|
||||
"picks": {
|
||||
"core": [
|
||||
{"risk_tag": "안정"}, {"risk_tag": "안정"}, {"risk_tag": "안정"},
|
||||
{"risk_tag": "균형"}, {"risk_tag": "공격"},
|
||||
],
|
||||
"bonus": [], "extended": [], "pool": [],
|
||||
},
|
||||
}
|
||||
text = _format_briefing(payload)
|
||||
assert "1154회" in text
|
||||
assert "신뢰도 72" in text
|
||||
assert "안정 3" in text
|
||||
assert "회고: 너 2.0" in text
|
||||
|
||||
|
||||
def test_briefing_without_retrospective():
|
||||
payload = {
|
||||
"draw_no": 1, "confidence": 50,
|
||||
"narrative": {"headline": "h", "summary_3lines": ["a","b","c"], "retrospective": ""},
|
||||
"picks": {"core": [{"risk_tag":"안정"}]*5, "bonus":[],"extended":[],"pool":[]},
|
||||
}
|
||||
text = _format_briefing(payload)
|
||||
assert "회고" not in text
|
||||
|
||||
|
||||
def test_prize_alert():
|
||||
text = _format_prize_alert({"draw_no": 1154, "match_count": 5, "numbers": [3,11,17,25,33,8]})
|
||||
assert "5개 일치" in text
|
||||
assert "3, 11, 17, 25, 33, 8" in text
|
||||
@@ -9,10 +9,8 @@ DB_PATH = "/app/data/lotto.db"
|
||||
|
||||
def _conn() -> sqlite3.Connection:
|
||||
os.makedirs(os.path.dirname(DB_PATH), exist_ok=True)
|
||||
conn = sqlite3.connect(DB_PATH, timeout=120.0)
|
||||
conn = sqlite3.connect(DB_PATH)
|
||||
conn.row_factory = sqlite3.Row
|
||||
conn.execute("PRAGMA journal_mode=WAL")
|
||||
conn.execute("PRAGMA busy_timeout=120000")
|
||||
return conn
|
||||
|
||||
def _ensure_column(conn: sqlite3.Connection, table: str, col: str, ddl: str) -> None:
|
||||
@@ -145,6 +143,44 @@ def init_db() -> None:
|
||||
"ON best_picks(is_active, score_total DESC);"
|
||||
)
|
||||
|
||||
# ── todos 테이블 ───────────────────────────────────────────────────────
|
||||
conn.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS todos (
|
||||
id TEXT PRIMARY KEY
|
||||
DEFAULT (lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2)))),
|
||||
title TEXT NOT NULL,
|
||||
description TEXT,
|
||||
status TEXT NOT NULL DEFAULT 'todo'
|
||||
CHECK(status IN ('todo','in_progress','done')),
|
||||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
|
||||
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
|
||||
);
|
||||
"""
|
||||
)
|
||||
conn.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_todos_created ON todos(created_at DESC);"
|
||||
)
|
||||
|
||||
# ── blog_posts 테이블 ──────────────────────────────────────────────────
|
||||
conn.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS blog_posts (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
title TEXT NOT NULL,
|
||||
body TEXT NOT NULL DEFAULT '',
|
||||
excerpt TEXT NOT NULL DEFAULT '',
|
||||
tags TEXT NOT NULL DEFAULT '[]',
|
||||
date TEXT NOT NULL DEFAULT (date('now','localtime')),
|
||||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
|
||||
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
|
||||
);
|
||||
"""
|
||||
)
|
||||
conn.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_blog_date ON blog_posts(date DESC);"
|
||||
)
|
||||
|
||||
# ── purchase_history 테이블 ────────────────────────────────────────────
|
||||
conn.execute(
|
||||
"""
|
||||
@@ -241,66 +277,134 @@ def init_db() -> None:
|
||||
conn.execute("CREATE INDEX IF NOT EXISTS idx_purchase_strategy ON purchase_history(source_strategy)")
|
||||
conn.execute("CREATE INDEX IF NOT EXISTS idx_purchase_checked ON purchase_history(draw_no, checked)")
|
||||
|
||||
# ── lotto_briefings 테이블 ─────────────────────────────────────────────
|
||||
conn.execute("""
|
||||
CREATE TABLE IF NOT EXISTS lotto_briefings (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
draw_no INTEGER UNIQUE NOT NULL,
|
||||
picks TEXT NOT NULL,
|
||||
narrative TEXT NOT NULL,
|
||||
confidence INTEGER NOT NULL,
|
||||
model TEXT NOT NULL,
|
||||
tokens_input INTEGER NOT NULL DEFAULT 0,
|
||||
tokens_output INTEGER NOT NULL DEFAULT 0,
|
||||
cache_read INTEGER NOT NULL DEFAULT 0,
|
||||
cache_write INTEGER NOT NULL DEFAULT 0,
|
||||
latency_ms INTEGER NOT NULL DEFAULT 0,
|
||||
source TEXT NOT NULL DEFAULT 'auto',
|
||||
generated_at TEXT NOT NULL DEFAULT (datetime('now','localtime'))
|
||||
)
|
||||
""")
|
||||
conn.execute("CREATE INDEX IF NOT EXISTS idx_briefings_draw ON lotto_briefings(draw_no DESC)")
|
||||
|
||||
# ── weekly_review 테이블 (큐레이터 자기 평가 + 사용자 패턴 갭) ────────
|
||||
conn.execute("""
|
||||
CREATE TABLE IF NOT EXISTS weekly_review (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
draw_no INTEGER UNIQUE NOT NULL,
|
||||
curator_avg_match REAL,
|
||||
curator_best_tier TEXT,
|
||||
curator_best_match INTEGER,
|
||||
curator_5plus_prizes INTEGER,
|
||||
user_avg_match REAL,
|
||||
user_best_match INTEGER,
|
||||
user_5plus_prizes INTEGER,
|
||||
user_pattern_summary TEXT,
|
||||
draw_pattern_summary TEXT,
|
||||
pattern_delta TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now','localtime'))
|
||||
)
|
||||
""")
|
||||
conn.execute("CREATE INDEX IF NOT EXISTS idx_review_draw ON weekly_review(draw_no DESC)")
|
||||
# ── todos CRUD ───────────────────────────────────────────────────────────────
|
||||
|
||||
# ── lotto_briefings.picks 4계층 마이그레이션 (1회 변환) ───────────────
|
||||
# 기존: picks가 JSON 리스트 [{numbers,risk_tag,reason}]
|
||||
# 신규: picks가 JSON 객체 {core:[...], bonus:[], extended:[], pool:[]}
|
||||
rows = conn.execute("SELECT id, picks FROM lotto_briefings").fetchall()
|
||||
for r in rows:
|
||||
try:
|
||||
p = json.loads(r["picks"])
|
||||
if isinstance(p, list):
|
||||
new_picks = {"core": p, "bonus": [], "extended": [], "pool": []}
|
||||
conn.execute(
|
||||
"UPDATE lotto_briefings SET picks=? WHERE id=?",
|
||||
(json.dumps(new_picks, ensure_ascii=False), r["id"]),
|
||||
)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
continue
|
||||
|
||||
_ensure_column(conn, "lotto_briefings", "tier_rationale",
|
||||
"ALTER TABLE lotto_briefings ADD COLUMN tier_rationale TEXT NOT NULL DEFAULT '{}'")
|
||||
def _todo_row_to_dict(r) -> Dict[str, Any]:
|
||||
return {
|
||||
"id": r["id"],
|
||||
"title": r["title"],
|
||||
"description": r["description"],
|
||||
"status": r["status"],
|
||||
"created_at": r["created_at"],
|
||||
"updated_at": r["updated_at"],
|
||||
}
|
||||
|
||||
|
||||
def get_all_todos() -> List[Dict[str, Any]]:
|
||||
with _conn() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM todos ORDER BY created_at DESC"
|
||||
).fetchall()
|
||||
return [_todo_row_to_dict(r) for r in rows]
|
||||
|
||||
|
||||
def create_todo(title: str, description: Optional[str], status: str) -> Dict[str, Any]:
|
||||
with _conn() as conn:
|
||||
conn.execute(
|
||||
"INSERT INTO todos (title, description, status) VALUES (?, ?, ?)",
|
||||
(title, description, status),
|
||||
)
|
||||
row = conn.execute(
|
||||
"SELECT * FROM todos WHERE rowid = last_insert_rowid()"
|
||||
).fetchone()
|
||||
return _todo_row_to_dict(row)
|
||||
|
||||
|
||||
def update_todo(todo_id: str, fields: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
||||
"""fields에 있는 항목만 업데이트 (PATCH 방식), updated_at 자동 갱신"""
|
||||
allowed = {"title", "description", "status"}
|
||||
updates = {k: v for k, v in fields.items() if k in allowed}
|
||||
if not updates:
|
||||
with _conn() as conn:
|
||||
row = conn.execute("SELECT * FROM todos WHERE id = ?", (todo_id,)).fetchone()
|
||||
return _todo_row_to_dict(row) if row else None
|
||||
|
||||
set_clauses = ", ".join(f"{k} = ?" for k in updates)
|
||||
set_clauses += ", updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')"
|
||||
args = list(updates.values()) + [todo_id]
|
||||
|
||||
with _conn() as conn:
|
||||
conn.execute(
|
||||
f"UPDATE todos SET {set_clauses} WHERE id = ?",
|
||||
args,
|
||||
)
|
||||
row = conn.execute("SELECT * FROM todos WHERE id = ?", (todo_id,)).fetchone()
|
||||
return _todo_row_to_dict(row) if row else None
|
||||
|
||||
|
||||
def delete_todo(todo_id: str) -> bool:
|
||||
with _conn() as conn:
|
||||
cur = conn.execute("DELETE FROM todos WHERE id = ?", (todo_id,))
|
||||
return cur.rowcount > 0
|
||||
|
||||
|
||||
def delete_done_todos() -> int:
|
||||
with _conn() as conn:
|
||||
cur = conn.execute("DELETE FROM todos WHERE status = 'done'")
|
||||
return cur.rowcount
|
||||
|
||||
|
||||
# ── blog_posts CRUD ──────────────────────────────────────────────────────────
|
||||
|
||||
def _post_row_to_dict(r) -> Dict[str, Any]:
|
||||
return {
|
||||
"id": r["id"],
|
||||
"title": r["title"],
|
||||
"body": r["body"],
|
||||
"excerpt": r["excerpt"],
|
||||
"tags": json.loads(r["tags"]) if r["tags"] else [],
|
||||
"date": r["date"],
|
||||
"created_at": r["created_at"],
|
||||
"updated_at": r["updated_at"],
|
||||
}
|
||||
|
||||
|
||||
def get_all_posts() -> List[Dict[str, Any]]:
|
||||
with _conn() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM blog_posts ORDER BY date DESC, id DESC"
|
||||
).fetchall()
|
||||
return [_post_row_to_dict(r) for r in rows]
|
||||
|
||||
|
||||
def create_post(title: str, body: str, excerpt: str, tags: List[str], date: str) -> Dict[str, Any]:
|
||||
with _conn() as conn:
|
||||
conn.execute(
|
||||
"INSERT INTO blog_posts (title, body, excerpt, tags, date) VALUES (?, ?, ?, ?, ?)",
|
||||
(title, body, excerpt, json.dumps(tags), date),
|
||||
)
|
||||
row = conn.execute(
|
||||
"SELECT * FROM blog_posts WHERE rowid = last_insert_rowid()"
|
||||
).fetchone()
|
||||
return _post_row_to_dict(row)
|
||||
|
||||
|
||||
def update_post(post_id: int, fields: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
||||
allowed = {"title", "body", "excerpt", "tags", "date"}
|
||||
updates = {k: v for k, v in fields.items() if k in allowed}
|
||||
if not updates:
|
||||
with _conn() as conn:
|
||||
row = conn.execute("SELECT * FROM blog_posts WHERE id = ?", (post_id,)).fetchone()
|
||||
return _post_row_to_dict(row) if row else None
|
||||
|
||||
if "tags" in updates:
|
||||
updates["tags"] = json.dumps(updates["tags"])
|
||||
|
||||
set_clauses = ", ".join(f"{k} = ?" for k in updates)
|
||||
set_clauses += ", updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')"
|
||||
args = list(updates.values()) + [post_id]
|
||||
|
||||
with _conn() as conn:
|
||||
conn.execute(f"UPDATE blog_posts SET {set_clauses} WHERE id = ?", args)
|
||||
row = conn.execute("SELECT * FROM blog_posts WHERE id = ?", (post_id,)).fetchone()
|
||||
return _post_row_to_dict(row) if row else None
|
||||
|
||||
|
||||
def delete_post(post_id: int) -> bool:
|
||||
with _conn() as conn:
|
||||
cur = conn.execute("DELETE FROM blog_posts WHERE id = ?", (post_id,))
|
||||
return cur.rowcount > 0
|
||||
|
||||
|
||||
def upsert_draw(row: Dict[str, Any]) -> None:
|
||||
@@ -992,239 +1096,3 @@ def update_purchase_results(purchase_id: int, results: list, total_prize: int) -
|
||||
(json.dumps(results, ensure_ascii=False), total_prize, purchase_id),
|
||||
)
|
||||
|
||||
|
||||
def bulk_insert_purchases_from_briefing(draw_no: int, tier_mode: str, amount: int) -> Dict[str, Any]:
|
||||
"""tier_mode 에 해당하는 큐레이터 picks 를 purchase_history 에 일괄 INSERT.
|
||||
|
||||
tier_mode: "core" | "core_bonus" | "core_bonus_extended" | "full"
|
||||
"""
|
||||
briefing = get_briefing(draw_no)
|
||||
if not briefing:
|
||||
return {"ok": False, "reason": "briefing not found"}
|
||||
|
||||
picks = briefing.get("picks") or {}
|
||||
if isinstance(picks, list):
|
||||
# 마이그레이션 이전 형태
|
||||
picks = {"core": picks, "bonus": [], "extended": [], "pool": []}
|
||||
|
||||
tier_chain = {
|
||||
"core": ["core"],
|
||||
"core_bonus": ["core", "bonus"],
|
||||
"core_bonus_extended": ["core", "bonus", "extended"],
|
||||
"full": ["core", "bonus", "extended", "pool"],
|
||||
}.get(tier_mode)
|
||||
if not tier_chain:
|
||||
return {"ok": False, "reason": f"unknown tier_mode: {tier_mode}"}
|
||||
|
||||
inserted_ids = []
|
||||
with _conn() as conn:
|
||||
for tier in tier_chain:
|
||||
for idx, pick in enumerate(picks.get(tier) or []):
|
||||
source_strategy = f"curator_{tier}"
|
||||
source_detail = json.dumps({
|
||||
"tier": tier,
|
||||
"role": pick.get("risk_tag"),
|
||||
"set_index": idx,
|
||||
"draw_no": draw_no,
|
||||
}, ensure_ascii=False)
|
||||
numbers_json = json.dumps([pick.get("numbers")], ensure_ascii=False)
|
||||
cur = conn.execute(
|
||||
"""INSERT INTO purchase_history
|
||||
(draw_no, amount, sets, prize, note, numbers, is_real, source_strategy, source_detail)
|
||||
VALUES (?, ?, 1, 0, '', ?, 1, ?, ?)""",
|
||||
(draw_no, 1000, numbers_json, source_strategy, source_detail),
|
||||
)
|
||||
inserted_ids.append(cur.lastrowid)
|
||||
return {"ok": True, "inserted_ids": inserted_ids, "sets": len(inserted_ids)}
|
||||
|
||||
|
||||
# --- Lotto Briefings ---
|
||||
|
||||
def save_briefing(data: Dict[str, Any]) -> int:
|
||||
picks_json = json.dumps(data["picks"], ensure_ascii=False)
|
||||
narrative_json = json.dumps(data["narrative"], ensure_ascii=False)
|
||||
tier_rationale_json = json.dumps(data.get("tier_rationale") or {}, ensure_ascii=False)
|
||||
with _conn() as conn:
|
||||
cur = conn.execute(
|
||||
"""
|
||||
INSERT INTO lotto_briefings
|
||||
(draw_no, picks, narrative, confidence, model,
|
||||
tokens_input, tokens_output, cache_read, cache_write,
|
||||
latency_ms, source, tier_rationale)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(draw_no) DO UPDATE SET
|
||||
picks=excluded.picks,
|
||||
narrative=excluded.narrative,
|
||||
confidence=excluded.confidence,
|
||||
model=excluded.model,
|
||||
tokens_input=excluded.tokens_input,
|
||||
tokens_output=excluded.tokens_output,
|
||||
cache_read=excluded.cache_read,
|
||||
cache_write=excluded.cache_write,
|
||||
latency_ms=excluded.latency_ms,
|
||||
source=excluded.source,
|
||||
tier_rationale=excluded.tier_rationale,
|
||||
generated_at=datetime('now','localtime')
|
||||
""",
|
||||
(
|
||||
data["draw_no"], picks_json, narrative_json,
|
||||
data["confidence"], data["model"],
|
||||
data.get("tokens_input", 0), data.get("tokens_output", 0),
|
||||
data.get("cache_read", 0), data.get("cache_write", 0),
|
||||
data.get("latency_ms", 0), data.get("source", "auto"),
|
||||
tier_rationale_json,
|
||||
),
|
||||
)
|
||||
return cur.lastrowid
|
||||
|
||||
|
||||
def _briefing_row(r) -> Dict[str, Any]:
|
||||
return {
|
||||
"id": r["id"],
|
||||
"draw_no": r["draw_no"],
|
||||
"picks": json.loads(r["picks"]),
|
||||
"narrative": json.loads(r["narrative"]),
|
||||
"tier_rationale": json.loads(r["tier_rationale"]) if r["tier_rationale"] else {},
|
||||
"confidence": r["confidence"],
|
||||
"model": r["model"],
|
||||
"tokens_input": r["tokens_input"],
|
||||
"tokens_output": r["tokens_output"],
|
||||
"cache_read": r["cache_read"],
|
||||
"cache_write": r["cache_write"],
|
||||
"latency_ms": r["latency_ms"],
|
||||
"source": r["source"],
|
||||
"generated_at": r["generated_at"],
|
||||
}
|
||||
|
||||
|
||||
def get_latest_briefing() -> Optional[Dict[str, Any]]:
|
||||
with _conn() as conn:
|
||||
r = conn.execute("SELECT * FROM lotto_briefings ORDER BY draw_no DESC LIMIT 1").fetchone()
|
||||
return _briefing_row(r) if r else None
|
||||
|
||||
|
||||
def get_briefing(draw_no: int) -> Optional[Dict[str, Any]]:
|
||||
with _conn() as conn:
|
||||
r = conn.execute("SELECT * FROM lotto_briefings WHERE draw_no=?", (draw_no,)).fetchone()
|
||||
return _briefing_row(r) if r else None
|
||||
|
||||
|
||||
def list_briefings(limit: int = 10) -> List[Dict[str, Any]]:
|
||||
with _conn() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM lotto_briefings ORDER BY draw_no DESC LIMIT ?",
|
||||
(limit,),
|
||||
).fetchall()
|
||||
return [_briefing_row(r) for r in rows]
|
||||
|
||||
|
||||
def get_curator_usage(days: int = 30) -> Dict[str, Any]:
|
||||
with _conn() as conn:
|
||||
r = conn.execute("""
|
||||
SELECT COUNT(*) AS calls,
|
||||
SUM(tokens_input) AS in_tokens,
|
||||
SUM(tokens_output) AS out_tokens,
|
||||
SUM(cache_read) AS cache_read,
|
||||
SUM(cache_write) AS cache_write,
|
||||
AVG(latency_ms) AS avg_latency
|
||||
FROM lotto_briefings
|
||||
WHERE generated_at >= datetime('now', ?, 'localtime')
|
||||
""", (f"-{int(days)} days",)).fetchone()
|
||||
cr = int(r["cache_read"] or 0)
|
||||
cw = int(r["cache_write"] or 0)
|
||||
return {
|
||||
"days": days,
|
||||
"calls": int(r["calls"] or 0),
|
||||
"tokens_input": int(r["in_tokens"] or 0),
|
||||
"tokens_output": int(r["out_tokens"] or 0),
|
||||
"cache_read": cr,
|
||||
"cache_write": cw,
|
||||
"cache_hit_rate": round(cr / (cr + cw), 3) if (cr + cw) > 0 else 0.0,
|
||||
"avg_latency_ms": round(float(r["avg_latency"] or 0), 1),
|
||||
}
|
||||
|
||||
|
||||
def save_review(data: Dict[str, Any]) -> int:
|
||||
with _conn() as conn:
|
||||
cur = conn.execute(
|
||||
"""
|
||||
INSERT INTO weekly_review (
|
||||
draw_no,
|
||||
curator_avg_match, curator_best_tier, curator_best_match, curator_5plus_prizes,
|
||||
user_avg_match, user_best_match, user_5plus_prizes,
|
||||
user_pattern_summary, draw_pattern_summary, pattern_delta
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(draw_no) DO UPDATE SET
|
||||
curator_avg_match=excluded.curator_avg_match,
|
||||
curator_best_tier=excluded.curator_best_tier,
|
||||
curator_best_match=excluded.curator_best_match,
|
||||
curator_5plus_prizes=excluded.curator_5plus_prizes,
|
||||
user_avg_match=excluded.user_avg_match,
|
||||
user_best_match=excluded.user_best_match,
|
||||
user_5plus_prizes=excluded.user_5plus_prizes,
|
||||
user_pattern_summary=excluded.user_pattern_summary,
|
||||
draw_pattern_summary=excluded.draw_pattern_summary,
|
||||
pattern_delta=excluded.pattern_delta
|
||||
""",
|
||||
(
|
||||
data["draw_no"],
|
||||
data.get("curator_avg_match"), data.get("curator_best_tier"),
|
||||
data.get("curator_best_match"), data.get("curator_5plus_prizes"),
|
||||
data.get("user_avg_match"), data.get("user_best_match"),
|
||||
data.get("user_5plus_prizes"),
|
||||
data.get("user_pattern_summary"), data.get("draw_pattern_summary"),
|
||||
data.get("pattern_delta"),
|
||||
),
|
||||
)
|
||||
return cur.lastrowid
|
||||
|
||||
|
||||
def _review_row(r) -> Optional[Dict[str, Any]]:
|
||||
if not r:
|
||||
return None
|
||||
return {
|
||||
"id": r["id"],
|
||||
"draw_no": r["draw_no"],
|
||||
"curator_avg_match": r["curator_avg_match"],
|
||||
"curator_best_tier": r["curator_best_tier"],
|
||||
"curator_best_match": r["curator_best_match"],
|
||||
"curator_5plus_prizes": r["curator_5plus_prizes"],
|
||||
"user_avg_match": r["user_avg_match"],
|
||||
"user_best_match": r["user_best_match"],
|
||||
"user_5plus_prizes": r["user_5plus_prizes"],
|
||||
"user_pattern_summary": r["user_pattern_summary"],
|
||||
"draw_pattern_summary": r["draw_pattern_summary"],
|
||||
"pattern_delta": r["pattern_delta"],
|
||||
"created_at": r["created_at"],
|
||||
}
|
||||
|
||||
|
||||
def get_review(draw_no: int) -> Optional[Dict[str, Any]]:
|
||||
with _conn() as conn:
|
||||
r = conn.execute("SELECT * FROM weekly_review WHERE draw_no=?", (draw_no,)).fetchone()
|
||||
return _review_row(r)
|
||||
|
||||
|
||||
def get_latest_review() -> Optional[Dict[str, Any]]:
|
||||
with _conn() as conn:
|
||||
r = conn.execute("SELECT * FROM weekly_review ORDER BY draw_no DESC LIMIT 1").fetchone()
|
||||
return _review_row(r)
|
||||
|
||||
|
||||
def get_reviews_range(start_drw: int, end_drw: int) -> List[Dict[str, Any]]:
|
||||
with _conn() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM weekly_review WHERE draw_no BETWEEN ? AND ? ORDER BY draw_no ASC",
|
||||
(start_drw, end_drw),
|
||||
).fetchall()
|
||||
return [_review_row(r) for r in rows]
|
||||
|
||||
|
||||
def list_reviews(limit: int = 10) -> List[Dict[str, Any]]:
|
||||
with _conn() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM weekly_review ORDER BY draw_no DESC LIMIT ?",
|
||||
(limit,),
|
||||
).fetchall()
|
||||
return [_review_row(r) for r in rows]
|
||||
|
||||
@@ -15,11 +15,14 @@ from .db import (
|
||||
update_recommendation,
|
||||
# 시뮬레이션 관련
|
||||
get_best_picks, get_simulation_runs, get_simulation_candidates,
|
||||
# todos
|
||||
get_all_todos, create_todo, update_todo, delete_todo, delete_done_todos,
|
||||
# blog
|
||||
get_all_posts, create_post, update_post, delete_post,
|
||||
# 성과 통계
|
||||
get_recommendation_performance,
|
||||
# Phase 2: 구매 이력
|
||||
add_purchase, get_purchases, update_purchase, delete_purchase, get_purchase_stats,
|
||||
bulk_insert_purchases_from_briefing,
|
||||
# Phase 2: 주간 리포트 캐시
|
||||
save_weekly_report, get_weekly_report_list, get_weekly_report,
|
||||
# Phase 2: 개인 패턴 분석
|
||||
@@ -38,15 +41,8 @@ from .strategy_evolver import (
|
||||
get_weights_with_trend, recalculate_weights,
|
||||
generate_smart_recommendation,
|
||||
)
|
||||
from .routers import curator as curator_router
|
||||
from .routers import briefing as briefing_router
|
||||
from .routers import review as review_router
|
||||
from .jobs.grade_weekly_review import run_for_latest as grade_run_for_latest
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(curator_router.router)
|
||||
app.include_router(briefing_router.router)
|
||||
app.include_router(review_router.router)
|
||||
scheduler = BackgroundScheduler(timezone=os.getenv("TZ", "Asia/Seoul"))
|
||||
|
||||
ALL_URL = os.getenv("LOTTO_ALL_URL", "https://smok95.github.io/lotto/results/all.json")
|
||||
@@ -99,17 +95,6 @@ def on_startup():
|
||||
|
||||
scheduler.add_job(_save_weekly_report_job, "cron", day_of_week="sat", hour=9, minute=0)
|
||||
|
||||
# 4. 주간 채점 (매주 일요일 03:00 KST — 토요일 추첨 다음날 새벽)
|
||||
# 당첨번호 sync 이후 추천 vs 실제 결과 비교 → reviews 테이블 저장
|
||||
scheduler.add_job(
|
||||
grade_run_for_latest,
|
||||
"cron",
|
||||
day_of_week="sun",
|
||||
hour=3,
|
||||
minute=0,
|
||||
id="grade_weekly_review",
|
||||
)
|
||||
|
||||
scheduler.start()
|
||||
|
||||
|
||||
@@ -344,22 +329,6 @@ def api_purchase_delete(purchase_id: int):
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
class BulkPurchaseRequest(BaseModel):
|
||||
draw_no: int
|
||||
tier_mode: str # core | core_bonus | core_bonus_extended | full
|
||||
sets: int # 검증용 — 실제 INSERT는 briefing 기준
|
||||
amount: int # 검증용
|
||||
|
||||
|
||||
@app.post("/api/lotto/purchase/bulk", status_code=201)
|
||||
def api_purchase_bulk(body: BulkPurchaseRequest):
|
||||
"""결정카드 원클릭 기록 — 큐레이터 브리핑 picks 를 tier_mode 기준으로 일괄 기록."""
|
||||
result = bulk_insert_purchases_from_briefing(body.draw_no, body.tier_mode, body.amount)
|
||||
if not result["ok"]:
|
||||
raise HTTPException(status_code=400, detail=result["reason"])
|
||||
return result
|
||||
|
||||
|
||||
# ── 전략 진화 API ──────────────────────────────────────────────────────────
|
||||
|
||||
@app.get("/api/lotto/strategy/weights")
|
||||
@@ -866,3 +835,99 @@ def version():
|
||||
return {"version": os.getenv("APP_VERSION", "dev")}
|
||||
|
||||
|
||||
# ── Todos API ─────────────────────────────────────────────────────────────────
|
||||
|
||||
class TodoCreate(BaseModel):
|
||||
title: str
|
||||
description: Optional[str] = None
|
||||
status: str = "todo"
|
||||
|
||||
|
||||
class TodoUpdate(BaseModel):
|
||||
title: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
status: Optional[str] = None
|
||||
|
||||
|
||||
@app.get("/api/todos")
|
||||
def api_todos_list():
|
||||
return get_all_todos()
|
||||
|
||||
|
||||
@app.post("/api/todos", status_code=201)
|
||||
def api_todos_create(body: TodoCreate):
|
||||
if body.status not in ("todo", "in_progress", "done"):
|
||||
raise HTTPException(status_code=422, detail="status must be todo | in_progress | done")
|
||||
return create_todo(body.title, body.description, body.status)
|
||||
|
||||
|
||||
# ⚠️ /done 라우트를 /{todo_id} 보다 먼저 등록해야 done이 id로 매칭되지 않음
|
||||
@app.delete("/api/todos/done")
|
||||
def api_todos_delete_done():
|
||||
deleted = delete_done_todos()
|
||||
return {"deleted": deleted}
|
||||
|
||||
|
||||
@app.put("/api/todos/{todo_id}")
|
||||
def api_todos_update(todo_id: str, body: TodoUpdate):
|
||||
if body.status is not None and body.status not in ("todo", "in_progress", "done"):
|
||||
raise HTTPException(status_code=422, detail="status must be todo | in_progress | done")
|
||||
updated = update_todo(todo_id, body.model_dump(exclude_none=True))
|
||||
if updated is None:
|
||||
raise HTTPException(status_code=404, detail="Todo not found")
|
||||
return updated
|
||||
|
||||
|
||||
@app.delete("/api/todos/{todo_id}")
|
||||
def api_todos_delete(todo_id: str):
|
||||
ok = delete_todo(todo_id)
|
||||
if not ok:
|
||||
raise HTTPException(status_code=404, detail="Todo not found")
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
# ── Blog API ──────────────────────────────────────────────────────────────────
|
||||
|
||||
class BlogPostCreate(BaseModel):
|
||||
title: str
|
||||
body: str = ""
|
||||
excerpt: str = ""
|
||||
tags: List[str] = []
|
||||
date: str = "" # 빈 문자열이면 오늘 날짜 사용
|
||||
|
||||
|
||||
class BlogPostUpdate(BaseModel):
|
||||
title: Optional[str] = None
|
||||
body: Optional[str] = None
|
||||
excerpt: Optional[str] = None
|
||||
tags: Optional[List[str]] = None
|
||||
date: Optional[str] = None
|
||||
|
||||
|
||||
@app.get("/api/blog/posts")
|
||||
def api_blog_list():
|
||||
return {"posts": get_all_posts()}
|
||||
|
||||
|
||||
@app.post("/api/blog/posts", status_code=201)
|
||||
def api_blog_create(body: BlogPostCreate):
|
||||
from datetime import date as _date
|
||||
post_date = body.date if body.date else _date.today().isoformat()
|
||||
post = create_post(body.title, body.body, body.excerpt, body.tags, post_date)
|
||||
return post
|
||||
|
||||
|
||||
@app.put("/api/blog/posts/{post_id}")
|
||||
def api_blog_update(post_id: int, body: BlogPostUpdate):
|
||||
updated = update_post(post_id, body.model_dump(exclude_none=True))
|
||||
if updated is None:
|
||||
raise HTTPException(status_code=404, detail="Post not found")
|
||||
return updated
|
||||
|
||||
|
||||
@app.delete("/api/blog/posts/{post_id}")
|
||||
def api_blog_delete(post_id: int):
|
||||
ok = delete_post(post_id)
|
||||
if not ok:
|
||||
raise HTTPException(status_code=404, detail="Post not found")
|
||||
return {"ok": True}
|
||||
@@ -97,20 +97,3 @@ def check_purchases_for_draw(drw_no: int) -> int:
|
||||
|
||||
logger.info(f"[purchase_manager] {drw_no}회차 구매 {count}건 체크 완료")
|
||||
return count
|
||||
|
||||
|
||||
def get_recent_performance(limit: int = 3) -> list:
|
||||
"""최근 N회차 내 구매 성과 요약. 없으면 빈 리스트."""
|
||||
from . import db
|
||||
purchases = db.get_purchases() or []
|
||||
by_draw: dict = {}
|
||||
for p in purchases:
|
||||
d = p.get("draw_no")
|
||||
if not d:
|
||||
continue
|
||||
results = p.get("results") or []
|
||||
max_correct = max((int(r.get("correct") or 0) for r in results), default=0)
|
||||
slot = by_draw.setdefault(d, {"draw_no": d, "purchased_sets": 0, "best_match": 0})
|
||||
slot["purchased_sets"] += int(p.get("sets") or 1)
|
||||
slot["best_match"] = max(slot["best_match"], max_correct)
|
||||
return sorted(by_draw.values(), key=lambda x: -x["draw_no"])[:limit]
|
||||
@@ -1,6 +1,5 @@
|
||||
fastapi==0.115.6
|
||||
uvicorn[standard]==0.30.6
|
||||
requests==2.32.3
|
||||
httpx==0.27.2
|
||||
beautifulsoup4==4.12.3
|
||||
APScheduler==3.10.4
|
||||
4
blog-lab/.dockerignore
Normal file
4
blog-lab/.dockerignore
Normal file
@@ -0,0 +1,4 @@
|
||||
__pycache__
|
||||
*.pyc
|
||||
.env
|
||||
data/
|
||||
@@ -2,9 +2,14 @@ FROM python:3.12-alpine
|
||||
ENV PYTHONUNBUFFERED=1
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
RUN apk add --no-cache gcc musl-dev
|
||||
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY . .
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||
15
blog-lab/app/config.py
Normal file
15
blog-lab/app/config.py
Normal file
@@ -0,0 +1,15 @@
|
||||
import os
|
||||
|
||||
# Anthropic Claude API
|
||||
ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY", "")
|
||||
CLAUDE_MODEL = os.getenv("CLAUDE_MODEL", "claude-sonnet-4-20250514")
|
||||
|
||||
# Naver Search API
|
||||
NAVER_CLIENT_ID = os.getenv("NAVER_CLIENT_ID", "")
|
||||
NAVER_CLIENT_SECRET = os.getenv("NAVER_CLIENT_SECRET", "")
|
||||
|
||||
# Database
|
||||
DB_PATH = os.getenv("BLOG_DB_PATH", "/app/data/blog_marketing.db")
|
||||
|
||||
# CORS
|
||||
CORS_ALLOW_ORIGINS = os.getenv("CORS_ALLOW_ORIGINS", "http://localhost:3007,http://localhost:8080")
|
||||
172
blog-lab/app/content_generator.py
Normal file
172
blog-lab/app/content_generator.py
Normal file
@@ -0,0 +1,172 @@
|
||||
"""Claude API 기반 콘텐츠 생성 — 트렌드 브리프 + 블로그 글 작성."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from datetime import date
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
import anthropic
|
||||
|
||||
from .config import ANTHROPIC_API_KEY, CLAUDE_MODEL
|
||||
from .db import get_template
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_client: Optional[anthropic.Anthropic] = None
|
||||
|
||||
|
||||
def _get_client() -> anthropic.Anthropic:
|
||||
global _client
|
||||
if _client is None:
|
||||
_client = anthropic.Anthropic(api_key=ANTHROPIC_API_KEY)
|
||||
return _client
|
||||
|
||||
|
||||
def _call_claude(prompt: str, max_tokens: int = 4096) -> str:
|
||||
"""Claude API 호출. 단일 user 메시지. 현재 날짜 시스템 프롬프트 포함."""
|
||||
client = _get_client()
|
||||
today = date.today().isoformat()
|
||||
resp = client.messages.create(
|
||||
model=CLAUDE_MODEL,
|
||||
max_tokens=max_tokens,
|
||||
system=f"현재 날짜는 {today}입니다. 모든 콘텐츠는 이 날짜 기준으로 작성하세요.",
|
||||
messages=[{"role": "user", "content": prompt}],
|
||||
)
|
||||
return resp.content[0].text
|
||||
|
||||
|
||||
def generate_trend_brief(analysis: Dict[str, Any]) -> str:
|
||||
"""키워드 분석 데이터를 바탕으로 트렌드 브리프 생성."""
|
||||
template = get_template("trend_brief")
|
||||
if not template:
|
||||
raise RuntimeError("trend_brief 템플릿이 없습니다")
|
||||
|
||||
top_blogs_text = "\n".join(
|
||||
f"- {b.get('title', '')}" for b in analysis.get("top_blogs", [])
|
||||
) or "없음"
|
||||
|
||||
top_products_text = "\n".join(
|
||||
f"- {p.get('title', '')} ({p.get('lprice', '?')}원, {p.get('mallName', '')})"
|
||||
for p in analysis.get("top_products", [])
|
||||
) or "없음"
|
||||
|
||||
prompt = template.format(
|
||||
keyword=analysis.get("keyword", ""),
|
||||
competition=analysis.get("competition", 0),
|
||||
opportunity=analysis.get("opportunity", 0),
|
||||
top_blogs=top_blogs_text,
|
||||
top_products=top_products_text,
|
||||
)
|
||||
|
||||
return _call_claude(prompt)
|
||||
|
||||
|
||||
def _parse_blog_json(raw: str, keyword: str) -> Dict[str, str]:
|
||||
"""Claude 응답에서 블로그 JSON을 파싱."""
|
||||
try:
|
||||
text = raw.strip()
|
||||
if text.startswith("```"):
|
||||
lines = text.split("\n")
|
||||
lines = [l for l in lines if not l.strip().startswith("```")]
|
||||
text = "\n".join(lines)
|
||||
result = json.loads(text)
|
||||
return {
|
||||
"title": result.get("title", ""),
|
||||
"body": result.get("body", ""),
|
||||
"excerpt": result.get("excerpt", ""),
|
||||
"tags": result.get("tags", []),
|
||||
}
|
||||
except (json.JSONDecodeError, KeyError):
|
||||
logger.warning("Blog post JSON parse failed, using raw text")
|
||||
return {
|
||||
"title": f"{keyword} 추천 리뷰",
|
||||
"body": raw,
|
||||
"excerpt": raw[:200],
|
||||
"tags": [keyword],
|
||||
}
|
||||
|
||||
|
||||
def generate_blog_post(
|
||||
analysis: Dict[str, Any],
|
||||
trend_brief: str,
|
||||
brand_links: Optional[list] = None,
|
||||
) -> Dict[str, str]:
|
||||
"""트렌드 브리프를 바탕으로 블로그 글 작성.
|
||||
|
||||
Returns:
|
||||
{"title": str, "body": str, "excerpt": str, "tags": [...]}
|
||||
"""
|
||||
template = get_template("blog_write")
|
||||
if not template:
|
||||
raise RuntimeError("blog_write 템플릿이 없습니다")
|
||||
|
||||
top_products_text = "\n".join(
|
||||
f"- {p.get('title', '')} ({p.get('lprice', '?')}원, {p.get('mallName', '')})"
|
||||
for p in analysis.get("top_products", [])
|
||||
) or "없음"
|
||||
|
||||
# 크롤링된 블로그 본문 참고 자료
|
||||
reference_blogs_text = ""
|
||||
for blog in analysis.get("top_blogs", []):
|
||||
content = blog.get("content", "")
|
||||
if content:
|
||||
reference_blogs_text += f"\n### {blog.get('title', '제목 없음')}\n{content}\n"
|
||||
if not reference_blogs_text:
|
||||
reference_blogs_text = "없음"
|
||||
|
||||
# 브랜드커넥트 링크 정보
|
||||
brand_products_text = ""
|
||||
if brand_links:
|
||||
for link in brand_links:
|
||||
brand_products_text += (
|
||||
f"- 상품명: {link.get('product_name', '')}\n"
|
||||
f" 설명: {link.get('description', '')}\n"
|
||||
f" 링크: {link.get('url', '')}\n"
|
||||
f" 배치 힌트: {link.get('placement_hint', '자연스럽게')}\n"
|
||||
)
|
||||
if not brand_products_text:
|
||||
brand_products_text = "없음 (제휴 링크 없이 일반 리뷰로 작성)"
|
||||
|
||||
prompt = template.format(
|
||||
keyword=analysis.get("keyword", ""),
|
||||
trend_brief=trend_brief,
|
||||
top_products=top_products_text,
|
||||
reference_blogs=reference_blogs_text,
|
||||
brand_products=brand_products_text,
|
||||
)
|
||||
|
||||
# 구조화된 응답을 위한 추가 지시
|
||||
prompt += (
|
||||
"\n\n---\n"
|
||||
"응답은 반드시 아래 JSON 형식으로 해주세요 (JSON만 출력, 다른 텍스트 없이):\n"
|
||||
'{"title": "블로그 제목", "body": "HTML 본문", "excerpt": "2줄 요약", '
|
||||
'"tags": ["태그1", "태그2", ...]}'
|
||||
)
|
||||
|
||||
raw = _call_claude(prompt, max_tokens=8192)
|
||||
return _parse_blog_json(raw, analysis.get("keyword", ""))
|
||||
|
||||
|
||||
def regenerate_blog_post(
|
||||
analysis: Dict[str, Any],
|
||||
trend_brief: str,
|
||||
previous_body: str,
|
||||
feedback: str,
|
||||
) -> Dict[str, str]:
|
||||
"""피드백을 반영하여 블로그 글 재생성."""
|
||||
prompt = (
|
||||
"당신은 네이버 블로그에서 월 100만 이상 수익을 올리는 전문 블로거입니다.\n"
|
||||
f"키워드: {analysis.get('keyword', '')}\n\n"
|
||||
f"이전에 작성한 글:\n{previous_body[:3000]}\n\n"
|
||||
f"리뷰어 피드백:\n{feedback}\n\n"
|
||||
"위 피드백을 반영하여 글을 개선해주세요.\n"
|
||||
"작성 규칙: 1인칭 체험기, 2,000자 이상, 자연스러운 구어체, "
|
||||
"제품 비교표 포함, 광고 고지 문구 포함.\n"
|
||||
"HTML 형식으로 작성하되, 네이버 블로그에서 바로 붙여넣기 가능한 형태로.\n\n"
|
||||
"---\n"
|
||||
"응답은 반드시 아래 JSON 형식으로 해주세요 (JSON만 출력):\n"
|
||||
'{"title": "블로그 제목", "body": "HTML 본문", "excerpt": "2줄 요약", '
|
||||
'"tags": ["태그1", "태그2", ...]}'
|
||||
)
|
||||
raw = _call_claude(prompt, max_tokens=8192)
|
||||
return _parse_blog_json(raw, analysis.get("keyword", ""))
|
||||
789
blog-lab/app/db.py
Normal file
789
blog-lab/app/db.py
Normal file
@@ -0,0 +1,789 @@
|
||||
import os
|
||||
import sqlite3
|
||||
import json
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from .config import DB_PATH
|
||||
|
||||
|
||||
def _conn() -> sqlite3.Connection:
|
||||
os.makedirs(os.path.dirname(DB_PATH), exist_ok=True)
|
||||
conn = sqlite3.connect(DB_PATH)
|
||||
conn.row_factory = sqlite3.Row
|
||||
conn.execute("PRAGMA journal_mode=WAL")
|
||||
return conn
|
||||
|
||||
|
||||
def init_db() -> None:
|
||||
with _conn() as conn:
|
||||
# 키워드/상품 분석 결과
|
||||
conn.execute("""
|
||||
CREATE TABLE IF NOT EXISTS keyword_analyses (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
keyword TEXT NOT NULL,
|
||||
blog_total INTEGER NOT NULL DEFAULT 0,
|
||||
shop_total INTEGER NOT NULL DEFAULT 0,
|
||||
competition REAL NOT NULL DEFAULT 0,
|
||||
opportunity REAL NOT NULL DEFAULT 0,
|
||||
avg_price INTEGER,
|
||||
min_price INTEGER,
|
||||
max_price INTEGER,
|
||||
top_products TEXT NOT NULL DEFAULT '[]',
|
||||
top_blogs TEXT NOT NULL DEFAULT '[]',
|
||||
ai_summary TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
|
||||
)
|
||||
""")
|
||||
conn.execute("CREATE INDEX IF NOT EXISTS idx_ka_created ON keyword_analyses(created_at DESC)")
|
||||
conn.execute("CREATE INDEX IF NOT EXISTS idx_ka_keyword ON keyword_analyses(keyword)")
|
||||
|
||||
# 블로그 포스트
|
||||
conn.execute("""
|
||||
CREATE TABLE IF NOT EXISTS blog_posts (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
keyword_id INTEGER REFERENCES keyword_analyses(id),
|
||||
title TEXT NOT NULL DEFAULT '',
|
||||
body TEXT NOT NULL DEFAULT '',
|
||||
excerpt TEXT NOT NULL DEFAULT '',
|
||||
tags TEXT NOT NULL DEFAULT '[]',
|
||||
status TEXT NOT NULL DEFAULT 'draft',
|
||||
review_score INTEGER,
|
||||
review_detail TEXT NOT NULL DEFAULT '{}',
|
||||
naver_url TEXT NOT NULL DEFAULT '',
|
||||
trend_brief TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
|
||||
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
|
||||
)
|
||||
""")
|
||||
conn.execute("CREATE INDEX IF NOT EXISTS idx_bp_created ON blog_posts(created_at DESC)")
|
||||
conn.execute("CREATE INDEX IF NOT EXISTS idx_bp_status ON blog_posts(status)")
|
||||
|
||||
# 수익(커미션) 추적
|
||||
conn.execute("""
|
||||
CREATE TABLE IF NOT EXISTS commissions (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
post_id INTEGER REFERENCES blog_posts(id),
|
||||
month TEXT NOT NULL,
|
||||
clicks INTEGER NOT NULL DEFAULT 0,
|
||||
purchases INTEGER NOT NULL DEFAULT 0,
|
||||
revenue INTEGER NOT NULL DEFAULT 0,
|
||||
note TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
|
||||
)
|
||||
""")
|
||||
conn.execute("CREATE INDEX IF NOT EXISTS idx_comm_month ON commissions(month)")
|
||||
conn.execute("CREATE INDEX IF NOT EXISTS idx_comm_post ON commissions(post_id)")
|
||||
|
||||
# 비동기 작업 상태 (research / generate / review)
|
||||
conn.execute("""
|
||||
CREATE TABLE IF NOT EXISTS generation_tasks (
|
||||
id TEXT PRIMARY KEY,
|
||||
type TEXT NOT NULL DEFAULT 'research',
|
||||
status TEXT NOT NULL DEFAULT 'queued',
|
||||
progress INTEGER NOT NULL DEFAULT 0,
|
||||
message TEXT NOT NULL DEFAULT '',
|
||||
result_id INTEGER,
|
||||
error TEXT,
|
||||
params TEXT NOT NULL DEFAULT '{}',
|
||||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
|
||||
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
|
||||
)
|
||||
""")
|
||||
conn.execute("CREATE INDEX IF NOT EXISTS idx_gt_created ON generation_tasks(created_at DESC)")
|
||||
|
||||
# AI 프롬프트 템플릿
|
||||
conn.execute("""
|
||||
CREATE TABLE IF NOT EXISTS prompt_templates (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL UNIQUE,
|
||||
description TEXT NOT NULL DEFAULT '',
|
||||
template TEXT NOT NULL DEFAULT '',
|
||||
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
|
||||
)
|
||||
""")
|
||||
|
||||
# 브랜드커넥트 제휴 링크
|
||||
conn.execute("""
|
||||
CREATE TABLE IF NOT EXISTS brand_links (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
post_id INTEGER REFERENCES blog_posts(id),
|
||||
keyword_id INTEGER REFERENCES keyword_analyses(id),
|
||||
url TEXT NOT NULL,
|
||||
product_name TEXT NOT NULL DEFAULT '',
|
||||
description TEXT NOT NULL DEFAULT '',
|
||||
placement_hint TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
|
||||
)
|
||||
""")
|
||||
conn.execute("CREATE INDEX IF NOT EXISTS idx_bl_post ON brand_links(post_id)")
|
||||
conn.execute("CREATE INDEX IF NOT EXISTS idx_bl_keyword ON brand_links(keyword_id)")
|
||||
|
||||
# 기본 프롬프트 템플릿 시딩 (존재하지 않을 때만)
|
||||
_seed_templates(conn)
|
||||
_migrate_templates(conn)
|
||||
|
||||
|
||||
def _seed_templates(conn: sqlite3.Connection) -> None:
|
||||
"""기본 프롬프트 템플릿을 DB에 시딩."""
|
||||
templates = [
|
||||
{
|
||||
"name": "trend_brief",
|
||||
"description": "네이버 블로그 트렌드 분석 + 제목/훅 전략 브리프",
|
||||
"template": (
|
||||
"당신은 네이버 블로그 마케팅 전문가입니다.\n"
|
||||
"아래 키워드 분석 데이터를 바탕으로 블로그 포스팅 전략 브리프를 작성하세요.\n\n"
|
||||
"키워드: {keyword}\n"
|
||||
"블로그 경쟁도: {competition} (0-100, 높을수록 경쟁 치열)\n"
|
||||
"쇼핑 기회 점수: {opportunity} (0-100, 높을수록 기회 큼)\n"
|
||||
"상위 블로그 제목들: {top_blogs}\n"
|
||||
"상위 상품들: {top_products}\n\n"
|
||||
"다음을 포함해주세요:\n"
|
||||
"1. 클릭을 유도하는 제목 공식 3가지\n"
|
||||
"2. 도입부 훅 전략 (공감형, 질문형, 충격형 중 추천)\n"
|
||||
"3. 추천 해시태그 5-10개\n"
|
||||
"4. 경쟁 분석 요약 (기존 글 대비 차별화 포인트)\n"
|
||||
"5. SEO 키워드 배치 전략"
|
||||
),
|
||||
},
|
||||
{
|
||||
"name": "blog_write",
|
||||
"description": "공감형 1인칭 체험기 블로그 글 작성",
|
||||
"template": (
|
||||
"당신은 네이버 블로그에서 월 100만 이상 수익을 올리는 전문 블로거입니다.\n"
|
||||
"아래 브리프를 바탕으로 블로그 글을 작성하세요.\n\n"
|
||||
"키워드: {keyword}\n"
|
||||
"트렌드 브리프: {trend_brief}\n"
|
||||
"상위 상품 정보: {top_products}\n\n"
|
||||
"작성 규칙:\n"
|
||||
"- 1인칭 체험기 형식 (\"제가 직접 써봤는데요\")\n"
|
||||
"- 1,500자 이상\n"
|
||||
"- 자연스러운 구어체 (네이버 블로그 톤)\n"
|
||||
"- 제품 비교표 포함 (마크다운 테이블)\n"
|
||||
"- 장단점 솔직하게 작성\n"
|
||||
"- 광고 고지 문구 포함: \"이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.\"\n"
|
||||
"- 추천 매트릭스 (가성비/품질/디자인 기준)\n"
|
||||
"- 자연스러운 CTA (구매 링크 유도)\n\n"
|
||||
"HTML 형식으로 작성하되, 네이버 블로그에서 바로 붙여넣기 가능한 형태로 만들어주세요."
|
||||
),
|
||||
},
|
||||
{
|
||||
"name": "quality_review",
|
||||
"description": "블로그 글 품질 리뷰 (6기준 × 10점)",
|
||||
"template": (
|
||||
"당신은 블로그 콘텐츠 품질 평가 전문가입니다.\n"
|
||||
"아래 블로그 글을 6가지 기준으로 평가해주세요.\n\n"
|
||||
"제목: {title}\n"
|
||||
"본문: {body}\n\n"
|
||||
"평가 기준 (각 1-10점):\n"
|
||||
"1. 독자 공감도 (empathy): 1인칭 체험기가 자연스럽고 공감되는가?\n"
|
||||
"2. 제목 클릭 유도력 (click_appeal): 검색 결과에서 클릭하고 싶은 제목인가?\n"
|
||||
"3. 구매 전환력 (conversion): 읽고 나서 제품을 사고 싶어지는가?\n"
|
||||
"4. SEO 최적화 (seo): 키워드 배치, 소제목, 길이가 적절한가?\n"
|
||||
"5. 형식 완성도 (format): 비교표, 이미지 설명, 단락 구성이 잘 되어있는가?\n"
|
||||
"6. 링크 자연스러움 (link_natural): 제휴 링크가 광고처럼 느껴지지 않고 자연스럽게 녹아있는가? (링크가 없으면 5점 기본)\n\n"
|
||||
"JSON 형식으로 응답:\n"
|
||||
"{{\n"
|
||||
" \"scores\": {{\n"
|
||||
" \"empathy\": N,\n"
|
||||
" \"click_appeal\": N,\n"
|
||||
" \"conversion\": N,\n"
|
||||
" \"seo\": N,\n"
|
||||
" \"format\": N,\n"
|
||||
" \"link_natural\": N\n"
|
||||
" }},\n"
|
||||
" \"total\": N,\n"
|
||||
" \"pass\": true/false,\n"
|
||||
" \"feedback\": \"개선 사항 설명\"\n"
|
||||
"}}"
|
||||
),
|
||||
},
|
||||
{
|
||||
"name": "marketer_enhance",
|
||||
"description": "마케터 전환율 강화 + 제휴 링크 삽입",
|
||||
"template": (
|
||||
"당신은 네이버 블로그 수익화 전문 마케터입니다.\n"
|
||||
"아래 블로그 초안에 제휴 링크를 자연스럽게 삽입하고 전환율을 강화하세요.\n\n"
|
||||
"=== 블로그 초안 ===\n{draft_body}\n\n"
|
||||
"=== 타겟 키워드 ===\n{keyword}\n\n"
|
||||
"=== 삽입할 제휴 링크 ===\n{brand_links_info}\n\n"
|
||||
"작업 규칙:\n"
|
||||
"- 제휴 링크를 <a href=\"URL\" target=\"_blank\">상품명</a> 형태로 본문 흐름에 맞게 2~3곳 삽입\n"
|
||||
"- 결론에 CTA(Call-to-Action) 블록 추가 (\"지금 확인하기\" 등)\n"
|
||||
"- 글 맨 아래에 광고 고지 문구 자동 삽입: \"이 포스팅은 브랜드로부터 소정의 수수료를 받을 수 있습니다\"\n"
|
||||
"- 작가의 1인칭 톤과 구어체를 유지\n"
|
||||
"- 과도한 광고 느낌 없이 자연스러운 추천 흐름 유지\n"
|
||||
"- 구매 심리를 자극하는 표현 강화 (한정 수량, 가격 비교, 실사용 만족도 등)\n"
|
||||
"- 배치 힌트가 있으면 참고하되, 문맥이 더 자연스러운 위치 우선\n"
|
||||
"- 기존 본문의 구조와 길이를 크게 변경하지 않음"
|
||||
),
|
||||
},
|
||||
]
|
||||
for t in templates:
|
||||
existing = conn.execute(
|
||||
"SELECT id FROM prompt_templates WHERE name = ?", (t["name"],)
|
||||
).fetchone()
|
||||
if not existing:
|
||||
conn.execute(
|
||||
"INSERT INTO prompt_templates (name, description, template) VALUES (?, ?, ?)",
|
||||
(t["name"], t["description"], t["template"]),
|
||||
)
|
||||
|
||||
|
||||
def _migrate_templates(conn: sqlite3.Connection) -> None:
|
||||
"""기존 템플릿을 최신 버전으로 업데이트."""
|
||||
new_blog_write = (
|
||||
"당신은 네이버 블로그에서 월 100만 이상 수익을 올리는 전문 블로거입니다.\n"
|
||||
"아래 브리프와 참고 자료를 바탕으로 블로그 글을 작성하세요.\n\n"
|
||||
"키워드: {keyword}\n"
|
||||
"트렌드 브리프: {trend_brief}\n\n"
|
||||
"=== 상위 블로그 참고 자료 ===\n"
|
||||
"{reference_blogs}\n\n"
|
||||
"=== 상위 상품 정보 ===\n"
|
||||
"{top_products}\n\n"
|
||||
"=== 제휴 상품 (브랜드커넥트 링크) ===\n"
|
||||
"{brand_products}\n\n"
|
||||
"작성 규칙:\n"
|
||||
"- 1인칭 체험기 형식 (\"제가 직접 써봤는데요\")\n"
|
||||
"- 2,000자 이상\n"
|
||||
"- 자연스러운 구어체 (네이버 블로그 톤)\n"
|
||||
"- 상위 블로그 참고하되 표절 금지 (자신만의 시각으로 재구성)\n"
|
||||
"- 제품 비교표 포함 (HTML 테이블)\n"
|
||||
"- 장단점 솔직하게 작성\n"
|
||||
"- 제휴 상품이 있으면 자연스럽게 체험 맥락에 녹여서 작성\n"
|
||||
"- 제휴 링크는 <a> 태그로 자연스럽게 삽입\n"
|
||||
"- 추천 매트릭스 (가성비/품질/디자인 기준)\n"
|
||||
"- 자연스러운 CTA (구매 링크 유도)\n\n"
|
||||
"HTML 형식으로 작성하되, 네이버 블로그에서 바로 붙여넣기 가능한 형태로 만들어주세요."
|
||||
)
|
||||
conn.execute(
|
||||
"UPDATE prompt_templates SET template = ?, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE name = 'blog_write'",
|
||||
(new_blog_write,),
|
||||
)
|
||||
|
||||
new_quality_review = (
|
||||
"당신은 블로그 콘텐츠 품질 평가 전문가입니다.\n"
|
||||
"아래 블로그 글을 6가지 기준으로 평가해주세요.\n\n"
|
||||
"제목: {title}\n"
|
||||
"본문: {body}\n\n"
|
||||
"평가 기준 (각 1-10점):\n"
|
||||
"1. 독자 공감도 (empathy): 1인칭 체험기가 자연스럽고 공감되는가?\n"
|
||||
"2. 제목 클릭 유도력 (click_appeal): 검색 결과에서 클릭하고 싶은 제목인가?\n"
|
||||
"3. 구매 전환력 (conversion): 읽고 나서 제품을 사고 싶어지는가?\n"
|
||||
"4. SEO 최적화 (seo): 키워드 배치, 소제목, 길이가 적절한가?\n"
|
||||
"5. 형식 완성도 (format): 비교표, 이미지 설명, 단락 구성이 잘 되어있는가?\n"
|
||||
"6. 링크 자연스러움 (link_natural): 제휴 링크가 광고처럼 느껴지지 않고 자연스럽게 녹아있는가? (링크가 없으면 5점 기본)\n\n"
|
||||
"JSON 형식으로 응답:\n"
|
||||
"{{\n"
|
||||
" \"scores\": {{\n"
|
||||
" \"empathy\": N,\n"
|
||||
" \"click_appeal\": N,\n"
|
||||
" \"conversion\": N,\n"
|
||||
" \"seo\": N,\n"
|
||||
" \"format\": N,\n"
|
||||
" \"link_natural\": N\n"
|
||||
" }},\n"
|
||||
" \"total\": N,\n"
|
||||
" \"pass\": true/false,\n"
|
||||
" \"feedback\": \"개선 사항 설명\"\n"
|
||||
"}}"
|
||||
)
|
||||
conn.execute(
|
||||
"UPDATE prompt_templates SET template = ?, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE name = 'quality_review'",
|
||||
(new_quality_review,),
|
||||
)
|
||||
|
||||
# marketer_enhance가 없으면 추가
|
||||
existing = conn.execute("SELECT id FROM prompt_templates WHERE name = 'marketer_enhance'").fetchone()
|
||||
if not existing:
|
||||
conn.execute(
|
||||
"INSERT INTO prompt_templates (name, description, template) VALUES (?, ?, ?)",
|
||||
("marketer_enhance", "마케터 전환율 강화 + 제휴 링크 삽입",
|
||||
"당신은 네이버 블로그 수익화 전문 마케터입니다.\n"
|
||||
"아래 블로그 초안에 제휴 링크를 자연스럽게 삽입하고 전환율을 강화하세요.\n\n"
|
||||
"=== 블로그 초안 ===\n{draft_body}\n\n"
|
||||
"=== 타겟 키워드 ===\n{keyword}\n\n"
|
||||
"=== 삽입할 제휴 링크 ===\n{brand_links_info}\n\n"
|
||||
"작업 규칙:\n"
|
||||
"- 제휴 링크를 <a href=\"URL\" target=\"_blank\">상품명</a> 형태로 본문 흐름에 맞게 2~3곳 삽입\n"
|
||||
"- 결론에 CTA(Call-to-Action) 블록 추가\n"
|
||||
"- 글 맨 아래에 광고 고지 문구 자동 삽입\n"
|
||||
"- 작가의 1인칭 톤과 구어체를 유지\n"
|
||||
"- 과도한 광고 느낌 없이 자연스러운 추천 흐름 유지"),
|
||||
)
|
||||
|
||||
|
||||
# ── keyword_analyses CRUD ────────────────────────────────────────────────────
|
||||
|
||||
def _ka_row_to_dict(r) -> Dict[str, Any]:
|
||||
return {
|
||||
"id": r["id"],
|
||||
"keyword": r["keyword"],
|
||||
"blog_total": r["blog_total"],
|
||||
"shop_total": r["shop_total"],
|
||||
"competition": r["competition"],
|
||||
"opportunity": r["opportunity"],
|
||||
"avg_price": r["avg_price"],
|
||||
"min_price": r["min_price"],
|
||||
"max_price": r["max_price"],
|
||||
"top_products": json.loads(r["top_products"]) if r["top_products"] else [],
|
||||
"top_blogs": json.loads(r["top_blogs"]) if r["top_blogs"] else [],
|
||||
"ai_summary": r["ai_summary"],
|
||||
"created_at": r["created_at"],
|
||||
}
|
||||
|
||||
|
||||
def add_keyword_analysis(data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
with _conn() as conn:
|
||||
conn.execute(
|
||||
"""INSERT INTO keyword_analyses
|
||||
(keyword, blog_total, shop_total, competition, opportunity,
|
||||
avg_price, min_price, max_price, top_products, top_blogs, ai_summary)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
|
||||
(
|
||||
data.get("keyword", ""),
|
||||
data.get("blog_total", 0),
|
||||
data.get("shop_total", 0),
|
||||
data.get("competition", 0),
|
||||
data.get("opportunity", 0),
|
||||
data.get("avg_price"),
|
||||
data.get("min_price"),
|
||||
data.get("max_price"),
|
||||
json.dumps(data.get("top_products", []), ensure_ascii=False),
|
||||
json.dumps(data.get("top_blogs", []), ensure_ascii=False),
|
||||
data.get("ai_summary", ""),
|
||||
),
|
||||
)
|
||||
row = conn.execute(
|
||||
"SELECT * FROM keyword_analyses WHERE rowid = last_insert_rowid()"
|
||||
).fetchone()
|
||||
return _ka_row_to_dict(row)
|
||||
|
||||
|
||||
def get_keyword_analysis(analysis_id: int) -> Optional[Dict[str, Any]]:
|
||||
with _conn() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT * FROM keyword_analyses WHERE id = ?", (analysis_id,)
|
||||
).fetchone()
|
||||
return _ka_row_to_dict(row) if row else None
|
||||
|
||||
|
||||
def get_keyword_analyses(limit: int = 30) -> List[Dict[str, Any]]:
|
||||
with _conn() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM keyword_analyses ORDER BY created_at DESC LIMIT ?", (limit,)
|
||||
).fetchall()
|
||||
return [_ka_row_to_dict(r) for r in rows]
|
||||
|
||||
|
||||
def delete_keyword_analysis(analysis_id: int) -> bool:
|
||||
with _conn() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT id FROM keyword_analyses WHERE id = ?", (analysis_id,)
|
||||
).fetchone()
|
||||
if not row:
|
||||
return False
|
||||
conn.execute("DELETE FROM keyword_analyses WHERE id = ?", (analysis_id,))
|
||||
return True
|
||||
|
||||
|
||||
# ── blog_posts CRUD ──────────────────────────────────────────────────────────
|
||||
|
||||
def _post_row_to_dict(r) -> Dict[str, Any]:
|
||||
return {
|
||||
"id": r["id"],
|
||||
"keyword_id": r["keyword_id"],
|
||||
"title": r["title"],
|
||||
"body": r["body"],
|
||||
"excerpt": r["excerpt"],
|
||||
"tags": json.loads(r["tags"]) if r["tags"] else [],
|
||||
"status": r["status"],
|
||||
"review_score": r["review_score"],
|
||||
"review_detail": json.loads(r["review_detail"]) if r["review_detail"] else {},
|
||||
"naver_url": r["naver_url"],
|
||||
"trend_brief": r["trend_brief"],
|
||||
"created_at": r["created_at"],
|
||||
"updated_at": r["updated_at"],
|
||||
}
|
||||
|
||||
|
||||
def add_post(data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
with _conn() as conn:
|
||||
conn.execute(
|
||||
"""INSERT INTO blog_posts
|
||||
(keyword_id, title, body, excerpt, tags, status, review_score,
|
||||
review_detail, naver_url, trend_brief)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
|
||||
(
|
||||
data.get("keyword_id"),
|
||||
data.get("title", ""),
|
||||
data.get("body", ""),
|
||||
data.get("excerpt", ""),
|
||||
json.dumps(data.get("tags", []), ensure_ascii=False),
|
||||
data.get("status", "draft"),
|
||||
data.get("review_score"),
|
||||
json.dumps(data.get("review_detail", {}), ensure_ascii=False),
|
||||
data.get("naver_url", ""),
|
||||
data.get("trend_brief", ""),
|
||||
),
|
||||
)
|
||||
row = conn.execute(
|
||||
"SELECT * FROM blog_posts WHERE rowid = last_insert_rowid()"
|
||||
).fetchone()
|
||||
return _post_row_to_dict(row)
|
||||
|
||||
|
||||
def get_post(post_id: int) -> Optional[Dict[str, Any]]:
|
||||
with _conn() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT * FROM blog_posts WHERE id = ?", (post_id,)
|
||||
).fetchone()
|
||||
return _post_row_to_dict(row) if row else None
|
||||
|
||||
|
||||
def get_posts(status: Optional[str] = None, limit: int = 50) -> List[Dict[str, Any]]:
|
||||
with _conn() as conn:
|
||||
if status:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM blog_posts WHERE status = ? ORDER BY created_at DESC LIMIT ?",
|
||||
(status, limit),
|
||||
).fetchall()
|
||||
else:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM blog_posts ORDER BY created_at DESC LIMIT ?", (limit,)
|
||||
).fetchall()
|
||||
return [_post_row_to_dict(r) for r in rows]
|
||||
|
||||
|
||||
def update_post(post_id: int, data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
||||
with _conn() as conn:
|
||||
fields = []
|
||||
values = []
|
||||
for k in ("title", "body", "excerpt", "status", "naver_url", "trend_brief"):
|
||||
if k in data:
|
||||
fields.append(f"{k} = ?")
|
||||
values.append(data[k])
|
||||
if "tags" in data:
|
||||
fields.append("tags = ?")
|
||||
values.append(json.dumps(data["tags"], ensure_ascii=False))
|
||||
if "review_score" in data:
|
||||
fields.append("review_score = ?")
|
||||
values.append(data["review_score"])
|
||||
if "review_detail" in data:
|
||||
fields.append("review_detail = ?")
|
||||
values.append(json.dumps(data["review_detail"], ensure_ascii=False))
|
||||
if not fields:
|
||||
return get_post(post_id)
|
||||
fields.append("updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')")
|
||||
values.append(post_id)
|
||||
conn.execute(
|
||||
f"UPDATE blog_posts SET {', '.join(fields)} WHERE id = ?", values
|
||||
)
|
||||
row = conn.execute(
|
||||
"SELECT * FROM blog_posts WHERE id = ?", (post_id,)
|
||||
).fetchone()
|
||||
return _post_row_to_dict(row) if row else None
|
||||
|
||||
|
||||
def delete_post(post_id: int) -> bool:
|
||||
with _conn() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT id FROM blog_posts WHERE id = ?", (post_id,)
|
||||
).fetchone()
|
||||
if not row:
|
||||
return False
|
||||
conn.execute("DELETE FROM blog_posts WHERE id = ?", (post_id,))
|
||||
return True
|
||||
|
||||
|
||||
# ── commissions CRUD ─────────────────────────────────────────────────────────
|
||||
|
||||
def _comm_row_to_dict(r) -> Dict[str, Any]:
|
||||
return {
|
||||
"id": r["id"],
|
||||
"post_id": r["post_id"],
|
||||
"month": r["month"],
|
||||
"clicks": r["clicks"],
|
||||
"purchases": r["purchases"],
|
||||
"revenue": r["revenue"],
|
||||
"note": r["note"],
|
||||
"created_at": r["created_at"],
|
||||
}
|
||||
|
||||
|
||||
def add_commission(data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
with _conn() as conn:
|
||||
conn.execute(
|
||||
"""INSERT INTO commissions (post_id, month, clicks, purchases, revenue, note)
|
||||
VALUES (?, ?, ?, ?, ?, ?)""",
|
||||
(
|
||||
data.get("post_id"),
|
||||
data.get("month", ""),
|
||||
data.get("clicks", 0),
|
||||
data.get("purchases", 0),
|
||||
data.get("revenue", 0),
|
||||
data.get("note", ""),
|
||||
),
|
||||
)
|
||||
row = conn.execute(
|
||||
"SELECT * FROM commissions WHERE rowid = last_insert_rowid()"
|
||||
).fetchone()
|
||||
return _comm_row_to_dict(row)
|
||||
|
||||
|
||||
def get_commissions(post_id: Optional[int] = None, limit: int = 100) -> List[Dict[str, Any]]:
|
||||
with _conn() as conn:
|
||||
if post_id:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM commissions WHERE post_id = ? ORDER BY month DESC LIMIT ?",
|
||||
(post_id, limit),
|
||||
).fetchall()
|
||||
else:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM commissions ORDER BY month DESC LIMIT ?", (limit,)
|
||||
).fetchall()
|
||||
return [_comm_row_to_dict(r) for r in rows]
|
||||
|
||||
|
||||
def update_commission(comm_id: int, data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
||||
with _conn() as conn:
|
||||
fields = []
|
||||
values = []
|
||||
for k in ("month", "clicks", "purchases", "revenue", "note"):
|
||||
if k in data:
|
||||
fields.append(f"{k} = ?")
|
||||
values.append(data[k])
|
||||
if not fields:
|
||||
return None
|
||||
values.append(comm_id)
|
||||
conn.execute(
|
||||
f"UPDATE commissions SET {', '.join(fields)} WHERE id = ?", values
|
||||
)
|
||||
row = conn.execute(
|
||||
"SELECT * FROM commissions WHERE id = ?", (comm_id,)
|
||||
).fetchone()
|
||||
return _comm_row_to_dict(row) if row else None
|
||||
|
||||
|
||||
def delete_commission(comm_id: int) -> bool:
|
||||
with _conn() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT id FROM commissions WHERE id = ?", (comm_id,)
|
||||
).fetchone()
|
||||
if not row:
|
||||
return False
|
||||
conn.execute("DELETE FROM commissions WHERE id = ?", (comm_id,))
|
||||
return True
|
||||
|
||||
|
||||
# ── brand_links CRUD ────────────────────────────────────────────────────────
|
||||
|
||||
def _bl_row_to_dict(r) -> Dict[str, Any]:
|
||||
return {
|
||||
"id": r["id"],
|
||||
"post_id": r["post_id"],
|
||||
"keyword_id": r["keyword_id"],
|
||||
"url": r["url"],
|
||||
"product_name": r["product_name"],
|
||||
"description": r["description"],
|
||||
"placement_hint": r["placement_hint"],
|
||||
"created_at": r["created_at"],
|
||||
}
|
||||
|
||||
|
||||
def add_brand_link(data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
with _conn() as conn:
|
||||
conn.execute(
|
||||
"""INSERT INTO brand_links (post_id, keyword_id, url, product_name, description, placement_hint)
|
||||
VALUES (?, ?, ?, ?, ?, ?)""",
|
||||
(
|
||||
data.get("post_id"),
|
||||
data.get("keyword_id"),
|
||||
data.get("url", ""),
|
||||
data.get("product_name", ""),
|
||||
data.get("description", ""),
|
||||
data.get("placement_hint", ""),
|
||||
),
|
||||
)
|
||||
row = conn.execute(
|
||||
"SELECT * FROM brand_links WHERE rowid = last_insert_rowid()"
|
||||
).fetchone()
|
||||
return _bl_row_to_dict(row)
|
||||
|
||||
|
||||
def get_brand_links(
|
||||
post_id: Optional[int] = None,
|
||||
keyword_id: Optional[int] = None,
|
||||
) -> List[Dict[str, Any]]:
|
||||
with _conn() as conn:
|
||||
if post_id is not None:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM brand_links WHERE post_id = ? ORDER BY id", (post_id,)
|
||||
).fetchall()
|
||||
elif keyword_id is not None:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM brand_links WHERE keyword_id = ? ORDER BY id", (keyword_id,)
|
||||
).fetchall()
|
||||
else:
|
||||
rows = conn.execute("SELECT * FROM brand_links ORDER BY id DESC LIMIT 100").fetchall()
|
||||
return [_bl_row_to_dict(r) for r in rows]
|
||||
|
||||
|
||||
def update_brand_link(link_id: int, data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
||||
with _conn() as conn:
|
||||
fields = []
|
||||
values = []
|
||||
for k in ("post_id", "keyword_id", "url", "product_name", "description", "placement_hint"):
|
||||
if k in data:
|
||||
fields.append(f"{k} = ?")
|
||||
values.append(data[k])
|
||||
if not fields:
|
||||
row = conn.execute("SELECT * FROM brand_links WHERE id = ?", (link_id,)).fetchone()
|
||||
return _bl_row_to_dict(row) if row else None
|
||||
values.append(link_id)
|
||||
conn.execute(f"UPDATE brand_links SET {', '.join(fields)} WHERE id = ?", values)
|
||||
row = conn.execute("SELECT * FROM brand_links WHERE id = ?", (link_id,)).fetchone()
|
||||
return _bl_row_to_dict(row) if row else None
|
||||
|
||||
|
||||
def delete_brand_link(link_id: int) -> bool:
|
||||
with _conn() as conn:
|
||||
row = conn.execute("SELECT id FROM brand_links WHERE id = ?", (link_id,)).fetchone()
|
||||
if not row:
|
||||
return False
|
||||
conn.execute("DELETE FROM brand_links WHERE id = ?", (link_id,))
|
||||
return True
|
||||
|
||||
|
||||
def link_brand_links_to_post(keyword_id: int, post_id: int) -> None:
|
||||
"""keyword_id로 등록된 링크들을 post_id에도 연결."""
|
||||
with _conn() as conn:
|
||||
conn.execute(
|
||||
"UPDATE brand_links SET post_id = ? WHERE keyword_id = ? AND post_id IS NULL",
|
||||
(post_id, keyword_id),
|
||||
)
|
||||
|
||||
|
||||
def get_dashboard_stats() -> Dict[str, Any]:
|
||||
"""대시보드 집계: 총 포스트/클릭/구매/수익 + 월별 추이."""
|
||||
with _conn() as conn:
|
||||
total_posts = conn.execute("SELECT COUNT(*) FROM blog_posts").fetchone()[0]
|
||||
published = conn.execute(
|
||||
"SELECT COUNT(*) FROM blog_posts WHERE status = 'published'"
|
||||
).fetchone()[0]
|
||||
|
||||
agg = conn.execute(
|
||||
"SELECT COALESCE(SUM(clicks),0), COALESCE(SUM(purchases),0), COALESCE(SUM(revenue),0) FROM commissions"
|
||||
).fetchone()
|
||||
|
||||
monthly = conn.execute(
|
||||
"""SELECT month, SUM(clicks) as clicks, SUM(purchases) as purchases, SUM(revenue) as revenue
|
||||
FROM commissions GROUP BY month ORDER BY month DESC LIMIT 12"""
|
||||
).fetchall()
|
||||
|
||||
top_posts = conn.execute(
|
||||
"""SELECT bp.id, bp.title, COALESCE(SUM(c.revenue),0) as total_revenue
|
||||
FROM blog_posts bp LEFT JOIN commissions c ON c.post_id = bp.id
|
||||
GROUP BY bp.id ORDER BY total_revenue DESC LIMIT 5"""
|
||||
).fetchall()
|
||||
|
||||
return {
|
||||
"total_posts": total_posts,
|
||||
"published_posts": published,
|
||||
"total_clicks": agg[0],
|
||||
"total_purchases": agg[1],
|
||||
"total_revenue": agg[2],
|
||||
"monthly": [
|
||||
{"month": r["month"], "clicks": r["clicks"], "purchases": r["purchases"], "revenue": r["revenue"]}
|
||||
for r in monthly
|
||||
],
|
||||
"top_posts": [
|
||||
{"id": r["id"], "title": r["title"], "total_revenue": r["total_revenue"]}
|
||||
for r in top_posts
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
# ── generation_tasks CRUD ────────────────────────────────────────────────────
|
||||
|
||||
def _task_row_to_dict(r) -> Dict[str, Any]:
|
||||
return {
|
||||
"task_id": r["id"],
|
||||
"type": r["type"],
|
||||
"status": r["status"],
|
||||
"progress": r["progress"],
|
||||
"message": r["message"],
|
||||
"result_id": r["result_id"],
|
||||
"error": r["error"],
|
||||
"params": json.loads(r["params"]) if r["params"] else {},
|
||||
"created_at": r["created_at"],
|
||||
"updated_at": r["updated_at"],
|
||||
}
|
||||
|
||||
|
||||
def create_task(task_id: str, task_type: str, params: Dict[str, Any]) -> Dict[str, Any]:
|
||||
with _conn() as conn:
|
||||
conn.execute(
|
||||
"INSERT INTO generation_tasks (id, type, params) VALUES (?, ?, ?)",
|
||||
(task_id, task_type, json.dumps(params, ensure_ascii=False)),
|
||||
)
|
||||
row = conn.execute(
|
||||
"SELECT * FROM generation_tasks WHERE id = ?", (task_id,)
|
||||
).fetchone()
|
||||
return _task_row_to_dict(row)
|
||||
|
||||
|
||||
def update_task(
|
||||
task_id: str,
|
||||
status: str,
|
||||
progress: int,
|
||||
message: str,
|
||||
result_id: Optional[int] = None,
|
||||
error: Optional[str] = None,
|
||||
) -> None:
|
||||
with _conn() as conn:
|
||||
conn.execute(
|
||||
"""UPDATE generation_tasks
|
||||
SET status = ?, progress = ?, message = ?, result_id = ?, error = ?,
|
||||
updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')
|
||||
WHERE id = ?""",
|
||||
(status, progress, message, result_id, error, task_id),
|
||||
)
|
||||
|
||||
|
||||
def get_task(task_id: str) -> Optional[Dict[str, Any]]:
|
||||
with _conn() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT * FROM generation_tasks WHERE id = ?", (task_id,)
|
||||
).fetchone()
|
||||
return _task_row_to_dict(row) if row else None
|
||||
|
||||
|
||||
# ── prompt_templates CRUD ────────────────────────────────────────────────────
|
||||
|
||||
def get_template(name: str) -> Optional[str]:
|
||||
with _conn() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT template FROM prompt_templates WHERE name = ?", (name,)
|
||||
).fetchone()
|
||||
return row["template"] if row else None
|
||||
|
||||
|
||||
def get_all_templates() -> List[Dict[str, Any]]:
|
||||
with _conn() as conn:
|
||||
rows = conn.execute("SELECT * FROM prompt_templates ORDER BY name").fetchall()
|
||||
return [
|
||||
{"id": r["id"], "name": r["name"], "description": r["description"],
|
||||
"template": r["template"], "updated_at": r["updated_at"]}
|
||||
for r in rows
|
||||
]
|
||||
|
||||
|
||||
def update_template(name: str, template: str) -> bool:
|
||||
with _conn() as conn:
|
||||
conn.execute(
|
||||
"UPDATE prompt_templates SET template = ?, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE name = ?",
|
||||
(template, name),
|
||||
)
|
||||
return conn.execute(
|
||||
"SELECT id FROM prompt_templates WHERE name = ?", (name,)
|
||||
).fetchone() is not None
|
||||
440
blog-lab/app/main.py
Normal file
440
blog-lab/app/main.py
Normal file
@@ -0,0 +1,440 @@
|
||||
import os
|
||||
import uuid
|
||||
import logging
|
||||
from fastapi import FastAPI, HTTPException, BackgroundTasks, Query
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from pydantic import BaseModel
|
||||
from typing import List, Optional
|
||||
|
||||
from .config import CORS_ALLOW_ORIGINS, NAVER_CLIENT_ID, ANTHROPIC_API_KEY
|
||||
from .db import (
|
||||
init_db,
|
||||
get_keyword_analyses, get_keyword_analysis, delete_keyword_analysis,
|
||||
add_keyword_analysis,
|
||||
get_posts, get_post, add_post, update_post, delete_post,
|
||||
get_commissions, add_commission, update_commission, delete_commission,
|
||||
get_dashboard_stats,
|
||||
get_task, create_task, update_task,
|
||||
add_brand_link, get_brand_links, update_brand_link, delete_brand_link,
|
||||
link_brand_links_to_post,
|
||||
)
|
||||
from .naver_search import analyze_keyword_with_crawling
|
||||
from .content_generator import generate_trend_brief, generate_blog_post, regenerate_blog_post
|
||||
from .quality_reviewer import review_post
|
||||
from .marketer import enhance_for_conversion
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
_cors_origins = CORS_ALLOW_ORIGINS.split(",")
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=[o.strip() for o in _cors_origins],
|
||||
allow_credentials=False,
|
||||
allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
|
||||
allow_headers=["Content-Type"],
|
||||
)
|
||||
|
||||
|
||||
@app.on_event("startup")
|
||||
def on_startup():
|
||||
init_db()
|
||||
os.makedirs("/app/data", exist_ok=True)
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
def health():
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@app.get("/api/blog-marketing/status")
|
||||
def service_status():
|
||||
"""서비스 상태 및 설정 현황."""
|
||||
return {
|
||||
"ok": True,
|
||||
"naver_api": bool(NAVER_CLIENT_ID),
|
||||
"claude_api": bool(ANTHROPIC_API_KEY),
|
||||
}
|
||||
|
||||
|
||||
# ── 키워드 분석 API ──────────────────────────────────────────────────────────
|
||||
|
||||
class ResearchRequest(BaseModel):
|
||||
keyword: str
|
||||
|
||||
|
||||
def _run_research(task_id: str, keyword: str):
|
||||
"""BackgroundTask: 네이버 검색 → 키워드 분석 → DB 저장."""
|
||||
try:
|
||||
update_task(task_id, "processing", 30, "네이버 검색 중...")
|
||||
result = analyze_keyword_with_crawling(keyword)
|
||||
|
||||
update_task(task_id, "processing", 80, "분석 결과 저장 중...")
|
||||
saved = add_keyword_analysis(result)
|
||||
|
||||
update_task(task_id, "succeeded", 100, "분석 완료", result_id=saved["id"])
|
||||
except Exception as e:
|
||||
logger.exception("Research failed for keyword=%s", keyword)
|
||||
update_task(task_id, "failed", 0, "", error=str(e))
|
||||
|
||||
|
||||
@app.post("/api/blog-marketing/research")
|
||||
def start_research(req: ResearchRequest, background_tasks: BackgroundTasks):
|
||||
"""키워드 분석 시작 (BackgroundTask). task_id 즉시 반환."""
|
||||
if not NAVER_CLIENT_ID:
|
||||
raise HTTPException(status_code=400, detail="Naver API 키가 설정되지 않았습니다")
|
||||
if not req.keyword.strip():
|
||||
raise HTTPException(status_code=400, detail="키워드를 입력하세요")
|
||||
|
||||
task_id = str(uuid.uuid4())
|
||||
create_task(task_id, "research", {"keyword": req.keyword.strip()})
|
||||
background_tasks.add_task(_run_research, task_id, req.keyword.strip())
|
||||
return {"task_id": task_id}
|
||||
|
||||
|
||||
@app.get("/api/blog-marketing/research/history")
|
||||
def list_research(limit: int = Query(30, ge=1, le=100)):
|
||||
return {"analyses": get_keyword_analyses(limit)}
|
||||
|
||||
|
||||
@app.get("/api/blog-marketing/research/{analysis_id}")
|
||||
def get_research(analysis_id: int):
|
||||
result = get_keyword_analysis(analysis_id)
|
||||
if not result:
|
||||
raise HTTPException(status_code=404, detail="Analysis not found")
|
||||
return result
|
||||
|
||||
|
||||
@app.delete("/api/blog-marketing/research/{analysis_id}")
|
||||
def remove_research(analysis_id: int):
|
||||
if not delete_keyword_analysis(analysis_id):
|
||||
raise HTTPException(status_code=404, detail="Analysis not found")
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
# ── 작업 상태 폴링 API ──────────────────────────────────────────────────────
|
||||
|
||||
@app.get("/api/blog-marketing/task/{task_id}")
|
||||
def get_task_status(task_id: str):
|
||||
task = get_task(task_id)
|
||||
if not task:
|
||||
raise HTTPException(status_code=404, detail="Task not found")
|
||||
return task
|
||||
|
||||
|
||||
# ── AI 글 생성 API ──────────────────────────────────────────────────────────
|
||||
|
||||
class GenerateRequest(BaseModel):
|
||||
keyword_id: int # keyword_analyses.id
|
||||
|
||||
|
||||
class LinkRequest(BaseModel):
|
||||
url: str
|
||||
product_name: str
|
||||
keyword_id: Optional[int] = None
|
||||
post_id: Optional[int] = None
|
||||
description: str = ""
|
||||
placement_hint: str = ""
|
||||
|
||||
|
||||
def _run_generate(task_id: str, keyword_id: int):
|
||||
"""BackgroundTask: 트렌드 브리프 → 블로그 글 생성 → DB 저장."""
|
||||
try:
|
||||
analysis = get_keyword_analysis(keyword_id)
|
||||
if not analysis:
|
||||
update_task(task_id, "failed", 0, "", error="키워드 분석 결과를 찾을 수 없습니다")
|
||||
return
|
||||
|
||||
# 연결된 브랜드커넥트 링크 조회
|
||||
brand_links = get_brand_links(keyword_id=keyword_id)
|
||||
|
||||
update_task(task_id, "processing", 20, "트렌드 브리프 생성 중...")
|
||||
trend_brief = generate_trend_brief(analysis)
|
||||
|
||||
update_task(task_id, "processing", 60, "블로그 글 작성 중...")
|
||||
post_data = generate_blog_post(analysis, trend_brief, brand_links=brand_links)
|
||||
|
||||
update_task(task_id, "processing", 90, "저장 중...")
|
||||
saved = add_post({
|
||||
"keyword_id": keyword_id,
|
||||
"title": post_data["title"],
|
||||
"body": post_data["body"],
|
||||
"excerpt": post_data["excerpt"],
|
||||
"tags": post_data["tags"],
|
||||
"status": "draft",
|
||||
"trend_brief": trend_brief,
|
||||
})
|
||||
|
||||
# keyword_id에 연결된 링크를 post_id에도 연결
|
||||
link_brand_links_to_post(keyword_id=keyword_id, post_id=saved["id"])
|
||||
|
||||
update_task(task_id, "succeeded", 100, "글 생성 완료", result_id=saved["id"])
|
||||
except Exception as e:
|
||||
logger.exception("Generate failed for keyword_id=%s", keyword_id)
|
||||
update_task(task_id, "failed", 0, "", error=str(e))
|
||||
|
||||
|
||||
@app.post("/api/blog-marketing/generate")
|
||||
def start_generate(req: GenerateRequest, background_tasks: BackgroundTasks):
|
||||
"""AI 블로그 글 생성 시작. task_id 즉시 반환."""
|
||||
if not ANTHROPIC_API_KEY:
|
||||
raise HTTPException(status_code=400, detail="Claude API 키가 설정되지 않았습니다")
|
||||
analysis = get_keyword_analysis(req.keyword_id)
|
||||
if not analysis:
|
||||
raise HTTPException(status_code=404, detail="키워드 분석 결과를 찾을 수 없습니다")
|
||||
|
||||
task_id = str(uuid.uuid4())
|
||||
create_task(task_id, "generate", {"keyword_id": req.keyword_id})
|
||||
background_tasks.add_task(_run_generate, task_id, req.keyword_id)
|
||||
return {"task_id": task_id}
|
||||
|
||||
|
||||
# ── 품질 리뷰 API ───────────────────────────────────────────────────────────
|
||||
|
||||
def _run_review(task_id: str, post_id: int):
|
||||
"""BackgroundTask: 블로그 글 품질 리뷰."""
|
||||
try:
|
||||
post = get_post(post_id)
|
||||
if not post:
|
||||
update_task(task_id, "failed", 0, "", error="포스트를 찾을 수 없습니다")
|
||||
return
|
||||
|
||||
update_task(task_id, "processing", 50, "품질 리뷰 중...")
|
||||
result = review_post(post["title"], post["body"])
|
||||
|
||||
update_post(post_id, {
|
||||
"review_score": result["total"],
|
||||
"review_detail": result,
|
||||
"status": "reviewed" if result["pass"] else "draft",
|
||||
})
|
||||
|
||||
update_task(task_id, "succeeded", 100, "리뷰 완료", result_id=post_id)
|
||||
except Exception as e:
|
||||
logger.exception("Review failed for post_id=%s", post_id)
|
||||
update_task(task_id, "failed", 0, "", error=str(e))
|
||||
|
||||
|
||||
@app.post("/api/blog-marketing/review/{post_id}")
|
||||
def start_review(post_id: int, background_tasks: BackgroundTasks):
|
||||
"""블로그 글 품질 리뷰 시작. task_id 즉시 반환."""
|
||||
if not ANTHROPIC_API_KEY:
|
||||
raise HTTPException(status_code=400, detail="Claude API 키가 설정되지 않았습니다")
|
||||
post = get_post(post_id)
|
||||
if not post:
|
||||
raise HTTPException(status_code=404, detail="Post not found")
|
||||
|
||||
task_id = str(uuid.uuid4())
|
||||
create_task(task_id, "review", {"post_id": post_id})
|
||||
background_tasks.add_task(_run_review, task_id, post_id)
|
||||
return {"task_id": task_id}
|
||||
|
||||
|
||||
# ── 재생성 API ───────────────────────────────────────────────────────────────
|
||||
|
||||
def _run_regenerate(task_id: str, post_id: int):
|
||||
"""BackgroundTask: 피드백 기반 블로그 글 재생성."""
|
||||
try:
|
||||
post = get_post(post_id)
|
||||
if not post:
|
||||
update_task(task_id, "failed", 0, "", error="포스트를 찾을 수 없습니다")
|
||||
return
|
||||
|
||||
analysis = get_keyword_analysis(post["keyword_id"]) if post["keyword_id"] else {}
|
||||
feedback = post.get("review_detail", {}).get("feedback", "개선이 필요합니다")
|
||||
|
||||
update_task(task_id, "processing", 50, "글 재생성 중...")
|
||||
result = regenerate_blog_post(
|
||||
analysis or {"keyword": ""},
|
||||
post.get("trend_brief", ""),
|
||||
post["body"],
|
||||
feedback,
|
||||
)
|
||||
|
||||
update_post(post_id, {
|
||||
"title": result["title"],
|
||||
"body": result["body"],
|
||||
"excerpt": result["excerpt"],
|
||||
"tags": result["tags"],
|
||||
"status": "draft",
|
||||
"review_score": None,
|
||||
"review_detail": {},
|
||||
})
|
||||
|
||||
update_task(task_id, "succeeded", 100, "재생성 완료", result_id=post_id)
|
||||
except Exception as e:
|
||||
logger.exception("Regenerate failed for post_id=%s", post_id)
|
||||
update_task(task_id, "failed", 0, "", error=str(e))
|
||||
|
||||
|
||||
@app.post("/api/blog-marketing/regenerate/{post_id}")
|
||||
def start_regenerate(post_id: int, background_tasks: BackgroundTasks):
|
||||
"""피드백 기반 블로그 글 재생성. task_id 즉시 반환."""
|
||||
if not ANTHROPIC_API_KEY:
|
||||
raise HTTPException(status_code=400, detail="Claude API 키가 설정되지 않았습니다")
|
||||
post = get_post(post_id)
|
||||
if not post:
|
||||
raise HTTPException(status_code=404, detail="Post not found")
|
||||
|
||||
task_id = str(uuid.uuid4())
|
||||
create_task(task_id, "regenerate", {"post_id": post_id})
|
||||
background_tasks.add_task(_run_regenerate, task_id, post_id)
|
||||
return {"task_id": task_id}
|
||||
|
||||
|
||||
# ── 포스트 CRUD API ──────────────────────────────────────────────────────────
|
||||
|
||||
@app.get("/api/blog-marketing/posts")
|
||||
def list_posts(status: str = None, limit: int = Query(50, ge=1, le=100)):
|
||||
return {"posts": get_posts(status=status, limit=limit)}
|
||||
|
||||
|
||||
@app.get("/api/blog-marketing/posts/{post_id}")
|
||||
def get_post_detail(post_id: int):
|
||||
post = get_post(post_id)
|
||||
if not post:
|
||||
raise HTTPException(status_code=404, detail="Post not found")
|
||||
return post
|
||||
|
||||
|
||||
@app.put("/api/blog-marketing/posts/{post_id}")
|
||||
def edit_post(post_id: int, data: dict):
|
||||
result = update_post(post_id, data)
|
||||
if not result:
|
||||
raise HTTPException(status_code=404, detail="Post not found")
|
||||
return result
|
||||
|
||||
|
||||
@app.delete("/api/blog-marketing/posts/{post_id}")
|
||||
def remove_post(post_id: int):
|
||||
if not delete_post(post_id):
|
||||
raise HTTPException(status_code=404, detail="Post not found")
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@app.post("/api/blog-marketing/posts/{post_id}/publish")
|
||||
def publish_post(post_id: int, data: dict = None):
|
||||
"""네이버 URL 등록 + 상태를 published로 변경."""
|
||||
naver_url = (data or {}).get("naver_url", "")
|
||||
result = update_post(post_id, {"status": "published", "naver_url": naver_url})
|
||||
if not result:
|
||||
raise HTTPException(status_code=404, detail="Post not found")
|
||||
return result
|
||||
|
||||
|
||||
# ── 브랜드커넥트 링크 API ──────────────────────────────────────────────────
|
||||
|
||||
@app.post("/api/blog-marketing/links", status_code=201)
|
||||
def create_link(req: LinkRequest):
|
||||
return add_brand_link(req.model_dump())
|
||||
|
||||
|
||||
@app.get("/api/blog-marketing/links")
|
||||
def list_links(post_id: int = None, keyword_id: int = None):
|
||||
return {"links": get_brand_links(post_id=post_id, keyword_id=keyword_id)}
|
||||
|
||||
|
||||
@app.put("/api/blog-marketing/links/{link_id}")
|
||||
def edit_link(link_id: int, data: dict):
|
||||
result = update_brand_link(link_id, data)
|
||||
if not result:
|
||||
raise HTTPException(status_code=404, detail="Link not found")
|
||||
return result
|
||||
|
||||
|
||||
@app.delete("/api/blog-marketing/links/{link_id}")
|
||||
def remove_link(link_id: int):
|
||||
if not delete_brand_link(link_id):
|
||||
raise HTTPException(status_code=404, detail="Link not found")
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
# ── 마케터 API ──────────────────────────────────────────────────────────────
|
||||
|
||||
def _run_market(task_id: str, post_id: int):
|
||||
"""BackgroundTask: 마케터 전환율 강화."""
|
||||
try:
|
||||
post = get_post(post_id)
|
||||
if not post:
|
||||
update_task(task_id, "failed", 0, "", error="포스트를 찾을 수 없습니다")
|
||||
return
|
||||
|
||||
brand_links = get_brand_links(post_id=post_id)
|
||||
if not brand_links and post.get("keyword_id"):
|
||||
brand_links = get_brand_links(keyword_id=post["keyword_id"])
|
||||
|
||||
if not brand_links:
|
||||
update_task(task_id, "failed", 0, "", error="브랜드커넥트 링크가 없습니다. 먼저 링크를 등록하세요.")
|
||||
return
|
||||
|
||||
analysis = get_keyword_analysis(post["keyword_id"]) if post.get("keyword_id") else {}
|
||||
keyword = (analysis or {}).get("keyword", "")
|
||||
|
||||
update_task(task_id, "processing", 50, "마케터가 전환율 강화 중...")
|
||||
result = enhance_for_conversion(
|
||||
post_body=post["body"],
|
||||
post_title=post["title"],
|
||||
brand_links=brand_links,
|
||||
keyword=keyword,
|
||||
)
|
||||
|
||||
update_post(post_id, {
|
||||
"title": result["title"],
|
||||
"body": result["body"],
|
||||
"excerpt": result["excerpt"],
|
||||
"status": "marketed",
|
||||
})
|
||||
|
||||
update_task(task_id, "succeeded", 100, "마케팅 강화 완료", result_id=post_id)
|
||||
except Exception as e:
|
||||
logger.exception("Market failed for post_id=%s", post_id)
|
||||
update_task(task_id, "failed", 0, "", error=str(e))
|
||||
|
||||
|
||||
@app.post("/api/blog-marketing/market/{post_id}")
|
||||
def start_market(post_id: int, background_tasks: BackgroundTasks):
|
||||
"""마케터 단계 실행. task_id 즉시 반환."""
|
||||
if not ANTHROPIC_API_KEY:
|
||||
raise HTTPException(status_code=400, detail="Claude API 키가 설정되지 않았습니다")
|
||||
post = get_post(post_id)
|
||||
if not post:
|
||||
raise HTTPException(status_code=404, detail="Post not found")
|
||||
|
||||
task_id = str(uuid.uuid4())
|
||||
create_task(task_id, "market", {"post_id": post_id})
|
||||
background_tasks.add_task(_run_market, task_id, post_id)
|
||||
return {"task_id": task_id}
|
||||
|
||||
|
||||
# ── 수익 추적 API ────────────────────────────────────────────────────────────
|
||||
|
||||
@app.get("/api/blog-marketing/commissions")
|
||||
def list_commissions(post_id: int = None, limit: int = Query(100, ge=1, le=100)):
|
||||
return {"commissions": get_commissions(post_id=post_id, limit=limit)}
|
||||
|
||||
|
||||
@app.post("/api/blog-marketing/commissions", status_code=201)
|
||||
def create_commission(data: dict):
|
||||
return add_commission(data)
|
||||
|
||||
|
||||
@app.put("/api/blog-marketing/commissions/{comm_id}")
|
||||
def edit_commission(comm_id: int, data: dict):
|
||||
result = update_commission(comm_id, data)
|
||||
if not result:
|
||||
raise HTTPException(status_code=404, detail="Commission not found")
|
||||
return result
|
||||
|
||||
|
||||
@app.delete("/api/blog-marketing/commissions/{comm_id}")
|
||||
def remove_commission(comm_id: int):
|
||||
if not delete_commission(comm_id):
|
||||
raise HTTPException(status_code=404, detail="Commission not found")
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
# ── 대시보드 API ─────────────────────────────────────────────────────────────
|
||||
|
||||
@app.get("/api/blog-marketing/dashboard")
|
||||
def dashboard():
|
||||
return get_dashboard_stats()
|
||||
105
blog-lab/app/marketer.py
Normal file
105
blog-lab/app/marketer.py
Normal file
@@ -0,0 +1,105 @@
|
||||
"""마케터 단계 — 전환율 강화 + 브랜드커넥트 링크 삽입."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from datetime import date
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
import anthropic
|
||||
|
||||
from .config import ANTHROPIC_API_KEY, CLAUDE_MODEL
|
||||
from .db import get_template
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_client: Optional[anthropic.Anthropic] = None
|
||||
|
||||
|
||||
def _get_client() -> anthropic.Anthropic:
|
||||
global _client
|
||||
if _client is None:
|
||||
_client = anthropic.Anthropic(api_key=ANTHROPIC_API_KEY)
|
||||
return _client
|
||||
|
||||
|
||||
def _call_claude(prompt: str, max_tokens: int = 8192) -> str:
|
||||
client = _get_client()
|
||||
today = date.today().isoformat()
|
||||
resp = client.messages.create(
|
||||
model=CLAUDE_MODEL,
|
||||
max_tokens=max_tokens,
|
||||
system=f"현재 날짜는 {today}입니다. 모든 콘텐츠는 이 날짜 기준으로 작성하세요.",
|
||||
messages=[{"role": "user", "content": prompt}],
|
||||
)
|
||||
return resp.content[0].text
|
||||
|
||||
|
||||
def enhance_for_conversion(
|
||||
post_body: str,
|
||||
post_title: str,
|
||||
brand_links: List[Dict[str, Any]],
|
||||
keyword: str,
|
||||
) -> Dict[str, str]:
|
||||
"""초안에 제휴 링크를 자연스럽게 삽입하고 전환율을 강화.
|
||||
|
||||
Args:
|
||||
post_body: 작가 초안 HTML 본문
|
||||
post_title: 작가 초안 제목
|
||||
brand_links: 브랜드커넥트 링크 리스트
|
||||
keyword: 타겟 키워드
|
||||
|
||||
Returns:
|
||||
{"title": str, "body": str, "excerpt": str}
|
||||
|
||||
Raises:
|
||||
ValueError: 브랜드 링크가 없을 때
|
||||
"""
|
||||
if not brand_links:
|
||||
raise ValueError("브랜드커넥트 링크가 필요합니다")
|
||||
|
||||
template = get_template("marketer_enhance")
|
||||
if not template:
|
||||
raise RuntimeError("marketer_enhance 템플릿이 없습니다")
|
||||
|
||||
brand_links_text = ""
|
||||
for i, link in enumerate(brand_links, 1):
|
||||
brand_links_text += (
|
||||
f"{i}. 상품명: {link.get('product_name', '')}\n"
|
||||
f" 설명: {link.get('description', '')}\n"
|
||||
f" URL: {link.get('url', '')}\n"
|
||||
f" 배치 힌트: {link.get('placement_hint', '자연스럽게')}\n\n"
|
||||
)
|
||||
|
||||
prompt = template.format(
|
||||
draft_body=post_body[:6000],
|
||||
keyword=keyword,
|
||||
brand_links_info=brand_links_text,
|
||||
)
|
||||
|
||||
prompt += (
|
||||
"\n\n---\n"
|
||||
"응답은 반드시 아래 JSON 형식으로 해주세요 (JSON만 출력):\n"
|
||||
'{"title": "개선된 제목", "body": "개선된 HTML 본문", "excerpt": "2줄 요약"}'
|
||||
)
|
||||
|
||||
raw = _call_claude(prompt)
|
||||
|
||||
try:
|
||||
text = raw.strip()
|
||||
if text.startswith("```"):
|
||||
lines = text.split("\n")
|
||||
lines = [l for l in lines if not l.strip().startswith("```")]
|
||||
text = "\n".join(lines)
|
||||
result = json.loads(text)
|
||||
return {
|
||||
"title": result.get("title", post_title),
|
||||
"body": result.get("body", post_body),
|
||||
"excerpt": result.get("excerpt", ""),
|
||||
}
|
||||
except (json.JSONDecodeError, KeyError):
|
||||
logger.warning("Marketer JSON parse failed, using raw text")
|
||||
return {
|
||||
"title": post_title,
|
||||
"body": raw,
|
||||
"excerpt": raw[:200],
|
||||
}
|
||||
203
blog-lab/app/naver_search.py
Normal file
203
blog-lab/app/naver_search.py
Normal file
@@ -0,0 +1,203 @@
|
||||
"""네이버 검색 API 연동 — 블로그 + 쇼핑 검색."""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import re
|
||||
import requests
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
from .config import NAVER_CLIENT_ID, NAVER_CLIENT_SECRET
|
||||
|
||||
BLOG_URL = "https://openapi.naver.com/v1/search/blog.json"
|
||||
SHOP_URL = "https://openapi.naver.com/v1/search/shop.json"
|
||||
|
||||
_HEADERS = {
|
||||
"X-Naver-Client-Id": NAVER_CLIENT_ID,
|
||||
"X-Naver-Client-Secret": NAVER_CLIENT_SECRET,
|
||||
}
|
||||
|
||||
_TAG_RE = re.compile(r"<[^>]+>")
|
||||
|
||||
|
||||
def _strip_html(text: str) -> str:
|
||||
return _TAG_RE.sub("", text).strip()
|
||||
|
||||
|
||||
def search_blog(keyword: str, display: int = 10, sort: str = "sim") -> Dict[str, Any]:
|
||||
"""네이버 블로그 검색.
|
||||
|
||||
Args:
|
||||
keyword: 검색 키워드
|
||||
display: 결과 수 (1-100)
|
||||
sort: sim(정확도) | date(날짜)
|
||||
|
||||
Returns:
|
||||
{"total": int, "items": [...]}
|
||||
"""
|
||||
resp = requests.get(
|
||||
BLOG_URL,
|
||||
headers=_HEADERS,
|
||||
params={"query": keyword, "display": display, "sort": sort},
|
||||
timeout=10,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
items = [
|
||||
{
|
||||
"title": _strip_html(item.get("title", "")),
|
||||
"description": _strip_html(item.get("description", "")),
|
||||
"link": item.get("link", ""),
|
||||
"bloggername": item.get("bloggername", ""),
|
||||
"postdate": item.get("postdate", ""),
|
||||
}
|
||||
for item in data.get("items", [])
|
||||
]
|
||||
return {"total": data.get("total", 0), "items": items}
|
||||
|
||||
|
||||
def search_shopping(keyword: str, display: int = 20, sort: str = "sim") -> Dict[str, Any]:
|
||||
"""네이버 쇼핑 검색.
|
||||
|
||||
Args:
|
||||
keyword: 검색 키워드
|
||||
display: 결과 수 (1-100)
|
||||
sort: sim(정확도) | date(날짜) | asc(가격↑) | dsc(가격↓)
|
||||
|
||||
Returns:
|
||||
{"total": int, "items": [...], "price_stats": {...}}
|
||||
"""
|
||||
resp = requests.get(
|
||||
SHOP_URL,
|
||||
headers=_HEADERS,
|
||||
params={"query": keyword, "display": display, "sort": sort},
|
||||
timeout=10,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
|
||||
items = []
|
||||
prices = []
|
||||
for item in data.get("items", []):
|
||||
lprice = _safe_int(item.get("lprice"))
|
||||
hprice = _safe_int(item.get("hprice"))
|
||||
parsed = {
|
||||
"title": _strip_html(item.get("title", "")),
|
||||
"link": item.get("link", ""),
|
||||
"image": item.get("image", ""),
|
||||
"lprice": lprice,
|
||||
"hprice": hprice,
|
||||
"mallName": item.get("mallName", ""),
|
||||
"productId": item.get("productId", ""),
|
||||
"productType": item.get("productType", ""),
|
||||
"category1": item.get("category1", ""),
|
||||
"category2": item.get("category2", ""),
|
||||
"category3": item.get("category3", ""),
|
||||
"brand": item.get("brand", ""),
|
||||
"maker": item.get("maker", ""),
|
||||
}
|
||||
items.append(parsed)
|
||||
if lprice and lprice > 0:
|
||||
prices.append(lprice)
|
||||
|
||||
price_stats = None
|
||||
if prices:
|
||||
price_stats = {
|
||||
"min": min(prices),
|
||||
"max": max(prices),
|
||||
"avg": int(sum(prices) / len(prices)),
|
||||
"count": len(prices),
|
||||
}
|
||||
|
||||
return {
|
||||
"total": data.get("total", 0),
|
||||
"items": items,
|
||||
"price_stats": price_stats,
|
||||
}
|
||||
|
||||
|
||||
def _safe_int(val) -> Optional[int]:
|
||||
if val is None:
|
||||
return None
|
||||
try:
|
||||
return int(val)
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
|
||||
|
||||
def analyze_keyword(keyword: str) -> Dict[str, Any]:
|
||||
"""키워드 경쟁도/기회 분석.
|
||||
|
||||
블로그 총 결과수, 쇼핑 총 결과수, 가격 통계를 기반으로
|
||||
competition_score(경쟁도)와 opportunity_score(기회점수) 산출.
|
||||
|
||||
Returns:
|
||||
{
|
||||
"keyword", "blog_total", "shop_total",
|
||||
"competition", "opportunity",
|
||||
"avg_price", "min_price", "max_price",
|
||||
"top_products": [...], "top_blogs": [...]
|
||||
}
|
||||
"""
|
||||
blog = search_blog(keyword, display=10, sort="sim")
|
||||
shop = search_shopping(keyword, display=20, sort="sim")
|
||||
|
||||
blog_total = blog["total"]
|
||||
shop_total = shop["total"]
|
||||
|
||||
# 경쟁도: 블로그 결과 수 기반 (로그 스케일 0-100)
|
||||
import math
|
||||
if blog_total > 0:
|
||||
competition = min(100, int(math.log10(blog_total + 1) * 15))
|
||||
else:
|
||||
competition = 0
|
||||
|
||||
# 기회 점수: 쇼핑 수요가 높고 블로그 경쟁이 낮을수록 높음
|
||||
if shop_total > 0 and blog_total > 0:
|
||||
ratio = shop_total / blog_total
|
||||
opportunity = min(100, int(ratio * 20))
|
||||
elif shop_total > 0:
|
||||
opportunity = 90 # 경쟁 없이 수요만 있으면 높은 기회
|
||||
else:
|
||||
opportunity = 10 # 쇼핑 수요 없음
|
||||
|
||||
price_stats = shop.get("price_stats") or {}
|
||||
|
||||
return {
|
||||
"keyword": keyword,
|
||||
"blog_total": blog_total,
|
||||
"shop_total": shop_total,
|
||||
"competition": competition,
|
||||
"opportunity": opportunity,
|
||||
"avg_price": price_stats.get("avg"),
|
||||
"min_price": price_stats.get("min"),
|
||||
"max_price": price_stats.get("max"),
|
||||
"top_products": shop["items"][:5],
|
||||
"top_blogs": blog["items"][:5],
|
||||
}
|
||||
|
||||
|
||||
def _run_enrich(top_blogs: list) -> list:
|
||||
"""동기 컨텍스트에서 비동기 enrich_top_blogs 실행."""
|
||||
from .web_crawler import enrich_top_blogs
|
||||
try:
|
||||
loop = asyncio.get_event_loop()
|
||||
if loop.is_running():
|
||||
import concurrent.futures
|
||||
with concurrent.futures.ThreadPoolExecutor() as pool:
|
||||
return pool.submit(
|
||||
asyncio.run, enrich_top_blogs(top_blogs)
|
||||
).result(timeout=60)
|
||||
else:
|
||||
return asyncio.run(enrich_top_blogs(top_blogs))
|
||||
except Exception as e:
|
||||
logger.warning("블로그 크롤링 실패, 기존 데이터 사용: %s", e)
|
||||
return top_blogs
|
||||
|
||||
|
||||
def analyze_keyword_with_crawling(keyword: str) -> Dict[str, Any]:
|
||||
"""analyze_keyword + 상위 블로그 본문 크롤링."""
|
||||
result = analyze_keyword(keyword)
|
||||
result["top_blogs"] = _run_enrich(result["top_blogs"])
|
||||
return result
|
||||
85
blog-lab/app/quality_reviewer.py
Normal file
85
blog-lab/app/quality_reviewer.py
Normal file
@@ -0,0 +1,85 @@
|
||||
"""Claude API 기반 블로그 글 품질 리뷰 — 6기준 × 10점, 42/60 통과."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from datetime import date
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
import anthropic
|
||||
|
||||
from .config import ANTHROPIC_API_KEY, CLAUDE_MODEL
|
||||
from .db import get_template
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
PASS_THRESHOLD = 42 # 60점 만점 중 42점 이상이면 통과 (70%)
|
||||
|
||||
_client: Optional[anthropic.Anthropic] = None
|
||||
|
||||
|
||||
def _get_client() -> anthropic.Anthropic:
|
||||
global _client
|
||||
if _client is None:
|
||||
_client = anthropic.Anthropic(api_key=ANTHROPIC_API_KEY)
|
||||
return _client
|
||||
|
||||
|
||||
def review_post(title: str, body: str) -> Dict[str, Any]:
|
||||
"""블로그 글 품질 리뷰.
|
||||
|
||||
Returns:
|
||||
{
|
||||
"scores": {
|
||||
"empathy": N, "click_appeal": N, "conversion": N,
|
||||
"seo": N, "format": N, "link_natural": N
|
||||
},
|
||||
"total": N,
|
||||
"pass": bool,
|
||||
"feedback": str
|
||||
}
|
||||
"""
|
||||
template = get_template("quality_review")
|
||||
if not template:
|
||||
raise RuntimeError("quality_review 템플릿이 없습니다")
|
||||
|
||||
prompt = template.format(title=title, body=body[:6000])
|
||||
|
||||
client = _get_client()
|
||||
today = date.today().isoformat()
|
||||
resp = client.messages.create(
|
||||
model=CLAUDE_MODEL,
|
||||
max_tokens=2048,
|
||||
system=f"현재 날짜는 {today}입니다.",
|
||||
messages=[{"role": "user", "content": prompt}],
|
||||
)
|
||||
raw = resp.content[0].text
|
||||
|
||||
try:
|
||||
text = raw.strip()
|
||||
if text.startswith("```"):
|
||||
lines = text.split("\n")
|
||||
lines = [l for l in lines if not l.strip().startswith("```")]
|
||||
text = "\n".join(lines)
|
||||
result = json.loads(text)
|
||||
|
||||
scores = result.get("scores", {})
|
||||
total = sum(scores.values())
|
||||
passed = total >= PASS_THRESHOLD
|
||||
|
||||
return {
|
||||
"scores": scores,
|
||||
"total": total,
|
||||
"pass": passed,
|
||||
"feedback": result.get("feedback", ""),
|
||||
}
|
||||
except (json.JSONDecodeError, KeyError, TypeError) as e:
|
||||
logger.warning("Quality review JSON parse failed: %s", e)
|
||||
return {
|
||||
"scores": {
|
||||
"empathy": 0, "click_appeal": 0, "conversion": 0,
|
||||
"seo": 0, "format": 0, "link_natural": 0,
|
||||
},
|
||||
"total": 0,
|
||||
"pass": False,
|
||||
"feedback": f"리뷰 파싱 실패. 원본 응답:\n{raw[:500]}",
|
||||
}
|
||||
97
blog-lab/app/web_crawler.py
Normal file
97
blog-lab/app/web_crawler.py
Normal file
@@ -0,0 +1,97 @@
|
||||
"""네이버 블로그 본문 크롤링 모듈."""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import re
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
import httpx
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_TIMEOUT = 10 # 글당 크롤링 타임아웃 (초)
|
||||
_MAX_CONTENT_LENGTH = 2000 # 본문 최대 길이
|
||||
|
||||
# 네이버 블로그 URL 패턴: blog.naver.com/{blogId}/{logNo}
|
||||
_BLOG_URL_RE = re.compile(r"blog\.naver\.com/([^/]+)/(\d+)")
|
||||
|
||||
|
||||
def _parse_naver_blog_url(url: str) -> Optional[Tuple[str, str]]:
|
||||
"""네이버 블로그 URL에서 blogId, logNo 추출. 실패 시 None."""
|
||||
match = _BLOG_URL_RE.search(url)
|
||||
if not match:
|
||||
return None
|
||||
return match.group(1), match.group(2)
|
||||
|
||||
|
||||
async def _fetch_html(url: str) -> str:
|
||||
"""URL에서 HTML을 가져온다."""
|
||||
async with httpx.AsyncClient(timeout=_TIMEOUT, follow_redirects=True) as client:
|
||||
resp = await client.get(url, headers={
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
|
||||
})
|
||||
resp.raise_for_status()
|
||||
return resp.text
|
||||
|
||||
|
||||
def _extract_text(html: str) -> str:
|
||||
"""HTML에서 본문 텍스트를 추출한다."""
|
||||
soup = BeautifulSoup(html, "html.parser")
|
||||
|
||||
# 스마트에디터 3 (SE3)
|
||||
container = soup.select_one("div.se-main-container")
|
||||
if not container:
|
||||
# 구 에디터
|
||||
container = soup.select_one("div#postViewArea")
|
||||
if not container:
|
||||
# 폴백: body 전체
|
||||
container = soup.body
|
||||
|
||||
if not container:
|
||||
return ""
|
||||
|
||||
# 스크립트/스타일 제거
|
||||
for tag in container.find_all(["script", "style"]):
|
||||
tag.decompose()
|
||||
|
||||
text = container.get_text(separator="\n", strip=True)
|
||||
return text[:_MAX_CONTENT_LENGTH]
|
||||
|
||||
|
||||
async def crawl_blog_content(url: str) -> str:
|
||||
"""네이버 블로그 URL에서 본문 텍스트 추출.
|
||||
|
||||
- 네이버 블로그가 아니면 빈 문자열
|
||||
- 크롤링 실패 시 빈 문자열 (에러 로그만)
|
||||
- 본문 최대 2,000자
|
||||
"""
|
||||
parsed = _parse_naver_blog_url(url)
|
||||
if not parsed:
|
||||
return ""
|
||||
|
||||
blog_id, log_no = parsed
|
||||
# iframe 내부 실제 본문 URL
|
||||
post_url = f"https://blog.naver.com/PostView.naver?blogId={blog_id}&logNo={log_no}"
|
||||
|
||||
try:
|
||||
html = await _fetch_html(post_url)
|
||||
return _extract_text(html)
|
||||
except Exception as e:
|
||||
logger.warning("블로그 크롤링 실패 (%s): %s", url, e)
|
||||
return ""
|
||||
|
||||
|
||||
async def enrich_top_blogs(top_blogs: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
||||
"""top_blogs 리스트 각 항목에 content 필드를 추가.
|
||||
|
||||
개별 크롤링 실패 시 해당 항목의 content를 빈 문자열로 설정하고 나머지 계속 진행.
|
||||
"""
|
||||
result = []
|
||||
for blog in top_blogs:
|
||||
enriched = dict(blog)
|
||||
try:
|
||||
enriched["content"] = await crawl_blog_content(blog.get("link", ""))
|
||||
except Exception:
|
||||
enriched["content"] = ""
|
||||
result.append(enriched)
|
||||
return result
|
||||
@@ -1,9 +1,6 @@
|
||||
fastapi==0.115.6
|
||||
uvicorn[standard]==0.34.0
|
||||
requests==2.32.3
|
||||
httpx>=0.27
|
||||
anthropic==0.52.0
|
||||
jinja2>=3.1.4
|
||||
playwright==1.48.0
|
||||
pytest>=8.0
|
||||
pytest-asyncio>=0.24
|
||||
beautifulsoup4>=4.12
|
||||
httpx>=0.27
|
||||
9
blog-lab/tests/conftest.py
Normal file
9
blog-lab/tests/conftest.py
Normal file
@@ -0,0 +1,9 @@
|
||||
"""공통 테스트 픽스처."""
|
||||
import os
|
||||
import sys
|
||||
|
||||
# app 패키지를 blog_lab_app으로도 import 가능하게
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
|
||||
if "blog_lab_app" not in sys.modules:
|
||||
import app as blog_lab_app
|
||||
sys.modules["blog_lab_app"] = blog_lab_app
|
||||
85
blog-lab/tests/test_api_links.py
Normal file
85
blog-lab/tests/test_api_links.py
Normal file
@@ -0,0 +1,85 @@
|
||||
"""브랜드커넥트 링크 API 테스트."""
|
||||
import os
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def setup_db(tmp_path):
|
||||
test_db = str(tmp_path / "test.db")
|
||||
import app.config as config
|
||||
config.DB_PATH = test_db
|
||||
from app import db
|
||||
db.DB_PATH = test_db
|
||||
db.init_db()
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
from app.main import app
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def test_create_link(client):
|
||||
resp = client.post("/api/blog-marketing/links", json={
|
||||
"keyword_id": 1,
|
||||
"url": "https://link.coupang.com/abc",
|
||||
"product_name": "테스트 상품",
|
||||
"description": "상품 설명",
|
||||
})
|
||||
assert resp.status_code == 201
|
||||
data = resp.json()
|
||||
assert data["url"] == "https://link.coupang.com/abc"
|
||||
assert data["product_name"] == "테스트 상품"
|
||||
|
||||
|
||||
def test_create_link_requires_url(client):
|
||||
resp = client.post("/api/blog-marketing/links", json={
|
||||
"product_name": "상품",
|
||||
})
|
||||
assert resp.status_code == 422
|
||||
|
||||
|
||||
def test_create_link_requires_product_name(client):
|
||||
resp = client.post("/api/blog-marketing/links", json={
|
||||
"url": "https://a.com",
|
||||
})
|
||||
assert resp.status_code == 422
|
||||
|
||||
|
||||
def test_list_links_by_keyword_id(client):
|
||||
client.post("/api/blog-marketing/links", json={
|
||||
"keyword_id": 1, "url": "https://a.com", "product_name": "A",
|
||||
})
|
||||
client.post("/api/blog-marketing/links", json={
|
||||
"keyword_id": 2, "url": "https://b.com", "product_name": "B",
|
||||
})
|
||||
resp = client.get("/api/blog-marketing/links?keyword_id=1")
|
||||
assert resp.status_code == 200
|
||||
assert len(resp.json()["links"]) == 1
|
||||
|
||||
|
||||
def test_update_link(client):
|
||||
create_resp = client.post("/api/blog-marketing/links", json={
|
||||
"url": "https://a.com", "product_name": "원래",
|
||||
})
|
||||
link_id = create_resp.json()["id"]
|
||||
resp = client.put(f"/api/blog-marketing/links/{link_id}", json={
|
||||
"product_name": "새이름",
|
||||
})
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["product_name"] == "새이름"
|
||||
|
||||
|
||||
def test_delete_link(client):
|
||||
create_resp = client.post("/api/blog-marketing/links", json={
|
||||
"url": "https://a.com", "product_name": "삭제",
|
||||
})
|
||||
link_id = create_resp.json()["id"]
|
||||
resp = client.delete(f"/api/blog-marketing/links/{link_id}")
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["ok"] is True
|
||||
|
||||
resp = client.delete(f"/api/blog-marketing/links/{link_id}")
|
||||
assert resp.status_code == 404
|
||||
67
blog-lab/tests/test_db_brand_links.py
Normal file
67
blog-lab/tests/test_db_brand_links.py
Normal file
@@ -0,0 +1,67 @@
|
||||
"""brand_links DB CRUD 테스트."""
|
||||
import os
|
||||
import pytest
|
||||
from app import db
|
||||
from app.config import DB_PATH
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def setup_db(tmp_path):
|
||||
"""테스트용 임시 DB 사용."""
|
||||
test_db = str(tmp_path / "test.db")
|
||||
import app.config as config
|
||||
config.DB_PATH = test_db
|
||||
db.DB_PATH = test_db
|
||||
db.init_db()
|
||||
yield
|
||||
|
||||
|
||||
def test_add_brand_link():
|
||||
link = db.add_brand_link({
|
||||
"keyword_id": 1,
|
||||
"url": "https://link.coupang.com/abc",
|
||||
"product_name": "테스트 상품",
|
||||
"description": "상품 설명",
|
||||
"placement_hint": "본문 중간",
|
||||
})
|
||||
assert link["id"] is not None
|
||||
assert link["url"] == "https://link.coupang.com/abc"
|
||||
assert link["product_name"] == "테스트 상품"
|
||||
assert link["keyword_id"] == 1
|
||||
assert link["post_id"] is None
|
||||
|
||||
|
||||
def test_get_brand_links_by_keyword_id():
|
||||
db.add_brand_link({"keyword_id": 1, "url": "https://a.com", "product_name": "A"})
|
||||
db.add_brand_link({"keyword_id": 1, "url": "https://b.com", "product_name": "B"})
|
||||
db.add_brand_link({"keyword_id": 2, "url": "https://c.com", "product_name": "C"})
|
||||
links = db.get_brand_links(keyword_id=1)
|
||||
assert len(links) == 2
|
||||
|
||||
|
||||
def test_get_brand_links_by_post_id():
|
||||
db.add_brand_link({"post_id": 10, "url": "https://a.com", "product_name": "A"})
|
||||
links = db.get_brand_links(post_id=10)
|
||||
assert len(links) == 1
|
||||
assert links[0]["post_id"] == 10
|
||||
|
||||
|
||||
def test_update_brand_link():
|
||||
link = db.add_brand_link({"url": "https://a.com", "product_name": "원래 이름"})
|
||||
updated = db.update_brand_link(link["id"], {"product_name": "새 이름", "post_id": 5})
|
||||
assert updated["product_name"] == "새 이름"
|
||||
assert updated["post_id"] == 5
|
||||
|
||||
|
||||
def test_delete_brand_link():
|
||||
link = db.add_brand_link({"url": "https://a.com", "product_name": "삭제할 링크"})
|
||||
assert db.delete_brand_link(link["id"]) is True
|
||||
assert db.delete_brand_link(link["id"]) is False
|
||||
|
||||
|
||||
def test_link_keyword_to_post():
|
||||
db.add_brand_link({"keyword_id": 1, "url": "https://a.com", "product_name": "A"})
|
||||
db.add_brand_link({"keyword_id": 1, "url": "https://b.com", "product_name": "B"})
|
||||
db.link_brand_links_to_post(keyword_id=1, post_id=10)
|
||||
links = db.get_brand_links(post_id=10)
|
||||
assert len(links) == 2
|
||||
74
blog-lab/tests/test_evaluator.py
Normal file
74
blog-lab/tests/test_evaluator.py
Normal file
@@ -0,0 +1,74 @@
|
||||
"""평가자 단계 테스트 — 6기준 60점."""
|
||||
import json
|
||||
import pytest
|
||||
from unittest.mock import patch
|
||||
|
||||
|
||||
def test_review_post_has_6_criteria():
|
||||
"""6개 기준으로 채점하는지 확인."""
|
||||
from app.quality_reviewer import review_post
|
||||
|
||||
mock_response = json.dumps({
|
||||
"scores": {
|
||||
"empathy": 8, "click_appeal": 7, "conversion": 9,
|
||||
"seo": 8, "format": 7, "link_natural": 9,
|
||||
},
|
||||
"total": 48,
|
||||
"pass": True,
|
||||
"feedback": "전체적으로 우수합니다",
|
||||
})
|
||||
|
||||
with patch("app.quality_reviewer._get_client") as mock_client_fn, \
|
||||
patch("app.quality_reviewer.get_template", return_value="제목: {title}\n본문: {body}"):
|
||||
mock_client = mock_client_fn.return_value
|
||||
mock_client.messages.create.return_value.content = [type("C", (), {"text": mock_response})()]
|
||||
result = review_post("테스트 제목", "<p>본문</p>")
|
||||
|
||||
assert "link_natural" in result["scores"]
|
||||
assert len(result["scores"]) == 6
|
||||
assert result["total"] == 48
|
||||
assert result["pass"] is True
|
||||
|
||||
|
||||
def test_review_pass_threshold_is_42():
|
||||
"""통과 기준이 42점인지 확인."""
|
||||
from app.quality_reviewer import PASS_THRESHOLD
|
||||
assert PASS_THRESHOLD == 42
|
||||
|
||||
|
||||
def test_review_fails_below_42():
|
||||
"""42점 미만이면 불통과."""
|
||||
from app.quality_reviewer import review_post
|
||||
|
||||
mock_response = json.dumps({
|
||||
"scores": {
|
||||
"empathy": 5, "click_appeal": 5, "conversion": 5,
|
||||
"seo": 5, "format": 5, "link_natural": 5,
|
||||
},
|
||||
"total": 30,
|
||||
"pass": False,
|
||||
"feedback": "개선 필요",
|
||||
})
|
||||
|
||||
with patch("app.quality_reviewer._get_client") as mock_client_fn, \
|
||||
patch("app.quality_reviewer.get_template", return_value="제목: {title}\n본문: {body}"):
|
||||
mock_client = mock_client_fn.return_value
|
||||
mock_client.messages.create.return_value.content = [type("C", (), {"text": mock_response})()]
|
||||
result = review_post("제목", "<p>본문</p>")
|
||||
|
||||
assert result["pass"] is False
|
||||
|
||||
|
||||
def test_review_handles_parse_failure():
|
||||
"""JSON 파싱 실패 시 기본값 반환 (6개 기준)."""
|
||||
from app.quality_reviewer import review_post
|
||||
|
||||
with patch("app.quality_reviewer._get_client") as mock_client_fn, \
|
||||
patch("app.quality_reviewer.get_template", return_value="제목: {title}\n본문: {body}"):
|
||||
mock_client = mock_client_fn.return_value
|
||||
mock_client.messages.create.return_value.content = [type("C", (), {"text": "잘못된 응답"})()]
|
||||
result = review_post("제목", "<p>본문</p>")
|
||||
|
||||
assert result["pass"] is False
|
||||
assert "link_natural" in result["scores"]
|
||||
assert result["total"] == 0
|
||||
66
blog-lab/tests/test_marketer.py
Normal file
66
blog-lab/tests/test_marketer.py
Normal file
@@ -0,0 +1,66 @@
|
||||
"""마케터 단계 테스트."""
|
||||
import json
|
||||
import pytest
|
||||
from unittest.mock import patch
|
||||
|
||||
|
||||
def test_enhance_for_conversion_inserts_links():
|
||||
"""마케터가 브랜드 링크를 본문에 삽입."""
|
||||
from app.marketer import enhance_for_conversion
|
||||
|
||||
brand_links = [
|
||||
{"url": "https://link.coupang.com/abc", "product_name": "갤럭시 버즈3",
|
||||
"description": "노이즈캔슬링", "placement_hint": "본문 중간"},
|
||||
]
|
||||
|
||||
mock_response = json.dumps({
|
||||
"title": "마케팅된 제목",
|
||||
"body": '<p>본문 <a href="https://link.coupang.com/abc">갤럭시 버즈3</a></p>',
|
||||
"excerpt": "요약",
|
||||
})
|
||||
|
||||
with patch("app.marketer._call_claude", return_value=mock_response) as mock_call, \
|
||||
patch("app.marketer.get_template", return_value="초안: {draft_body}\n키워드: {keyword}\n링크:\n{brand_links_info}"):
|
||||
result = enhance_for_conversion(
|
||||
post_body="<p>초안 본문</p>",
|
||||
post_title="초안 제목",
|
||||
brand_links=brand_links,
|
||||
keyword="무선 이어폰",
|
||||
)
|
||||
|
||||
prompt_used = mock_call.call_args[0][0]
|
||||
assert "갤럭시 버즈3" in prompt_used
|
||||
assert "노이즈캔슬링" in prompt_used
|
||||
assert result["title"] == "마케팅된 제목"
|
||||
|
||||
|
||||
def test_enhance_requires_brand_links():
|
||||
"""브랜드 링크가 없으면 ValueError."""
|
||||
from app.marketer import enhance_for_conversion
|
||||
|
||||
with pytest.raises(ValueError, match="브랜드커넥트 링크가 필요합니다"):
|
||||
enhance_for_conversion(
|
||||
post_body="<p>본문</p>",
|
||||
post_title="제목",
|
||||
brand_links=[],
|
||||
keyword="테스트",
|
||||
)
|
||||
|
||||
|
||||
def test_enhance_json_parse_fallback():
|
||||
"""JSON 파싱 실패 시 원본 제목 유지."""
|
||||
from app.marketer import enhance_for_conversion
|
||||
|
||||
brand_links = [{"url": "https://a.com", "product_name": "상품"}]
|
||||
|
||||
with patch("app.marketer._call_claude", return_value="잘못된 JSON"), \
|
||||
patch("app.marketer.get_template", return_value="초안: {draft_body}\n키워드: {keyword}\n링크:\n{brand_links_info}"):
|
||||
result = enhance_for_conversion(
|
||||
post_body="<p>원본</p>",
|
||||
post_title="원본 제목",
|
||||
brand_links=brand_links,
|
||||
keyword="테스트",
|
||||
)
|
||||
|
||||
assert result["title"] == "원본 제목"
|
||||
assert result["body"] == "잘못된 JSON"
|
||||
146
blog-lab/tests/test_pipeline_integration.py
Normal file
146
blog-lab/tests/test_pipeline_integration.py
Normal file
@@ -0,0 +1,146 @@
|
||||
"""4단계 파이프라인 통합 테스트."""
|
||||
import os
|
||||
import pytest
|
||||
from unittest.mock import patch
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def setup_db(tmp_path):
|
||||
test_db = str(tmp_path / "test.db")
|
||||
import app.config as config
|
||||
config.DB_PATH = test_db
|
||||
from app import db
|
||||
db.DB_PATH = test_db
|
||||
db.init_db()
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
from app.main import app
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def test_full_pipeline_status_flow(client):
|
||||
"""draft → marketed → reviewed → published 상태 흐름."""
|
||||
from app import db
|
||||
|
||||
# 1. 키워드 분석 결과 직접 삽입
|
||||
analysis = db.add_keyword_analysis({
|
||||
"keyword": "무선 이어폰",
|
||||
"blog_total": 1000,
|
||||
"shop_total": 500,
|
||||
"competition": 45,
|
||||
"opportunity": 60,
|
||||
"top_products": [{"title": "에어팟", "lprice": 200000, "mallName": "애플"}],
|
||||
"top_blogs": [{"title": "리뷰", "link": "https://blog.naver.com/user/123", "content": "본문"}],
|
||||
})
|
||||
|
||||
# 2. 브랜드 링크 등록
|
||||
resp = client.post("/api/blog-marketing/links", json={
|
||||
"keyword_id": analysis["id"],
|
||||
"url": "https://link.coupang.com/abc",
|
||||
"product_name": "삼성 버즈3",
|
||||
"description": "노이즈캔슬링",
|
||||
})
|
||||
assert resp.status_code == 201
|
||||
|
||||
# 3. 포스트 직접 생성 (generate는 Claude API 필요)
|
||||
post = db.add_post({
|
||||
"keyword_id": analysis["id"],
|
||||
"title": "무선 이어폰 추천",
|
||||
"body": "<p>초안 본문</p>",
|
||||
"excerpt": "요약",
|
||||
"tags": ["이어폰"],
|
||||
"status": "draft",
|
||||
})
|
||||
db.link_brand_links_to_post(keyword_id=analysis["id"], post_id=post["id"])
|
||||
|
||||
# 4. 상태 확인: draft
|
||||
resp = client.get(f"/api/blog-marketing/posts/{post['id']}")
|
||||
assert resp.json()["status"] == "draft"
|
||||
|
||||
# 5. marketed 상태
|
||||
db.update_post(post["id"], {"status": "marketed", "body": "<p>마케팅된 본문</p>"})
|
||||
resp = client.get(f"/api/blog-marketing/posts/{post['id']}")
|
||||
assert resp.json()["status"] == "marketed"
|
||||
|
||||
# 6. reviewed 상태 (점수 48/60 = 통과)
|
||||
db.update_post(post["id"], {
|
||||
"status": "reviewed",
|
||||
"review_score": 48,
|
||||
"review_detail": {
|
||||
"scores": {"empathy": 8, "click_appeal": 8, "conversion": 8, "seo": 8, "format": 8, "link_natural": 8},
|
||||
"total": 48, "pass": True, "feedback": "우수"
|
||||
},
|
||||
})
|
||||
resp = client.get(f"/api/blog-marketing/posts/{post['id']}")
|
||||
assert resp.json()["status"] == "reviewed"
|
||||
assert resp.json()["review_score"] == 48
|
||||
|
||||
# 7. 발행
|
||||
resp = client.post(f"/api/blog-marketing/posts/{post['id']}/publish", json={
|
||||
"naver_url": "https://blog.naver.com/mypost/123",
|
||||
})
|
||||
assert resp.json()["status"] == "published"
|
||||
|
||||
|
||||
def test_links_associated_with_post(client):
|
||||
"""keyword_id로 등록한 링크가 post 생성 후 post_id로도 조회 가능."""
|
||||
from app import db
|
||||
|
||||
analysis = db.add_keyword_analysis({"keyword": "테스트", "blog_total": 10, "shop_total": 5})
|
||||
client.post("/api/blog-marketing/links", json={
|
||||
"keyword_id": analysis["id"],
|
||||
"url": "https://link.com/1",
|
||||
"product_name": "상품1",
|
||||
})
|
||||
|
||||
post = db.add_post({"keyword_id": analysis["id"], "title": "제목", "body": "본문", "status": "draft"})
|
||||
db.link_brand_links_to_post(keyword_id=analysis["id"], post_id=post["id"])
|
||||
|
||||
resp = client.get(f"/api/blog-marketing/links?post_id={post['id']}")
|
||||
links = resp.json()["links"]
|
||||
assert len(links) == 1
|
||||
assert links[0]["product_name"] == "상품1"
|
||||
|
||||
|
||||
@patch("app.main.ANTHROPIC_API_KEY", "fake-key-for-test")
|
||||
def test_market_endpoint_returns_404_for_missing_post(client):
|
||||
"""존재하지 않는 post_id로 마케터 호출 시 404."""
|
||||
resp = client.post("/api/blog-marketing/market/9999")
|
||||
assert resp.status_code == 404
|
||||
|
||||
|
||||
@patch("app.main.ANTHROPIC_API_KEY", "fake-key-for-test")
|
||||
def test_review_endpoint_returns_404_for_missing_post(client):
|
||||
"""존재하지 않는 post_id로 리뷰 호출 시 404."""
|
||||
resp = client.post("/api/blog-marketing/review/9999")
|
||||
assert resp.status_code == 404
|
||||
|
||||
|
||||
def test_multiple_links_per_keyword(client):
|
||||
"""하나의 키워드에 복수 링크 등록 가능."""
|
||||
from app import db
|
||||
analysis = db.add_keyword_analysis({"keyword": "테스트", "blog_total": 10, "shop_total": 5})
|
||||
|
||||
for i in range(3):
|
||||
resp = client.post("/api/blog-marketing/links", json={
|
||||
"keyword_id": analysis["id"],
|
||||
"url": f"https://link.com/{i}",
|
||||
"product_name": f"상품{i}",
|
||||
})
|
||||
assert resp.status_code == 201
|
||||
|
||||
resp = client.get(f"/api/blog-marketing/links?keyword_id={analysis['id']}")
|
||||
assert len(resp.json()["links"]) == 3
|
||||
|
||||
|
||||
def test_dashboard_still_works(client):
|
||||
"""대시보드 API가 여전히 정상 작동."""
|
||||
resp = client.get("/api/blog-marketing/dashboard")
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert "total_posts" in data
|
||||
assert "published_posts" in data
|
||||
58
blog-lab/tests/test_research_crawling.py
Normal file
58
blog-lab/tests/test_research_crawling.py
Normal file
@@ -0,0 +1,58 @@
|
||||
"""리서치 단계 크롤링 통합 테스트."""
|
||||
from unittest.mock import patch
|
||||
|
||||
|
||||
def test_analyze_keyword_with_crawling_enriches_top_blogs():
|
||||
"""analyze_keyword_with_crawling가 top_blogs에 content 필드를 추가."""
|
||||
from app.naver_search import analyze_keyword_with_crawling
|
||||
|
||||
mock_blog_result = {
|
||||
"total": 100,
|
||||
"items": [
|
||||
{"title": "테스트 블로그", "link": "https://blog.naver.com/user1/111",
|
||||
"bloggername": "유저1", "description": "설명", "postdate": "20260401"},
|
||||
],
|
||||
}
|
||||
mock_shop_result = {
|
||||
"total": 50,
|
||||
"items": [{"title": "상품1", "lprice": 10000, "mallName": "쿠팡"}],
|
||||
"price_stats": {"min": 10000, "max": 10000, "avg": 10000, "count": 1},
|
||||
}
|
||||
|
||||
with patch("app.naver_search.search_blog", return_value=mock_blog_result), \
|
||||
patch("app.naver_search.search_shopping", return_value=mock_shop_result), \
|
||||
patch("app.naver_search._run_enrich", return_value=[
|
||||
{"title": "테스트 블로그", "link": "https://blog.naver.com/user1/111",
|
||||
"bloggername": "유저1", "description": "설명", "postdate": "20260401",
|
||||
"content": "크롤링된 본문 내용"}
|
||||
]):
|
||||
result = analyze_keyword_with_crawling("테스트 키워드")
|
||||
|
||||
assert "content" in result["top_blogs"][0]
|
||||
assert result["top_blogs"][0]["content"] == "크롤링된 본문 내용"
|
||||
|
||||
|
||||
def test_analyze_keyword_with_crawling_fallback_on_enrich_failure():
|
||||
"""크롤링 실패 시 기존 데이터 유지."""
|
||||
from app.naver_search import analyze_keyword_with_crawling
|
||||
|
||||
mock_blog_result = {
|
||||
"total": 50,
|
||||
"items": [{"title": "블로그", "link": "https://blog.naver.com/u/1", "bloggername": "유저", "description": "설명"}],
|
||||
}
|
||||
mock_shop_result = {"total": 10, "items": [], "price_stats": None}
|
||||
|
||||
with patch("app.naver_search.search_blog", return_value=mock_blog_result), \
|
||||
patch("app.naver_search.search_shopping", return_value=mock_shop_result), \
|
||||
patch("app.naver_search._run_enrich", side_effect=Exception("크롤링 실패")):
|
||||
# _run_enrich 내부에서 예외를 잡으므로 실제로는 이 테스트에서는
|
||||
# _run_enrich 자체가 예외를 던지는 상황을 시뮬레이션
|
||||
# 하지만 _run_enrich는 내부에서 잡으므로, 직접 fallback 테스트
|
||||
pass
|
||||
|
||||
# _run_enrich 자체 fallback 테스트
|
||||
from app.naver_search import _run_enrich
|
||||
original_blogs = [{"title": "원본", "link": "https://blog.naver.com/u/1"}]
|
||||
with patch("app.web_crawler.enrich_top_blogs", side_effect=Exception("fail")):
|
||||
result = _run_enrich(original_blogs)
|
||||
assert result == original_blogs # fallback으로 원본 반환
|
||||
94
blog-lab/tests/test_web_crawler.py
Normal file
94
blog-lab/tests/test_web_crawler.py
Normal file
@@ -0,0 +1,94 @@
|
||||
"""web_crawler 모듈 테스트."""
|
||||
import pytest
|
||||
from unittest.mock import patch, AsyncMock
|
||||
from app.web_crawler import crawl_blog_content, enrich_top_blogs, _parse_naver_blog_url, _extract_text
|
||||
|
||||
|
||||
def test_parse_naver_blog_url_valid():
|
||||
"""blog.naver.com URL에서 blogId와 logNo를 올바르게 파싱."""
|
||||
result = _parse_naver_blog_url("https://blog.naver.com/testuser/123456")
|
||||
assert result == ("testuser", "123456")
|
||||
|
||||
|
||||
def test_parse_returns_none_for_invalid_url():
|
||||
"""잘못된 URL은 None 반환."""
|
||||
result = _parse_naver_blog_url("https://example.com/post")
|
||||
assert result is None
|
||||
|
||||
|
||||
def test_extract_text_prefers_se_main_container():
|
||||
"""SE3 에디터 컨테이너를 우선 선택."""
|
||||
html = '<div class="se-main-container"><p>SE3 본문</p></div><div id="postViewArea"><p>구 에디터</p></div>'
|
||||
assert _extract_text(html) == "SE3 본문"
|
||||
|
||||
|
||||
def test_extract_text_falls_back_to_post_view_area():
|
||||
"""SE3 없으면 구 에디터 컨테이너 사용."""
|
||||
html = '<div id="postViewArea"><p>구 에디터 본문</p></div>'
|
||||
assert _extract_text(html) == "구 에디터 본문"
|
||||
|
||||
|
||||
def test_extract_text_removes_script_and_style():
|
||||
"""스크립트/스타일 태그 제거."""
|
||||
html = '<div class="se-main-container"><p>본문</p><script>alert(1)</script><style>.x{}</style></div>'
|
||||
result = _extract_text(html)
|
||||
assert "alert" not in result
|
||||
assert ".x" not in result
|
||||
assert "본문" in result
|
||||
|
||||
|
||||
def test_extract_text_returns_empty_on_no_container():
|
||||
"""컨테이너가 없고 body도 없으면 빈 문자열."""
|
||||
assert _extract_text("") == ""
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_crawl_returns_empty_on_non_naver_url():
|
||||
"""네이버 블로그가 아닌 URL은 빈 문자열 반환."""
|
||||
result = await crawl_blog_content("https://example.com/post")
|
||||
assert result == ""
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_crawl_truncates_to_2000_chars():
|
||||
"""본문이 2000자를 초과하면 잘라낸다."""
|
||||
long_html = f'<div class="se-main-container"><p>{"가" * 3000}</p></div>'
|
||||
with patch("app.web_crawler._fetch_html", new_callable=AsyncMock, return_value=long_html):
|
||||
result = await crawl_blog_content("https://blog.naver.com/testuser/123")
|
||||
assert len(result) <= 2000
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_crawl_returns_empty_on_fetch_failure():
|
||||
"""HTTP 요청 실패 시 빈 문자열 반환."""
|
||||
with patch("app.web_crawler._fetch_html", new_callable=AsyncMock, side_effect=Exception("timeout")):
|
||||
result = await crawl_blog_content("https://blog.naver.com/testuser/123")
|
||||
assert result == ""
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_enrich_top_blogs_adds_content_field():
|
||||
"""enrich_top_blogs가 각 블로그에 content 필드를 추가."""
|
||||
blogs = [
|
||||
{"title": "테스트", "link": "https://blog.naver.com/user1/111", "bloggername": "유저1", "description": "설명"},
|
||||
{"title": "테스트2", "link": "https://blog.naver.com/user2/222", "bloggername": "유저2", "description": "설명2"},
|
||||
]
|
||||
with patch("app.web_crawler.crawl_blog_content", new_callable=AsyncMock, return_value="크롤링된 본문"):
|
||||
result = await enrich_top_blogs(blogs)
|
||||
assert len(result) == 2
|
||||
assert result[0]["content"] == "크롤링된 본문"
|
||||
assert result[1]["content"] == "크롤링된 본문"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_enrich_top_blogs_handles_partial_failure():
|
||||
"""일부 크롤링 실패 시에도 나머지는 정상 처리."""
|
||||
blogs = [
|
||||
{"title": "성공", "link": "https://blog.naver.com/user1/111"},
|
||||
{"title": "실패", "link": "https://blog.naver.com/user2/222"},
|
||||
]
|
||||
side_effects = ["성공 본문", Exception("fail")]
|
||||
with patch("app.web_crawler.crawl_blog_content", new_callable=AsyncMock, side_effect=side_effects):
|
||||
result = await enrich_top_blogs(blogs)
|
||||
assert result[0]["content"] == "성공 본문"
|
||||
assert result[1]["content"] == ""
|
||||
86
blog-lab/tests/test_writer.py
Normal file
86
blog-lab/tests/test_writer.py
Normal file
@@ -0,0 +1,86 @@
|
||||
"""작가 단계 테스트 -- 크롤링 본문 + 링크 참조 글 생성."""
|
||||
import json
|
||||
import pytest
|
||||
from unittest.mock import patch
|
||||
|
||||
|
||||
def test_generate_blog_post_includes_crawled_content():
|
||||
"""크롤링 본문이 프롬프트에 포함되는지 확인."""
|
||||
from app.content_generator import generate_blog_post
|
||||
|
||||
analysis = {
|
||||
"keyword": "무선 이어폰",
|
||||
"top_products": [{"title": "에어팟", "lprice": 200000, "mallName": "애플"}],
|
||||
"top_blogs": [
|
||||
{"title": "에어팟 리뷰", "content": "에어팟을 한 달간 써봤는데 음질이 정말 좋았습니다."},
|
||||
],
|
||||
}
|
||||
|
||||
mock_response = json.dumps({
|
||||
"title": "무선 이어폰 추천",
|
||||
"body": "<p>본문</p>",
|
||||
"excerpt": "요약",
|
||||
"tags": ["이어폰"],
|
||||
})
|
||||
|
||||
with patch("app.content_generator._call_claude", return_value=mock_response) as mock_call, \
|
||||
patch("app.content_generator.get_template", return_value=(
|
||||
"키워드: {keyword}\n참고 블로그:\n{reference_blogs}\n상품: {top_products}\n링크 상품: {brand_products}"
|
||||
)):
|
||||
result = generate_blog_post(analysis, "트렌드 브리프", brand_links=[])
|
||||
|
||||
prompt_used = mock_call.call_args[0][0]
|
||||
assert "에어팟을 한 달간 써봤는데" in prompt_used
|
||||
assert result["title"] == "무선 이어폰 추천"
|
||||
|
||||
|
||||
def test_generate_blog_post_includes_brand_links():
|
||||
"""브랜드커넥트 링크 정보가 프롬프트에 포함되는지 확인."""
|
||||
from app.content_generator import generate_blog_post
|
||||
|
||||
analysis = {"keyword": "무선 이어폰", "top_products": [], "top_blogs": []}
|
||||
brand_links = [
|
||||
{"url": "https://link.coupang.com/abc", "product_name": "삼성 버즈3",
|
||||
"description": "노이즈캔슬링 지원", "placement_hint": "본문 중간"},
|
||||
]
|
||||
|
||||
mock_response = json.dumps({
|
||||
"title": "제목", "body": "<p>본문</p>", "excerpt": "요약", "tags": ["태그"],
|
||||
})
|
||||
|
||||
with patch("app.content_generator._call_claude", return_value=mock_response) as mock_call, \
|
||||
patch("app.content_generator.get_template", return_value=(
|
||||
"키워드: {keyword}\n참고 블로그:\n{reference_blogs}\n상품: {top_products}\n링크 상품: {brand_products}"
|
||||
)):
|
||||
result = generate_blog_post(analysis, "트렌드 브리프", brand_links=brand_links)
|
||||
|
||||
prompt_used = mock_call.call_args[0][0]
|
||||
assert "삼성 버즈3" in prompt_used
|
||||
assert "노이즈캔슬링 지원" in prompt_used
|
||||
|
||||
|
||||
def test_generate_blog_post_works_without_links():
|
||||
"""링크 없이도 정상 동작."""
|
||||
from app.content_generator import generate_blog_post
|
||||
|
||||
analysis = {"keyword": "테스트", "top_products": [], "top_blogs": []}
|
||||
mock_response = json.dumps({
|
||||
"title": "제목", "body": "<p>본문</p>", "excerpt": "요약", "tags": ["태그"],
|
||||
})
|
||||
|
||||
with patch("app.content_generator._call_claude", return_value=mock_response), \
|
||||
patch("app.content_generator.get_template", return_value=(
|
||||
"키워드: {keyword}\n참고 블로그:\n{reference_blogs}\n상품: {top_products}\n링크 상품: {brand_products}"
|
||||
)):
|
||||
result = generate_blog_post(analysis, "브리프")
|
||||
|
||||
assert result["title"] == "제목"
|
||||
|
||||
|
||||
def test_parse_blog_json_fallback():
|
||||
"""JSON 파싱 실패 시 원본 텍스트를 body로 사용."""
|
||||
from app.content_generator import _parse_blog_json
|
||||
|
||||
result = _parse_blog_json("잘못된 JSON", "테스트 키워드")
|
||||
assert result["title"] == "테스트 키워드 추천 리뷰"
|
||||
assert result["body"] == "잘못된 JSON"
|
||||
@@ -1,12 +1,12 @@
|
||||
name: webpage
|
||||
|
||||
services:
|
||||
lotto:
|
||||
backend:
|
||||
build:
|
||||
context: ./lotto
|
||||
context: ./backend
|
||||
args:
|
||||
APP_VERSION: ${APP_VERSION:-dev}
|
||||
container_name: lotto
|
||||
container_name: lotto-backend
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "18000:8000"
|
||||
@@ -22,12 +22,12 @@ services:
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
|
||||
stock:
|
||||
stock-lab:
|
||||
build:
|
||||
context: ./stock
|
||||
context: ./stock-lab
|
||||
args:
|
||||
APP_VERSION: ${APP_VERSION:-dev}
|
||||
container_name: stock
|
||||
container_name: stock-lab
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "18500:8000"
|
||||
@@ -38,12 +38,7 @@ services:
|
||||
- GEMINI_MODEL=${GEMINI_MODEL:-gemini-1.5-flash}
|
||||
- ADMIN_API_KEY=${ADMIN_API_KEY:-}
|
||||
- ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY:-}
|
||||
- ANTHROPIC_MODEL=${ANTHROPIC_MODEL:-claude-haiku-4-5-20251001}
|
||||
- LLM_PROVIDER=${LLM_PROVIDER:-claude}
|
||||
- OLLAMA_URL=${OLLAMA_URL:-http://192.168.45.59:11435}
|
||||
- OLLAMA_MODEL=${OLLAMA_MODEL:-qwen3:14b}
|
||||
- CORS_ALLOW_ORIGINS=${CORS_ALLOW_ORIGINS:-http://localhost:3007,http://localhost:8080}
|
||||
- WEBAI_API_KEY=${WEBAI_API_KEY:-}
|
||||
volumes:
|
||||
- ${RUNTIME_PATH}/data/stock:/app/data
|
||||
healthcheck:
|
||||
@@ -65,46 +60,29 @@ services:
|
||||
- SUNO_API_KEY=${SUNO_API_KEY:-}
|
||||
- MUSIC_MEDIA_BASE=${MUSIC_MEDIA_BASE:-/media/music}
|
||||
- CORS_ALLOW_ORIGINS=${CORS_ALLOW_ORIGINS:-http://localhost:3007,http://localhost:8080}
|
||||
- PEXELS_API_KEY=${PEXELS_API_KEY:-}
|
||||
- ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY:-}
|
||||
- OPENAI_API_KEY=${OPENAI_API_KEY:-}
|
||||
- YOUTUBE_OAUTH_CLIENT_ID=${YOUTUBE_OAUTH_CLIENT_ID:-}
|
||||
- YOUTUBE_OAUTH_CLIENT_SECRET=${YOUTUBE_OAUTH_CLIENT_SECRET:-}
|
||||
- YOUTUBE_OAUTH_REDIRECT_URI=${YOUTUBE_OAUTH_REDIRECT_URI:-}
|
||||
- CLAUDE_HAIKU_MODEL=${CLAUDE_HAIKU_MODEL:-claude-haiku-4-5-20251001}
|
||||
- CLAUDE_SONNET_MODEL=${CLAUDE_SONNET_MODEL:-claude-sonnet-4-6}
|
||||
- VIDEO_DATA_DIR=${VIDEO_DATA_DIR:-/app/data/videos}
|
||||
- WINDOWS_VIDEO_ENCODER_URL=${WINDOWS_VIDEO_ENCODER_URL:-}
|
||||
- NAS_VIDEOS_ROOT=${NAS_VIDEOS_ROOT:-/volume1/docker/webpage/data/videos}
|
||||
- NAS_MUSIC_ROOT=${NAS_MUSIC_ROOT:-/volume1/docker/webpage/data/music}
|
||||
volumes:
|
||||
- ${RUNTIME_PATH}/data/music:/app/data
|
||||
- ${RUNTIME_PATH:-.}/data/videos:/app/data/videos
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
|
||||
insta-lab:
|
||||
blog-lab:
|
||||
build:
|
||||
context: ./insta-lab
|
||||
container_name: insta-lab
|
||||
context: ./blog-lab
|
||||
container_name: blog-lab
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "18700:8000"
|
||||
environment:
|
||||
- TZ=${TZ:-Asia/Seoul}
|
||||
- ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY:-}
|
||||
- ANTHROPIC_MODEL_HAIKU=${ANTHROPIC_MODEL_HAIKU:-claude-haiku-4-5-20251001}
|
||||
- ANTHROPIC_MODEL_SONNET=${ANTHROPIC_MODEL_SONNET:-claude-sonnet-4-6}
|
||||
- NAVER_CLIENT_ID=${NAVER_CLIENT_ID:-}
|
||||
- NAVER_CLIENT_SECRET=${NAVER_CLIENT_SECRET:-}
|
||||
- INSTA_DATA_PATH=/app/data
|
||||
- CARD_TEMPLATE_DIR=/app/app/templates
|
||||
- CORS_ALLOW_ORIGINS=${CORS_ALLOW_ORIGINS:-http://localhost:3007,http://localhost:8080}
|
||||
volumes:
|
||||
- ${RUNTIME_PATH}/data/insta:/app/data
|
||||
- ${RUNTIME_PATH}/data/blog:/app/data
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"]
|
||||
interval: 30s
|
||||
@@ -122,7 +100,6 @@ services:
|
||||
- TZ=${TZ:-Asia/Seoul}
|
||||
- DATA_GO_KR_API_KEY=${DATA_GO_KR_API_KEY:-}
|
||||
- CORS_ALLOW_ORIGINS=${CORS_ALLOW_ORIGINS:-http://localhost:3007,http://localhost:8080}
|
||||
- AGENT_OFFICE_URL=${AGENT_OFFICE_URL:-http://agent-office:8000}
|
||||
volumes:
|
||||
- ${RUNTIME_PATH}/data/realestate:/app/data
|
||||
healthcheck:
|
||||
@@ -141,77 +118,16 @@ services:
|
||||
environment:
|
||||
- TZ=${TZ:-Asia/Seoul}
|
||||
- CORS_ALLOW_ORIGINS=${CORS_ALLOW_ORIGINS:-http://localhost:3007,http://localhost:8080}
|
||||
- STOCK_URL=http://stock:8000
|
||||
- STOCK_LAB_URL=http://stock-lab:8000
|
||||
- MUSIC_LAB_URL=http://music-lab:8000
|
||||
- INSTA_LAB_URL=http://insta-lab:8000
|
||||
- REALESTATE_LAB_URL=http://realestate-lab:8000
|
||||
- REALESTATE_DASHBOARD_URL=${REALESTATE_DASHBOARD_URL:-http://localhost:8080/realestate}
|
||||
- TELEGRAM_BOT_TOKEN=${TELEGRAM_BOT_TOKEN:-}
|
||||
- TELEGRAM_CHAT_ID=${TELEGRAM_CHAT_ID:-}
|
||||
- TELEGRAM_WEBHOOK_URL=${TELEGRAM_WEBHOOK_URL:-}
|
||||
- TELEGRAM_WIFE_CHAT_ID=${TELEGRAM_WIFE_CHAT_ID:-}
|
||||
- ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY:-}
|
||||
- CLAUDE_HAIKU_MODEL=${CLAUDE_HAIKU_MODEL:-claude-haiku-4-5-20251001}
|
||||
- CLAUDE_SONNET_MODEL=${CLAUDE_SONNET_MODEL:-claude-sonnet-4-6}
|
||||
- LOTTO_BACKEND_URL=${LOTTO_BACKEND_URL:-http://lotto:8000}
|
||||
- LOTTO_CURATOR_MODEL=${LOTTO_CURATOR_MODEL:-claude-sonnet-4-5}
|
||||
- CONVERSATION_MODEL=${CONVERSATION_MODEL:-claude-haiku-4-5-20251001}
|
||||
- CONVERSATION_HISTORY_LIMIT=${CONVERSATION_HISTORY_LIMIT:-20}
|
||||
- CONVERSATION_RATE_PER_MIN=${CONVERSATION_RATE_PER_MIN:-6}
|
||||
- YOUTUBE_DATA_API_KEY=${YOUTUBE_DATA_API_KEY:-}
|
||||
volumes:
|
||||
- ${RUNTIME_PATH:-.}/data/agent-office:/app/data
|
||||
depends_on:
|
||||
- stock
|
||||
- stock-lab
|
||||
- music-lab
|
||||
- insta-lab
|
||||
- realestate-lab
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
|
||||
personal:
|
||||
build:
|
||||
context: ./personal
|
||||
container_name: personal
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "18850:8000"
|
||||
environment:
|
||||
- TZ=${TZ:-Asia/Seoul}
|
||||
- PORTFOLIO_EDIT_PASSWORD=${PORTFOLIO_EDIT_PASSWORD:-}
|
||||
- CORS_ALLOW_ORIGINS=${CORS_ALLOW_ORIGINS:-http://localhost:3007,http://localhost:8080}
|
||||
volumes:
|
||||
- ${RUNTIME_PATH:-.}/data/personal:/app/data
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
|
||||
packs-lab:
|
||||
build:
|
||||
context: ./packs-lab
|
||||
container_name: packs-lab
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "18950:8000"
|
||||
environment:
|
||||
- TZ=${TZ:-Asia/Seoul}
|
||||
- DSM_HOST=${DSM_HOST:-}
|
||||
- DSM_USER=${DSM_USER:-}
|
||||
- DSM_PASS=${DSM_PASS:-}
|
||||
- DSM_VERIFY_SSL=${DSM_VERIFY_SSL:-true}
|
||||
- BACKEND_HMAC_SECRET=${BACKEND_HMAC_SECRET:-}
|
||||
- SUPABASE_URL=${SUPABASE_URL:-}
|
||||
- SUPABASE_SERVICE_KEY=${SUPABASE_SERVICE_KEY:-}
|
||||
- UPLOAD_TOKEN_TTL_SEC=${UPLOAD_TOKEN_TTL_SEC:-1800}
|
||||
- PACK_BASE_DIR=${PACK_BASE_DIR:-/app/data/packs}
|
||||
- PACK_HOST_DIR=${PACK_HOST_DIR:-${PACK_DATA_PATH:-./data/packs}}
|
||||
volumes:
|
||||
- ${PACK_DATA_PATH:-./data/packs}:${PACK_BASE_DIR:-/app/data/packs}
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"]
|
||||
interval: 30s
|
||||
@@ -230,7 +146,7 @@ services:
|
||||
- TRAVEL_ROOT=${TRAVEL_ROOT:-/data/travel}
|
||||
- TRAVEL_THUMB_ROOT=${TRAVEL_THUMB_ROOT:-/data/thumbs}
|
||||
- TRAVEL_MEDIA_BASE=${TRAVEL_MEDIA_BASE:-/media/travel}
|
||||
- TRAVEL_DB_PATH=${TRAVEL_DB_PATH:-/data/thumbs/travel.db}
|
||||
- TRAVEL_CACHE_TTL=${TRAVEL_CACHE_TTL:-300}
|
||||
- CORS_ALLOW_ORIGINS=${CORS_ALLOW_ORIGINS:-http://localhost:3007,http://localhost:8080}
|
||||
volumes:
|
||||
- ${PHOTO_PATH}:/data/travel:ro
|
||||
@@ -243,18 +159,12 @@ services:
|
||||
|
||||
frontend:
|
||||
image: nginx:alpine
|
||||
container_name: frontend
|
||||
container_name: lotto-frontend
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
- lotto
|
||||
- stock
|
||||
- music-lab
|
||||
- insta-lab
|
||||
- blog-lab
|
||||
- realestate-lab
|
||||
- agent-office
|
||||
- personal
|
||||
- packs-lab
|
||||
- travel-proxy
|
||||
ports:
|
||||
- "8080:80"
|
||||
volumes:
|
||||
@@ -263,7 +173,6 @@ services:
|
||||
- ${PHOTO_PATH}:/data/travel:ro
|
||||
- ${RUNTIME_PATH}/travel-thumbs:/data/thumbs:ro
|
||||
- ${RUNTIME_PATH}/data/music:/data/music:ro
|
||||
- ${RUNTIME_PATH}/data/videos:/data/videos:ro
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
healthcheck:
|
||||
@@ -281,8 +190,6 @@ services:
|
||||
environment:
|
||||
- TZ=${TZ:-Asia/Seoul}
|
||||
- WEBHOOK_SECRET=${WEBHOOK_SECRET}
|
||||
- PUID=${PUID:-1026}
|
||||
- PGID=${PGID:-100}
|
||||
volumes:
|
||||
- ${REPO_PATH}:/repo:rw
|
||||
- ${RUNTIME_PATH}:/runtime:rw
|
||||
|
||||
@@ -1,252 +0,0 @@
|
||||
# 로또랩 프리미엄 서비스 고도화 로드맵
|
||||
|
||||
> 작성일: 2026-03-19
|
||||
> 목표: 번호 생성 도구 → 데이터 기반 로또 전략 코치
|
||||
|
||||
---
|
||||
|
||||
## 1. 현재 서비스 한계
|
||||
|
||||
현재 구조는 **"번호 생성 도구"** 수준으로 수익화에 한계가 있음.
|
||||
|
||||
| 문제 | 내용 |
|
||||
|------|------|
|
||||
| 차별점 부재 | 무료 로또 번호 생성기와 구분되지 않음 |
|
||||
| 신뢰 근거 부족 | 사용자가 결과를 믿을 데이터 시각화 없음 |
|
||||
| 리텐션 약함 | 지속적으로 돌아올 이유가 없음 |
|
||||
|
||||
---
|
||||
|
||||
## 2. 포지셔닝 전환
|
||||
|
||||
> **"번호 생성"이 아니라 "데이터 기반 로또 전략 코치"**
|
||||
|
||||
사람들이 구독료를 지불하는 심리적 동기:
|
||||
|
||||
- **확신**: 내가 선택한 번호가 좋은 선택이라는 데이터 근거
|
||||
- **FOMO**: 이번 주 리포트를 못 받으면 놓치는 느낌
|
||||
- **소유감**: 내 데이터와 이력이 축적된다는 느낌
|
||||
|
||||
---
|
||||
|
||||
## 3. 고도화 방향 (5가지)
|
||||
|
||||
### 3-1. 당첨 근접도 추적 — 신뢰 기반 구축
|
||||
|
||||
**목표**: 기존 채점 데이터(`check_results_for_draw`)를 신뢰 지표로 전환
|
||||
|
||||
**구현 내용**:
|
||||
- 추천 번호의 회차별 일치 개수 통계 집계
|
||||
- 전국 평균 대비 성과 비교 지표 노출
|
||||
- 매주 "지난 주 내 번호 성과" 이메일/푸시 발송
|
||||
|
||||
**예시 UI 문구**:
|
||||
```
|
||||
"지난 52주간 우리 추천번호의 평균 일치 개수: 2.7개 (전국 평균 1.9개)"
|
||||
"3개 일치율이 일반 무작위 대비 43% 높습니다"
|
||||
```
|
||||
|
||||
**활용 데이터**: 기존 `recommendations` + `draws` 테이블 채점 결과
|
||||
|
||||
**우선순위**: ⭐⭐⭐ (데이터 이미 존재, 즉시 구현 가능)
|
||||
|
||||
---
|
||||
|
||||
### 3-2. 개인화 분석 리포트 — 프리미엄 핵심 기능
|
||||
|
||||
**목표**: 모든 사용자에게 동일한 번호 → 개인 패턴 기반 맞춤 추천
|
||||
|
||||
**구현 내용**:
|
||||
- 사용자 번호 선택 이력 패턴 분석
|
||||
- 홀짝 비율, 번호대 분포, 연속번호 포함률 등 개인 성향 분석
|
||||
- 약점을 보완한 AI 보정 추천번호 생성
|
||||
|
||||
**예시 분석 항목**:
|
||||
```
|
||||
"당신은 홀수를 선호하는 경향 (67%)"
|
||||
"당신이 자주 피하는 번호대: 30번대"
|
||||
"당신 번호의 약점: 연속번호 포함률 낮음"
|
||||
→ "이를 보완한 AI 보정 추천번호 제공"
|
||||
```
|
||||
|
||||
**신규 테이블**: `user_preferences`
|
||||
|
||||
**우선순위**: ⭐⭐ (신규 테이블 및 분석 로직 필요)
|
||||
|
||||
---
|
||||
|
||||
### 3-3. 회차별 공략 리포트 — 킬러 콘텐츠
|
||||
|
||||
**목표**: 매주 추첨 전 발행하는 주간 분석 레포트 → 구독 유지 동기
|
||||
|
||||
**구현 내용**:
|
||||
- 매주 자동 생성되는 회차별 공략 리포트
|
||||
- 과출현/냉각 번호 분석
|
||||
- 패턴 기반 번호군 추천
|
||||
- AI 신뢰도 점수 표시
|
||||
|
||||
**예시 리포트 구조**:
|
||||
```
|
||||
[1180회 공략 리포트]
|
||||
- 최근 10회 과출현 번호 제외 추천
|
||||
- 이번 주 "냉각 구간" 번호 (오랫동안 미출현)
|
||||
- 패턴 분석: 직전 3회 연속 출현한 번호군
|
||||
- AI 신뢰도 점수: 87/100
|
||||
```
|
||||
|
||||
**스케줄러**: 매주 토요일 추첨 전 자동 생성 (APScheduler)
|
||||
|
||||
**우선순위**: ⭐⭐⭐ (주간 구독 모델의 핵심 훅)
|
||||
|
||||
---
|
||||
|
||||
### 3-4. 번호 포트폴리오 관리 — 차별화 UX
|
||||
|
||||
**목표**: 로또를 투자처럼 관리하는 경험 제공
|
||||
|
||||
**구현 내용**:
|
||||
- 세트 분류: 고위험/안정형/균형형
|
||||
- 구매 금액 직접 입력 → 수익률 자동 계산
|
||||
- 누적 투자 대비 당첨금 통계
|
||||
|
||||
**예시 화면**:
|
||||
```
|
||||
내 번호 포트폴리오
|
||||
├── 고위험/고수익 세트 (출현 빈도 낮은 번호 조합)
|
||||
├── 안정형 세트 (평균 출현 패턴)
|
||||
└── 균형형 세트 (시뮬레이션 최적화)
|
||||
|
||||
이번 주 매입: 3세트 (₩3,000)
|
||||
누적 투자: ₩240,000 / 누적 당첨: ₩45,000
|
||||
수익률: -81.2% (전국 평균 대비 +12.1%)
|
||||
```
|
||||
|
||||
**활용 데이터**: `best_picks`, `recommendations` 확장
|
||||
|
||||
**우선순위**: ⭐⭐ (UX 임팩트 큼, 중기 구현)
|
||||
|
||||
---
|
||||
|
||||
### 3-5. 커뮤니티 + 소셜 증거 — 바이럴 유도
|
||||
|
||||
**목표**: 사용자 참여 및 구전 마케팅
|
||||
|
||||
**구현 내용**:
|
||||
- 이번 주 가장 많이 선택된 번호 TOP 10 공개
|
||||
- "나와 같은 번호 선택한 회원 수" 표시
|
||||
- AI 추천으로 X개 일치 달성한 회원 수 표시
|
||||
|
||||
**예시**:
|
||||
```
|
||||
"이번 주 가장 많이 선택된 번호 TOP 10"
|
||||
"AI 추천 번호로 3개 일치 달성한 회원: 1,247명"
|
||||
"나와 같은 번호를 선택한 회원: 34명"
|
||||
```
|
||||
|
||||
**전략**: 무료 티어에 일부 공개 → 상세 분석은 유료 전환
|
||||
|
||||
**우선순위**: ⭐ (회원 시스템 구축 후 가능)
|
||||
|
||||
---
|
||||
|
||||
## 4. 구독 티어 설계
|
||||
|
||||
| 기능 | 무료 | 스탠다드 (₩2,900/월) | 프리미엄 (₩5,900/월) |
|
||||
|------|:----:|:----:|:----:|
|
||||
| 기본 추천 번호 | 1세트 | 5세트 | 무제한 |
|
||||
| 통계 분석 | 기본 | 심화 | 전체 |
|
||||
| 회차 공략 리포트 | - | 주간 요약 | 풀 리포트 |
|
||||
| 개인 패턴 분석 | - | - | ✓ |
|
||||
| 번호 포트폴리오 | - | ✓ | ✓ |
|
||||
| 당첨 근접도 통계 | - | ✓ | ✓ |
|
||||
| 당첨 알림 | - | 이메일 | 이메일 + 앱 |
|
||||
|
||||
---
|
||||
|
||||
## 5. 기술 구현 로드맵
|
||||
|
||||
### Phase 1 — 즉시 가능 (데이터 이미 존재)
|
||||
|
||||
- [ ] 추천 이력 채점 통계 API (`GET /api/lotto/stats/performance`)
|
||||
- [ ] 신뢰도 지표 UI (평균 일치 개수, 전국 평균 비교)
|
||||
- [ ] 회차별 공략 리포트 API (`GET /api/lotto/report/{drw_no}`)
|
||||
- [ ] 개인 추천 이력 성과 대시보드
|
||||
|
||||
### Phase 2 — 단기 (1-2주)
|
||||
|
||||
- [ ] `user_preferences` 테이블 설계 및 구현
|
||||
- [ ] 개인 패턴 분석 API (`GET /api/lotto/analysis/personal`)
|
||||
- [ ] 주간 리포트 자동 생성 스케줄러 (토요일 오전)
|
||||
- [ ] 투자 추적 기능 (구매 금액 입력 → 수익률 계산)
|
||||
- [ ] `purchase_history` 테이블 추가
|
||||
|
||||
### Phase 3 — 중기 (1개월)
|
||||
|
||||
- [ ] 회원 시스템 구축 (JWT 인증, SQLite `users` 테이블)
|
||||
- [ ] 구독 플랜 관리 (`subscription_plans`, `user_subscriptions` 테이블)
|
||||
- [ ] 결제 연동 (Toss Payments 또는 Stripe)
|
||||
- [ ] 이메일 발송 자동화 (SendGrid)
|
||||
- [ ] 소셜 증거 데이터 집계 API
|
||||
|
||||
---
|
||||
|
||||
## 6. DB 스키마 확장 계획
|
||||
|
||||
```sql
|
||||
-- Phase 2
|
||||
CREATE TABLE purchase_history (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
draw_no INTEGER NOT NULL,
|
||||
amount INTEGER NOT NULL, -- 구매 금액 (원)
|
||||
sets INTEGER NOT NULL DEFAULT 1, -- 구매 세트 수
|
||||
prize INTEGER DEFAULT 0, -- 당첨금
|
||||
note TEXT,
|
||||
created_at TEXT DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
CREATE TABLE user_preferences (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
odd_ratio REAL, -- 홀수 선호 비율
|
||||
high_ratio REAL, -- 고번호(23+) 선호 비율
|
||||
consecutive INTEGER, -- 연속번호 포함 선호 여부
|
||||
excluded_numbers TEXT, -- JSON 배열, 기피 번호
|
||||
updated_at TEXT DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
-- Phase 3
|
||||
CREATE TABLE users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
email TEXT UNIQUE NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
plan TEXT DEFAULT 'free', -- free | standard | premium
|
||||
plan_expires_at TEXT,
|
||||
created_at TEXT DEFAULT (datetime('now'))
|
||||
);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. API 확장 계획
|
||||
|
||||
| Phase | 메서드 | 경로 | 설명 |
|
||||
|-------|--------|------|------|
|
||||
| 1 | GET | `/api/lotto/stats/performance` | 추천 성과 통계 (평균 일치 수 등) |
|
||||
| 1 | GET | `/api/lotto/report/latest` | 최신 회차 공략 리포트 |
|
||||
| 1 | GET | `/api/lotto/report/{drw_no}` | 특정 회차 공략 리포트 |
|
||||
| 2 | GET | `/api/lotto/purchase` | 구매 이력 조회 |
|
||||
| 2 | POST | `/api/lotto/purchase` | 구매 이력 추가 |
|
||||
| 2 | GET | `/api/lotto/purchase/stats` | 투자 수익률 통계 |
|
||||
| 2 | GET | `/api/lotto/analysis/personal` | 개인 패턴 분석 |
|
||||
| 3 | POST | `/api/auth/register` | 회원가입 |
|
||||
| 3 | POST | `/api/auth/login` | 로그인 |
|
||||
| 3 | GET | `/api/subscription/plans` | 구독 플랜 목록 |
|
||||
| 3 | POST | `/api/subscription/checkout` | 결제 시작 |
|
||||
|
||||
---
|
||||
|
||||
## 참고
|
||||
|
||||
- 현재 운영 중인 lotto API: `CLAUDE.md` → `lotto-lab API 목록` 섹션 참고
|
||||
- 채점 로직: `backend/app/checker.py`
|
||||
- 시뮬레이션 로직: `backend/app/recommender.py`
|
||||
- DB 스키마: `backend/app/db.py` `init_db()`
|
||||
File diff suppressed because it is too large
Load Diff
1509
docs/superpowers/plans/2026-04-05-realestate-lab.md
Normal file
1509
docs/superpowers/plans/2026-04-05-realestate-lab.md
Normal file
File diff suppressed because it is too large
Load Diff
2594
docs/superpowers/plans/2026-04-08-music-lab-suno-enhancement.md
Normal file
2594
docs/superpowers/plans/2026-04-08-music-lab-suno-enhancement.md
Normal file
File diff suppressed because it is too large
Load Diff
2961
docs/superpowers/plans/2026-04-11-agent-office.md
Normal file
2961
docs/superpowers/plans/2026-04-11-agent-office.md
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,977 +0,0 @@
|
||||
# packs-lab 인프라 통합 + admin mint-token Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** packs-lab을 운영 가능 상태로 만든다 — admin upload 토큰 발급 endpoint + Supabase 스키마 + docker-compose/nginx/env 통합 + 통합 테스트 + 문서 갱신.
|
||||
|
||||
**Architecture:** 기존 코드(HMAC + DSM client + 4 라우트)는 그대로 유지하고, 신규 라우트 1개(`POST /api/packs/admin/mint-token`)를 routes.py에 추가한다. Supabase `pack_files` DDL 파일과 인프라(docker-compose 18950, nginx 5GB streaming, .env.example 6+1 환경변수)를 신설하고, 통합 테스트(routes + dsm_client mock)와 CLAUDE.md 5+1곳을 갱신한다.
|
||||
|
||||
**Tech Stack:** Python 3.12 / FastAPI / pytest + unittest.mock / Supabase(PostgreSQL) / Synology DSM 7.x API / nginx / Docker Compose
|
||||
|
||||
**스펙 참조:** `docs/superpowers/specs/2026-05-05-packs-lab-infra-integration-design.md`
|
||||
|
||||
**작업 디렉토리:** `C:\Users\jaeoh\Desktop\workspace\web-backend` (기존 web-backend repo)
|
||||
|
||||
---
|
||||
|
||||
## Task 1: 테스트 인프라 — `tests/conftest.py`
|
||||
|
||||
기존 `tests/test_auth.py`는 `BACKEND_HMAC_SECRET=secret` 같은 fixture가 없어 환경변수 의존. 모든 테스트가 동일한 secret으로 동작하도록 autouse fixture를 conftest에 정리.
|
||||
|
||||
**Files:**
|
||||
- Create: `packs-lab/tests/conftest.py`
|
||||
|
||||
- [ ] **Step 1: conftest.py 생성**
|
||||
|
||||
`packs-lab/tests/conftest.py`:
|
||||
|
||||
```python
|
||||
"""packs-lab 테스트 공통 fixture."""
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _hmac_secret(monkeypatch):
|
||||
"""모든 테스트에서 동일한 HMAC secret 사용. auth._SECRET 모듈 캐시까지 갱신."""
|
||||
monkeypatch.setenv("BACKEND_HMAC_SECRET", "test-secret-do-not-use-in-prod")
|
||||
# auth.py 모듈은 import 시점에 _SECRET을 캐시하므로 monkeypatch로 함께 갱신
|
||||
from app import auth
|
||||
monkeypatch.setattr(auth, "_SECRET", "test-secret-do-not-use-in-prod")
|
||||
```
|
||||
|
||||
- [ ] **Step 2: 기존 test_auth.py 회귀 검증**
|
||||
|
||||
```bash
|
||||
cd C:\Users\jaeoh\Desktop\workspace\web-backend\packs-lab
|
||||
python -m pytest tests/test_auth.py -v
|
||||
```
|
||||
|
||||
Expected: 기존 테스트 모두 PASS (conftest 영향 없거나 PASS 그대로 유지). 만약 secret 인코딩 차이로 실패 시 해당 테스트의 secret 사용 부분을 conftest 값과 일치시킨다.
|
||||
|
||||
- [ ] **Step 3: 커밋**
|
||||
|
||||
```bash
|
||||
git add packs-lab/tests/conftest.py
|
||||
git commit -m "test(packs-lab): conftest로 HMAC secret 통일"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 2: admin mint-token 라우트 (스키마 + 구현 + 테스트)
|
||||
|
||||
`POST /api/packs/admin/mint-token` 신규. Pydantic 스키마 추가 + 라우트 구현 + 통합 테스트.
|
||||
|
||||
**Files:**
|
||||
- Modify: `packs-lab/app/models.py` (스키마 2개 추가)
|
||||
- Modify: `packs-lab/app/routes.py` (import 보강 + 라우트 추가)
|
||||
- Create: `packs-lab/tests/test_routes.py` (mint-token 관련 테스트만 우선)
|
||||
|
||||
- [ ] **Step 1: failing 테스트 작성**
|
||||
|
||||
`packs-lab/tests/test_routes.py`:
|
||||
|
||||
```python
|
||||
"""packs-lab 라우트 통합 테스트.
|
||||
|
||||
DSM·Supabase는 mock. HMAC 검증·토큰 발급·검증은 실제 코드 사용.
|
||||
"""
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import time
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.main import app
|
||||
|
||||
SECRET = "test-secret-do-not-use-in-prod"
|
||||
|
||||
|
||||
def _hmac_headers(body_bytes: bytes) -> dict:
|
||||
"""body에 대한 X-Timestamp + X-Signature 헤더 생성."""
|
||||
ts = str(int(time.time()))
|
||||
sig = hmac.new(SECRET.encode(), ts.encode() + b"." + body_bytes, hashlib.sha256).hexdigest()
|
||||
return {"X-Timestamp": ts, "X-Signature": sig}
|
||||
|
||||
|
||||
def test_mint_token_hmac_required():
|
||||
"""HMAC 헤더 누락 → 401."""
|
||||
client = TestClient(app)
|
||||
body = {"tier": "pro", "label": "샘플", "filename": "x.zip", "size_bytes": 1024}
|
||||
resp = client.post("/api/packs/admin/mint-token", json=body)
|
||||
assert resp.status_code == 401
|
||||
|
||||
|
||||
def test_mint_token_returns_valid_token():
|
||||
"""발급된 token이 verify_upload_token으로 통과해야 한다."""
|
||||
from app.auth import verify_upload_token
|
||||
|
||||
body = {"tier": "pro", "label": "샘플", "filename": "test.zip", "size_bytes": 2048}
|
||||
body_bytes = json.dumps(body).encode()
|
||||
headers = _hmac_headers(body_bytes)
|
||||
headers["Content-Type"] = "application/json"
|
||||
|
||||
client = TestClient(app)
|
||||
resp = client.post("/api/packs/admin/mint-token", content=body_bytes, headers=headers)
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert "token" in data and "expires_at" in data and "jti" in data
|
||||
|
||||
payload = verify_upload_token(data["token"])
|
||||
assert payload["tier"] == "pro"
|
||||
assert payload["label"] == "샘플"
|
||||
assert payload["filename"] == "test.zip"
|
||||
assert payload["size_bytes"] == 2048
|
||||
assert payload["jti"] == data["jti"]
|
||||
|
||||
|
||||
def test_mint_token_invalid_filename():
|
||||
"""허용 외 확장자 → 400."""
|
||||
body = {"tier": "pro", "label": "샘플", "filename": "x.exe", "size_bytes": 1024}
|
||||
body_bytes = json.dumps(body).encode()
|
||||
headers = _hmac_headers(body_bytes)
|
||||
headers["Content-Type"] = "application/json"
|
||||
|
||||
client = TestClient(app)
|
||||
resp = client.post("/api/packs/admin/mint-token", content=body_bytes, headers=headers)
|
||||
assert resp.status_code == 400
|
||||
```
|
||||
|
||||
- [ ] **Step 2: 실패 확인**
|
||||
|
||||
```bash
|
||||
cd packs-lab
|
||||
python -m pytest tests/test_routes.py -v
|
||||
```
|
||||
|
||||
Expected: 모든 테스트 FAIL — `/api/packs/admin/mint-token` 라우트 없음 (404 또는 405).
|
||||
|
||||
- [ ] **Step 3: models.py에 스키마 추가**
|
||||
|
||||
`packs-lab/app/models.py` 끝부분에 추가:
|
||||
|
||||
```python
|
||||
class MintTokenRequest(BaseModel):
|
||||
"""Vercel → backend: admin upload 토큰 발급 요청."""
|
||||
tier: PackTier
|
||||
label: str = Field(..., max_length=200)
|
||||
filename: str = Field(..., max_length=255)
|
||||
size_bytes: int = Field(..., gt=0, le=5 * 1024 * 1024 * 1024)
|
||||
|
||||
|
||||
class MintTokenResponse(BaseModel):
|
||||
token: str
|
||||
expires_at: datetime
|
||||
jti: str
|
||||
```
|
||||
|
||||
- [ ] **Step 4: routes.py에 mint-token 라우트 추가**
|
||||
|
||||
`packs-lab/app/routes.py` 상단 import 블록에 다음을 추가:
|
||||
|
||||
```python
|
||||
import time
|
||||
from datetime import timezone
|
||||
```
|
||||
|
||||
(이미 `import uuid`, `from datetime import datetime`은 있음)
|
||||
|
||||
`from .auth import` 라인을 다음과 같이 확장:
|
||||
|
||||
```python
|
||||
from .auth import mint_upload_token, verify_request_hmac, verify_upload_token
|
||||
```
|
||||
|
||||
`from .models import` 라인을 다음과 같이 확장:
|
||||
|
||||
```python
|
||||
from .models import (
|
||||
MintTokenRequest,
|
||||
MintTokenResponse,
|
||||
PackFileItem,
|
||||
SignLinkRequest,
|
||||
SignLinkResponse,
|
||||
UploadResponse,
|
||||
)
|
||||
```
|
||||
|
||||
상수 추가 (`MAX_BYTES` 다음 줄에):
|
||||
|
||||
```python
|
||||
UPLOAD_TOKEN_TTL_SEC = int(os.getenv("UPLOAD_TOKEN_TTL_SEC", "1800")) # 30분 default
|
||||
```
|
||||
|
||||
라우트 추가 (`sign_link` 함수 다음, `upload` 함수 앞):
|
||||
|
||||
```python
|
||||
@router.post("/admin/mint-token", response_model=MintTokenResponse)
|
||||
async def mint_token(
|
||||
request: Request,
|
||||
x_timestamp: str = Header(""),
|
||||
x_signature: str = Header(""),
|
||||
):
|
||||
body = await request.body()
|
||||
verify_request_hmac(body, x_timestamp, x_signature)
|
||||
payload = MintTokenRequest.model_validate_json(body)
|
||||
_check_filename(payload.filename)
|
||||
|
||||
jti = str(uuid.uuid4())
|
||||
expires_ts = int(time.time()) + UPLOAD_TOKEN_TTL_SEC
|
||||
token = mint_upload_token({
|
||||
"tier": payload.tier,
|
||||
"label": payload.label,
|
||||
"filename": payload.filename,
|
||||
"size_bytes": payload.size_bytes,
|
||||
"jti": jti,
|
||||
"expires_at": expires_ts,
|
||||
})
|
||||
return MintTokenResponse(
|
||||
token=token,
|
||||
expires_at=datetime.fromtimestamp(expires_ts, tz=timezone.utc),
|
||||
jti=jti,
|
||||
)
|
||||
```
|
||||
|
||||
- [ ] **Step 5: 테스트 통과 확인**
|
||||
|
||||
```bash
|
||||
cd packs-lab
|
||||
python -m pytest tests/test_routes.py -v
|
||||
```
|
||||
|
||||
Expected: 3 passed.
|
||||
|
||||
- [ ] **Step 6: 커밋**
|
||||
|
||||
```bash
|
||||
git add packs-lab/app/models.py packs-lab/app/routes.py packs-lab/tests/test_routes.py
|
||||
git commit -m "feat(packs-lab): POST /api/packs/admin/mint-token 라우트 + 통합 테스트"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 3: 기존 4 라우트 통합 테스트 (sign-link / upload / list / delete)
|
||||
|
||||
기존 라우트는 변경 없음. 테스트만 추가해 회귀 안전망 확보.
|
||||
|
||||
**Files:**
|
||||
- Modify: `packs-lab/tests/test_routes.py` (테스트 8개 추가)
|
||||
|
||||
- [ ] **Step 1: sign-link 테스트 추가**
|
||||
|
||||
`tests/test_routes.py` 끝에 추가:
|
||||
|
||||
```python
|
||||
def test_sign_link_hmac_required():
|
||||
"""HMAC 헤더 없으면 401."""
|
||||
client = TestClient(app)
|
||||
body = {"file_path": "/volume1/docker/webpage/media/packs/pro/x.zip"}
|
||||
resp = client.post("/api/packs/sign-link", json=body)
|
||||
assert resp.status_code == 401
|
||||
|
||||
|
||||
def test_sign_link_outside_base_dir():
|
||||
"""PACK_BASE_DIR 외부 경로 → 400."""
|
||||
body = {"file_path": "/etc/passwd"}
|
||||
body_bytes = json.dumps(body).encode()
|
||||
headers = _hmac_headers(body_bytes)
|
||||
headers["Content-Type"] = "application/json"
|
||||
|
||||
client = TestClient(app)
|
||||
resp = client.post("/api/packs/sign-link", content=body_bytes, headers=headers)
|
||||
assert resp.status_code == 400
|
||||
|
||||
|
||||
def test_sign_link_calls_dsm():
|
||||
"""DSM client 호출되고 응답 URL 반환."""
|
||||
from datetime import datetime, timezone
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
body = {"file_path": "/volume1/docker/webpage/media/packs/pro/sample.zip"}
|
||||
body_bytes = json.dumps(body).encode()
|
||||
headers = _hmac_headers(body_bytes)
|
||||
headers["Content-Type"] = "application/json"
|
||||
|
||||
fake_url = "https://gahusb.synology.me:5001/sharing/abc123"
|
||||
fake_expires = datetime(2026, 5, 5, 13, 0, tzinfo=timezone.utc)
|
||||
|
||||
with patch("app.routes.create_share_link", new=AsyncMock(return_value=(fake_url, fake_expires))) as mock:
|
||||
client = TestClient(app)
|
||||
resp = client.post("/api/packs/sign-link", content=body_bytes, headers=headers)
|
||||
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["url"] == fake_url
|
||||
mock.assert_awaited_once()
|
||||
```
|
||||
|
||||
- [ ] **Step 2: upload 테스트 추가**
|
||||
|
||||
```python
|
||||
def _make_upload_token(tier="pro", label="샘플", filename="test.zip", size_bytes=1024, jti=None, ttl=1800):
|
||||
"""테스트용 upload token 생성. mint_token endpoint 거치지 않고 직접."""
|
||||
import uuid
|
||||
from app.auth import mint_upload_token
|
||||
return mint_upload_token({
|
||||
"tier": tier,
|
||||
"label": label,
|
||||
"filename": filename,
|
||||
"size_bytes": size_bytes,
|
||||
"jti": jti or str(uuid.uuid4()),
|
||||
"expires_at": int(time.time()) + ttl,
|
||||
})
|
||||
|
||||
|
||||
def test_upload_token_required():
|
||||
"""Authorization Bearer 누락 → 401."""
|
||||
client = TestClient(app)
|
||||
resp = client.post("/api/packs/upload", files={"file": ("x.zip", b"hello")})
|
||||
assert resp.status_code == 401
|
||||
|
||||
|
||||
def test_upload_size_mismatch(tmp_path, monkeypatch):
|
||||
"""토큰 size_bytes ≠ 실제 → 400 + 파일 정리됨."""
|
||||
monkeypatch.setattr("app.routes.PACK_BASE_DIR", tmp_path)
|
||||
token = _make_upload_token(size_bytes=999) # 실제 5바이트지만 토큰엔 999
|
||||
|
||||
client = TestClient(app)
|
||||
resp = client.post(
|
||||
"/api/packs/upload",
|
||||
files={"file": ("test.zip", b"hello")},
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
)
|
||||
assert resp.status_code == 400
|
||||
assert "크기" in resp.json()["detail"]
|
||||
|
||||
|
||||
def test_upload_jti_replay(tmp_path, monkeypatch):
|
||||
"""같은 jti 토큰 두 번 → 두 번째 409."""
|
||||
monkeypatch.setattr("app.routes.PACK_BASE_DIR", tmp_path)
|
||||
|
||||
fake_supabase = MagicMock()
|
||||
fake_supabase.table.return_value.insert.return_value.execute.return_value = MagicMock(
|
||||
data=[{"uploaded_at": "2026-05-05T12:00:00+00:00"}]
|
||||
)
|
||||
|
||||
token = _make_upload_token(filename="replay.zip", size_bytes=5, jti="replay-jti-1")
|
||||
|
||||
with patch("app.routes._supabase", return_value=fake_supabase):
|
||||
client = TestClient(app)
|
||||
|
||||
# 1차: 성공
|
||||
resp1 = client.post(
|
||||
"/api/packs/upload",
|
||||
files={"file": ("replay.zip", b"hello")},
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
)
|
||||
assert resp1.status_code == 200
|
||||
|
||||
# 2차: 동일 토큰 재사용 — 두 번째 파일은 다른 이름으로 보내 파일명 충돌 회피
|
||||
resp2 = client.post(
|
||||
"/api/packs/upload",
|
||||
files={"file": ("replay.zip", b"world")},
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
)
|
||||
assert resp2.status_code == 409
|
||||
```
|
||||
|
||||
- [ ] **Step 3: list / delete 테스트 추가**
|
||||
|
||||
```python
|
||||
def test_list_returns_active_only():
|
||||
"""mock supabase가 deleted_at IS NULL 행만 반환하는지 (쿼리 빌더 호출 검증)."""
|
||||
fake_rows = [
|
||||
{
|
||||
"id": "11111111-1111-1111-1111-111111111111",
|
||||
"min_tier": "pro",
|
||||
"label": "샘플",
|
||||
"file_path": "/volume1/docker/webpage/media/packs/pro/a.zip",
|
||||
"filename": "a.zip",
|
||||
"size_bytes": 1024,
|
||||
"sort_order": 0,
|
||||
"uploaded_at": "2026-05-05T12:00:00+00:00",
|
||||
}
|
||||
]
|
||||
|
||||
fake_supabase = MagicMock()
|
||||
chain = fake_supabase.table.return_value.select.return_value
|
||||
chain.is_.return_value.order.return_value.order.return_value.execute.return_value = MagicMock(data=fake_rows)
|
||||
|
||||
body_bytes = b""
|
||||
headers = _hmac_headers(body_bytes)
|
||||
|
||||
with patch("app.routes._supabase", return_value=fake_supabase):
|
||||
client = TestClient(app)
|
||||
resp = client.get("/api/packs/list", headers=headers)
|
||||
|
||||
assert resp.status_code == 200
|
||||
items = resp.json()
|
||||
assert len(items) == 1
|
||||
assert items[0]["filename"] == "a.zip"
|
||||
fake_supabase.table.return_value.select.return_value.is_.assert_called_with("deleted_at", "null")
|
||||
|
||||
|
||||
def test_delete_soft_deletes():
|
||||
"""DELETE 시 supabase update에 deleted_at ISO timestamp가 들어가야 한다."""
|
||||
fake_supabase = MagicMock()
|
||||
fake_supabase.table.return_value.update.return_value.eq.return_value.execute.return_value = MagicMock(
|
||||
data=[{"id": "abc"}]
|
||||
)
|
||||
|
||||
body_bytes = b""
|
||||
headers = _hmac_headers(body_bytes)
|
||||
|
||||
with patch("app.routes._supabase", return_value=fake_supabase):
|
||||
client = TestClient(app)
|
||||
resp = client.delete("/api/packs/abc", headers=headers)
|
||||
|
||||
assert resp.status_code == 200
|
||||
update_call = fake_supabase.table.return_value.update.call_args
|
||||
update_kwargs = update_call.args[0]
|
||||
assert "deleted_at" in update_kwargs
|
||||
# ISO 8601 timestamp 형식 검증 (예: 2026-05-05T12:00:00+00:00)
|
||||
assert "T" in update_kwargs["deleted_at"]
|
||||
```
|
||||
|
||||
- [ ] **Step 4: 테스트 실행**
|
||||
|
||||
```bash
|
||||
cd packs-lab
|
||||
python -m pytest tests/test_routes.py -v
|
||||
```
|
||||
|
||||
Expected: 11 passed (3 from Task 2 + 3 sign-link + 3 upload + 2 list/delete).
|
||||
|
||||
- [ ] **Step 5: 커밋**
|
||||
|
||||
```bash
|
||||
git add packs-lab/tests/test_routes.py
|
||||
git commit -m "test(packs-lab): 기존 4 라우트 통합 테스트 (sign-link, upload, list, delete)"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 4: `tests/test_dsm_client.py` — DSM client mock 테스트
|
||||
|
||||
**Files:**
|
||||
- Create: `packs-lab/tests/test_dsm_client.py`
|
||||
|
||||
- [ ] **Step 1: DSM client 테스트 작성**
|
||||
|
||||
`packs-lab/tests/test_dsm_client.py`:
|
||||
|
||||
```python
|
||||
"""DSM 7.x API client 테스트 — httpx mock으로 외부 호출 차단."""
|
||||
import asyncio
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
import pytest
|
||||
import httpx
|
||||
|
||||
from app.dsm_client import create_share_link, DSMError, _login, _logout
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _dsm_env(monkeypatch):
|
||||
monkeypatch.setenv("DSM_HOST", "https://test-nas:5001")
|
||||
monkeypatch.setenv("DSM_USER", "test-user")
|
||||
monkeypatch.setenv("DSM_PASS", "test-pass")
|
||||
# 모듈 캐시도 갱신
|
||||
from app import dsm_client
|
||||
monkeypatch.setattr(dsm_client, "DSM_HOST", "https://test-nas:5001")
|
||||
monkeypatch.setattr(dsm_client, "DSM_USER", "test-user")
|
||||
monkeypatch.setattr(dsm_client, "DSM_PASS", "test-pass")
|
||||
|
||||
|
||||
def _make_response(json_data, status_code=200):
|
||||
"""httpx.Response mock."""
|
||||
mock = MagicMock(spec=httpx.Response)
|
||||
mock.json.return_value = json_data
|
||||
mock.status_code = status_code
|
||||
mock.raise_for_status = MagicMock()
|
||||
return mock
|
||||
|
||||
|
||||
def test_create_share_link_login_logout():
|
||||
"""login → Sharing.create → logout 순서가 보장되어야 한다."""
|
||||
call_order = []
|
||||
|
||||
async def fake_get(self, url, *, params=None, **kw):
|
||||
api = (params or {}).get("api", "")
|
||||
method = (params or {}).get("method", "")
|
||||
call_order.append(f"{api}.{method}")
|
||||
if api == "SYNO.API.Auth" and method == "login":
|
||||
return _make_response({"success": True, "data": {"sid": "fake-sid"}})
|
||||
if api == "SYNO.API.Auth" and method == "logout":
|
||||
return _make_response({"success": True})
|
||||
if api == "SYNO.FileStation.Sharing" and method == "create":
|
||||
return _make_response({
|
||||
"success": True,
|
||||
"data": {"links": [{"url": "https://test-nas:5001/sharing/abc"}]},
|
||||
})
|
||||
return _make_response({"success": False, "error": "unexpected"})
|
||||
|
||||
with patch.object(httpx.AsyncClient, "get", new=fake_get):
|
||||
url, expires_at = asyncio.run(create_share_link("/volume1/test/file.zip", expires_in_sec=3600))
|
||||
|
||||
assert url == "https://test-nas:5001/sharing/abc"
|
||||
assert call_order == [
|
||||
"SYNO.API.Auth.login",
|
||||
"SYNO.FileStation.Sharing.create",
|
||||
"SYNO.API.Auth.logout",
|
||||
]
|
||||
|
||||
|
||||
def test_create_share_link_returns_url_and_expiry():
|
||||
"""응답 파싱 — links[0].url 사용."""
|
||||
async def fake_get(self, url, *, params=None, **kw):
|
||||
method = (params or {}).get("method", "")
|
||||
if method == "login":
|
||||
return _make_response({"success": True, "data": {"sid": "sid"}})
|
||||
if method == "create":
|
||||
return _make_response({
|
||||
"success": True,
|
||||
"data": {"links": [{"url": "https://nas/sharing/xyz"}]},
|
||||
})
|
||||
return _make_response({"success": True})
|
||||
|
||||
with patch.object(httpx.AsyncClient, "get", new=fake_get):
|
||||
url, expires_at = asyncio.run(create_share_link("/volume1/test/file.zip", expires_in_sec=7200))
|
||||
|
||||
assert url == "https://nas/sharing/xyz"
|
||||
assert expires_at is not None
|
||||
|
||||
|
||||
def test_dsm_login_failure_raises():
|
||||
"""login API success=False → DSMError."""
|
||||
async def fake_get(self, url, *, params=None, **kw):
|
||||
return _make_response({"success": False, "error": {"code": 400}})
|
||||
|
||||
with patch.object(httpx.AsyncClient, "get", new=fake_get):
|
||||
with pytest.raises(DSMError, match="login 실패"):
|
||||
asyncio.run(create_share_link("/volume1/test/file.zip"))
|
||||
|
||||
|
||||
def test_dsm_share_failure_logs_out():
|
||||
"""Sharing.create 실패해도 logout 호출 (try/finally)."""
|
||||
call_order = []
|
||||
|
||||
async def fake_get(self, url, *, params=None, **kw):
|
||||
method = (params or {}).get("method", "")
|
||||
call_order.append(method)
|
||||
if method == "login":
|
||||
return _make_response({"success": True, "data": {"sid": "sid"}})
|
||||
if method == "create":
|
||||
return _make_response({"success": False, "error": {"code": 401}})
|
||||
if method == "logout":
|
||||
return _make_response({"success": True})
|
||||
return _make_response({"success": False})
|
||||
|
||||
with patch.object(httpx.AsyncClient, "get", new=fake_get):
|
||||
with pytest.raises(DSMError, match="Sharing.create 실패"):
|
||||
asyncio.run(create_share_link("/volume1/test/file.zip"))
|
||||
|
||||
assert "login" in call_order
|
||||
assert "logout" in call_order, "logout이 호출되지 않음 (finally 누락 의심)"
|
||||
```
|
||||
|
||||
- [ ] **Step 2: 테스트 실행**
|
||||
|
||||
```bash
|
||||
cd packs-lab
|
||||
python -m pytest tests/test_dsm_client.py -v
|
||||
```
|
||||
|
||||
Expected: 4 passed.
|
||||
|
||||
- [ ] **Step 3: 커밋**
|
||||
|
||||
```bash
|
||||
git add packs-lab/tests/test_dsm_client.py
|
||||
git commit -m "test(packs-lab): DSM client mock 테스트 (login/share/logout 순서)"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 5: DELETE 라우트 docstring 수정
|
||||
|
||||
`routes.py` 모듈 docstring의 한 줄 변경.
|
||||
|
||||
**Files:**
|
||||
- Modify: `packs-lab/app/routes.py:1-7` (모듈 docstring)
|
||||
|
||||
- [ ] **Step 1: docstring 수정**
|
||||
|
||||
`packs-lab/app/routes.py` 첫 docstring을 다음으로 변경:
|
||||
|
||||
```python
|
||||
"""packs-lab API 엔드포인트.
|
||||
|
||||
- POST /api/packs/sign-link — Vercel HMAC 인증 → DSM 공유 링크
|
||||
- POST /api/packs/admin/mint-token — Vercel HMAC 인증 → 일회성 upload 토큰
|
||||
- POST /api/packs/upload — 일회성 토큰 인증 → multipart 저장 + supabase INSERT
|
||||
- GET /api/packs/list — Vercel HMAC 인증 → pack_files 전체 조회
|
||||
- DELETE /api/packs/{file_id} — Vercel HMAC 인증 → soft delete (DSM 공유는 자동 만료)
|
||||
"""
|
||||
```
|
||||
|
||||
(변경: `정리` → `자동 만료`, mint-token 줄 추가)
|
||||
|
||||
- [ ] **Step 2: 회귀 검증**
|
||||
|
||||
```bash
|
||||
cd packs-lab
|
||||
python -m pytest tests/ -v
|
||||
```
|
||||
|
||||
Expected: 모든 테스트 그대로 통과 (15 passed).
|
||||
|
||||
- [ ] **Step 3: 커밋**
|
||||
|
||||
```bash
|
||||
git add packs-lab/app/routes.py
|
||||
git commit -m "docs(packs-lab): routes 모듈 docstring 정리 (mint-token 추가, DSM 자동 만료 명시)"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 6: Supabase `pack_files` DDL
|
||||
|
||||
운영 적용 시 Supabase SQL editor에서 실행할 SQL 파일.
|
||||
|
||||
**Files:**
|
||||
- Create: `packs-lab/supabase/pack_files.sql`
|
||||
|
||||
- [ ] **Step 1: SQL 파일 생성**
|
||||
|
||||
`packs-lab/supabase/pack_files.sql`:
|
||||
|
||||
```sql
|
||||
-- pack_files: NAS에 저장된 다운로드 가능한 패키지 파일 메타
|
||||
-- 운영 적용: Supabase Dashboard → SQL editor에서 실행
|
||||
create table if not exists public.pack_files (
|
||||
id uuid primary key default gen_random_uuid(),
|
||||
min_tier text not null check (min_tier in ('starter','pro','master')),
|
||||
label text not null,
|
||||
file_path text not null unique,
|
||||
filename text not null,
|
||||
size_bytes bigint not null check (size_bytes > 0),
|
||||
sort_order integer not null default 0,
|
||||
uploaded_at timestamptz not null default now(),
|
||||
deleted_at timestamptz
|
||||
);
|
||||
|
||||
-- list 라우트 hot path: deleted_at IS NULL + tier/order 정렬
|
||||
create index if not exists pack_files_active_idx
|
||||
on public.pack_files (min_tier, sort_order)
|
||||
where deleted_at is null;
|
||||
|
||||
-- soft-deleted 통계 / cleanup 잡 대비
|
||||
create index if not exists pack_files_deleted_at_idx
|
||||
on public.pack_files (deleted_at)
|
||||
where deleted_at is not null;
|
||||
```
|
||||
|
||||
- [ ] **Step 2: 커밋**
|
||||
|
||||
```bash
|
||||
git add packs-lab/supabase/pack_files.sql
|
||||
git commit -m "feat(packs-lab): Supabase pack_files DDL + 활성/삭제 인덱스"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 7: 인프라 통합 — docker-compose / nginx / .env.example / deploy-nas.sh
|
||||
|
||||
**Files:**
|
||||
- Modify: `docker-compose.yml` (packs-lab 서비스 추가, env에 PACK_BASE_DIR/PACK_HOST_DIR 포함)
|
||||
- Modify: `nginx/default.conf` (`/api/packs/` 라우팅)
|
||||
- Modify: `.env.example` (DSM/HMAC/Supabase 6 + PACK 3 path)
|
||||
- Modify: `scripts/deploy-nas.sh` (SERVICES 화이트리스트에 `packs-lab` 추가 — 누락 시 NAS 컨테이너 미등장)
|
||||
|
||||
- [ ] **Step 1: docker-compose.yml — packs-lab 서비스 추가**
|
||||
|
||||
`docker-compose.yml`에서 다른 lab 서비스(예: `realestate-lab`) 정의 다음에 추가:
|
||||
|
||||
```yaml
|
||||
packs-lab:
|
||||
build:
|
||||
context: ./packs-lab
|
||||
dockerfile: Dockerfile
|
||||
container_name: packs-lab
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "18950:8000"
|
||||
environment:
|
||||
TZ: Asia/Seoul
|
||||
DSM_HOST: ${DSM_HOST}
|
||||
DSM_USER: ${DSM_USER}
|
||||
DSM_PASS: ${DSM_PASS}
|
||||
BACKEND_HMAC_SECRET: ${BACKEND_HMAC_SECRET}
|
||||
SUPABASE_URL: ${SUPABASE_URL}
|
||||
SUPABASE_SERVICE_KEY: ${SUPABASE_SERVICE_KEY}
|
||||
UPLOAD_TOKEN_TTL_SEC: ${UPLOAD_TOKEN_TTL_SEC:-1800}
|
||||
volumes:
|
||||
- ${PACK_DATA_PATH:-./data/packs}:/volume1/docker/webpage/media/packs
|
||||
```
|
||||
|
||||
- [ ] **Step 2: nginx/default.conf — /api/packs/ 라우팅**
|
||||
|
||||
기존 `location /api/agent-office/ { ... }` 다음(또는 다른 `/api/...` 라우트들 근처)에 추가:
|
||||
|
||||
```nginx
|
||||
location /api/packs/ {
|
||||
proxy_pass http://packs-lab:8000;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
|
||||
# 5GB 멀티파트 업로드 대응
|
||||
client_max_body_size 5G;
|
||||
proxy_request_buffering off;
|
||||
proxy_read_timeout 1800s;
|
||||
proxy_send_timeout 1800s;
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 3: .env.example — 6+1 환경변수 추가**
|
||||
|
||||
`.env.example` 끝에 추가:
|
||||
|
||||
```bash
|
||||
|
||||
# ─── packs-lab — NAS 자료 다운로드 자동화 ────────────────────────────
|
||||
# Synology DSM 7.x 인증 (공유 링크 발급용)
|
||||
DSM_HOST=https://gahusb.synology.me:5001
|
||||
DSM_USER=
|
||||
DSM_PASS=
|
||||
|
||||
# Vercel SaaS ↔ backend HMAC 시크릿 (양쪽 동일 값)
|
||||
BACKEND_HMAC_SECRET=
|
||||
|
||||
# Supabase pack_files 테이블 접근 (service_role 키, RLS 우회)
|
||||
SUPABASE_URL=https://<project>.supabase.co
|
||||
SUPABASE_SERVICE_KEY=
|
||||
|
||||
# admin upload 토큰 TTL (초). default 1800 = 30분
|
||||
UPLOAD_TOKEN_TTL_SEC=1800
|
||||
|
||||
# 로컬 개발: ./data/packs / NAS 운영: /volume1/docker/webpage/media/packs
|
||||
PACK_DATA_PATH=./data/packs
|
||||
```
|
||||
|
||||
- [ ] **Step 4: docker compose config 검증**
|
||||
|
||||
```bash
|
||||
cd C:\Users\jaeoh\Desktop\workspace\web-backend
|
||||
docker compose config 2>&1 | grep -A 10 "packs-lab:"
|
||||
```
|
||||
|
||||
Expected: packs-lab 서비스 정의가 정상 출력 (port mapping, environment 변수, volumes 모두 보임). 환경변수가 비어있어도 docker compose config는 통과.
|
||||
|
||||
> ⚠️ Docker가 로컬에 설치되어 있어야 검증 가능. 실제 실행은 NAS에서. 로컬 docker가 없으면 step skip하고 nginx config 문법만 별도 검증.
|
||||
|
||||
- [ ] **Step 5: 커밋**
|
||||
|
||||
```bash
|
||||
git add docker-compose.yml nginx/default.conf .env.example
|
||||
git commit -m "chore(infra): packs-lab 서비스 통합 (compose 18950 + nginx 5GB streaming + env 7개)"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 8: NAS 디렉토리 준비 가이드 + 문서 갱신
|
||||
|
||||
**Files:**
|
||||
- Modify: `web-backend/CLAUDE.md` (5곳 갱신)
|
||||
- Modify: `workspace/CLAUDE.md` (1줄 추가)
|
||||
|
||||
- [ ] **Step 1: web-backend/CLAUDE.md — 1.프로젝트 개요**
|
||||
|
||||
찾을 위치 (1.프로젝트 개요 섹션):
|
||||
|
||||
```
|
||||
- **서비스**: lotto-lab, stock-lab, travel-proxy, music-lab, blog-lab, realestate-lab, agent-office, personal, deployer (9개)
|
||||
```
|
||||
|
||||
다음으로 수정:
|
||||
|
||||
```
|
||||
- **서비스**: lotto-lab, stock-lab, travel-proxy, music-lab, blog-lab, realestate-lab, agent-office, personal, packs-lab, deployer (10개)
|
||||
```
|
||||
|
||||
같은 섹션의 인프라 줄도:
|
||||
|
||||
```
|
||||
- **인프라**: Docker Compose (10컨테이너) + Nginx(리버스 프록시) + Gitea Webhook 자동 배포
|
||||
```
|
||||
|
||||
- [ ] **Step 2: web-backend/CLAUDE.md — 4.Docker 서비스 표**
|
||||
|
||||
표 마지막에 신규 행 추가 (deployer 행 직전 또는 personal 행 다음 — 알파벳 순):
|
||||
|
||||
```
|
||||
| `packs-lab` | 18950 | NAS 자료 다운로드 자동화 (DSM 공유 링크 + 5GB 업로드, Vercel SaaS와 HMAC 통신) |
|
||||
```
|
||||
|
||||
- [ ] **Step 3: web-backend/CLAUDE.md — 5.Nginx 라우팅 표**
|
||||
|
||||
표 적절한 위치에 신규 행 추가:
|
||||
|
||||
```
|
||||
| `/api/packs/` | `packs-lab:8000` | 5GB 업로드 대응 (`client_max_body_size 5G`, `proxy_request_buffering off`, 1800s timeout) |
|
||||
```
|
||||
|
||||
- [ ] **Step 4: web-backend/CLAUDE.md — 8.로컬 개발 표**
|
||||
|
||||
표 끝에 신규 행 추가:
|
||||
|
||||
```
|
||||
| Packs Lab | http://localhost:18950 |
|
||||
```
|
||||
|
||||
- [ ] **Step 5: web-backend/CLAUDE.md — 9.서비스별 packs-lab 신규 섹션**
|
||||
|
||||
`### deployer (deployer/)` 섹션 직전에 추가 (또는 personal 다음):
|
||||
|
||||
```
|
||||
### packs-lab (packs-lab/)
|
||||
- NAS 자료 다운로드 자동화 — Synology DSM 공유링크 발급 + 5GB 멀티파트 업로드 수신
|
||||
- Vercel SaaS와 HMAC 인증으로 통신, 사용자 인증은 Vercel이 Supabase로 처리 (본 서비스는 외부 인증 없음)
|
||||
- DB: 외부 Supabase `pack_files` 테이블 (DDL: `packs-lab/supabase/pack_files.sql`)
|
||||
- 파일 구조: `app/main.py`, `app/auth.py`, `app/dsm_client.py`, `app/routes.py`, `app/models.py`
|
||||
- 운영 디렉토리: `/volume1/docker/webpage/media/packs/{starter,pro,master}/` (NAS PUID:PGID 권한 필요)
|
||||
|
||||
**환경변수**
|
||||
- `DSM_HOST` / `DSM_USER` / `DSM_PASS`: Synology DSM 7.x 인증 (공유 링크 발급용)
|
||||
- `BACKEND_HMAC_SECRET`: Vercel SaaS와 양쪽 공유 시크릿 (HMAC SHA256)
|
||||
- `SUPABASE_URL` / `SUPABASE_SERVICE_KEY`: Supabase pack_files 테이블 접근 (service_role, RLS 우회)
|
||||
- `UPLOAD_TOKEN_TTL_SEC`: admin upload 토큰 TTL (기본 1800초 = 30분)
|
||||
- `PACK_DATA_PATH`: 호스트 마운트 경로 (로컬 `./data/packs`, NAS `/volume1/docker/webpage/media/packs`)
|
||||
|
||||
**HMAC 인증 패턴**
|
||||
- Vercel → backend 요청: `X-Timestamp` (UNIX 초) + `X-Signature` (HMAC_SHA256(timestamp + "." + body, secret))
|
||||
- Replay 방어: 타임스탬프 ±5분 윈도우
|
||||
- admin browser → backend upload: `Authorization: Bearer <token>` (jti 단발성)
|
||||
|
||||
**packs-lab API 목록**
|
||||
|
||||
| 메서드 | 경로 | 설명 |
|
||||
|--------|------|------|
|
||||
| POST | `/api/packs/sign-link` | Vercel HMAC → DSM Sharing.create로 4시간 유효 다운로드 URL 발급 |
|
||||
| POST | `/api/packs/admin/mint-token` | Vercel HMAC → 일회성 upload 토큰 발급 (기본 30분 TTL) |
|
||||
| POST | `/api/packs/upload` | Bearer token → multipart 5GB 저장 + Supabase INSERT |
|
||||
| GET | `/api/packs/list` | Vercel HMAC → 활성 pack_files 목록 (deleted_at IS NULL) |
|
||||
| DELETE | `/api/packs/{file_id}` | Vercel HMAC → soft delete (DSM 공유는 자동 만료) |
|
||||
```
|
||||
|
||||
- [ ] **Step 6: workspace/CLAUDE.md — 컨테이너 표 한 줄 추가**
|
||||
|
||||
`workspace/CLAUDE.md`의 "Docker 서비스 & 포트" 표에 추가:
|
||||
|
||||
```
|
||||
| `packs-lab` | 18950 | NAS 자료 다운로드 자동화 (Vercel SaaS와 HMAC 통신) |
|
||||
```
|
||||
|
||||
(personal 행 다음 또는 적절한 위치)
|
||||
|
||||
- [ ] **Step 7: 커밋 (web-backend repo의 CLAUDE.md만)**
|
||||
|
||||
작업 디렉토리는 `C:\Users\jaeoh\Desktop\workspace\web-backend`. 그 안의 `CLAUDE.md`만 git 추적 대상.
|
||||
|
||||
```bash
|
||||
git add CLAUDE.md
|
||||
git commit -m "docs(claude): packs-lab 10번째 서비스로 등록 (포트/라우팅/API 표 + 신규 섹션)"
|
||||
```
|
||||
|
||||
> ℹ️ `workspace/CLAUDE.md`(상위 디렉토리의 워크스페이스 메모)는 git repo가 아님. 텍스트 편집만 하고 commit 대상에서 제외.
|
||||
|
||||
---
|
||||
|
||||
## Task 9: 회귀 검증 + NAS 디렉토리 가이드
|
||||
|
||||
전체 테스트 + docker compose config + NAS 배포 전 가이드.
|
||||
|
||||
**Files:**
|
||||
- (검증만)
|
||||
|
||||
- [ ] **Step 1: 전체 pytest**
|
||||
|
||||
```bash
|
||||
cd packs-lab
|
||||
python -m pytest tests/ -v
|
||||
```
|
||||
|
||||
Expected: 모든 테스트 통과 (test_auth + test_routes + test_dsm_client = 약 15+ tests).
|
||||
|
||||
- [ ] **Step 2: docker compose config 검증**
|
||||
|
||||
```bash
|
||||
cd C:\Users\jaeoh\Desktop\workspace\web-backend
|
||||
docker compose config 2>&1 | tail -30
|
||||
```
|
||||
|
||||
Expected: error 없이 packs-lab 포함된 전체 config 출력.
|
||||
|
||||
> ⚠️ Docker 미설치 시 skip. NAS에서 git push 후 webhook 배포 시점에 검증됨.
|
||||
|
||||
- [ ] **Step 3: NAS 배포 전 가이드 출력**
|
||||
|
||||
배포 전 NAS에서 SSH로 1회 실행할 명령들을 README 또는 NAS 배포 노트로 정리. 본 task에서는 명령만 제시 (실행은 사용자):
|
||||
|
||||
```bash
|
||||
# NAS SSH로 접속 후
|
||||
mkdir -p /volume1/docker/webpage/media/packs/{starter,pro,master}
|
||||
chown -R PUID:PGID /volume1/docker/webpage/media/packs # PUID/PGID는 .env 값 사용
|
||||
|
||||
# .env에 신규 환경변수 추가 (DSM_*, BACKEND_HMAC_SECRET, SUPABASE_*, UPLOAD_TOKEN_TTL_SEC, PACK_DATA_PATH=/volume1/docker/webpage/media/packs)
|
||||
|
||||
# Supabase에서 packs-lab/supabase/pack_files.sql 실행
|
||||
|
||||
# git push 후 webhook이 자동 배포
|
||||
```
|
||||
|
||||
- [ ] **Step 4: 최종 commit (검증 결과 빈 commit으로 마일스톤 표시 — 선택)**
|
||||
|
||||
```bash
|
||||
# 만약 위 step에서 어떤 자동 수정이 있었으면 commit. 없으면 skip.
|
||||
git status
|
||||
```
|
||||
|
||||
회귀 검증으로 변경 사항 없으면 별도 commit 없이 종료.
|
||||
|
||||
---
|
||||
|
||||
## 완료 기준
|
||||
|
||||
- 모든 task의 step 통과 (체크박스 모두 체크)
|
||||
- `cd packs-lab && python -m pytest tests/ -v` — 통과 (test_auth + test_routes + test_dsm_client)
|
||||
- `docker compose config` — packs-lab 포함된 전체 config 정상
|
||||
- web-backend/CLAUDE.md 5곳 갱신 + workspace/CLAUDE.md 1줄
|
||||
- Supabase DDL 파일 존재 (운영 적용은 사용자가 NAS에서 SQL editor로)
|
||||
- NAS 디렉토리 준비 명령은 사용자가 SSH로 실행 (배포 전 1회)
|
||||
|
||||
---
|
||||
|
||||
## 배포
|
||||
|
||||
git push → Gitea webhook → deployer rsync → docker compose up -d --build (자동).
|
||||
|
||||
**배포 전 사용자 액션 (1회)**:
|
||||
1. Supabase에서 `pack_files` 테이블 생성 (DDL 실행)
|
||||
2. NAS SSH로 `/volume1/docker/webpage/media/packs/{starter,pro,master}` 디렉토리 생성 + 권한
|
||||
3. NAS `.env`에 신규 7개 환경변수 입력 (DSM 인증, HMAC secret, Supabase 키 등)
|
||||
|
||||
---
|
||||
|
||||
## 참고 — 후속 별도 plan (스코프 외)
|
||||
|
||||
- Vercel SaaS-side admin UI / 사용자 다운로드 UI / Supabase user 테이블
|
||||
- DSM 공유 추적 (즉시 차단 필요 시)
|
||||
- deleted_at + N일 후 실제 파일 삭제 cron
|
||||
- multi-admin 토큰 발급 권한 분리
|
||||
- resumable multipart 업로드 (5GB tus 등)
|
||||
- pack_files sort_order 편집 endpoint
|
||||
- 모니터링 (업로드 실패율, DSM API latency)
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,737 +0,0 @@
|
||||
# GPU 영상 인코딩 오프로드 — 구현 계획
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development.
|
||||
|
||||
**Goal:** NAS의 ffmpeg 영상 인코딩을 Windows PC(RTX 5070 Ti) NVENC로 오프로드.
|
||||
|
||||
**Architecture:** music-lab(NAS) → HTTP POST → music_ai(Windows, port 8765 `/encode_video`) → ffmpeg NVENC → SMB로 NAS에 직접 mp4 저장. Windows 서버 다운 시 NAS는 즉시 실패.
|
||||
|
||||
**Tech Stack:** httpx (NAS 측 HTTP 클라이언트), FastAPI (Windows 서버 endpoint), ffmpeg.exe with NVENC.
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-05-09-gpu-video-offload-design.md`
|
||||
|
||||
---
|
||||
|
||||
## File Structure
|
||||
|
||||
| 경로 | 책임 |
|
||||
|------|------|
|
||||
| `music_ai/video_encoder.py` (new) | 경로 변환 + ffmpeg NVENC subprocess 호출 + 검증 |
|
||||
| `music_ai/server.py` (modify) | `/encode_video` POST endpoint 등록, `/health`에 ffmpeg/nvenc 정보 추가 |
|
||||
| `music_ai/.env.example` (modify) | NAS_VOLUME_PREFIX, WINDOWS_DRIVE_ROOT, FFMPEG_PATH 문서화 |
|
||||
| `music_ai/tests/test_video_encoder.py` (new) | translate_path, encode endpoint 단위 테스트 |
|
||||
| `music-lab/app/pipeline/video.py` (rewrite) | subprocess 제거, httpx로 Windows 서버 호출 |
|
||||
| `music-lab/tests/test_video_thumb.py` (rewrite video tests) | respx mock 기반 |
|
||||
| `web-backend/docker-compose.yml` (modify) | music-lab env 3개 추가 |
|
||||
|
||||
---
|
||||
|
||||
## Task 1: Windows `music_ai/video_encoder.py` + 테스트
|
||||
|
||||
**Files:**
|
||||
- Create: `music_ai/video_encoder.py`
|
||||
- Create: `music_ai/tests/test_video_encoder.py`
|
||||
|
||||
### Step 1: Write failing test
|
||||
|
||||
```python
|
||||
# music_ai/tests/test_video_encoder.py
|
||||
import os
|
||||
import pytest
|
||||
from unittest.mock import patch, MagicMock
|
||||
from video_encoder import translate_path, encode_video, EncodeError
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def env(monkeypatch):
|
||||
monkeypatch.setenv("NAS_VOLUME_PREFIX", "/volume1/")
|
||||
monkeypatch.setenv("WINDOWS_DRIVE_ROOT", "Z:\\")
|
||||
monkeypatch.setenv("FFMPEG_PATH", "C:\\ffmpeg\\bin\\ffmpeg.exe")
|
||||
|
||||
|
||||
def test_translate_path_basic(env):
|
||||
assert translate_path("/volume1/docker/webpage/data/x.jpg") == r"Z:\docker\webpage\data\x.jpg"
|
||||
|
||||
|
||||
def test_translate_path_nested(env):
|
||||
assert translate_path("/volume1/docker/webpage/data/videos/3/cover.jpg") == r"Z:\docker\webpage\data\videos\3\cover.jpg"
|
||||
|
||||
|
||||
def test_translate_path_rejects_bad_prefix(env):
|
||||
with pytest.raises(ValueError):
|
||||
translate_path("/etc/passwd")
|
||||
|
||||
|
||||
@patch("subprocess.run")
|
||||
def test_encode_video_success(mock_run, env, tmp_path):
|
||||
# 입력 파일 fake
|
||||
cover = tmp_path / "cover.jpg"
|
||||
cover.write_bytes(b"\x00" * 100)
|
||||
audio = tmp_path / "audio.mp3"
|
||||
audio.write_bytes(b"\x00" * 100)
|
||||
out = tmp_path / "video.mp4"
|
||||
|
||||
def fake_run(cmd, **kwargs):
|
||||
# ffmpeg 실행을 흉내내어 출력 파일을 만듦
|
||||
out.write_bytes(b"\x00" * (2 * 1024 * 1024)) # 2MB
|
||||
return MagicMock(returncode=0, stderr="")
|
||||
mock_run.side_effect = fake_run
|
||||
|
||||
# translate_path를 mock해서 입력 경로를 직접 사용
|
||||
with patch("video_encoder.translate_path", side_effect=lambda p: str(p).replace("/volume1/", str(tmp_path) + "/")):
|
||||
result = encode_video(
|
||||
cover_path_nas="/volume1/cover.jpg",
|
||||
audio_path_nas="/volume1/audio.mp3",
|
||||
output_path_nas="/volume1/video.mp4",
|
||||
resolution="1920x1080",
|
||||
duration_sec=120,
|
||||
)
|
||||
assert result["ok"] is True
|
||||
assert result["encoder"] == "h264_nvenc"
|
||||
assert result["output_bytes"] > 1024 * 1024
|
||||
|
||||
|
||||
@patch("subprocess.run")
|
||||
def test_encode_video_input_missing(mock_run, env, tmp_path):
|
||||
with pytest.raises(EncodeError) as exc:
|
||||
encode_video(
|
||||
cover_path_nas="/volume1/missing.jpg",
|
||||
audio_path_nas="/volume1/missing.mp3",
|
||||
output_path_nas="/volume1/out.mp4",
|
||||
resolution="1920x1080",
|
||||
duration_sec=120,
|
||||
)
|
||||
assert "input_validation" in str(exc.value)
|
||||
|
||||
|
||||
@patch("subprocess.run")
|
||||
def test_encode_video_ffmpeg_failure(mock_run, env, tmp_path):
|
||||
cover = tmp_path / "cover.jpg"; cover.write_bytes(b"\x00")
|
||||
audio = tmp_path / "audio.mp3"; audio.write_bytes(b"\x00")
|
||||
mock_run.return_value = MagicMock(returncode=1, stderr="invalid codec\n" * 50)
|
||||
|
||||
with patch("video_encoder.translate_path", side_effect=lambda p: str(p).replace("/volume1/", str(tmp_path) + "/")):
|
||||
with pytest.raises(EncodeError) as exc:
|
||||
encode_video(
|
||||
cover_path_nas="/volume1/cover.jpg",
|
||||
audio_path_nas="/volume1/audio.mp3",
|
||||
output_path_nas="/volume1/out.mp4",
|
||||
resolution="1920x1080",
|
||||
duration_sec=120,
|
||||
)
|
||||
assert "ffmpeg" in str(exc.value).lower()
|
||||
|
||||
|
||||
@patch("subprocess.run")
|
||||
def test_encode_video_output_too_small(mock_run, env, tmp_path):
|
||||
cover = tmp_path / "cover.jpg"; cover.write_bytes(b"\x00")
|
||||
audio = tmp_path / "audio.mp3"; audio.write_bytes(b"\x00")
|
||||
def fake_run(cmd, **kwargs):
|
||||
(tmp_path / "out.mp4").write_bytes(b"\x00" * 100) # 100 bytes — too small
|
||||
return MagicMock(returncode=0, stderr="")
|
||||
mock_run.side_effect = fake_run
|
||||
|
||||
with patch("video_encoder.translate_path", side_effect=lambda p: str(p).replace("/volume1/", str(tmp_path) + "/")):
|
||||
with pytest.raises(EncodeError) as exc:
|
||||
encode_video(
|
||||
cover_path_nas="/volume1/cover.jpg",
|
||||
audio_path_nas="/volume1/audio.mp3",
|
||||
output_path_nas="/volume1/out.mp4",
|
||||
resolution="1920x1080",
|
||||
duration_sec=120,
|
||||
)
|
||||
assert "output_check" in str(exc.value)
|
||||
|
||||
|
||||
def test_resolution_validation(env):
|
||||
with pytest.raises(EncodeError) as exc:
|
||||
encode_video(
|
||||
cover_path_nas="/volume1/x.jpg",
|
||||
audio_path_nas="/volume1/x.mp3",
|
||||
output_path_nas="/volume1/out.mp4",
|
||||
resolution="invalid",
|
||||
duration_sec=120,
|
||||
)
|
||||
assert "resolution" in str(exc.value).lower()
|
||||
```
|
||||
|
||||
### Step 2: Run test to verify it fails
|
||||
|
||||
```bash
|
||||
cd music_ai && python -m pytest tests/test_video_encoder.py -v
|
||||
```
|
||||
|
||||
Expected: ImportError on `video_encoder` module.
|
||||
|
||||
### Step 3: Implement `video_encoder.py`
|
||||
|
||||
```python
|
||||
"""GPU(NVENC) 영상 인코더 — NAS music-lab에서 호출."""
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger("music_ai.video_encoder")
|
||||
|
||||
NAS_VOLUME_PREFIX = os.getenv("NAS_VOLUME_PREFIX", "/volume1/")
|
||||
WINDOWS_DRIVE_ROOT = os.getenv("WINDOWS_DRIVE_ROOT", "Z:\\")
|
||||
FFMPEG_PATH = os.getenv("FFMPEG_PATH", "ffmpeg")
|
||||
FFMPEG_TIMEOUT_S = 180
|
||||
RESOLUTION_RE = re.compile(r"^\d{3,4}x\d{3,4}$")
|
||||
MIN_OUTPUT_BYTES = 1024 * 1024 # 1MB
|
||||
|
||||
|
||||
class EncodeError(Exception):
|
||||
"""{stage: input_validation|path_translate|ffmpeg|output_check, message: ...}"""
|
||||
def __init__(self, stage: str, message: str):
|
||||
self.stage = stage
|
||||
self.message = message
|
||||
super().__init__(f"[{stage}] {message}")
|
||||
|
||||
|
||||
def translate_path(nas_path: str) -> str:
|
||||
"""NAS 절대경로 → Windows SMB 경로."""
|
||||
if not nas_path.startswith(NAS_VOLUME_PREFIX):
|
||||
raise ValueError(f"NAS prefix 불일치: {nas_path}")
|
||||
rel = nas_path[len(NAS_VOLUME_PREFIX):]
|
||||
return WINDOWS_DRIVE_ROOT + rel.replace("/", "\\")
|
||||
|
||||
|
||||
def encode_video(*, cover_path_nas: str, audio_path_nas: str,
|
||||
output_path_nas: str, resolution: str,
|
||||
duration_sec: int = 0, style: str = "visualizer") -> dict:
|
||||
"""영상 인코딩 + Z:\\에 직접 저장."""
|
||||
# 1) Resolution 검증
|
||||
if not RESOLUTION_RE.match(resolution):
|
||||
raise EncodeError("input_validation", f"invalid resolution: {resolution}")
|
||||
w, h = resolution.split("x")
|
||||
|
||||
# 2) 경로 변환
|
||||
try:
|
||||
cover_win = translate_path(cover_path_nas)
|
||||
audio_win = translate_path(audio_path_nas)
|
||||
out_win = translate_path(output_path_nas)
|
||||
except ValueError as e:
|
||||
raise EncodeError("path_translate", str(e))
|
||||
|
||||
# 3) 입력 존재 확인
|
||||
if not os.path.isfile(cover_win):
|
||||
raise EncodeError("input_validation", f"cover not found: {cover_win}")
|
||||
if not os.path.isfile(audio_win):
|
||||
raise EncodeError("input_validation", f"audio not found: {audio_win}")
|
||||
|
||||
# 4) 출력 디렉토리 보장
|
||||
os.makedirs(os.path.dirname(out_win), exist_ok=True)
|
||||
|
||||
# 5) ffmpeg 명령
|
||||
cmd = [
|
||||
FFMPEG_PATH, "-y",
|
||||
"-hwaccel", "cuda",
|
||||
"-loop", "1", "-i", cover_win,
|
||||
"-i", audio_win,
|
||||
"-filter_complex",
|
||||
f"[0:v]scale={w}:{h},format=yuv420p[bg];"
|
||||
f"[1:a]showwaves=s={w}x200:mode=cline:colors=0xFF4444@0.8[wave];"
|
||||
f"[bg][wave]overlay=0:({h}-200)[out]",
|
||||
"-map", "[out]", "-map", "1:a",
|
||||
"-c:v", "h264_nvenc",
|
||||
"-preset", "p4",
|
||||
"-rc", "vbr",
|
||||
"-cq", "23",
|
||||
"-b:v", "0",
|
||||
"-pix_fmt", "yuv420p",
|
||||
"-c:a", "aac", "-b:a", "192k",
|
||||
"-shortest", out_win,
|
||||
]
|
||||
logger.info("ffmpeg: %s", " ".join(cmd))
|
||||
|
||||
# 6) ffmpeg 실행
|
||||
import time
|
||||
t0 = time.time()
|
||||
try:
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, timeout=FFMPEG_TIMEOUT_S)
|
||||
except subprocess.TimeoutExpired:
|
||||
raise EncodeError("ffmpeg", f"timeout after {FFMPEG_TIMEOUT_S}s")
|
||||
duration_ms = int((time.time() - t0) * 1000)
|
||||
|
||||
if result.returncode != 0:
|
||||
raise EncodeError("ffmpeg", f"returncode={result.returncode}: {result.stderr[-800:]}")
|
||||
|
||||
# 7) 출력 검증
|
||||
if not os.path.isfile(out_win):
|
||||
raise EncodeError("output_check", "output file not created")
|
||||
output_bytes = os.path.getsize(out_win)
|
||||
if output_bytes < MIN_OUTPUT_BYTES:
|
||||
raise EncodeError("output_check", f"output too small: {output_bytes} bytes")
|
||||
|
||||
return {
|
||||
"ok": True,
|
||||
"duration_ms": duration_ms,
|
||||
"output_path_nas": output_path_nas,
|
||||
"output_bytes": output_bytes,
|
||||
"encoder": "h264_nvenc",
|
||||
"preset": "p4",
|
||||
}
|
||||
|
||||
|
||||
def check_ffmpeg_nvenc() -> bool:
|
||||
"""서버 시작 시 NVENC 가용성 확인."""
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[FFMPEG_PATH, "-encoders"],
|
||||
capture_output=True, text=True, timeout=10,
|
||||
)
|
||||
return "h264_nvenc" in result.stdout
|
||||
except Exception:
|
||||
return False
|
||||
```
|
||||
|
||||
### Step 4: Run tests
|
||||
|
||||
```bash
|
||||
cd music_ai && python -m pytest tests/test_video_encoder.py -v
|
||||
```
|
||||
|
||||
Expected: 6 PASS
|
||||
|
||||
### Step 5: Commit
|
||||
|
||||
```bash
|
||||
cd C:/Users/jaeoh/Desktop/workspace/music_ai
|
||||
git init 2>/dev/null || true # may not be a git repo, that's OK
|
||||
# music_ai is local-only per CLAUDE.md, no remote push
|
||||
```
|
||||
|
||||
(music_ai is local-only; just save the file. No git push needed.)
|
||||
|
||||
---
|
||||
|
||||
## Task 2: Windows `music_ai/server.py` — `/encode_video` endpoint + 헬스 확장
|
||||
|
||||
**Files:**
|
||||
- Modify: `music_ai/server.py`
|
||||
- Modify: `music_ai/.env.example`
|
||||
|
||||
### Step 1: Read existing server.py to understand FastAPI pattern + existing /health
|
||||
|
||||
### Step 2: Add `/encode_video` endpoint
|
||||
|
||||
```python
|
||||
# server.py — 추가
|
||||
from pydantic import BaseModel
|
||||
from fastapi import HTTPException
|
||||
import video_encoder
|
||||
|
||||
|
||||
class EncodeVideoRequest(BaseModel):
|
||||
cover_path_nas: str
|
||||
audio_path_nas: str
|
||||
output_path_nas: str
|
||||
resolution: str = "1920x1080"
|
||||
duration_sec: int = 0
|
||||
style: str = "visualizer"
|
||||
|
||||
|
||||
@app.post("/encode_video")
|
||||
def encode_video_endpoint(req: EncodeVideoRequest):
|
||||
try:
|
||||
result = video_encoder.encode_video(
|
||||
cover_path_nas=req.cover_path_nas,
|
||||
audio_path_nas=req.audio_path_nas,
|
||||
output_path_nas=req.output_path_nas,
|
||||
resolution=req.resolution,
|
||||
duration_sec=req.duration_sec,
|
||||
style=req.style,
|
||||
)
|
||||
return result
|
||||
except video_encoder.EncodeError as e:
|
||||
# input_validation, path_translate → 400
|
||||
# ffmpeg, output_check → 500
|
||||
status_code = 400 if e.stage in ("input_validation", "path_translate") else 500
|
||||
raise HTTPException(
|
||||
status_code=status_code,
|
||||
detail={"ok": False, "stage": e.stage, "error": e.message},
|
||||
)
|
||||
```
|
||||
|
||||
### Step 3: 확장된 `/health`
|
||||
|
||||
기존 `/health` 응답에 추가:
|
||||
```python
|
||||
import torch # if existing health uses it
|
||||
import video_encoder
|
||||
|
||||
# Module-level cache so health doesn't run ffmpeg every call
|
||||
_FFMPEG_NVENC_CACHED = None
|
||||
def _ffmpeg_nvenc_available():
|
||||
global _FFMPEG_NVENC_CACHED
|
||||
if _FFMPEG_NVENC_CACHED is None:
|
||||
_FFMPEG_NVENC_CACHED = video_encoder.check_ffmpeg_nvenc()
|
||||
return _FFMPEG_NVENC_CACHED
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
def health():
|
||||
return {
|
||||
"ok": True,
|
||||
"gpu": torch.cuda.get_device_name(0) if torch.cuda.is_available() else None, # 또는 기존 형식 유지
|
||||
"musicgen_loaded": True, # 기존 그대로
|
||||
"ffmpeg_path": video_encoder.FFMPEG_PATH,
|
||||
"ffmpeg_nvenc": _ffmpeg_nvenc_available(),
|
||||
}
|
||||
```
|
||||
|
||||
(기존 `/health`의 정확한 형식은 코드 읽고 매칭. 위는 예시.)
|
||||
|
||||
### Step 4: `.env.example` 업데이트
|
||||
|
||||
```env
|
||||
# Existing
|
||||
MODEL_NAME=facebook/musicgen-stereo-large
|
||||
OUTPUT_DIR=output
|
||||
SERVER_PORT=8765
|
||||
|
||||
# New for video encoder
|
||||
NAS_VOLUME_PREFIX=/volume1/
|
||||
WINDOWS_DRIVE_ROOT=Z:\
|
||||
FFMPEG_PATH=C:\ffmpeg\bin\ffmpeg.exe
|
||||
```
|
||||
|
||||
### Step 5: 수동 검증
|
||||
|
||||
```bash
|
||||
cd music_ai && start.bat # 또는 적절한 시작 명령
|
||||
curl http://localhost:8765/health
|
||||
# Expected: {..., "ffmpeg_nvenc": true}
|
||||
|
||||
curl -X POST http://localhost:8765/encode_video -H "Content-Type: application/json" -d '{
|
||||
"cover_path_nas": "/volume1/docker/webpage/data/videos/3/cover.jpg",
|
||||
"audio_path_nas": "/volume1/docker/webpage/data/1c695df3-8a82-4c09-ba7b-82c07608ec5b.mp3",
|
||||
"output_path_nas": "/volume1/docker/webpage/data/videos/test/video.mp4",
|
||||
"resolution": "1920x1080",
|
||||
"duration_sec": 176
|
||||
}'
|
||||
# Expected: 200 + duration_ms ~ 10-20초
|
||||
```
|
||||
|
||||
(실제 파일 경로는 사용자 환경에 맞게 조정)
|
||||
|
||||
### Step 6: Commit (music_ai is local-only, no remote)
|
||||
|
||||
---
|
||||
|
||||
## Task 3: NAS music-lab — `pipeline/video.py` 재작성 + 테스트
|
||||
|
||||
**Files:**
|
||||
- Rewrite: `music-lab/app/pipeline/video.py`
|
||||
- Rewrite: `music-lab/tests/test_video_thumb.py` (video 부분만)
|
||||
|
||||
### Step 1: Replace failing tests
|
||||
|
||||
```python
|
||||
# music-lab/tests/test_video_thumb.py — video 관련 테스트 부분만 교체
|
||||
import pytest
|
||||
import respx
|
||||
import httpx
|
||||
from httpx import Response
|
||||
from app.pipeline import video, thumb, storage
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def encoder_env(monkeypatch):
|
||||
monkeypatch.setenv("WINDOWS_VIDEO_ENCODER_URL", "http://192.168.45.59:8765")
|
||||
monkeypatch.setattr(video, "ENCODER_URL", "http://192.168.45.59:8765")
|
||||
|
||||
|
||||
@respx.mock
|
||||
def test_generate_video_calls_remote_encoder(encoder_env, tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(storage, "VIDEO_DATA_DIR", str(tmp_path))
|
||||
respx.post("http://192.168.45.59:8765/encode_video").mock(
|
||||
return_value=Response(200, json={
|
||||
"ok": True, "duration_ms": 12000,
|
||||
"output_path_nas": "/volume1/docker/webpage/data/videos/3/video.mp4",
|
||||
"output_bytes": 28000000,
|
||||
"encoder": "h264_nvenc", "preset": "p4",
|
||||
})
|
||||
)
|
||||
out = video.generate(
|
||||
pipeline_id=3,
|
||||
audio_path="/app/data/1c695df3.mp3",
|
||||
cover_path="/app/data/videos/3/cover.jpg",
|
||||
genre="lo-fi", duration_sec=120, resolution="1920x1080",
|
||||
style="visualizer",
|
||||
)
|
||||
assert out["url"].endswith("/3/video.mp4")
|
||||
assert out["used_fallback"] is False
|
||||
assert out["encode_duration_ms"] == 12000
|
||||
|
||||
|
||||
@respx.mock
|
||||
def test_generate_video_raises_on_connection_error(encoder_env, monkeypatch, tmp_path):
|
||||
monkeypatch.setattr(storage, "VIDEO_DATA_DIR", str(tmp_path))
|
||||
respx.post("http://192.168.45.59:8765/encode_video").mock(
|
||||
side_effect=httpx.ConnectError("Connection refused")
|
||||
)
|
||||
with pytest.raises(video.VideoGenerationError) as exc:
|
||||
video.generate(
|
||||
pipeline_id=4,
|
||||
audio_path="/app/data/x.mp3", cover_path="/app/data/videos/4/cover.jpg",
|
||||
genre="lo-fi", duration_sec=120, resolution="1920x1080",
|
||||
)
|
||||
assert "연결 실패" in str(exc.value) or "Connection" in str(exc.value)
|
||||
|
||||
|
||||
@respx.mock
|
||||
def test_generate_video_raises_on_500(encoder_env, monkeypatch, tmp_path):
|
||||
monkeypatch.setattr(storage, "VIDEO_DATA_DIR", str(tmp_path))
|
||||
respx.post("http://192.168.45.59:8765/encode_video").mock(
|
||||
return_value=Response(500, json={"ok": False, "stage": "ffmpeg", "error": "bad codec"})
|
||||
)
|
||||
with pytest.raises(video.VideoGenerationError) as exc:
|
||||
video.generate(
|
||||
pipeline_id=5,
|
||||
audio_path="/app/data/x.mp3", cover_path="/app/data/videos/5/cover.jpg",
|
||||
genre="lo-fi", duration_sec=120, resolution="1920x1080",
|
||||
)
|
||||
assert "Windows 인코더 오류" in str(exc.value)
|
||||
assert "ffmpeg" in str(exc.value)
|
||||
|
||||
|
||||
def test_generate_video_no_url_configured(monkeypatch, tmp_path):
|
||||
monkeypatch.setattr(storage, "VIDEO_DATA_DIR", str(tmp_path))
|
||||
monkeypatch.setattr(video, "ENCODER_URL", "")
|
||||
with pytest.raises(video.VideoGenerationError) as exc:
|
||||
video.generate(
|
||||
pipeline_id=6,
|
||||
audio_path="/app/data/x.mp3", cover_path="/app/data/videos/6/cover.jpg",
|
||||
genre="lo-fi", duration_sec=120, resolution="1920x1080",
|
||||
)
|
||||
assert "WINDOWS_VIDEO_ENCODER_URL" in str(exc.value)
|
||||
|
||||
|
||||
def test_container_to_nas_videos_path(monkeypatch):
|
||||
monkeypatch.setenv("NAS_VIDEOS_ROOT", "/volume1/docker/webpage/data/videos")
|
||||
monkeypatch.setenv("NAS_MUSIC_ROOT", "/volume1/docker/webpage/data/music")
|
||||
assert video._container_to_nas("/app/data/videos/3/cover.jpg") == "/volume1/docker/webpage/data/videos/3/cover.jpg"
|
||||
|
||||
|
||||
def test_container_to_nas_music_path(monkeypatch):
|
||||
monkeypatch.setenv("NAS_VIDEOS_ROOT", "/volume1/docker/webpage/data/videos")
|
||||
monkeypatch.setenv("NAS_MUSIC_ROOT", "/volume1/docker/webpage/data/music")
|
||||
assert video._container_to_nas("/app/data/abc.mp3") == "/volume1/docker/webpage/data/music/abc.mp3"
|
||||
```
|
||||
|
||||
기존 `test_generate_video_calls_ffmpeg`, `test_generate_video_failure_marks_failed` 삭제. thumb 관련 테스트는 그대로 유지.
|
||||
|
||||
### Step 2: Run, verify fail
|
||||
|
||||
```bash
|
||||
cd music-lab && python -m pytest tests/test_video_thumb.py -v
|
||||
```
|
||||
|
||||
Expected: video 관련 테스트들이 실패 (또는 ImportError).
|
||||
|
||||
### Step 3: Rewrite `app/pipeline/video.py`
|
||||
|
||||
```python
|
||||
"""영상 비주얼 생성 — Windows GPU 서버 (NVENC) 호출.
|
||||
|
||||
Windows 서버 다운/실패 시 즉시 예외 (NAS 로컬 폴백 없음 — 의도적 결정).
|
||||
"""
|
||||
import os
|
||||
import logging
|
||||
import httpx
|
||||
|
||||
from . import storage
|
||||
|
||||
logger = logging.getLogger("music-lab.video")
|
||||
|
||||
ENCODER_URL = os.getenv("WINDOWS_VIDEO_ENCODER_URL", "")
|
||||
ENCODER_TIMEOUT_S = 200 # Windows 서버 ffmpeg 180s + 마진
|
||||
|
||||
# NAS 호스트 절대경로 prefix — docker bind mount의 host 측
|
||||
NAS_VIDEOS_ROOT = os.getenv("NAS_VIDEOS_ROOT", "/volume1/docker/webpage/data/videos")
|
||||
NAS_MUSIC_ROOT = os.getenv("NAS_MUSIC_ROOT", "/volume1/docker/webpage/data/music")
|
||||
|
||||
|
||||
class VideoGenerationError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def generate(*, pipeline_id: int, audio_path: str, cover_path: str,
|
||||
genre: str, duration_sec: int, resolution: str = "1920x1080",
|
||||
style: str = "visualizer") -> dict:
|
||||
"""원격 Windows GPU 서버 호출. 다운/실패 시 즉시 예외."""
|
||||
if not ENCODER_URL:
|
||||
raise VideoGenerationError(
|
||||
"WINDOWS_VIDEO_ENCODER_URL 미설정 — Windows 인코더 서버 주소 필요"
|
||||
)
|
||||
|
||||
out_path = os.path.join(storage.pipeline_dir(pipeline_id), "video.mp4")
|
||||
nas_audio = _container_to_nas(audio_path)
|
||||
nas_cover = _container_to_nas(cover_path)
|
||||
nas_output = _container_to_nas(out_path)
|
||||
|
||||
payload = {
|
||||
"cover_path_nas": nas_cover,
|
||||
"audio_path_nas": nas_audio,
|
||||
"output_path_nas": nas_output,
|
||||
"resolution": resolution,
|
||||
"duration_sec": duration_sec,
|
||||
"style": style,
|
||||
}
|
||||
|
||||
logger.info("Windows 인코더 호출: pipeline=%d audio=%s", pipeline_id, audio_path)
|
||||
try:
|
||||
with httpx.Client(timeout=ENCODER_TIMEOUT_S) as client:
|
||||
resp = client.post(f"{ENCODER_URL}/encode_video", json=payload)
|
||||
except (httpx.ConnectError, httpx.ReadTimeout, httpx.WriteTimeout, httpx.NetworkError) as e:
|
||||
raise VideoGenerationError(f"Windows 인코더 연결 실패: {e}")
|
||||
|
||||
if resp.status_code != 200:
|
||||
try:
|
||||
detail = resp.json().get("detail", resp.json())
|
||||
except Exception:
|
||||
detail = {"error": resp.text[:300]}
|
||||
stage = detail.get("stage", "?") if isinstance(detail, dict) else "?"
|
||||
error = detail.get("error", str(detail)) if isinstance(detail, dict) else str(detail)
|
||||
raise VideoGenerationError(
|
||||
f"Windows 인코더 오류 ({resp.status_code}): {stage} — {error}"
|
||||
)
|
||||
|
||||
data = resp.json()
|
||||
if not data.get("ok"):
|
||||
raise VideoGenerationError(f"Windows 인코더 응답 ok=false: {data}")
|
||||
|
||||
return {
|
||||
"url": storage.media_url(pipeline_id, "video.mp4"),
|
||||
"used_fallback": False,
|
||||
"duration_sec": duration_sec,
|
||||
"encode_duration_ms": data.get("duration_ms"),
|
||||
"encoder": data.get("encoder", "h264_nvenc"),
|
||||
}
|
||||
|
||||
|
||||
def _container_to_nas(container_path: str) -> str:
|
||||
""" /app/data/videos/3/cover.jpg → /volume1/docker/webpage/data/videos/3/cover.jpg
|
||||
/app/data/abc.mp3 → /volume1/docker/webpage/data/music/abc.mp3
|
||||
"""
|
||||
if container_path.startswith("/app/data/videos/"):
|
||||
return container_path.replace("/app/data/videos/", NAS_VIDEOS_ROOT + "/", 1)
|
||||
if container_path.startswith("/app/data/"):
|
||||
rel = container_path[len("/app/data/"):]
|
||||
return NAS_MUSIC_ROOT + "/" + rel
|
||||
return container_path
|
||||
```
|
||||
|
||||
### Step 4: Run tests
|
||||
|
||||
```bash
|
||||
cd music-lab && python -m pytest tests/ -v
|
||||
```
|
||||
|
||||
Expected: 73 PASS — 2 (제거) + 6 (신규) = 77? 아니면 73 그대로 — count 확인.
|
||||
|
||||
### Step 5: Commit + push
|
||||
|
||||
```bash
|
||||
git -C C:/Users/jaeoh/Desktop/workspace/web-backend add music-lab/app/pipeline/video.py \
|
||||
music-lab/tests/test_video_thumb.py
|
||||
git -C C:/Users/jaeoh/Desktop/workspace/web-backend commit -m "feat(music-lab): 영상 인코딩을 Windows GPU 서버로 오프로드
|
||||
|
||||
- pipeline/video.py 재작성: subprocess.run 제거, httpx로 192.168.45.59:8765/encode_video 호출
|
||||
- Windows 서버 다운 시 즉시 VideoGenerationError (NAS 로컬 폴백 X)
|
||||
- /app/data/* → /volume1/docker/webpage/data/* 경로 변환 (_container_to_nas)
|
||||
- 테스트는 respx mock 기반으로 교체 (6개 신규)"
|
||||
git -C C:/Users/jaeoh/Desktop/workspace/web-backend push origin main
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 4: docker-compose.yml env 추가
|
||||
|
||||
**Files:**
|
||||
- Modify: `web-backend/docker-compose.yml`
|
||||
|
||||
### Step 1: music-lab 서비스 environment에 추가
|
||||
|
||||
```yaml
|
||||
music-lab:
|
||||
environment:
|
||||
# ... existing ...
|
||||
- WINDOWS_VIDEO_ENCODER_URL=${WINDOWS_VIDEO_ENCODER_URL}
|
||||
- NAS_VIDEOS_ROOT=${NAS_VIDEOS_ROOT:-/volume1/docker/webpage/data/videos}
|
||||
- NAS_MUSIC_ROOT=${NAS_MUSIC_ROOT:-/volume1/docker/webpage/data/music}
|
||||
```
|
||||
|
||||
### Step 2: docker-compose syntax 검증
|
||||
|
||||
```bash
|
||||
cd C:/Users/jaeoh/Desktop/workspace/web-backend && python -c "import yaml; yaml.safe_load(open('docker-compose.yml'))" && echo OK
|
||||
```
|
||||
|
||||
### Step 3: Commit + push
|
||||
|
||||
```bash
|
||||
git -C C:/Users/jaeoh/Desktop/workspace/web-backend add docker-compose.yml
|
||||
git -C C:/Users/jaeoh/Desktop/workspace/web-backend commit -m "chore(infra): GPU 인코더 env 추가 (WINDOWS_VIDEO_ENCODER_URL)"
|
||||
git -C C:/Users/jaeoh/Desktop/workspace/web-backend push origin main
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 5: 사용자 매뉴얼 단계 (사람이 직접)
|
||||
|
||||
후속 단계, 코드 작업 아님:
|
||||
|
||||
1. **Windows PC: ffmpeg 설치 + PATH 설정**
|
||||
- https://www.gyan.dev/ffmpeg/builds/ → "release full" 다운로드
|
||||
- `C:\ffmpeg\` 압축 해제 → `C:\ffmpeg\bin\ffmpeg.exe` 확인
|
||||
- 시스템 PATH에 `C:\ffmpeg\bin` 추가
|
||||
- 검증: `ffmpeg -version` + `ffmpeg -encoders | findstr h264_nvenc`
|
||||
|
||||
2. **Windows PC: `music_ai/.env` 추가**
|
||||
```env
|
||||
NAS_VOLUME_PREFIX=/volume1/
|
||||
WINDOWS_DRIVE_ROOT=Z:\
|
||||
FFMPEG_PATH=C:\ffmpeg\bin\ffmpeg.exe
|
||||
```
|
||||
|
||||
3. **Windows PC: SMB 마운트 확인** — `Z:\docker\webpage\data\` 접근 가능
|
||||
|
||||
4. **Windows PC: `music_ai` 서버 재시작** — `start.bat`
|
||||
|
||||
5. **Windows PC 헬스 체크** — `curl http://localhost:8765/health` → `ffmpeg_nvenc: true` 확인
|
||||
|
||||
6. **NAS `.env`에 추가**
|
||||
```env
|
||||
WINDOWS_VIDEO_ENCODER_URL=http://192.168.45.59:8765
|
||||
```
|
||||
|
||||
7. **NAS music-lab 재시작** — `docker compose up -d music-lab`
|
||||
|
||||
8. **E2E 테스트** — 진행 탭에서 새 파이프라인 시작, 영상 단계가 10–20초에 완료되는지 확인
|
||||
|
||||
---
|
||||
|
||||
## Self-Review
|
||||
|
||||
**Spec coverage:**
|
||||
- §4 Windows endpoint → Task 1, 2 ✓
|
||||
- §5 NAS video.py → Task 3 ✓
|
||||
- §6 에러 처리 → Task 3 (httpx 예외 catch) ✓
|
||||
- §7 헬스 모니터링 → Task 2 (`/health` 확장) ✓
|
||||
- §8 테스트 → Task 1, 3 ✓
|
||||
- §9 Windows 사전 준비 → Task 5 (사용자 수동) ✓
|
||||
- §10 산출물 → 4 task로 모두 커버
|
||||
|
||||
**Placeholder scan:** 없음.
|
||||
|
||||
**Type consistency:**
|
||||
- `EncodeError(stage, message)` Task 1 정의, Task 2에서 `e.stage`/`e.message` 사용 ✓
|
||||
- `VideoGenerationError` Task 3에서 raise, 기존 orchestrator에서 catch ✓
|
||||
- 응답 JSON 형식 spec §4-2와 일치 ✓
|
||||
- 환경변수 이름 일관 (`NAS_VOLUME_PREFIX`, `WINDOWS_DRIVE_ROOT`, `FFMPEG_PATH`, `WINDOWS_VIDEO_ENCODER_URL`, `NAS_VIDEOS_ROOT`, `NAS_MUSIC_ROOT`)
|
||||
|
||||
---
|
||||
@@ -1,815 +0,0 @@
|
||||
# Batch Music Generation — Implementation Plan
|
||||
|
||||
> **For agentic workers:** Use `superpowers:subagent-driven-development`. Steps use `- [ ]` checkboxes.
|
||||
|
||||
**Goal:** 장르 1개로 N(1-10) 트랙 Suno 자동 순차 생성 + 자동 컴파일 + 영상 파이프라인 자동 시작.
|
||||
|
||||
**Architecture:** music-lab 신규 `batch_generator` 모듈이 BackgroundTask로 N회 Suno 호출 → compile_job 자동 생성 → orchestrator.run_step("cover") 자동 호출.
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-05-10-batch-music-generation-design.md`
|
||||
|
||||
---
|
||||
|
||||
## File Structure
|
||||
|
||||
| 경로 | 책임 |
|
||||
|------|------|
|
||||
| `music-lab/app/db.py` (modify) | `music_batch_jobs` 테이블 + 5 헬퍼 |
|
||||
| `music-lab/app/random_pools.py` (new) | 장르별 mood/instr/BPM/key/scale 랜덤 풀 + `randomize()` |
|
||||
| `music-lab/app/batch_generator.py` (new) | `run_batch(batch_id)` 순차 오케스트레이션 |
|
||||
| `music-lab/app/main.py` (modify) | 3개 endpoint (POST /generate-batch, GET /:id, GET 목록) |
|
||||
| `web-ui/src/api.js` (modify) | 3개 헬퍼 |
|
||||
| `web-ui/src/pages/music/components/BatchProgress.jsx` (new) | 진행 표시 컴포넌트 |
|
||||
| `web-ui/src/pages/music/MusicStudio.jsx` (modify) | Create 탭에 배치 섹션 + 폴링 |
|
||||
| `web-ui/src/pages/music/MusicStudio.css` (modify) | 배치 섹션 스타일 |
|
||||
|
||||
---
|
||||
|
||||
## Task 1: DB 테이블 + 헬퍼 + random_pools
|
||||
|
||||
**Files:**
|
||||
- Modify: `music-lab/app/db.py`
|
||||
- Create: `music-lab/app/random_pools.py`
|
||||
- Test: `music-lab/tests/test_batch_db.py`
|
||||
|
||||
- [ ] **Step 1: random_pools.py 작성**
|
||||
|
||||
```python
|
||||
"""장르별 음악 파라미터 랜덤 풀."""
|
||||
import random
|
||||
|
||||
POOLS = {
|
||||
"lo-fi": {
|
||||
"moods": ["chill", "relaxing", "dreamy", "melancholic", "mellow", "nostalgic", "peaceful"],
|
||||
"instruments_pool": ["piano", "synth", "drums", "vinyl", "rhodes", "soft bass", "ambient pads"],
|
||||
"instruments_count": (3, 4),
|
||||
"bpm": (70, 90),
|
||||
"keys": ["C", "D", "F", "G", "A"],
|
||||
"scales": ["minor", "major"],
|
||||
"prompt_modifiers": ["cozy bedroom vibes", "rainy night", "late night study", "cafe ambience"],
|
||||
},
|
||||
"phonk": {
|
||||
"moods": ["dark", "aggressive", "moody", "intense", "hypnotic"],
|
||||
"instruments_pool": ["808 bass", "hi-hat", "synth lead", "vocal chops", "bass drops", "trap drums"],
|
||||
"instruments_count": (3, 4),
|
||||
"bpm": (130, 160),
|
||||
"keys": ["C", "D", "F", "G"],
|
||||
"scales": ["minor"],
|
||||
"prompt_modifiers": ["drift atmosphere", "dark neon", "midnight drive"],
|
||||
},
|
||||
"ambient": {
|
||||
"moods": ["peaceful", "meditative", "ethereal", "spacious", "dreamy"],
|
||||
"instruments_pool": ["pad synths", "atmospheric guitar", "soft strings", "field recordings", "drone bass"],
|
||||
"instruments_count": (2, 3),
|
||||
"bpm": (50, 75),
|
||||
"keys": ["C", "D", "E", "G", "A"],
|
||||
"scales": ["major", "minor"],
|
||||
"prompt_modifiers": ["misty mountain morning", "deep space", "still water", "forest dawn"],
|
||||
},
|
||||
"pop": {
|
||||
"moods": ["uplifting", "happy", "energetic", "romantic", "catchy"],
|
||||
"instruments_pool": ["acoustic guitar", "piano", "drums", "bass", "synth", "vocals harmonies"],
|
||||
"instruments_count": (3, 5),
|
||||
"bpm": (95, 130),
|
||||
"keys": ["C", "D", "E", "F", "G", "A"],
|
||||
"scales": ["major"],
|
||||
"prompt_modifiers": ["radio-ready", "summer vibe", "feel-good"],
|
||||
},
|
||||
"default": {
|
||||
"moods": ["chill", "relaxing", "uplifting", "mellow"],
|
||||
"instruments_pool": ["piano", "synth", "drums", "guitar", "bass", "strings"],
|
||||
"instruments_count": (3, 4),
|
||||
"bpm": (80, 110),
|
||||
"keys": ["C", "D", "F", "G", "A"],
|
||||
"scales": ["minor", "major"],
|
||||
"prompt_modifiers": [""],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def randomize(genre: str, rng=None) -> dict:
|
||||
rng = rng or random.Random()
|
||||
pool = POOLS.get(genre.lower(), POOLS["default"])
|
||||
n_instr = rng.randint(*pool["instruments_count"])
|
||||
instruments = rng.sample(pool["instruments_pool"], min(n_instr, len(pool["instruments_pool"])))
|
||||
return {
|
||||
"moods": [rng.choice(pool["moods"])],
|
||||
"instruments": instruments,
|
||||
"bpm": rng.randint(*pool["bpm"]),
|
||||
"key": rng.choice(pool["keys"]),
|
||||
"scale": rng.choice(pool["scales"]),
|
||||
"prompt_modifier": rng.choice(pool["prompt_modifiers"]),
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: DB 테이블 + 헬퍼 추가** (db.py)
|
||||
|
||||
`init_db()`에 추가:
|
||||
```python
|
||||
cursor.execute("""
|
||||
CREATE TABLE IF NOT EXISTS music_batch_jobs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
genre TEXT NOT NULL,
|
||||
count INTEGER NOT NULL,
|
||||
target_duration_sec INTEGER NOT NULL DEFAULT 180,
|
||||
auto_pipeline INTEGER NOT NULL DEFAULT 1,
|
||||
completed INTEGER NOT NULL DEFAULT 0,
|
||||
track_ids_json TEXT NOT NULL DEFAULT '[]',
|
||||
current_track_index INTEGER NOT NULL DEFAULT 0,
|
||||
current_track_status TEXT,
|
||||
status TEXT NOT NULL DEFAULT 'queued',
|
||||
error TEXT,
|
||||
compile_job_id INTEGER,
|
||||
pipeline_id INTEGER,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
)
|
||||
""")
|
||||
```
|
||||
|
||||
`db.py` 끝에 헬퍼:
|
||||
```python
|
||||
_BATCH_ALLOWED_COLS = frozenset([
|
||||
"completed", "track_ids_json", "current_track_index",
|
||||
"current_track_status", "status", "error",
|
||||
"compile_job_id", "pipeline_id",
|
||||
])
|
||||
|
||||
|
||||
def create_batch_job(genre: str, count: int, target_duration_sec: int = 180,
|
||||
auto_pipeline: bool = True) -> int:
|
||||
with _conn() as conn:
|
||||
now = _now()
|
||||
cur = conn.cursor()
|
||||
cur.execute("""
|
||||
INSERT INTO music_batch_jobs
|
||||
(genre, count, target_duration_sec, auto_pipeline,
|
||||
status, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, 'queued', ?, ?)
|
||||
""", (genre, count, target_duration_sec, 1 if auto_pipeline else 0, now, now))
|
||||
return cur.lastrowid
|
||||
|
||||
|
||||
def get_batch_job(batch_id: int) -> dict | None:
|
||||
with _conn() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT * FROM music_batch_jobs WHERE id = ?", (batch_id,)
|
||||
).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
d = dict(row)
|
||||
d["track_ids"] = json.loads(d.get("track_ids_json") or "[]")
|
||||
return d
|
||||
|
||||
|
||||
def update_batch_job(batch_id: int, **fields) -> None:
|
||||
unknown = set(fields) - _BATCH_ALLOWED_COLS
|
||||
if unknown:
|
||||
raise ValueError(f"unknown batch job columns: {unknown}")
|
||||
cols = ", ".join(f"{k} = ?" for k in fields)
|
||||
vals = list(fields.values()) + [_now(), batch_id]
|
||||
with _conn() as conn:
|
||||
conn.execute(
|
||||
f"UPDATE music_batch_jobs SET {cols}, updated_at = ? WHERE id = ?",
|
||||
vals,
|
||||
)
|
||||
|
||||
|
||||
def append_batch_track(batch_id: int, track_id: int) -> None:
|
||||
"""track_ids_json에 새 track_id 추가 + completed += 1 (atomic)."""
|
||||
with _conn() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT track_ids_json, completed FROM music_batch_jobs WHERE id = ?",
|
||||
(batch_id,),
|
||||
).fetchone()
|
||||
if not row:
|
||||
return
|
||||
ids = json.loads(row["track_ids_json"] or "[]")
|
||||
ids.append(track_id)
|
||||
conn.execute(
|
||||
"UPDATE music_batch_jobs SET track_ids_json = ?, completed = ?, updated_at = ? WHERE id = ?",
|
||||
(json.dumps(ids), row["completed"] + 1, _now(), batch_id),
|
||||
)
|
||||
|
||||
|
||||
def list_batch_jobs(active_only: bool = False) -> list[dict]:
|
||||
sql = "SELECT * FROM music_batch_jobs"
|
||||
if active_only:
|
||||
sql += " WHERE status NOT IN ('failed','cancelled','piped')"
|
||||
sql += " ORDER BY created_at DESC"
|
||||
with _conn() as conn:
|
||||
rows = conn.execute(sql).fetchall()
|
||||
out = []
|
||||
for r in rows:
|
||||
d = dict(r)
|
||||
d["track_ids"] = json.loads(d.get("track_ids_json") or "[]")
|
||||
out.append(d)
|
||||
return out
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Test 작성**
|
||||
|
||||
```python
|
||||
# tests/test_batch_db.py
|
||||
import pytest
|
||||
from app import db
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fresh_db(monkeypatch, tmp_path):
|
||||
monkeypatch.setattr(db, "DB_PATH", str(tmp_path / "music.db"))
|
||||
db.init_db()
|
||||
return db
|
||||
|
||||
|
||||
def test_create_batch_job(fresh_db):
|
||||
bid = db.create_batch_job(genre="lo-fi", count=10)
|
||||
j = db.get_batch_job(bid)
|
||||
assert j["genre"] == "lo-fi"
|
||||
assert j["count"] == 10
|
||||
assert j["status"] == "queued"
|
||||
assert j["track_ids"] == []
|
||||
assert j["auto_pipeline"] == 1
|
||||
|
||||
|
||||
def test_update_batch_job(fresh_db):
|
||||
bid = db.create_batch_job(genre="phonk", count=5)
|
||||
db.update_batch_job(bid, status="generating", current_track_index=2)
|
||||
j = db.get_batch_job(bid)
|
||||
assert j["status"] == "generating"
|
||||
assert j["current_track_index"] == 2
|
||||
|
||||
|
||||
def test_update_batch_rejects_unknown_col(fresh_db):
|
||||
bid = db.create_batch_job(genre="lo-fi", count=1)
|
||||
with pytest.raises(ValueError):
|
||||
db.update_batch_job(bid, evil_col="x")
|
||||
|
||||
|
||||
def test_append_batch_track(fresh_db):
|
||||
bid = db.create_batch_job(genre="lo-fi", count=3)
|
||||
db.append_batch_track(bid, 101)
|
||||
db.append_batch_track(bid, 102)
|
||||
j = db.get_batch_job(bid)
|
||||
assert j["track_ids"] == [101, 102]
|
||||
assert j["completed"] == 2
|
||||
|
||||
|
||||
def test_list_batch_jobs_active_filter(fresh_db):
|
||||
b1 = db.create_batch_job(genre="lo-fi", count=1)
|
||||
b2 = db.create_batch_job(genre="phonk", count=1)
|
||||
db.update_batch_job(b1, status="failed")
|
||||
actives = db.list_batch_jobs(active_only=True)
|
||||
assert all(j["status"] not in ("failed",) for j in actives)
|
||||
assert any(j["id"] == b2 for j in actives)
|
||||
assert not any(j["id"] == b1 for j in actives)
|
||||
|
||||
|
||||
def test_random_pools_randomize():
|
||||
from app.random_pools import randomize, POOLS
|
||||
import random
|
||||
rng = random.Random(42)
|
||||
result = randomize("lo-fi", rng)
|
||||
assert result["bpm"] in range(70, 91)
|
||||
assert result["key"] in POOLS["lo-fi"]["keys"]
|
||||
assert result["scale"] in POOLS["lo-fi"]["scales"]
|
||||
assert len(result["moods"]) == 1
|
||||
assert result["moods"][0] in POOLS["lo-fi"]["moods"]
|
||||
assert 3 <= len(result["instruments"]) <= 4
|
||||
|
||||
|
||||
def test_random_pools_unknown_genre_uses_default():
|
||||
from app.random_pools import randomize, POOLS
|
||||
import random
|
||||
result = randomize("nonexistent", random.Random(0))
|
||||
assert result["bpm"] in range(80, 111) # default range
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run + commit**
|
||||
|
||||
```bash
|
||||
cd music-lab && python -m pytest tests/test_batch_db.py -v
|
||||
```
|
||||
Expected: 7 PASS.
|
||||
|
||||
```bash
|
||||
git add music-lab/app/db.py music-lab/app/random_pools.py music-lab/tests/test_batch_db.py
|
||||
git commit -m "feat(music-lab): music_batch_jobs 테이블 + 장르별 랜덤 풀"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 2: batch_generator + 3 엔드포인트
|
||||
|
||||
**Files:**
|
||||
- Create: `music-lab/app/batch_generator.py`
|
||||
- Modify: `music-lab/app/main.py`
|
||||
- Test: `music-lab/tests/test_batch_endpoints.py`
|
||||
|
||||
- [ ] **Step 1: batch_generator.py 작성**
|
||||
|
||||
```python
|
||||
"""배치 음악 생성 + 자동 컴파일·영상 파이프라인."""
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
from . import db
|
||||
from .random_pools import randomize
|
||||
|
||||
logger = logging.getLogger("music-lab.batch")
|
||||
|
||||
POLL_INTERVAL_S = 5
|
||||
TRACK_GEN_TIMEOUT_S = 240
|
||||
|
||||
|
||||
async def run_batch(batch_id: int) -> None:
|
||||
job = db.get_batch_job(batch_id)
|
||||
if not job:
|
||||
return
|
||||
genre = job["genre"]
|
||||
count = job["count"]
|
||||
duration = job["target_duration_sec"]
|
||||
auto_pipe = bool(job["auto_pipeline"])
|
||||
|
||||
db.update_batch_job(batch_id, status="generating")
|
||||
|
||||
track_ids: list[int] = []
|
||||
for i in range(1, count + 1):
|
||||
title = f"{genre.title()} Mix Track {i}"
|
||||
params = randomize(genre)
|
||||
db.update_batch_job(batch_id,
|
||||
current_track_index=i,
|
||||
current_track_status="generating")
|
||||
|
||||
track_id = await _generate_one_track(title=title, genre=genre,
|
||||
duration_sec=duration,
|
||||
params=params)
|
||||
if track_id:
|
||||
track_ids.append(track_id)
|
||||
db.append_batch_track(batch_id, track_id)
|
||||
db.update_batch_job(batch_id, current_track_status="succeeded")
|
||||
else:
|
||||
db.update_batch_job(batch_id, current_track_status="failed")
|
||||
logger.warning("배치 %d 트랙 %d 실패 — 계속 진행", batch_id, i)
|
||||
|
||||
if not track_ids:
|
||||
db.update_batch_job(batch_id, status="failed",
|
||||
error="모든 트랙 생성 실패")
|
||||
return
|
||||
|
||||
db.update_batch_job(batch_id, status="generated")
|
||||
|
||||
if not auto_pipe:
|
||||
return
|
||||
|
||||
# 자동 컴파일
|
||||
db.update_batch_job(batch_id, status="compiling")
|
||||
try:
|
||||
compile_id = db.create_compile_job(
|
||||
title=f"{genre.title()} Mix",
|
||||
track_ids=track_ids,
|
||||
crossfade_sec=3,
|
||||
)
|
||||
db.update_batch_job(batch_id, compile_job_id=compile_id)
|
||||
except Exception as e:
|
||||
db.update_batch_job(batch_id, status="failed", error=f"compile create: {e}")
|
||||
return
|
||||
|
||||
from . import compiler
|
||||
try:
|
||||
await asyncio.to_thread(compiler.run, compile_id)
|
||||
except Exception as e:
|
||||
db.update_batch_job(batch_id, status="failed", error=f"compile run: {e}")
|
||||
return
|
||||
|
||||
job_after = db.get_compile_job(compile_id)
|
||||
if not job_after or job_after.get("status") not in ("done", "succeeded"):
|
||||
db.update_batch_job(
|
||||
batch_id, status="failed",
|
||||
error=f"compile not done (status={job_after.get('status') if job_after else 'unknown'})"
|
||||
)
|
||||
return
|
||||
|
||||
# 자동 영상 파이프라인
|
||||
pipeline_id = db.create_pipeline(compile_job_id=compile_id)
|
||||
db.update_batch_job(batch_id, pipeline_id=pipeline_id, status="piped")
|
||||
|
||||
from .pipeline import orchestrator
|
||||
await orchestrator.run_step(pipeline_id, "cover")
|
||||
|
||||
|
||||
async def _generate_one_track(*, title: str, genre: str, duration_sec: int,
|
||||
params: dict) -> int | None:
|
||||
"""기존 Suno generate 호출 + 완료까지 polling. 성공 시 새 track id 반환."""
|
||||
from .suno_provider import run_suno_generation
|
||||
from .db import create_task, get_task
|
||||
import uuid
|
||||
|
||||
task_id = str(uuid.uuid4())
|
||||
suno_params = {
|
||||
"title": title,
|
||||
"genre": genre,
|
||||
"moods": params["moods"],
|
||||
"instruments": params["instruments"],
|
||||
"duration_sec": duration_sec,
|
||||
"bpm": params["bpm"],
|
||||
"key": params["key"],
|
||||
"scale": params["scale"],
|
||||
"prompt": params.get("prompt_modifier", ""),
|
||||
}
|
||||
create_task(task_id, suno_params, provider="suno")
|
||||
|
||||
# Suno background task 직접 호출 (BackgroundTasks 미사용 — 우리가 await)
|
||||
asyncio.create_task(asyncio.to_thread(run_suno_generation, task_id, suno_params))
|
||||
|
||||
# Polling
|
||||
waited = 0
|
||||
while waited < TRACK_GEN_TIMEOUT_S:
|
||||
await asyncio.sleep(POLL_INTERVAL_S)
|
||||
waited += POLL_INTERVAL_S
|
||||
task = get_task(task_id)
|
||||
if not task:
|
||||
continue
|
||||
if task.get("status") == "succeeded":
|
||||
tr = task.get("track")
|
||||
return tr.get("id") if tr else None
|
||||
if task.get("status") == "failed":
|
||||
return None
|
||||
return None # timeout
|
||||
```
|
||||
|
||||
NOTE: This assumes existing `db.create_task`, `db.get_task`, `suno_provider.run_suno_generation` are reusable. Read existing code to confirm function signatures, adjust if needed (especially `task["track"]["id"]` vs other format).
|
||||
|
||||
- [ ] **Step 2: main.py에 3 endpoint 추가**
|
||||
|
||||
```python
|
||||
from app.batch_generator import run_batch as _run_batch
|
||||
|
||||
|
||||
class BatchGenerateRequest(BaseModel):
|
||||
genre: str
|
||||
count: int = 10
|
||||
target_duration_sec: int = 180
|
||||
auto_pipeline: bool = True
|
||||
|
||||
|
||||
@app.post("/api/music/generate-batch", status_code=201)
|
||||
async def generate_batch(req: BatchGenerateRequest, bg: BackgroundTasks):
|
||||
if not (1 <= req.count <= 10):
|
||||
raise HTTPException(400, "count는 1-10 사이")
|
||||
if not (60 <= req.target_duration_sec <= 300):
|
||||
raise HTTPException(400, "target_duration_sec는 60-300 사이")
|
||||
if not req.genre:
|
||||
raise HTTPException(400, "genre 필수")
|
||||
if not SUNO_API_KEY:
|
||||
raise HTTPException(400, "SUNO_API_KEY 미설정")
|
||||
|
||||
batch_id = _db_module.create_batch_job(
|
||||
genre=req.genre, count=req.count,
|
||||
target_duration_sec=req.target_duration_sec,
|
||||
auto_pipeline=req.auto_pipeline,
|
||||
)
|
||||
bg.add_task(_run_batch, batch_id)
|
||||
return _db_module.get_batch_job(batch_id)
|
||||
|
||||
|
||||
@app.get("/api/music/generate-batch/{batch_id}")
|
||||
def get_batch(batch_id: int):
|
||||
j = _db_module.get_batch_job(batch_id)
|
||||
if not j:
|
||||
raise HTTPException(404)
|
||||
# tracks 메타 LEFT JOIN (id, title, audio_url)
|
||||
if j["track_ids"]:
|
||||
ids_csv = ",".join(str(i) for i in j["track_ids"])
|
||||
# 간단한 in-Python 매핑 (sqlite IN (...))
|
||||
import sqlite3
|
||||
conn = sqlite3.connect(_db_module.DB_PATH)
|
||||
conn.row_factory = sqlite3.Row
|
||||
rows = conn.execute(
|
||||
f"SELECT id, title, audio_url, duration_sec FROM music_library WHERE id IN ({ids_csv})"
|
||||
).fetchall()
|
||||
conn.close()
|
||||
j["tracks"] = [dict(r) for r in rows]
|
||||
else:
|
||||
j["tracks"] = []
|
||||
return j
|
||||
|
||||
|
||||
@app.get("/api/music/generate-batch")
|
||||
def list_batches(status: str = "all"):
|
||||
return {"batches": _db_module.list_batch_jobs(active_only=(status == "active"))}
|
||||
```
|
||||
|
||||
(SUNO_API_KEY는 main.py에 이미 import돼있다고 가정. 없으면 `_db_module` 패턴처럼 처리.)
|
||||
|
||||
- [ ] **Step 3: 테스트 작성**
|
||||
|
||||
```python
|
||||
# tests/test_batch_endpoints.py
|
||||
import pytest
|
||||
from unittest.mock import AsyncMock, patch, MagicMock
|
||||
from fastapi.testclient import TestClient
|
||||
from app.main import app
|
||||
from app import db
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(monkeypatch, tmp_path):
|
||||
monkeypatch.setattr(db, "DB_PATH", str(tmp_path / "music.db"))
|
||||
db.init_db()
|
||||
monkeypatch.setenv("SUNO_API_KEY", "test")
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def test_create_batch_201(client):
|
||||
with patch("app.main._run_batch", new=AsyncMock()):
|
||||
r = client.post("/api/music/generate-batch",
|
||||
json={"genre": "lo-fi", "count": 3})
|
||||
assert r.status_code == 201
|
||||
body = r.json()
|
||||
assert body["genre"] == "lo-fi"
|
||||
assert body["count"] == 3
|
||||
assert body["status"] == "queued"
|
||||
|
||||
|
||||
def test_create_batch_rejects_count_too_high(client):
|
||||
r = client.post("/api/music/generate-batch",
|
||||
json={"genre": "lo-fi", "count": 11})
|
||||
assert r.status_code == 400
|
||||
|
||||
|
||||
def test_create_batch_rejects_count_zero(client):
|
||||
r = client.post("/api/music/generate-batch",
|
||||
json={"genre": "lo-fi", "count": 0})
|
||||
assert r.status_code == 400
|
||||
|
||||
|
||||
def test_create_batch_rejects_no_genre(client):
|
||||
r = client.post("/api/music/generate-batch", json={"count": 3})
|
||||
# Pydantic missing 필드 → 422 (FastAPI default validation)
|
||||
assert r.status_code in (400, 422)
|
||||
|
||||
|
||||
def test_get_batch_returns_tracks(client):
|
||||
bid = db.create_batch_job(genre="lo-fi", count=2)
|
||||
db.append_batch_track(bid, 999) # phantom track id (not in library)
|
||||
r = client.get(f"/api/music/generate-batch/{bid}")
|
||||
assert r.status_code == 200
|
||||
body = r.json()
|
||||
assert body["track_ids"] == [999]
|
||||
# tracks 배열은 비어있음 (해당 track 미존재)
|
||||
assert body["tracks"] == []
|
||||
|
||||
|
||||
def test_list_batches(client):
|
||||
db.create_batch_job(genre="lo-fi", count=1)
|
||||
db.create_batch_job(genre="phonk", count=2)
|
||||
r = client.get("/api/music/generate-batch")
|
||||
assert len(r.json()["batches"]) == 2
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run + commit + push**
|
||||
|
||||
```bash
|
||||
cd music-lab && python -m pytest tests/ -v
|
||||
```
|
||||
Expected: 모두 PASS.
|
||||
|
||||
```bash
|
||||
git -C C:/Users/jaeoh/Desktop/workspace/web-backend add music-lab/app/batch_generator.py \
|
||||
music-lab/app/main.py \
|
||||
music-lab/tests/test_batch_endpoints.py
|
||||
git -C C:/Users/jaeoh/Desktop/workspace/web-backend commit -m "feat(music-lab): 배치 음악 생성 endpoint + orchestrator"
|
||||
git -C C:/Users/jaeoh/Desktop/workspace/web-backend push origin main
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 3: Frontend Create 탭 배치 섹션
|
||||
|
||||
**Files:**
|
||||
- Modify: `web-ui/src/api.js`
|
||||
- Create: `web-ui/src/pages/music/components/BatchProgress.jsx`
|
||||
- Modify: `web-ui/src/pages/music/MusicStudio.jsx`
|
||||
- Modify: `web-ui/src/pages/music/MusicStudio.css`
|
||||
|
||||
- [ ] **Step 1: api.js 헬퍼**
|
||||
|
||||
```javascript
|
||||
// === Batch generation ===
|
||||
export const startBatchGen = (payload) => apiPost('/api/music/generate-batch', payload);
|
||||
export const getBatchJob = (id) => apiGet(`/api/music/generate-batch/${id}`);
|
||||
export const listBatchJobs = (status='all') => apiGet(`/api/music/generate-batch?status=${status}`);
|
||||
```
|
||||
|
||||
- [ ] **Step 2: BatchProgress.jsx 신규**
|
||||
|
||||
```jsx
|
||||
const STATUS_LABELS = {
|
||||
queued: '대기 중', generating: '음악 생성 중', generated: '음악 완료, 컴파일 대기',
|
||||
compiling: '컴파일 중', piped: '영상 파이프라인 시작됨',
|
||||
failed: '실패', cancelled: '취소',
|
||||
};
|
||||
|
||||
export default function BatchProgress({ batch }) {
|
||||
if (!batch) return null;
|
||||
const trackList = Array.from({ length: batch.count }, (_, i) => i + 1);
|
||||
return (
|
||||
<div className="ms-batch-progress">
|
||||
<div className="ms-batch-header">
|
||||
배치 #{batch.id} — {batch.genre} ·{' '}
|
||||
{batch.completed}/{batch.count} 완료 ·{' '}
|
||||
<strong>{STATUS_LABELS[batch.status] || batch.status}</strong>
|
||||
</div>
|
||||
{batch.error && <div className="ms-error">에러: {batch.error}</div>}
|
||||
<ol className="ms-batch-tracks">
|
||||
{trackList.map(n => {
|
||||
const completed = n <= batch.completed;
|
||||
const current = n === batch.current_track_index && batch.status === 'generating';
|
||||
const tr = (batch.tracks || [])[n - 1];
|
||||
return (
|
||||
<li key={n} className={completed ? 'done' : current ? 'current' : 'pending'}>
|
||||
{completed ? '✓' : current ? '⏳' : '○'}
|
||||
{' '}Track {n}: {tr?.title || (current ? '생성 중...' : '대기')}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
{batch.compile_job_id && (
|
||||
<div className="ms-batch-link">📀 컴파일 #{batch.compile_job_id}</div>
|
||||
)}
|
||||
{batch.pipeline_id && (
|
||||
<div className="ms-batch-link">
|
||||
🎬 영상 파이프라인 #{batch.pipeline_id} —
|
||||
{' '}<em>YouTube 탭 → 진행 탭에서 확인</em>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 3: MusicStudio.jsx Create 탭에 배치 섹션 추가**
|
||||
|
||||
Create 탭 jsx 영역 (handleGenerate 근처) 위 또는 옆에:
|
||||
|
||||
```jsx
|
||||
import BatchProgress from './components/BatchProgress';
|
||||
import { startBatchGen, getBatchJob } from '../../api';
|
||||
|
||||
// 컴포넌트 내부 state:
|
||||
const [batchOpen, setBatchOpen] = useState(false);
|
||||
const [batchGenre, setBatchGenre] = useState('lo-fi');
|
||||
const [batchCount, setBatchCount] = useState(10);
|
||||
const [batchDuration, setBatchDuration] = useState(180);
|
||||
const [batchAutoPipe, setBatchAutoPipe] = useState(true);
|
||||
const [currentBatch, setCurrentBatch] = useState(null);
|
||||
const [batchPolling, setBatchPolling] = useState(false);
|
||||
const batchPollRef = useRef(null);
|
||||
|
||||
const startBatch = async () => {
|
||||
try {
|
||||
const res = await startBatchGen({
|
||||
genre: batchGenre,
|
||||
count: batchCount,
|
||||
target_duration_sec: batchDuration,
|
||||
auto_pipeline: batchAutoPipe,
|
||||
});
|
||||
setCurrentBatch(res);
|
||||
setBatchPolling(true);
|
||||
} catch (e) {
|
||||
alert(`배치 시작 실패: ${e.message || e}`);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!batchPolling || !currentBatch?.id) return;
|
||||
const tick = async () => {
|
||||
const j = await getBatchJob(currentBatch.id).catch(() => null);
|
||||
if (j) {
|
||||
setCurrentBatch(j);
|
||||
if (['piped', 'failed', 'cancelled'].includes(j.status)) {
|
||||
setBatchPolling(false);
|
||||
if (j.pipeline_id) loadLibrary?.(); // refresh library to show new tracks
|
||||
}
|
||||
}
|
||||
};
|
||||
batchPollRef.current = setInterval(tick, 5000);
|
||||
return () => clearInterval(batchPollRef.current);
|
||||
}, [batchPolling, currentBatch?.id]);
|
||||
|
||||
// ... Create 탭 jsx 안:
|
||||
<details className="ms-batch-section" open={batchOpen} onToggle={(e) => setBatchOpen(e.target.open)}>
|
||||
<summary>🎲 배치 생성 (장르 → 1-10트랙 + 자동 영상)</summary>
|
||||
<div className="ms-batch-form">
|
||||
<label>장르
|
||||
<select value={batchGenre} onChange={e => setBatchGenre(e.target.value)}>
|
||||
<option value="lo-fi">Lo-Fi</option>
|
||||
<option value="phonk">Phonk</option>
|
||||
<option value="ambient">Ambient</option>
|
||||
<option value="pop">Pop</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>트랙 수: {batchCount}
|
||||
<input type="range" min={1} max={10} value={batchCount}
|
||||
onChange={e => setBatchCount(parseInt(e.target.value))} />
|
||||
</label>
|
||||
<label>트랙당 길이: {batchDuration}초
|
||||
<input type="range" min={60} max={300} step={10} value={batchDuration}
|
||||
onChange={e => setBatchDuration(parseInt(e.target.value))} />
|
||||
</label>
|
||||
<label className="ms-batch-checkbox">
|
||||
<input type="checkbox" checked={batchAutoPipe}
|
||||
onChange={e => setBatchAutoPipe(e.target.checked)} />
|
||||
모든 트랙 생성 후 자동 영상 파이프라인 시작
|
||||
</label>
|
||||
<p className="ms-batch-estimate">
|
||||
예상: 약 {Math.ceil(batchCount * 1.5)}-{batchCount * 2}분 ·
|
||||
비용 ~${(batchCount * 0.005 + (batchAutoPipe ? 0.05 : 0)).toFixed(2)}
|
||||
</p>
|
||||
<button className="button primary" onClick={startBatch}
|
||||
disabled={batchPolling}>
|
||||
🎵 배치 생성 시작
|
||||
</button>
|
||||
</div>
|
||||
{currentBatch && <BatchProgress batch={currentBatch} />}
|
||||
</details>
|
||||
```
|
||||
|
||||
- [ ] **Step 4: CSS 추가**
|
||||
|
||||
```css
|
||||
/* === Batch generation section === */
|
||||
.ms-batch-section { margin: 16px 0; padding: 12px; background: rgba(0,0,0,.2);
|
||||
border: 1px solid var(--ms-line, #2a2a3a); border-radius: 12px; }
|
||||
.ms-batch-section summary { cursor: pointer; font-weight: bold; color: var(--ms-text, #f0f0f5); }
|
||||
.ms-batch-form { display: flex; flex-direction: column; gap: 10px; padding: 12px 0; }
|
||||
.ms-batch-form label { display: flex; flex-direction: column; gap: 4px; font-size: 13px; }
|
||||
.ms-batch-form input[type="range"] { width: 100%; }
|
||||
.ms-batch-checkbox { flex-direction: row !important; align-items: center; gap: 8px; }
|
||||
.ms-batch-checkbox input { width: auto; }
|
||||
.ms-batch-estimate { font-size: 12px; color: var(--ms-muted, #a0a0b0); }
|
||||
|
||||
.ms-batch-progress { margin-top: 12px; padding: 12px; background: rgba(0,0,0,.3);
|
||||
border-radius: 8px; }
|
||||
.ms-batch-header { font-size: 13px; margin-bottom: 8px; }
|
||||
.ms-batch-tracks { padding-left: 24px; font-size: 12px; }
|
||||
.ms-batch-tracks li { margin: 2px 0; }
|
||||
.ms-batch-tracks li.done { color: #86efac; }
|
||||
.ms-batch-tracks li.current { color: var(--ms-accent, #38bdf8); font-weight: bold; }
|
||||
.ms-batch-tracks li.pending { color: var(--ms-muted, #a0a0b0); }
|
||||
.ms-batch-link { margin-top: 8px; font-size: 12px; color: var(--ms-muted, #a0a0b0); }
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Build + verify + commit + push + deploy**
|
||||
|
||||
```bash
|
||||
cd web-ui && npm run build 2>&1 | tail -5
|
||||
npx eslint src/pages/music/components/BatchProgress.jsx src/pages/music/MusicStudio.jsx 2>&1 | tail
|
||||
```
|
||||
|
||||
```bash
|
||||
git -C C:/Users/jaeoh/Desktop/workspace/web-ui add src/api.js \
|
||||
src/pages/music/components/BatchProgress.jsx \
|
||||
src/pages/music/MusicStudio.jsx \
|
||||
src/pages/music/MusicStudio.css
|
||||
git -C C:/Users/jaeoh/Desktop/workspace/web-ui commit -m "feat(web-ui): Create 탭 배치 생성 섹션 + BatchProgress"
|
||||
git -C C:/Users/jaeoh/Desktop/workspace/web-ui push origin main
|
||||
cd C:/Users/jaeoh/Desktop/workspace/web-ui && npm run release:nas
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 4: 수동 E2E 검증
|
||||
|
||||
- [ ] Create 탭 → 배치 생성 섹션 펼침 → genre=lo-fi, count=3 (테스트로 적게), duration=120s, auto_pipeline=on → "배치 생성 시작"
|
||||
- [ ] BatchProgress에 Track 1/2/3 진행 표시 확인
|
||||
- [ ] ~5분 후 Library에 3개 트랙 추가됨
|
||||
- [ ] 컴파일 진행 확인 (status: compiling)
|
||||
- [ ] 영상 파이프라인 시작됨 (status: piped) + pipeline_id 표시
|
||||
- [ ] YouTube 탭 → 진행 탭에 새 카드, cover 단계 진행 중
|
||||
- [ ] 텔레그램에 cover 알림 도착
|
||||
- [ ] 일반 흐름대로 5단계 승인 후 발행
|
||||
|
||||
---
|
||||
|
||||
## Self-Review
|
||||
|
||||
**Spec coverage:**
|
||||
- §3 사용자 흐름 → Task 3 (UI 섹션)
|
||||
- §4 데이터 모델 → Task 1
|
||||
- §5 백엔드 (random_pools, batch_generator) → Task 1, 2
|
||||
- §6 API → Task 2
|
||||
- §7 프론트엔드 → Task 3
|
||||
- §8 에러 처리 → Task 2 (validation, try/except)
|
||||
- §9 테스트 → Task 1, 2
|
||||
- §10 산출물 → 4 task로 모두 커버
|
||||
|
||||
**Placeholder scan:** 없음.
|
||||
|
||||
**Type consistency:**
|
||||
- `batch_id` int, `count` int, `genre` str — 일관
|
||||
- `track_ids` list[int]
|
||||
- `status` 7값 (queued/generating/generated/compiling/piped/failed/cancelled) 일관
|
||||
|
||||
**스펙 보정:** §5-2 batch_generator의 `_generate_one_track`에서 `db.create_task`/`db.get_task` 사용 — 이 함수들이 기존 db.py에 있는지 미확인. Task 2 Step 1 NOTE에 명시함.
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user