feat: Pipeline V2 — 3-phase analysis with verified channel discovery
Restructured the entire analysis pipeline from AI-guessing social handles to deterministic 3-phase discovery + collection + generation. Phase 1 (discover-channels): 3-source channel discovery - Firecrawl scrape: extract social links from HTML - Perplexity search: find handles via web search - URL regex parsing: deterministic link extraction - Handle verification: HEAD requests + YouTube API - DB: creates row with verified_channels + scrape_data Phase 2 (collect-channel-data): 9 parallel data collectors - Instagram (Apify), YouTube (Data API v3), Facebook (Apify) - 강남언니 (Firecrawl), Naver Blog + Place (Naver API) - Google Maps (Apify), Market analysis (Perplexity 4x parallel) - DB: stores ALL raw data in channel_data column Phase 3 (generate-report): AI report from real data - Reads channel_data + analysis_data from DB - Builds channel summary with real metrics - AI generates report using only verified data - V1 backwards compatibility preserved (url-based flow) Supporting changes: - DB migration: status, verified_channels, channel_data columns - _shared/extractSocialLinks.ts: regex-based social link parser - _shared/verifyHandles.ts: multi-platform handle verifier - AnalysisLoadingPage: real 3-phase progress + channel panel - useReport: channel_data column support + V2 enrichment merge - 강남언니 rating: auto-correct 5→10 scale + search fallback - KPIDashboard: navigate() instead of <a href> - Loading text: 20-30초 → 1-2분 Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
da267fd744
commit
7557ef774c
14 files changed
+1506
-253
No files matched your search
@@ -0,0 +1,134 @@
|
||||
/**
|
||||
* Extract social media handles from a list of URLs.
|
||||
* Parses known platform patterns deterministically — no AI guessing.
|
||||
*/
|
||||
|
||||
export interface ExtractedSocialLinks {
|
||||
instagram: string[];
|
||||
youtube: string[];
|
||||
facebook: string[];
|
||||
naverBlog: string[];
|
||||
tiktok: string[];
|
||||
kakao: string[];
|
||||
}
|
||||
|
||||
const PATTERNS: { platform: keyof ExtractedSocialLinks; regex: RegExp; extract: (m: RegExpMatchArray) => string }[] = [
|
||||
// Instagram: instagram.com/{handle} or instagram.com/p/{postId} (skip posts)
|
||||
{
|
||||
platform: 'instagram',
|
||||
regex: /(?:www\.)?instagram\.com\/([a-zA-Z0-9._]+)\/?(?:\?|$)/,
|
||||
extract: (m) => m[1],
|
||||
},
|
||||
// YouTube: youtube.com/@{handle} or youtube.com/channel/{id} or youtube.com/c/{custom}
|
||||
{
|
||||
platform: 'youtube',
|
||||
regex: /(?:www\.)?youtube\.com\/(?:@([a-zA-Z0-9._-]+)|channel\/(UC[a-zA-Z0-9_-]+)|c\/([a-zA-Z0-9._-]+))/,
|
||||
extract: (m) => m[1] ? `@${m[1]}` : m[2] || m[3] || '',
|
||||
},
|
||||
// Facebook: facebook.com/{page} (skip common paths)
|
||||
{
|
||||
platform: 'facebook',
|
||||
regex: /(?:www\.)?facebook\.com\/([a-zA-Z0-9._-]+)\/?(?:\?|$)/,
|
||||
extract: (m) => m[1],
|
||||
},
|
||||
// Naver Blog: blog.naver.com/{blogId}
|
||||
{
|
||||
platform: 'naverBlog',
|
||||
regex: /blog\.naver\.com\/([a-zA-Z0-9_-]+)/,
|
||||
extract: (m) => m[1],
|
||||
},
|
||||
// TikTok: tiktok.com/@{handle}
|
||||
{
|
||||
platform: 'tiktok',
|
||||
regex: /(?:www\.)?tiktok\.com\/@([a-zA-Z0-9._-]+)/,
|
||||
extract: (m) => m[1],
|
||||
},
|
||||
// KakaoTalk Channel: pf.kakao.com/{id}
|
||||
{
|
||||
platform: 'kakao',
|
||||
regex: /pf\.kakao\.com\/([a-zA-Z0-9_-]+)/,
|
||||
extract: (m) => m[1],
|
||||
},
|
||||
];
|
||||
|
||||
// Common Facebook paths that are NOT page names
|
||||
const FB_SKIP = new Set([
|
||||
'sharer', 'share', 'login', 'help', 'pages', 'events', 'groups',
|
||||
'marketplace', 'watch', 'gaming', 'privacy', 'policies', 'tr',
|
||||
'dialog', 'plugins', 'photo', 'video', 'reel',
|
||||
]);
|
||||
|
||||
// Common Instagram paths that are NOT handles
|
||||
const IG_SKIP = new Set([
|
||||
'p', 'reel', 'reels', 'stories', 'explore', 'accounts', 'about',
|
||||
'developer', 'legal', 'privacy', 'terms',
|
||||
]);
|
||||
|
||||
export function extractSocialLinks(urls: string[]): ExtractedSocialLinks {
|
||||
const result: ExtractedSocialLinks = {
|
||||
instagram: [],
|
||||
youtube: [],
|
||||
facebook: [],
|
||||
naverBlog: [],
|
||||
tiktok: [],
|
||||
kakao: [],
|
||||
};
|
||||
|
||||
const seen: Record<string, Set<string>> = {};
|
||||
for (const key of Object.keys(result)) {
|
||||
seen[key] = new Set();
|
||||
}
|
||||
|
||||
for (const url of urls) {
|
||||
if (!url || typeof url !== 'string') continue;
|
||||
|
||||
for (const { platform, regex, extract } of PATTERNS) {
|
||||
const match = url.match(regex);
|
||||
if (!match) continue;
|
||||
|
||||
const handle = extract(match);
|
||||
if (!handle || handle.length < 2) continue;
|
||||
|
||||
// Skip known non-handle paths
|
||||
if (platform === 'facebook' && FB_SKIP.has(handle.toLowerCase())) continue;
|
||||
if (platform === 'instagram' && IG_SKIP.has(handle.toLowerCase())) continue;
|
||||
|
||||
const normalized = handle.toLowerCase();
|
||||
if (!seen[platform].has(normalized)) {
|
||||
seen[platform].add(normalized);
|
||||
result[platform].push(handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge social links from multiple sources, deduplicating.
|
||||
*/
|
||||
export function mergeSocialLinks(...sources: Partial<ExtractedSocialLinks>[]): ExtractedSocialLinks {
|
||||
const merged: ExtractedSocialLinks = {
|
||||
instagram: [],
|
||||
youtube: [],
|
||||
facebook: [],
|
||||
naverBlog: [],
|
||||
tiktok: [],
|
||||
kakao: [],
|
||||
};
|
||||
|
||||
for (const source of sources) {
|
||||
for (const key of Object.keys(merged) as (keyof ExtractedSocialLinks)[]) {
|
||||
const vals = source[key];
|
||||
if (Array.isArray(vals)) {
|
||||
for (const v of vals) {
|
||||
if (v && !merged[key].some(existing => existing.toLowerCase() === v.toLowerCase())) {
|
||||
merged[key].push(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return merged;
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
/**
|
||||
* Verify social media handles exist via lightweight API checks.
|
||||
* Each check runs independently — one failure doesn't block others.
|
||||
*/
|
||||
|
||||
export interface VerifiedChannel {
|
||||
handle: string;
|
||||
verified: boolean;
|
||||
url?: string;
|
||||
channelId?: string; // YouTube channel ID if resolved
|
||||
}
|
||||
|
||||
export interface VerifiedChannels {
|
||||
instagram: VerifiedChannel[];
|
||||
youtube: VerifiedChannel | null;
|
||||
facebook: VerifiedChannel | null;
|
||||
naverBlog: VerifiedChannel | null;
|
||||
gangnamUnni: VerifiedChannel | null;
|
||||
tiktok: VerifiedChannel | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify an Instagram handle exists.
|
||||
* Uses a lightweight fetch to the profile page.
|
||||
*/
|
||||
async function verifyInstagram(handle: string): Promise<VerifiedChannel> {
|
||||
try {
|
||||
const url = `https://www.instagram.com/${handle}/`;
|
||||
const res = await fetch(url, {
|
||||
method: 'GET',
|
||||
headers: { 'User-Agent': 'Mozilla/5.0' },
|
||||
redirect: 'follow',
|
||||
});
|
||||
// Instagram returns 200 for existing profiles, 404 for missing
|
||||
return {
|
||||
handle,
|
||||
verified: res.status === 200,
|
||||
url,
|
||||
};
|
||||
} catch {
|
||||
return { handle, verified: false };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify a YouTube handle/channel exists using YouTube Data API v3.
|
||||
*/
|
||||
async function verifyYouTube(handle: string, apiKey: string): Promise<VerifiedChannel> {
|
||||
try {
|
||||
const YT_BASE = 'https://www.googleapis.com/youtube/v3';
|
||||
const cleanHandle = handle.replace(/^@/, '');
|
||||
|
||||
// Try forHandle first, then forUsername
|
||||
for (const param of ['forHandle', 'forUsername']) {
|
||||
const res = await fetch(`${YT_BASE}/channels?part=id,snippet&${param}=${cleanHandle}&key=${apiKey}`);
|
||||
const data = await res.json();
|
||||
const channel = data.items?.[0];
|
||||
if (channel) {
|
||||
return {
|
||||
handle,
|
||||
verified: true,
|
||||
channelId: channel.id,
|
||||
url: `https://youtube.com/@${cleanHandle}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Try as channel ID directly (starts with UC)
|
||||
if (handle.startsWith('UC')) {
|
||||
const res = await fetch(`${YT_BASE}/channels?part=id&id=${handle}&key=${apiKey}`);
|
||||
const data = await res.json();
|
||||
if (data.items?.[0]) {
|
||||
return { handle, verified: true, channelId: handle, url: `https://youtube.com/channel/${handle}` };
|
||||
}
|
||||
}
|
||||
|
||||
return { handle, verified: false };
|
||||
} catch {
|
||||
return { handle, verified: false };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify a Facebook page exists via HEAD request.
|
||||
*/
|
||||
async function verifyFacebook(handle: string): Promise<VerifiedChannel> {
|
||||
try {
|
||||
const url = `https://www.facebook.com/${handle}/`;
|
||||
const res = await fetch(url, {
|
||||
method: 'HEAD',
|
||||
headers: { 'User-Agent': 'Mozilla/5.0' },
|
||||
redirect: 'follow',
|
||||
});
|
||||
return { handle, verified: res.status === 200, url };
|
||||
} catch {
|
||||
return { handle, verified: false };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify Naver Blog exists.
|
||||
*/
|
||||
async function verifyNaverBlog(blogId: string): Promise<VerifiedChannel> {
|
||||
try {
|
||||
const url = `https://blog.naver.com/${blogId}`;
|
||||
const res = await fetch(url, {
|
||||
method: 'HEAD',
|
||||
redirect: 'follow',
|
||||
});
|
||||
return { handle: blogId, verified: res.status === 200, url };
|
||||
} catch {
|
||||
return { handle: blogId, verified: false };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Find and verify gangnamunni hospital page using Firecrawl search.
|
||||
*/
|
||||
async function verifyGangnamUnni(
|
||||
clinicName: string,
|
||||
firecrawlKey: string,
|
||||
hintUrl?: string,
|
||||
): Promise<VerifiedChannel> {
|
||||
try {
|
||||
// If we already have a URL hint from Perplexity, just verify it
|
||||
if (hintUrl && hintUrl.includes('gangnamunni.com/hospitals/')) {
|
||||
const res = await fetch(hintUrl, { method: 'HEAD', redirect: 'follow' });
|
||||
if (res.status === 200) {
|
||||
return { handle: clinicName, verified: true, url: hintUrl };
|
||||
}
|
||||
}
|
||||
|
||||
// Otherwise, search with multiple fallback queries
|
||||
const shortName = clinicName.replace(/성형외과|의원|병원|클리닉|피부과/g, '').trim();
|
||||
const queries = [
|
||||
`${clinicName} site:gangnamunni.com`,
|
||||
`${shortName} 성형외과 site:gangnamunni.com`,
|
||||
`${clinicName} 강남언니`,
|
||||
];
|
||||
|
||||
for (const query of queries) {
|
||||
const searchRes = await fetch('https://api.firecrawl.dev/v1/search', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${firecrawlKey}`,
|
||||
},
|
||||
body: JSON.stringify({ query, limit: 5 }),
|
||||
});
|
||||
const data = await searchRes.json();
|
||||
const url = (data.data || [])
|
||||
.map((r: Record<string, string>) => r.url)
|
||||
.find((u: string) => u?.includes('gangnamunni.com/hospitals/'));
|
||||
|
||||
if (url) {
|
||||
return { handle: clinicName, verified: true, url };
|
||||
}
|
||||
}
|
||||
|
||||
return { handle: clinicName, verified: false };
|
||||
} catch {
|
||||
return { handle: clinicName, verified: false };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify all discovered handles in parallel.
|
||||
*/
|
||||
export async function verifyAllHandles(
|
||||
candidates: {
|
||||
instagram: string[];
|
||||
youtube: string[];
|
||||
facebook: string[];
|
||||
naverBlog: string[];
|
||||
tiktok: string[];
|
||||
},
|
||||
clinicName: string,
|
||||
gangnamUnniHintUrl?: string,
|
||||
): Promise<VerifiedChannels> {
|
||||
const YOUTUBE_API_KEY = Deno.env.get('YOUTUBE_API_KEY') || '';
|
||||
const FIRECRAWL_API_KEY = Deno.env.get('FIRECRAWL_API_KEY') || '';
|
||||
|
||||
const tasks: Promise<void>[] = [];
|
||||
const result: VerifiedChannels = {
|
||||
instagram: [],
|
||||
youtube: null,
|
||||
facebook: null,
|
||||
naverBlog: null,
|
||||
gangnamUnni: null,
|
||||
tiktok: null,
|
||||
};
|
||||
|
||||
// Instagram — verify each candidate
|
||||
for (const handle of candidates.instagram.slice(0, 5)) {
|
||||
tasks.push(
|
||||
verifyInstagram(handle).then(v => { if (v.verified) result.instagram.push(v); })
|
||||
);
|
||||
}
|
||||
|
||||
// YouTube — first candidate
|
||||
if (candidates.youtube.length > 0) {
|
||||
tasks.push(
|
||||
verifyYouTube(candidates.youtube[0], YOUTUBE_API_KEY).then(v => { result.youtube = v; })
|
||||
);
|
||||
}
|
||||
|
||||
// Facebook — first candidate
|
||||
if (candidates.facebook.length > 0) {
|
||||
tasks.push(
|
||||
verifyFacebook(candidates.facebook[0]).then(v => { result.facebook = v; })
|
||||
);
|
||||
}
|
||||
|
||||
// Naver Blog — first candidate
|
||||
if (candidates.naverBlog.length > 0) {
|
||||
tasks.push(
|
||||
verifyNaverBlog(candidates.naverBlog[0]).then(v => { result.naverBlog = v; })
|
||||
);
|
||||
}
|
||||
|
||||
// 강남언니 — always try if clinicName exists
|
||||
if (clinicName && FIRECRAWL_API_KEY) {
|
||||
tasks.push(
|
||||
verifyGangnamUnni(clinicName, FIRECRAWL_API_KEY, gangnamUnniHintUrl)
|
||||
.then(v => { result.gangnamUnni = v; })
|
||||
);
|
||||
}
|
||||
|
||||
// TikTok — skip verification for now (TikTok blocks HEAD requests)
|
||||
if (candidates.tiktok.length > 0) {
|
||||
result.tiktok = { handle: candidates.tiktok[0], verified: false, url: `https://tiktok.com/@${candidates.tiktok[0]}` };
|
||||
}
|
||||
|
||||
await Promise.allSettled(tasks);
|
||||
return result;
|
||||
}
|
||||
Reference in new issue
Block a user