[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -1,115 +1,204 @@
|
||||
---
|
||||
id: wiki-2026-0508-my-videos-check
|
||||
title: my videos check
|
||||
title: my_videos_check (Personal YouTube Channel Monitor)
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: []
|
||||
aliases: [Channel Health Monitor, YT Self-monitor, Video Stats Watcher]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.92
|
||||
tags: [uncategorized]
|
||||
confidence_score: 0.85
|
||||
verification_status: applied
|
||||
tags: [youtube-api, monitoring, cron, analytics, creator-tooling]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-08
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: Python 3.12
|
||||
framework: YouTube Analytics API + DuckDB + cron
|
||||
---
|
||||
|
||||
# 🎬 내 영상 체크
|
||||
# my_videos_check (Personal YouTube Channel Monitor)
|
||||
|
||||
본인 채널의 최근 영상이 잘 올라갔는지 한눈에 봅니다. 조회수 중간값을 기준선으로 삼아 떡상/부진 영상을 자동 분류하고, 다음에 뭘 할지 짧은 제안까지 만들어줘요.
|
||||
## 매 한 줄
|
||||
> **"매 own 의 YouTube 채널 의 매 video 마다 매 view/like/comment/CTR/AVD 의 daily snapshot 을 매 fetch → DuckDB → 매 anomaly alert"**. 2026 creator workflow 의 기본 component. 매 YouTube Studio 의 dashboard 보다 훨씬 매 customizable + 매 multi-channel 비교 + 매 LLM 기반 insight.
|
||||
|
||||
## 어떻게 도와주나요?
|
||||
- 🎬 본인 채널 최근 N개 영상 메타·통계 수집
|
||||
- 📊 조회수 **중간값** 계산 → 1.5배 이상 = 🔥 떡상, 0.5배 미만 = 🥶 부진
|
||||
- 🧭 떡상/부진 비율 보고 다음 액션 1~3개 제안
|
||||
- 📨 `[[youtube_account|youtube_account]].json`에 텔레그램이 설정돼있으면 보고를 메시지로도 보내줌
|
||||
## 매 핵심
|
||||
|
||||
## 시작하기 전 체크
|
||||
- `youtube_account.json`의 `YOUTUBE_API_KEY` + `MY_CHANNEL_HANDLE` 또는 `MY_CHANNEL_ID` 채워야 함
|
||||
- 핸들만 있어도 자동으로 채널 ID를 조회합니다 (검색 1회 사용)
|
||||
### 매 Data sources
|
||||
- **YouTube Data API v3**: video metadata, current snapshot stats.
|
||||
- **YouTube Analytics API v2**: time-series (impressions, CTR, AVD, retention, traffic source) — 매 OAuth 필요.
|
||||
- **YouTube Reporting API**: bulk daily CSV (매 large channel 에 적합).
|
||||
|
||||
## 설정값 (my_videos_check.json)
|
||||
- `LOOKBACK_DAYS` — 며칠치 영상 볼지 (기본 30)
|
||||
- `TOP_N` — 최대 몇 개 분석할지 (기본 10)
|
||||
### 매 Snapshot schema
|
||||
- `video_id, captured_at, views, likes, comments, watch_time_min, avd_sec, ctr, impressions`.
|
||||
- Time-series: `(video_id, day, metric)` — 매 partitioned.
|
||||
|
||||
## 출력
|
||||
- 콘솔에 영상별 조회수·라이크·댓글 수
|
||||
- `my_videos_check_report.md`에 누적 저장
|
||||
- (선택) 텔레그램 알림
|
||||
### 매 Alerts
|
||||
- View rate (24h growth) 가 매 baseline 의 3σ 밖.
|
||||
- 매 Comment rate spike — possible viral 또는 controversy.
|
||||
- CTR drop > 30% on recent uploads.
|
||||
- 매 watch time 의 sudden cliff at specific timestamp (retention curve).
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
### 매 응용
|
||||
1. 매 daily morning briefing (Telegram bot).
|
||||
2. Auto-thumbnail A/B 결정.
|
||||
3. 매 evergreen vs. 매 short-lived video classification.
|
||||
4. Topic-level trending in own catalog.
|
||||
|
||||
> *(TODO: 한 문장으로 핵심 통찰을 작성. "X는 Y 조건에서 Z 효과를 낸다" 구조 권장.)*
|
||||
## 💻 패턴
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
|
||||
**추출된 패턴:**
|
||||
> *(TODO)*
|
||||
|
||||
**세부 내용:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
|
||||
- **과거 데이터와의 충돌:** 없음
|
||||
- **정책 변화:** 없음
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
|
||||
- **Parent:** [[10_Wiki/Topics]]
|
||||
- **Related:** *(TODO: 최소 2개)*
|
||||
- **Opposite / Trade-off:** *(TODO)*
|
||||
- **Raw Source:** 직접 입력
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
### OAuth setup (one-time)
|
||||
```python
|
||||
from google_auth_oauthlib.flow import InstalledAppFlow
|
||||
SCOPES = ['https://www.googleapis.com/auth/yt-analytics.readonly',
|
||||
'https://www.googleapis.com/auth/youtube.readonly']
|
||||
flow = InstalledAppFlow.from_client_secrets_file('client_secret.json', SCOPES)
|
||||
creds = flow.run_local_server(port=0)
|
||||
with open('token.json', 'w') as f: f.write(creds.to_json())
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Daily snapshot
|
||||
```python
|
||||
from googleapiclient.discovery import build
|
||||
from google.oauth2.credentials import Credentials
|
||||
import duckdb, datetime as dt
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
creds = Credentials.from_authorized_user_file('token.json')
|
||||
yt = build('youtube', 'v3', credentials=creds)
|
||||
yta = build('youtubeAnalytics', 'v2', credentials=creds)
|
||||
con = duckdb.connect('mychannel.db')
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
con.execute("""CREATE TABLE IF NOT EXISTS snapshots(
|
||||
video_id VARCHAR, captured_at TIMESTAMP, views BIGINT, likes BIGINT,
|
||||
comments BIGINT, watch_min DOUBLE, avd_sec DOUBLE, ctr DOUBLE, impressions BIGINT,
|
||||
PRIMARY KEY (video_id, captured_at)
|
||||
)""")
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
def list_my_videos():
|
||||
res = yt.search().list(forMine=True, type='video', part='id', maxResults=50).execute()
|
||||
return [item['id']['videoId'] for item in res['items']]
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
def fetch_snapshot(video_ids):
|
||||
res = yt.videos().list(part='statistics,contentDetails,snippet', id=','.join(video_ids)).execute()
|
||||
rows = []
|
||||
for v in res['items']:
|
||||
s = v['statistics']
|
||||
rows.append({
|
||||
'video_id': v['id'],
|
||||
'views': int(s.get('viewCount', 0)),
|
||||
'likes': int(s.get('likeCount', 0)),
|
||||
'comments': int(s.get('commentCount', 0)),
|
||||
})
|
||||
return rows
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
def fetch_analytics(video_id, days=7):
|
||||
end = dt.date.today()
|
||||
start = end - dt.timedelta(days=days)
|
||||
res = yta.reports().query(
|
||||
ids='channel==MINE', startDate=str(start), endDate=str(end),
|
||||
metrics='views,estimatedMinutesWatched,averageViewDuration,impressions,impressionsCtr',
|
||||
dimensions='video', filters=f'video=={video_id}',
|
||||
).execute()
|
||||
return res.get('rows', [[]])[0] if res.get('rows') else None
|
||||
```
|
||||
|
||||
### Anomaly detector (Z-score)
|
||||
```python
|
||||
import statistics
|
||||
def is_spike(video_id, metric='views', window=14, z=3.0):
|
||||
rows = con.execute(f"""
|
||||
SELECT {metric} FROM snapshots WHERE video_id=?
|
||||
ORDER BY captured_at DESC LIMIT {window+1}
|
||||
""", [video_id]).fetchall()
|
||||
if len(rows) < window + 1: return False
|
||||
today, hist = rows[0][0], [r[0] for r in rows[1:]]
|
||||
deltas = [hist[i] - hist[i+1] for i in range(len(hist)-1)]
|
||||
today_delta = today - hist[0]
|
||||
if not deltas or statistics.pstdev(deltas) == 0: return False
|
||||
return abs(today_delta - statistics.mean(deltas)) / statistics.pstdev(deltas) > z
|
||||
```
|
||||
|
||||
### Telegram alert
|
||||
```python
|
||||
import requests, os
|
||||
def alert(msg):
|
||||
requests.post(
|
||||
f"https://api.telegram.org/bot{os.environ['TG_TOKEN']}/sendMessage",
|
||||
json={'chat_id': os.environ['TG_CHAT'], 'text': msg, 'parse_mode': 'Markdown'},
|
||||
)
|
||||
|
||||
for vid in list_my_videos():
|
||||
if is_spike(vid):
|
||||
title = con.execute("SELECT title FROM videos WHERE video_id=?", [vid]).fetchone()[0]
|
||||
alert(f"*Spike*: [{title}](https://youtu.be/{vid})")
|
||||
```
|
||||
|
||||
### LLM weekly digest (Claude)
|
||||
```python
|
||||
from anthropic import Anthropic
|
||||
top = con.execute("""
|
||||
SELECT v.title, s.views, s.ctr, s.avd_sec
|
||||
FROM snapshots s JOIN videos v USING(video_id)
|
||||
WHERE s.captured_at::DATE = current_date
|
||||
ORDER BY s.views DESC LIMIT 10
|
||||
""").fetchall()
|
||||
|
||||
resp = Anthropic().messages.create(
|
||||
model='claude-opus-4-7',
|
||||
max_tokens=1000,
|
||||
messages=[{'role': 'user', 'content':
|
||||
f"Weekly channel digest. Identify 3 actions. Data:\n{top}"}],
|
||||
)
|
||||
print(resp.content[0].text)
|
||||
```
|
||||
|
||||
### Cron (systemd timer)
|
||||
```ini
|
||||
# ~/.config/systemd/user/yt-check.timer
|
||||
[Unit]
|
||||
Description=Daily YouTube channel snapshot
|
||||
[Timer]
|
||||
OnCalendar=*-*-* 09:00:00
|
||||
Persistent=true
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Single channel, ≤ 500 videos | API v3 + Analytics v2, daily |
|
||||
| 5k+ videos | Reporting API bulk CSV |
|
||||
| Real-time spike | poll every 15m for new uploads only |
|
||||
| Multi-channel agency | per-channel OAuth tokens, rate-limit pool |
|
||||
| Privacy / no Google | 매 X — Analytics 의 own data 만 own 가 access |
|
||||
|
||||
**기본값**: daily 09:00 cron + Analytics v2 + DuckDB + 3σ Z-score alert + Telegram + weekly LLM digest.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[YouTube-Creator-Tooling]] · [[Personal-Monitoring]]
|
||||
- 변형: [[comment_harvester]] · [[Channel-Analytics-Dashboard]]
|
||||
- 응용: [[Telegram-Notify]] · [[Anomaly-Detection]]
|
||||
- Adjacent: [[YouTube-Analytics-API]] · [[DuckDB]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: weekly digest, anomaly explanation, A/B thumbnail copy 의 generation.
|
||||
**언제 X**: 매 ground-truth metric 의 fabrication — always cite raw numbers.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Polling stats every minute**: quota 의 burn — 매 actual update lag 이 hours.
|
||||
- **No baseline window**: every uptick = "spike" = noise.
|
||||
- **Storing only current snapshot**: 매 trend 의 재구성 불가.
|
||||
- **Hard-coded video list**: 매 new upload 의 miss.
|
||||
- **OAuth token in repo**: revoke 즉시 필요. Use secret manager.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (YouTube Data API v3, Analytics API v2 docs, YouTube Reporting API guide).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — channel monitor + anomaly + LLM digest |
|
||||
|
||||
Reference in New Issue
Block a user