feat(supporters): 유튜브·로고 단계 — collect_youtube.mjs(API 집계·정보형 필터·쇼츠 판별), 워커 youtube 단계(로고·파비콘·homeVideos), 글↔영상 매칭, 카드 로고 대체, 기존 글 보존 재실행. 원진 재배포
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
1 parent
572978c316
commit
eb873bc43a
12 files changed
+353
-15
No files matched your search
@@ -13,8 +13,10 @@ import { cpSync, existsSync, mkdirSync, readFileSync, writeFileSync, readdirSync
|
||||
import { join, resolve, dirname } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { homedir } from 'node:os';
|
||||
import { createRequire } from 'node:module';
|
||||
|
||||
const ROOT = resolve(fileURLToPath(new URL('../../', import.meta.url)));
|
||||
const yaml = createRequire(join(ROOT, 'supporters', 'package.json'))('js-yaml'); // supporters 의존성 재사용 (js-yaml v4 load 는 safe)
|
||||
const SUP = join(ROOT, 'supporters');
|
||||
const TEMPLATE = join(ROOT, 'templates', 'supporters-astro');
|
||||
const args = process.argv.slice(2);
|
||||
@@ -24,7 +26,7 @@ const clinic = opt('clinic'); const url = opt('url');
|
||||
if (!clinic || !url) { console.error('사용법: --clinic <id> --url <https://...>'); process.exit(2); }
|
||||
const WORK = resolve(opt('work', join(homedir(), 'supporters-builds', clinic)));
|
||||
const today = new Date().toISOString().slice(0, 10);
|
||||
const PHASES = ['evidence', 'data', 'inputs', 'briefs', 'generate', 'build', 'deploy', 'done'];
|
||||
const PHASES = ['evidence', 'data', 'youtube', 'inputs', 'briefs', 'generate', 'build', 'deploy', 'done'];
|
||||
const startFrom = opt('from', 'evidence');
|
||||
|
||||
(function loadEnv() { const p = join(ROOT, '.env'); if (!existsSync(p)) return; for (const line of readFileSync(p, 'utf8').split('\n')) { const m = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*)\s*$/); if (m && !process.env[m[1]]) process.env[m[1]] = m[2].replace(/^["']|["']$/g, ''); } })();
|
||||
@@ -86,8 +88,14 @@ await phase('evidence', () => {
|
||||
// 2. 템플릿 복제 + 팩트 시트·의료진 초안
|
||||
await phase('data', () => {
|
||||
if (!existsSync(TEMPLATE)) throw new Error(`템플릿 없음: ${TEMPLATE} (supporters 에서 npm run export:template)`);
|
||||
// 재실행이면 이미 만든 글과 유튜브 집계는 보존한다(생성 비용·API 절약). --regenerate 면 글도 버린다.
|
||||
const KEEP = join(WORK, 'keep'); rmSync(KEEP, { recursive: true, force: true }); mkdirSync(KEEP, { recursive: true });
|
||||
if (existsSync(POSTS) && !flag('regenerate')) cpSync(POSTS, join(KEEP, 'posts'), { recursive: true });
|
||||
if (existsSync(join(DATA, 'videos.json'))) cpSync(join(DATA, 'videos.json'), join(KEEP, 'videos.json'));
|
||||
rmSync(SITE, { recursive: true, force: true });
|
||||
cpSync(TEMPLATE, SITE, { recursive: true, filter: (s) => !/\/(node_modules|dist|\.astro)(\/|$)/.test(s) });
|
||||
if (existsSync(join(KEEP, 'posts'))) cpSync(join(KEEP, 'posts'), POSTS, { recursive: true });
|
||||
if (existsSync(join(KEEP, 'videos.json'))) cpSync(join(KEEP, 'videos.json'), join(DATA, 'videos.json'));
|
||||
for (const rel of ['astro.config.mjs', 'vercel.json']) { const p = join(SITE, rel); writeFileSync(p, readFileSync(p, 'utf8').split('__CLINIC_ID__').join(clinic)); }
|
||||
cpSync(join(EV, 'home_text.txt'), join(SITE, 'scripts', 'home_text.txt'));
|
||||
|
||||
@@ -113,6 +121,60 @@ await phase('data', () => {
|
||||
return `${fact.shortName || '(상호 확인 대기)'} · 전화 ${fact.phone || '확인 대기'} · 의료진 ${doctors.length}명`;
|
||||
});
|
||||
|
||||
// 2b. 로고·파비콘 (--logo <svg|png 파일>) + 유튜브 채널 집계 (--youtube <채널> 또는 근거의 유튜브 링크 자동 발견)
|
||||
await phase('youtube', () => {
|
||||
const notes = [];
|
||||
// 로고: 헤더·푸터·카드 대체 이미지·파비콘. SVG 는 viewBox 를 정사각 파비콘으로 감싼다.
|
||||
const logoPath = opt('logo') ? resolve(opt('logo')) : null;
|
||||
if (logoPath && existsSync(logoPath)) {
|
||||
const ext = logoPath.toLowerCase().endsWith('.svg') ? 'svg' : logoPath.toLowerCase().endsWith('.png') ? 'png' : 'jpg';
|
||||
mkdirSync(join(SITE, 'public/img'), { recursive: true });
|
||||
cpSync(logoPath, join(SITE, 'public/img', `logo.${ext}`));
|
||||
const site = readJson(join(DATA, 'site.json'));
|
||||
let width = 150, height = 40;
|
||||
if (ext === 'svg') {
|
||||
const svg = readFileSync(logoPath, 'utf8');
|
||||
const vb = svg.match(/viewBox="([\d.\s-]+)"/)?.[1]?.split(/\s+/).map(Number);
|
||||
if (vb && vb[2] && vb[3]) { height = 40; width = Math.round((vb[2] / vb[3]) * 40); }
|
||||
// 파비콘: 흰 정사각 배경 + 로고 중앙 (가로 로고면 폭 기준 88%)
|
||||
const inner = svg.replace(/^[\s\S]*?<svg[^>]*>/, '').replace(/<\/svg>\s*$/, '');
|
||||
const [vx, vy, vw, vh] = vb ?? [0, 0, 100, 100];
|
||||
const scale = Math.min(56 / vw, 56 / vh); const w = vw * scale, h = vh * scale;
|
||||
const fav = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="12" fill="#ffffff"/><svg x="${(64 - w) / 2}" y="${(64 - h) / 2}" width="${w}" height="${h}" viewBox="${vx} ${vy} ${vw} ${vh}">${inner}</svg></svg>`;
|
||||
writeFileSync(join(SITE, 'public/favicon.svg'), fav);
|
||||
} else {
|
||||
cpSync(logoPath, join(SITE, 'public', `favicon.${ext}`));
|
||||
}
|
||||
site.logo = { src: `/img/logo.${ext}`, alt: `${readJson(join(DATA, 'factSheet.json')).shortName || ''} 로고`.trim(), width, height };
|
||||
site.logoFoot = site.logo;
|
||||
writeJson(join(DATA, 'site.json'), site);
|
||||
notes.push(`로고 ${ext} · 파비콘`);
|
||||
} else if (opt('logo')) notes.push(`로고 파일 없음: ${opt('logo')}`);
|
||||
|
||||
// 유튜브: 채널 인자 없으면 근거 페이지 링크에서 youtube.com/channel|@handle 을 찾는다
|
||||
let channel = opt('youtube') ?? null;
|
||||
if (!channel) {
|
||||
const idx = readJson(join(EV, 'index.json'));
|
||||
outer: for (const p of idx.pages.slice(0, 30)) {
|
||||
const pg = readJson(join(EV, p.file));
|
||||
for (const l of pg.links ?? []) { const u = String(l.href ?? l.url ?? l ?? ''); const m = u.match(/youtube\.com\/(channel\/UC[\w-]+|@[\w.-]+)/); if (m) { channel = m[0]; break outer; } }
|
||||
}
|
||||
}
|
||||
if (!channel) return (notes.concat('유튜브 채널 없음 (--youtube 로 지정 가능)')).join(' · ');
|
||||
const prev = existsSync(join(DATA, 'videos.json')) ? readJson(join(DATA, 'videos.json')) : null;
|
||||
if (prev?.fetchedAt === today && prev.channel?.id) notes.push('오늘 집계본 재사용');
|
||||
else { const r = run('node', ['scripts/collect_youtube.mjs', '--channel', channel, '--out', join(DATA, 'videos.json')]); if (!r.ok) throw new Error(`유튜브 집계 실패\n${tail(r.out)}`); }
|
||||
const v = readJson(join(DATA, 'videos.json'));
|
||||
// 홈 "Doctors Explain" 3편 + 팩트 시트 surfaces.youtube
|
||||
const site = readJson(join(DATA, 'site.json'));
|
||||
site.homeVideos = (v.topLong ?? []).slice(0, 3).map((x) => ({ id: x.id, title: x.title, published: x.published }));
|
||||
writeJson(join(DATA, 'site.json'), site);
|
||||
const fact = readJson(join(DATA, 'factSheet.json'));
|
||||
fact.surfaces = { ...(fact.surfaces ?? {}), youtube: { label: '유튜브', url: v.channel.url, title: v.channel.title, subscribers: v.channel.subscribers, videos: v.channel.videos, checked: v.fetchedAt } };
|
||||
writeJson(join(DATA, 'factSheet.json'), fact);
|
||||
return notes.concat(`${v.channel.title} · 영상 ${v.channel.videos} · 설명형 롱폼 ${v.topLong.length} · 쇼츠 ${v.topShorts.length}`).join(' · ');
|
||||
});
|
||||
|
||||
// 3. 병원 입력 반영 (있으면)
|
||||
await phase('inputs', () => {
|
||||
if (!opt('inputs') && !flag('from-supabase')) return '입력 없음 (확인 대기로 발행)';
|
||||
@@ -136,6 +198,26 @@ await phase('briefs', () => {
|
||||
await phase('generate', () => {
|
||||
if (flag('skip-generate')) return '건너뜀 (--skip-generate)';
|
||||
const GEN = join(WORK, 'gen');
|
||||
// 이미 생성된 글이 있고 --regenerate 가 없으면 다시 만들지 않고, brief 의 영상만 frontmatter 에 붙인다(비용 0).
|
||||
const existing = existsSync(POSTS) ? readdirSync(POSTS).filter((f) => f.endsWith('.md')) : [];
|
||||
if (existing.length && !flag('regenerate')) {
|
||||
const briefs = readJson(join(WORK, 'briefs.json')).posts ?? [];
|
||||
let attached = 0;
|
||||
for (const b of briefs) {
|
||||
const p = join(POSTS, `${b.id}.md`);
|
||||
if (!existsSync(p)) continue;
|
||||
const src = readFileSync(p, 'utf8');
|
||||
const m = src.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/); if (!m) continue;
|
||||
const data = yaml.load(m[1]) ?? {};
|
||||
const next = b.videos ?? [];
|
||||
if (JSON.stringify(data.videos ?? []) === JSON.stringify(next)) continue; // brief 가 영상의 단일 원본. 같으면 건너뛴다
|
||||
data.videos = next;
|
||||
writeFileSync(p, `---\n${yaml.dump(data, { lineWidth: -1, noRefs: true, quotingType: '"' })}---\n${m[2].trim()}\n`);
|
||||
attached++;
|
||||
}
|
||||
status.posts = (status.posts ?? []).map((x) => ({ ...x, videos: (briefs.find((b) => b.id === x.id)?.videos ?? []).length }));
|
||||
return `기존 글 ${existing.length}편 유지 (--regenerate 없음) · 영상 붙임 ${attached}편`;
|
||||
}
|
||||
const argv = ['scripts/generate_posts.mjs', '--clinic', clinic, '--site', SITE, '--evidence', EV, '--brief', join(WORK, 'briefs.json'), '--out', GEN, '--today', today];
|
||||
argv.push('--max-cost-usd', opt('max-cost-usd', '10')); // v2 §9-5 haewon 결정: 병원당 한 번 실행 $10
|
||||
const r = run('node', argv);
|
||||
|
||||
Reference in new issue
Block a user