fix: add Authorization header to all Edge Function calls + fix Vision Analysis
- All fetch calls to Supabase Edge Functions now include Authorization: Bearer <anon_key> (was missing → 401 errors) - Fix Firecrawl screenshot API: remove invalid screenshotOptions, use "screenshot@fullPage" format (v2 API compatibility) - Fix screenshot response handling: v2 returns URL not base64, now downloads and converts to base64 for Gemini Vision - Add about page to Vision Analysis capture targets - Add retry utility, channel error tracking, pipeline resume, enrichment retry, EmptyState improvements (Sprint 2-3) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
1 parent
2f2aa5a5b6
commit
79950925a1
12 files changed
+961
-214
No files matched your search
@@ -0,0 +1,224 @@
|
||||
/**
|
||||
* Retry utility for external API calls.
|
||||
*
|
||||
* Features:
|
||||
* - Exponential backoff with jitter
|
||||
* - Respects Retry-After header (429)
|
||||
* - Permanent failure detection (400/401/403/404 → no retry)
|
||||
* - Per-request timeout via AbortController
|
||||
* - Domain-level rate limiting (e.g., Firecrawl 500ms gap)
|
||||
*/
|
||||
|
||||
// ─── Types ───
|
||||
|
||||
export interface RetryOptions {
|
||||
/** Max number of retries (default: 2) */
|
||||
maxRetries?: number;
|
||||
/** Backoff delays in ms per attempt (default: [1000, 3000]) */
|
||||
backoffMs?: number[];
|
||||
/** HTTP status codes to retry on (default: [429, 500, 502, 503]) */
|
||||
retryOn?: number[];
|
||||
/** Per-request timeout in ms (default: 45000) */
|
||||
timeoutMs?: number;
|
||||
/** Label for logging */
|
||||
label?: string;
|
||||
}
|
||||
|
||||
interface RetryResult {
|
||||
response: Response;
|
||||
attempts: number;
|
||||
retried: boolean;
|
||||
}
|
||||
|
||||
// ─── Domain Rate Limiter ───
|
||||
|
||||
const domainLastCall = new Map<string, number>();
|
||||
const DOMAIN_INTERVALS: Record<string, number> = {
|
||||
"api.firecrawl.dev": 500,
|
||||
"api.perplexity.ai": 200,
|
||||
};
|
||||
|
||||
function getDomain(url: string): string {
|
||||
try {
|
||||
return new URL(url).hostname;
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
async function waitForDomainSlot(url: string): Promise<void> {
|
||||
const domain = getDomain(url);
|
||||
const interval = DOMAIN_INTERVALS[domain];
|
||||
if (!interval) return;
|
||||
|
||||
const last = domainLastCall.get(domain) || 0;
|
||||
const elapsed = Date.now() - last;
|
||||
if (elapsed < interval) {
|
||||
await new Promise((r) => setTimeout(r, interval - elapsed));
|
||||
}
|
||||
domainLastCall.set(domain, Date.now());
|
||||
}
|
||||
|
||||
// ─── Permanent failure codes (never retry) ───
|
||||
|
||||
const PERMANENT_FAILURES = new Set([400, 401, 403, 404, 405, 409, 422]);
|
||||
|
||||
// ─── Main Function ───
|
||||
|
||||
/**
|
||||
* fetch() with automatic retry, timeout, and rate limiting.
|
||||
*
|
||||
* @example
|
||||
* const res = await fetchWithRetry("https://api.example.com/data", {
|
||||
* method: "POST",
|
||||
* headers: { "Content-Type": "application/json" },
|
||||
* body: JSON.stringify({ query: "test" }),
|
||||
* }, { maxRetries: 2, timeoutMs: 30000, label: "example-api" });
|
||||
*/
|
||||
export async function fetchWithRetry(
|
||||
url: string,
|
||||
init?: RequestInit,
|
||||
opts?: RetryOptions,
|
||||
): Promise<Response> {
|
||||
const {
|
||||
maxRetries = 2,
|
||||
backoffMs = [1000, 3000],
|
||||
retryOn = [429, 500, 502, 503],
|
||||
timeoutMs = 45000,
|
||||
label = getDomain(url),
|
||||
} = opts || {};
|
||||
|
||||
let lastError: Error | null = null;
|
||||
const retrySet = new Set(retryOn);
|
||||
|
||||
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
||||
// Rate limit between domain calls
|
||||
await waitForDomainSlot(url);
|
||||
|
||||
// AbortController for per-request timeout
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
...init,
|
||||
signal: controller.signal,
|
||||
});
|
||||
clearTimeout(timer);
|
||||
|
||||
// Success
|
||||
if (response.ok) return response;
|
||||
|
||||
// Permanent failure — don't retry
|
||||
if (PERMANENT_FAILURES.has(response.status)) {
|
||||
console.warn(
|
||||
`[retry:${label}] Permanent failure ${response.status} on attempt ${attempt + 1}`,
|
||||
);
|
||||
return response;
|
||||
}
|
||||
|
||||
// Retryable failure
|
||||
if (retrySet.has(response.status) && attempt < maxRetries) {
|
||||
let delay = backoffMs[attempt] || backoffMs[backoffMs.length - 1] || 3000;
|
||||
|
||||
// Respect Retry-After header for 429
|
||||
if (response.status === 429) {
|
||||
const retryAfter = response.headers.get("Retry-After");
|
||||
if (retryAfter) {
|
||||
const parsed = parseInt(retryAfter, 10);
|
||||
if (!isNaN(parsed)) {
|
||||
delay = Math.max(delay, parsed * 1000);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Add jitter (±20%)
|
||||
delay = delay * (0.8 + Math.random() * 0.4);
|
||||
|
||||
console.warn(
|
||||
`[retry:${label}] Status ${response.status}, retrying in ${Math.round(delay)}ms (attempt ${attempt + 1}/${maxRetries + 1})`,
|
||||
);
|
||||
await new Promise((r) => setTimeout(r, delay));
|
||||
continue;
|
||||
}
|
||||
|
||||
// Non-retryable or exhausted retries
|
||||
return response;
|
||||
} catch (err) {
|
||||
clearTimeout(timer);
|
||||
lastError = err instanceof Error ? err : new Error(String(err));
|
||||
|
||||
if (attempt < maxRetries) {
|
||||
const delay = (backoffMs[attempt] || 3000) * (0.8 + Math.random() * 0.4);
|
||||
console.warn(
|
||||
`[retry:${label}] Network error: ${lastError.message}, retrying in ${Math.round(delay)}ms (attempt ${attempt + 1}/${maxRetries + 1})`,
|
||||
);
|
||||
await new Promise((r) => setTimeout(r, delay));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
throw lastError || new Error(`[retry:${label}] All ${maxRetries + 1} attempts failed`);
|
||||
}
|
||||
|
||||
// ─── Convenience: JSON fetch with retry ───
|
||||
|
||||
export async function fetchJsonWithRetry<T = unknown>(
|
||||
url: string,
|
||||
init?: RequestInit,
|
||||
opts?: RetryOptions,
|
||||
): Promise<{ data: T | null; status: number; error?: string }> {
|
||||
try {
|
||||
const res = await fetchWithRetry(url, init, opts);
|
||||
if (!res.ok) {
|
||||
const text = await res.text().catch(() => "");
|
||||
return { data: null, status: res.status, error: `HTTP ${res.status}: ${text.slice(0, 200)}` };
|
||||
}
|
||||
const data = (await res.json()) as T;
|
||||
return { data, status: res.status };
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
return { data: null, status: 0, error: msg };
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Channel Task Wrapper ───
|
||||
|
||||
export interface ChannelTaskResult {
|
||||
channel: string;
|
||||
success: boolean;
|
||||
error?: string;
|
||||
httpStatus?: number;
|
||||
durationMs: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps a channel collection task with timing and error capture.
|
||||
* Used by collect-channel-data to track per-channel success/failure.
|
||||
*
|
||||
* @example
|
||||
* const [result, taskMeta] = await wrapChannelTask("instagram", async () => {
|
||||
* // ... collect instagram data ...
|
||||
* channelData.instagram = data;
|
||||
* });
|
||||
*/
|
||||
export async function wrapChannelTask(
|
||||
channel: string,
|
||||
task: () => Promise<void>,
|
||||
): Promise<ChannelTaskResult> {
|
||||
const start = Date.now();
|
||||
try {
|
||||
await task();
|
||||
return { channel, success: true, durationMs: Date.now() - start };
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
console.error(`[channel:${channel}] Error: ${msg}`);
|
||||
return {
|
||||
channel,
|
||||
success: false,
|
||||
error: msg,
|
||||
durationMs: Date.now() - start,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
export interface VerifiedChannel {
|
||||
handle: string;
|
||||
verified: boolean;
|
||||
verified: boolean | "unverifiable";
|
||||
url?: string;
|
||||
channelId?: string; // YouTube channel ID if resolved
|
||||
}
|
||||
@@ -28,17 +28,36 @@ async function verifyInstagram(handle: string): Promise<VerifiedChannel> {
|
||||
const url = `https://www.instagram.com/${handle}/`;
|
||||
const res = await fetch(url, {
|
||||
method: 'GET',
|
||||
headers: { 'User-Agent': 'Mozilla/5.0' },
|
||||
redirect: 'follow',
|
||||
headers: { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)' },
|
||||
redirect: 'manual', // Don't follow redirects — detect login page
|
||||
});
|
||||
// Instagram returns 200 for existing profiles, 404 for missing
|
||||
return {
|
||||
handle,
|
||||
verified: res.status === 200,
|
||||
url,
|
||||
};
|
||||
|
||||
// 302/301 to login page → Instagram blocks unauthenticated access
|
||||
if (res.status === 301 || res.status === 302) {
|
||||
const location = res.headers.get('location') || '';
|
||||
if (location.includes('/accounts/login') || location.includes('/challenge')) {
|
||||
return { handle, verified: 'unverifiable', url };
|
||||
}
|
||||
}
|
||||
|
||||
// 200 → profile exists; 404 → definitely not found
|
||||
if (res.status === 200) {
|
||||
// Double-check: some 200 responses are actually the login page
|
||||
const bodySnippet = await res.text().then(t => t.slice(0, 2000)).catch(() => '');
|
||||
if (bodySnippet.includes('/accounts/login') && !bodySnippet.includes(`"username":"${handle}"`)) {
|
||||
return { handle, verified: 'unverifiable', url };
|
||||
}
|
||||
return { handle, verified: true, url };
|
||||
}
|
||||
|
||||
if (res.status === 404) {
|
||||
return { handle, verified: false, url };
|
||||
}
|
||||
|
||||
// Any other status → unverifiable (don't assume it doesn't exist)
|
||||
return { handle, verified: 'unverifiable', url };
|
||||
} catch {
|
||||
return { handle, verified: false };
|
||||
return { handle, verified: 'unverifiable' };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,14 +105,30 @@ async function verifyYouTube(handle: string, apiKey: string): Promise<VerifiedCh
|
||||
async function verifyFacebook(handle: string): Promise<VerifiedChannel> {
|
||||
try {
|
||||
const url = `https://www.facebook.com/${handle}/`;
|
||||
// Use GET instead of HEAD — Facebook blocks HEAD requests
|
||||
const res = await fetch(url, {
|
||||
method: 'HEAD',
|
||||
headers: { 'User-Agent': 'Mozilla/5.0' },
|
||||
method: 'GET',
|
||||
headers: { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)' },
|
||||
redirect: 'follow',
|
||||
});
|
||||
return { handle, verified: res.status === 200, url };
|
||||
|
||||
if (res.status === 200) {
|
||||
// Check if it's a real page or a redirect to login/error
|
||||
const bodySnippet = await res.text().then(t => t.slice(0, 3000)).catch(() => '');
|
||||
if (bodySnippet.includes('page_not_found') || bodySnippet.includes('This content isn')) {
|
||||
return { handle, verified: false, url };
|
||||
}
|
||||
return { handle, verified: true, url };
|
||||
}
|
||||
|
||||
if (res.status === 404) {
|
||||
return { handle, verified: false, url };
|
||||
}
|
||||
|
||||
// Facebook often blocks bots → unverifiable, not false
|
||||
return { handle, verified: 'unverifiable', url };
|
||||
} catch {
|
||||
return { handle, verified: false };
|
||||
return { handle, verified: 'unverifiable' };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
* certifications, social icons, brand colors, etc.).
|
||||
*/
|
||||
|
||||
import { fetchWithRetry } from "./retry.ts";
|
||||
|
||||
const FIRECRAWL_BASE = "https://api.firecrawl.dev/v1";
|
||||
|
||||
export interface ScreenshotResult {
|
||||
@@ -34,15 +36,20 @@ export interface VisionAnalysisResult {
|
||||
}
|
||||
|
||||
/**
|
||||
* Capture screenshot of a URL via Firecrawl.
|
||||
* Returns base64 image data.
|
||||
* Capture screenshot of a URL via Firecrawl v2.
|
||||
* Returns { screenshotUrl, base64 } — URL from Firecrawl, base64 fetched for Vision analysis.
|
||||
*
|
||||
* Firecrawl v2 returns a GCS URL (not base64). We download it and convert to base64
|
||||
* so Gemini Vision can consume it via inlineData.
|
||||
*/
|
||||
async function captureScreenshot(
|
||||
url: string,
|
||||
firecrawlKey: string,
|
||||
): Promise<string | null> {
|
||||
): Promise<{ screenshotUrl: string; base64: string } | null> {
|
||||
try {
|
||||
const res = await fetch(`${FIRECRAWL_BASE}/scrape`, {
|
||||
console.log(`[vision] Capturing screenshot: ${url}`);
|
||||
// Firecrawl v2: use "screenshot@fullPage" format (no separate screenshotOptions)
|
||||
const res = await fetchWithRetry(`${FIRECRAWL_BASE}/scrape`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
@@ -50,18 +57,47 @@ async function captureScreenshot(
|
||||
},
|
||||
body: JSON.stringify({
|
||||
url,
|
||||
formats: ["screenshot"],
|
||||
formats: ["screenshot@fullPage"],
|
||||
waitFor: 5000,
|
||||
screenshotOptions: {
|
||||
fullPage: false,
|
||||
quality: 80,
|
||||
},
|
||||
}),
|
||||
});
|
||||
if (!res.ok) return null;
|
||||
}, { label: `firecrawl-screenshot`, timeoutMs: 45000, maxRetries: 1 });
|
||||
|
||||
if (!res.ok) {
|
||||
const errText = await res.text().catch(() => "");
|
||||
console.error(`[vision] Screenshot failed for ${url}: HTTP ${res.status} — ${errText.slice(0, 200)}`);
|
||||
return null;
|
||||
}
|
||||
const data = await res.json();
|
||||
return data.data?.screenshot || null; // base64 string
|
||||
} catch {
|
||||
const screenshotUrl: string | null = data.data?.screenshot || null;
|
||||
if (!screenshotUrl) {
|
||||
console.warn(`[vision] Screenshot response OK but no screenshot URL for ${url}. Keys: ${JSON.stringify(Object.keys(data.data || {}))}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
console.log(`[vision] Screenshot URL received: ${url} → ${screenshotUrl.slice(0, 80)}...`);
|
||||
|
||||
// Download the screenshot image and convert to base64 for Gemini Vision
|
||||
const imgRes = await fetchWithRetry(screenshotUrl, undefined, {
|
||||
label: `screenshot-download`,
|
||||
timeoutMs: 30000,
|
||||
maxRetries: 1,
|
||||
});
|
||||
if (!imgRes.ok) {
|
||||
console.error(`[vision] Failed to download screenshot image: HTTP ${imgRes.status}`);
|
||||
return null;
|
||||
}
|
||||
const imgBuffer = await imgRes.arrayBuffer();
|
||||
const bytes = new Uint8Array(imgBuffer);
|
||||
|
||||
// Use Deno's standard base64 encoding (efficient for large binaries)
|
||||
const { encode: encodeBase64 } = await import("https://deno.land/std@0.224.0/encoding/base64.ts");
|
||||
const base64 = encodeBase64(bytes);
|
||||
|
||||
console.log(`[vision] Screenshot captured & converted: ${url} (${Math.round(base64.length / 1024)}KB base64, ${Math.round(bytes.length / 1024)}KB raw)`);
|
||||
|
||||
return { screenshotUrl, base64 };
|
||||
} catch (err) {
|
||||
console.error(`[vision] Screenshot error for ${url}:`, err instanceof Error ? err.message : err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -125,6 +161,9 @@ export async function captureAllScreenshots(
|
||||
if (pages.surgeryPage) {
|
||||
captureTargets.push({ id: 'website-surgery', url: pages.surgeryPage, channel: '웹사이트', caption: '시술 안내 페이지' });
|
||||
}
|
||||
if (pages.aboutPage) {
|
||||
captureTargets.push({ id: 'website-about', url: pages.aboutPage, channel: '웹사이트', caption: '병원 소개 페이지' });
|
||||
}
|
||||
|
||||
// YouTube channel landing
|
||||
const yt = verifiedChannels.youtube as Record<string, unknown> | null;
|
||||
@@ -154,16 +193,16 @@ export async function captureAllScreenshots(
|
||||
|
||||
// Capture all in parallel (max 6 concurrent)
|
||||
const capturePromises = captureTargets.map(async (target) => {
|
||||
const base64 = await captureScreenshot(target.url, firecrawlKey);
|
||||
if (base64) {
|
||||
const result = await captureScreenshot(target.url, firecrawlKey);
|
||||
if (result) {
|
||||
results.push({
|
||||
id: target.id,
|
||||
url: `data:image/png;base64,${base64.slice(0, 100)}...`, // Placeholder — will be replaced with Storage URL
|
||||
url: result.screenshotUrl, // GCS URL from Firecrawl (permanent for ~7 days)
|
||||
channel: target.channel,
|
||||
capturedAt: now,
|
||||
caption: target.caption,
|
||||
sourceUrl: target.url,
|
||||
base64,
|
||||
base64: result.base64,
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -181,19 +220,41 @@ export async function analyzeScreenshot(
|
||||
geminiKey: string,
|
||||
): Promise<VisionAnalysisResult> {
|
||||
const prompts: Record<string, string> = {
|
||||
'website-main': `이 한국 성형외과 병원 메인 페이지 스크린샷을 분석해줘. 다음 정보를 JSON으로 추출해줘:
|
||||
- foundingYear: 개원 연도 (배너에 "SINCE 2004", "21년 무사고" 등이 있으면)
|
||||
'website-main': `이 한국 성형외과/피부과 병원 메인 페이지 스크린샷을 꼼꼼히 분석해줘. 다음 정보를 JSON으로 추출해줘:
|
||||
|
||||
- foundingYear: 개원 연도. 반드시 찾아줘! 다음 패턴 중 하나라도 있으면 계산해:
|
||||
"22주년" → 2026 - 22 = 2004
|
||||
"22년 동안" → 2026 - 22 = 2004
|
||||
"SINCE 2004" → 2004
|
||||
"20년 전통" → 2026 - 20 = 2006
|
||||
"개원 15주년" → 2026 - 15 = 2011
|
||||
배너, 이벤트 팝업, 로고 옆 텍스트, 하단 footer 등 모든 곳을 확인해줘.
|
||||
- operationYears: 운영 기간 (숫자만. "22주년"이면 22)
|
||||
- certifications: 인증 마크 (JCI, 보건복지부, 의료관광 등)
|
||||
- socialIcons: 보이는 소셜 미디어 아이콘 (Instagram, YouTube, Facebook, Blog, KakaoTalk 등)
|
||||
- floatingButtons: 플로팅 상담 버튼 (카카오톡, LINE, WhatsApp 등)
|
||||
- brandColors: 메인 컬러와 액센트 컬러 (hex)
|
||||
- slogans: 배너 텍스트나 슬로건
|
||||
- slogans: 배너 텍스트나 슬로건 (이벤트 텍스트 포함)
|
||||
- serviceCategories: 네비게이션 메뉴에 보이는 시술 카테고리`,
|
||||
|
||||
'website-doctors': `이 성형외과 의료진 페이지 스크린샷을 분석해줘. JSON으로 추출:
|
||||
- doctors: [{name: "이름", specialty: "전문 분야", position: "대표원장/원장 등"}]
|
||||
프로필 사진 옆에 적힌 이름과 전문 분야를 모두 읽어줘.`,
|
||||
|
||||
'website-about': `이 성형외과 병원 소개 페이지를 꼼꼼히 분석해줘. JSON으로 추출:
|
||||
|
||||
- foundingYear: 개원 연도. 반드시 찾아줘! 소개 페이지에 자주 나오는 패턴:
|
||||
"22주년" → 2026 - 22 = 2004
|
||||
"22년 동안" → 2026 - 22 = 2004
|
||||
"SINCE 2004" → 2004
|
||||
"2004년 개원" → 2004
|
||||
"20년 전통" → 2026 - 20 = 2006
|
||||
연혁, 소개글, 대표원장 인사말 등 모든 텍스트를 꼼꼼히 확인해줘.
|
||||
- operationYears: 운영 기간 (숫자만)
|
||||
- doctors: [{name: "이름", specialty: "전문 분야", position: "대표원장/원장 등"}]
|
||||
- certifications: 인증 마크 (JCI, 보건복지부, 의료관광 등)
|
||||
- slogans: 소개 텍스트, 미션/비전 문구`,
|
||||
|
||||
'website-surgery': `이 성형외과 시술 안내 페이지를 분석해줘. JSON으로 추출:
|
||||
- serviceCategories: 보이는 시술 카테고리 목록 (눈성형, 코성형, 가슴성형, 안면윤곽 등)
|
||||
- certifications: 보이는 인증/수상 마크`,
|
||||
@@ -212,7 +273,8 @@ export async function analyzeScreenshot(
|
||||
const prompt = prompts[pageType] || `이 웹페이지 스크린샷을 분석해줘. 보이는 모든 텍스트와 정보를 JSON으로 추출해줘.`;
|
||||
|
||||
try {
|
||||
const res = await fetch(
|
||||
console.log(`[vision] Analyzing screenshot: ${pageType} (${Math.round(base64.length / 1024)}KB)`);
|
||||
const res = await fetchWithRetry(
|
||||
`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=${geminiKey}`,
|
||||
{
|
||||
method: "POST",
|
||||
@@ -230,18 +292,27 @@ export async function analyzeScreenshot(
|
||||
},
|
||||
}),
|
||||
},
|
||||
{ label: `gemini-vision:${pageType}`, timeoutMs: 45000, maxRetries: 1 },
|
||||
);
|
||||
|
||||
if (!res.ok) return {};
|
||||
if (!res.ok) {
|
||||
const errText = await res.text().catch(() => "");
|
||||
console.error(`[vision] Gemini failed for ${pageType}: HTTP ${res.status} — ${errText.slice(0, 200)}`);
|
||||
return {};
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
const text = data.candidates?.[0]?.content?.parts?.[0]?.text || "";
|
||||
const jsonMatch = text.match(/\{[\s\S]*\}/);
|
||||
if (jsonMatch) {
|
||||
return JSON.parse(jsonMatch[0]);
|
||||
const result = JSON.parse(jsonMatch[0]);
|
||||
console.log(`[vision] Gemini result for ${pageType}:`, JSON.stringify(result).slice(0, 300));
|
||||
return result;
|
||||
}
|
||||
console.warn(`[vision] Gemini returned no JSON for ${pageType}. Raw: ${text.slice(0, 200)}`);
|
||||
return {};
|
||||
} catch {
|
||||
} catch (err) {
|
||||
console.error(`[vision] Gemini error for ${pageType}:`, err instanceof Error ? err.message : err);
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user