feat: clinic registry DB + pipeline audit P0 fixes
## Clinic Registry - data/clinic-registry/clinic_registry_working.csv — 91개 병원 채널 마스터 DB - data/clinic-registry/INFINITH_Outbound_List.csv — BD팀 아웃바운드 리스트 (17컬럼) - data/clinic-registry/update_csv.py — 안전 CSV 업데이트 스크립트 (빈 필드만 채움) - data/clinic-registry/extract_place_ids.py — 네이버 플레이스 ID 추출기 - scripts/import-registry.ts — CSV → Supabase clinic_registry 테이블 임포트 - supabase/migrations/20260406_clinic_registry.sql — clinic_registry 테이블 스키마 ## Pipeline P0 Bug Fixes (전수 감사 후) - fix(collect-channel-data): 강남언니 rating 0-10 스케일 오변환 제거 - 기존: rating ≤ 5이면 ×2 → 4.8/10을 9.6/10으로 잘못 변환 - 수정: Firecrawl 프롬프트가 이미 0-10 지시 → rawValue 직접 신뢰 - fix(generate-report): Perplexity 단일 fetch → fetchWithRetry 교체 - maxRetries:2, backoffMs:[5000,15000], timeoutMs:90s - 기존: 타임아웃/429 시 리포트 생성 전체 실패 - 수정: 자동 재시도로 일시적 API 오류 극복 ## Docs - docs/PIPELINE_IMPROVEMENT_PLAN.md — Sprint 0/1/2 완료 표시 + 전수 감사 결과 추가 - docs/REGISTRY_FUNCTIONAL_SPECS.md, DB_SCHEMA_V3.md 외 기획 문서 다수 추가 ## New Components & Features - supabase/functions/generate-content-plan, adjust-strategy — 콘텐츠 플랜/전략 조정 - src/components/plan/EditEntryModal, StrategyAdjustmentSection — 플랜 편집 UI - supabase/functions/_shared/dataQuality, foundingYearExtractor, urlClassifier — 데이터 품질 유틸 Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
1 parent
ec991057e6
commit
d5f7f24e0a
51 files changed
+5390
-252
No files matched your search
@@ -0,0 +1,192 @@
|
||||
/**
|
||||
* Missing Value Guard & Report Quality Validator — Harness 3
|
||||
*
|
||||
* Detects all known variants of "no data" from LLM outputs and
|
||||
* provides a quality score for generated reports.
|
||||
*
|
||||
* Usage:
|
||||
* - isMissingValue(val) → boolean (use everywhere you check for missing data)
|
||||
* - validateReportQuality(report) → DataQualityReport (use before saving reports)
|
||||
*/
|
||||
|
||||
// ─── Missing Value Detection ───
|
||||
|
||||
/**
|
||||
* All known LLM expressions for "no data available".
|
||||
* Normalized to lowercase for comparison.
|
||||
*/
|
||||
const MISSING_PATTERNS: ReadonlyArray<string> = [
|
||||
// Korean
|
||||
"데이터 없음", "데이터없음", "데이터 미확인", "데이터미확인",
|
||||
"정보없음", "정보 없음", "정보 미제공", "미제공",
|
||||
"확인불가", "확인 불가", "미확인", "미발견",
|
||||
"알 수 없음", "알수없음", "해당 없음", "해당없음",
|
||||
"없음", "미정",
|
||||
// English
|
||||
"n/a", "na", "none", "null", "undefined",
|
||||
"not available", "unknown", "not found", "no data",
|
||||
// Symbols
|
||||
"-", "—", "–", ".", "...", "N/A",
|
||||
];
|
||||
|
||||
/**
|
||||
* Check if a value represents missing/unavailable data.
|
||||
* Handles null, undefined, empty strings, zero, and LLM "no data" variants.
|
||||
*/
|
||||
export function isMissingValue(val: unknown): boolean {
|
||||
if (val == null) return true;
|
||||
|
||||
if (typeof val === "number") return val === 0 || isNaN(val);
|
||||
|
||||
const s = String(val).trim().toLowerCase();
|
||||
if (s === "" || s === "0") return true;
|
||||
|
||||
return MISSING_PATTERNS.some((p) => s === p.toLowerCase());
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean a value: return it if valid, or return the fallback if missing.
|
||||
* Useful for providing defaults without silent data loss.
|
||||
*/
|
||||
export function cleanValue<T>(val: unknown, fallback: T): T | unknown {
|
||||
return isMissingValue(val) ? fallback : val;
|
||||
}
|
||||
|
||||
// ─── Report Quality Validation ───
|
||||
|
||||
export interface DataQualityReport {
|
||||
score: number; // 0-100
|
||||
missingCritical: string[]; // Missing critical fields
|
||||
missingImportant: string[]; // Missing important fields
|
||||
missingOptional: string[]; // Missing optional fields
|
||||
warnings: string[]; // Human-readable warnings
|
||||
}
|
||||
|
||||
/** Fields that MUST be present for a valid report */
|
||||
const CRITICAL_FIELDS = [
|
||||
"clinicInfo.name",
|
||||
"clinicInfo.established",
|
||||
];
|
||||
|
||||
/** Fields that significantly impact report quality */
|
||||
const IMPORTANT_FIELDS = [
|
||||
"clinicInfo.doctors",
|
||||
"channelAnalysis.youtube",
|
||||
"channelAnalysis.instagram",
|
||||
"channelAnalysis.naverBlog",
|
||||
"channelAnalysis.gangnamUnni",
|
||||
];
|
||||
|
||||
/** Nice-to-have fields */
|
||||
const OPTIONAL_FIELDS = [
|
||||
"channelAnalysis.facebook",
|
||||
"channelAnalysis.tiktok",
|
||||
"channelAnalysis.naverPlace",
|
||||
"channelAnalysis.googleMaps",
|
||||
"clinicInfo.location",
|
||||
];
|
||||
|
||||
/**
|
||||
* Validate report data quality and return a score with details.
|
||||
*
|
||||
* Scoring:
|
||||
* - Each critical field missing: -20 points
|
||||
* - Each important field missing: -5 points
|
||||
* - Each optional field missing: -2 points
|
||||
*/
|
||||
export function validateReportQuality(
|
||||
report: Record<string, unknown>,
|
||||
): DataQualityReport {
|
||||
const result: DataQualityReport = {
|
||||
score: 100,
|
||||
missingCritical: [],
|
||||
missingImportant: [],
|
||||
missingOptional: [],
|
||||
warnings: [],
|
||||
};
|
||||
|
||||
// Check critical fields
|
||||
for (const path of CRITICAL_FIELDS) {
|
||||
const val = getNestedValue(report, path);
|
||||
if (isMissingValue(val)) {
|
||||
result.missingCritical.push(path);
|
||||
result.score -= 20;
|
||||
result.warnings.push(`❌ Critical: '${path}' is missing`);
|
||||
}
|
||||
}
|
||||
|
||||
// Check important fields
|
||||
for (const path of IMPORTANT_FIELDS) {
|
||||
const val = getNestedValue(report, path);
|
||||
if (isMissingValue(val)) {
|
||||
result.missingImportant.push(path);
|
||||
result.score -= 5;
|
||||
result.warnings.push(`⚠️ Important: '${path}' is missing`);
|
||||
}
|
||||
}
|
||||
|
||||
// Check optional fields
|
||||
for (const path of OPTIONAL_FIELDS) {
|
||||
const val = getNestedValue(report, path);
|
||||
if (isMissingValue(val)) {
|
||||
result.missingOptional.push(path);
|
||||
result.score -= 2;
|
||||
}
|
||||
}
|
||||
|
||||
result.score = Math.max(0, result.score);
|
||||
return result;
|
||||
}
|
||||
|
||||
// ─── Helpers ───
|
||||
|
||||
/**
|
||||
* Traverse a nested object by dot-separated path.
|
||||
* e.g., getNestedValue({ a: { b: 1 } }, "a.b") → 1
|
||||
*/
|
||||
function getNestedValue(obj: Record<string, unknown>, path: string): unknown {
|
||||
return path.split(".").reduce(
|
||||
(current, key) => {
|
||||
if (current == null || typeof current !== "object") return undefined;
|
||||
return (current as Record<string, unknown>)[key];
|
||||
},
|
||||
obj as unknown,
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Self-Test ───
|
||||
|
||||
const MISSING_VALUE_TEST_CORPUS: ReadonlyArray<readonly [unknown, boolean]> = [
|
||||
[null, true],
|
||||
[undefined, true],
|
||||
["", true],
|
||||
[" ", true],
|
||||
[0, true],
|
||||
["데이터 없음", true],
|
||||
["데이터없음", true],
|
||||
["N/A", true],
|
||||
["n/a", true],
|
||||
["확인 불가", true],
|
||||
["미확인", true],
|
||||
["unknown", true],
|
||||
["-", true],
|
||||
["—", true],
|
||||
["none", true],
|
||||
// Valid values
|
||||
["뷰성형외과", false],
|
||||
[4.5, false],
|
||||
["2004", false],
|
||||
[387, false],
|
||||
["https://example.com", false],
|
||||
];
|
||||
|
||||
export function validateDataQuality(): { pass: boolean; failures: string[] } {
|
||||
const failures: string[] = [];
|
||||
for (const [val, expected] of MISSING_VALUE_TEST_CORPUS) {
|
||||
const result = isMissingValue(val);
|
||||
if (result !== expected) {
|
||||
failures.push(`isMissingValue(${JSON.stringify(val)}): expected ${expected}, got ${result}`);
|
||||
}
|
||||
}
|
||||
return { pass: failures.length === 0, failures };
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* Founding Year Extraction Guard — Harness 2
|
||||
*
|
||||
* Regex-based founding year extraction to complement Gemini Vision.
|
||||
* Acts as a fallback when the LLM misses patterns like "2004년개원 이래".
|
||||
*
|
||||
* Defense layers:
|
||||
* 1. Gemini Vision (primary)
|
||||
* 2. This module on scraped text (secondary)
|
||||
* 3. generate-report post-processing on all channel_data text (tertiary)
|
||||
*/
|
||||
|
||||
// ─── Patterns ───
|
||||
|
||||
/**
|
||||
* Regex patterns for founding year detection.
|
||||
* Each captures a numeric group that is either:
|
||||
* - A 4-digit year (1950–currentYear)
|
||||
* - A 1-2 digit number to subtract from currentYear
|
||||
*/
|
||||
const FOUNDING_PATTERNS: RegExp[] = [
|
||||
// Direct year expressions
|
||||
/(\d{4})년\s*개원/, // "2004년개원", "2004년 개원"
|
||||
/(\d{4})년개원\s*이래/, // "2004년개원 이래" ← 그랜드 패턴
|
||||
/개원\s*(\d{4})년/, // "개원 2004년"
|
||||
/설립\s*(\d{4})년/, // "설립 2004년"
|
||||
/(\d{4})년\s*설립/, // "2004년 설립"
|
||||
/since\s*(\d{4})/i, // "SINCE 2004"
|
||||
/established\s*(?:in\s*)?(\d{4})/i, // "Established in 2004"
|
||||
/(\d{4})년\s*오픈/, // "2004년 오픈"
|
||||
/(\d{4})년\s*개업/, // "2004년 개업"
|
||||
/개원일?\s*:\s*(\d{4})/, // "개원: 2004", "개원일: 2004"
|
||||
// Anniversary / relative year expressions
|
||||
/(\d{1,2})주년/, // "22주년" → currentYear-22
|
||||
/(\d{1,2})년\s*전통/, // "20년 전통" → currentYear-20
|
||||
/(\d{1,2})년\s*동안/, // "22년 동안" → currentYear-22
|
||||
/개원\s*(\d{1,2})주년/, // "개원 15주년" → currentYear-15
|
||||
/(\d{1,2})년\s*역사/, // "20년 역사" → currentYear-20
|
||||
];
|
||||
|
||||
// ─── Extraction Function ───
|
||||
|
||||
/**
|
||||
* Extract founding year from arbitrary text.
|
||||
* Returns a 4-digit year or null if no pattern matches.
|
||||
*
|
||||
* @param text - Any text (HTML markdown, scraped content, vision output)
|
||||
* @param currentYear - For relative calculations (default: current year)
|
||||
*/
|
||||
export function extractFoundingYear(
|
||||
text: string,
|
||||
currentYear: number = new Date().getFullYear(),
|
||||
): number | null {
|
||||
for (const pattern of FOUNDING_PATTERNS) {
|
||||
const match = text.match(pattern);
|
||||
if (!match) continue;
|
||||
|
||||
const num = parseInt(match[1], 10);
|
||||
|
||||
// 4-digit: direct year
|
||||
if (num >= 1950 && num <= currentYear) return num;
|
||||
|
||||
// 1-2 digit: years ago → subtract from currentYear
|
||||
if (num >= 1 && num <= 80) return currentYear - num;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// ─── Test Corpus ───
|
||||
|
||||
export const FOUNDING_YEAR_TEST_CORPUS: ReadonlyArray<readonly [string, number | null]> = [
|
||||
["2004년개원 이래 중국, 베트남 환자들이 찾아오고 있습니다", 2004],
|
||||
["SINCE 2004", 2004],
|
||||
["22주년 기념 이벤트", 2004], // 2026-22
|
||||
["개원 15주년을 맞이하여", 2011], // 2026-15
|
||||
["20년 전통의 성형외과", 2006], // 2026-20
|
||||
["2005년 설립된 뷰성형외과", 2005],
|
||||
["설립 2010년, 강남에 위치한", 2010],
|
||||
["Established in 2003", 2003],
|
||||
["2018년 오픈한 신규 클리닉", 2018],
|
||||
["개원: 2015", 2015],
|
||||
["아무 관련 없는 텍스트입니다", null],
|
||||
["전화번호 02-1234-5678", null],
|
||||
];
|
||||
|
||||
/**
|
||||
* Self-test: validate all known patterns.
|
||||
* Uses fixed currentYear=2026 for deterministic results.
|
||||
*/
|
||||
export function validateFoundingYearExtractor(): { pass: boolean; failures: string[] } {
|
||||
const failures: string[] = [];
|
||||
for (const [text, expected] of FOUNDING_YEAR_TEST_CORPUS) {
|
||||
const result = extractFoundingYear(text, 2026);
|
||||
if (result !== expected) {
|
||||
failures.push(`"${text.slice(0, 30)}...": expected ${expected}, got ${result}`);
|
||||
}
|
||||
}
|
||||
return { pass: failures.length === 0, failures };
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
/**
|
||||
* URL Classification Guard — Harness 1
|
||||
*
|
||||
* Separates URL classification into a testable pure function with
|
||||
* an embedded test corpus. Prevents misclassification bugs like
|
||||
* `/about/meet-our-doctors.php` being tagged as an "about" page.
|
||||
*
|
||||
* Priority: doctor > surgery > about (specific → general)
|
||||
*/
|
||||
|
||||
// ─── Pattern Definitions ───
|
||||
|
||||
const PAGE_PATTERNS = {
|
||||
doctor: {
|
||||
positive: [
|
||||
"/doctor", "/doctors", "/team", "/staff", "/specialist", "/professor",
|
||||
"/의료진", "/원장", "meet-our-doctor", "/physicians", "/surgeon",
|
||||
"our-team", "our-doctors",
|
||||
],
|
||||
},
|
||||
surgery: {
|
||||
positive: [
|
||||
"/surgery", "/service", "/procedure", "/treatment", "/시술", "/수술",
|
||||
"/procedures", "/treatments", "/services", "/진료",
|
||||
],
|
||||
},
|
||||
about: {
|
||||
positive: [
|
||||
"/about", "/intro", "/소개", "/greeting", "/인사말", "/history", "/연혁",
|
||||
"/company", "/clinic-info",
|
||||
],
|
||||
negative: [
|
||||
"/doctor", "/doctors", "/procedure", "/surgery", "/service",
|
||||
"/treatment", "meet-our", "/team", "/staff", "/specialist",
|
||||
"/의료진", "/원장", "/시술", "/수술", "/진료",
|
||||
"our-team", "our-doctors",
|
||||
],
|
||||
},
|
||||
} as const;
|
||||
|
||||
// ─── Classification Function ───
|
||||
|
||||
/**
|
||||
* Classify a URL into one of: 'doctor' | 'surgery' | 'about' | null.
|
||||
* Uses priority ordering (doctor > surgery > about) so that
|
||||
* compound URLs like `/about/meet-our-doctors.php` correctly resolve
|
||||
* to the more specific category.
|
||||
*/
|
||||
export function classifyPageUrl(url: string): "doctor" | "surgery" | "about" | null {
|
||||
const lower = url.toLowerCase();
|
||||
|
||||
// Priority 1: Doctor pages
|
||||
if (PAGE_PATTERNS.doctor.positive.some((p) => lower.includes(p))) {
|
||||
return "doctor";
|
||||
}
|
||||
|
||||
// Priority 2: Surgery/service pages
|
||||
if (PAGE_PATTERNS.surgery.positive.some((p) => lower.includes(p))) {
|
||||
return "surgery";
|
||||
}
|
||||
|
||||
// Priority 3: About pages (with negative exclusion)
|
||||
if (PAGE_PATTERNS.about.positive.some((p) => lower.includes(p))) {
|
||||
if (PAGE_PATTERNS.about.negative.some((p) => lower.includes(p))) {
|
||||
return null; // Contains about + doctor/surgery keyword → ambiguous, skip
|
||||
}
|
||||
return "about";
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// ─── Test Corpus ───
|
||||
|
||||
/**
|
||||
* Known failure cases and expected classifications.
|
||||
* Used by validateClassifier() for regression prevention.
|
||||
*/
|
||||
export const CLASSIFICATION_TEST_CORPUS: ReadonlyArray<readonly [string, "doctor" | "surgery" | "about" | null]> = [
|
||||
// Bug cases (historically misclassified)
|
||||
["/about/meet-our-doctors.php", "doctor"], // 그랜드성형외과 bug
|
||||
["/about/procedures.php", "surgery"], // 그랜드성형외과
|
||||
// Standard doctor pages
|
||||
["/doctors", "doctor"],
|
||||
["/의료진", "doctor"],
|
||||
["/team/professor-kim", "doctor"],
|
||||
["/about/our-team", "doctor"],
|
||||
// Standard surgery pages
|
||||
["/surgery/rhinoplasty", "surgery"],
|
||||
["/시술안내", "surgery"],
|
||||
["/services/breast", "surgery"],
|
||||
// Standard about pages
|
||||
["/about/", "about"],
|
||||
["/about/greeting.php", "about"],
|
||||
["/about/intro", "about"],
|
||||
["/about/history", "about"],
|
||||
["/소개", "about"],
|
||||
["/인사말", "about"],
|
||||
// Null cases
|
||||
["/gallery", null],
|
||||
["/contact", null],
|
||||
["/blog/post-123", null],
|
||||
];
|
||||
|
||||
// ─── Self-Test ───
|
||||
|
||||
/**
|
||||
* Run classification against the test corpus.
|
||||
* Call during Edge Function cold-start for automatic regression detection.
|
||||
*/
|
||||
export function validateClassifier(): { pass: boolean; failures: string[] } {
|
||||
const failures: string[] = [];
|
||||
for (const [url, expected] of CLASSIFICATION_TEST_CORPUS) {
|
||||
const result = classifyPageUrl(url);
|
||||
if (result !== expected) {
|
||||
failures.push(`${url}: expected '${expected}', got '${result}'`);
|
||||
}
|
||||
}
|
||||
return { pass: failures.length === 0, failures };
|
||||
}
|
||||
@@ -7,6 +7,13 @@
|
||||
*/
|
||||
|
||||
import { fetchWithRetry } from "./retry.ts";
|
||||
import { classifyPageUrl, validateClassifier } from "./urlClassifier.ts";
|
||||
|
||||
// Run URL classifier self-test on cold-start
|
||||
const classifierValidation = validateClassifier();
|
||||
if (!classifierValidation.pass) {
|
||||
console.warn(`[harness] URL classifier self-test FAILED:`, classifierValidation.failures);
|
||||
}
|
||||
|
||||
const FIRECRAWL_BASE = "https://api.firecrawl.dev/v1";
|
||||
|
||||
@@ -124,54 +131,28 @@ async function captureScreenshot(
|
||||
|
||||
/**
|
||||
* Find relevant sub-pages from siteMap for additional screenshots.
|
||||
* Delegates classification to urlClassifier.ts for testability.
|
||||
*/
|
||||
export function findRelevantPages(
|
||||
siteMap: string[],
|
||||
baseUrl: string,
|
||||
_baseUrl: string,
|
||||
): { doctorPage?: string; surgeryPage?: string; aboutPage?: string } {
|
||||
const result: { doctorPage?: string; surgeryPage?: string; aboutPage?: string } = {};
|
||||
|
||||
// Phase 1: Classify each URL into one category (doctor > surgery > about priority)
|
||||
const doctorUrls: string[] = [];
|
||||
const surgeryUrls: string[] = [];
|
||||
const aboutUrls: string[] = [];
|
||||
|
||||
for (const url of siteMap) {
|
||||
const lower = url.toLowerCase();
|
||||
|
||||
const isDoctor = (
|
||||
lower.includes('/doctor') || lower.includes('/doctors') ||
|
||||
lower.includes('/team') || lower.includes('/staff') ||
|
||||
lower.includes('/specialist') || lower.includes('/professor') ||
|
||||
lower.includes('/의료진') || lower.includes('/원장') ||
|
||||
lower.includes('meet-our-doctor') // 하이픈 패턴 (그랜드성형외과 등)
|
||||
);
|
||||
const isSurgery = (
|
||||
lower.includes('/surgery') || lower.includes('/service') || lower.includes('/procedure') ||
|
||||
lower.includes('/treatment') || lower.includes('/시술') || lower.includes('/수술')
|
||||
);
|
||||
const isAbout = (
|
||||
lower.includes('/about') || lower.includes('/intro') || lower.includes('/소개') ||
|
||||
lower.includes('/greeting') || lower.includes('/인사말') || lower.includes('/history') ||
|
||||
lower.includes('/연혁')
|
||||
);
|
||||
|
||||
// Priority: specific page type > generic /about
|
||||
if (isDoctor) {
|
||||
doctorUrls.push(url);
|
||||
} else if (isSurgery) {
|
||||
surgeryUrls.push(url);
|
||||
} else if (isAbout) {
|
||||
aboutUrls.push(url);
|
||||
}
|
||||
const category = classifyPageUrl(url);
|
||||
if (category === "doctor") doctorUrls.push(url);
|
||||
else if (category === "surgery") surgeryUrls.push(url);
|
||||
else if (category === "about") aboutUrls.push(url);
|
||||
}
|
||||
|
||||
// Phase 2: Pick best URL per category
|
||||
result.doctorPage = doctorUrls[0];
|
||||
result.surgeryPage = surgeryUrls[0];
|
||||
result.aboutPage = aboutUrls[0];
|
||||
|
||||
return result;
|
||||
return {
|
||||
doctorPage: doctorUrls[0],
|
||||
surgeryPage: surgeryUrls[0],
|
||||
aboutPage: aboutUrls[0],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user