AI Resource Pro / website / scripts / audit-tags.mjs
| 1 | import { createClient } from '@supabase/supabase-js'; |
| 2 | import dotenv from 'dotenv'; |
| 3 | import fs from 'fs'; |
| 4 | import path from 'path'; |
| 5 | |
| 6 | const envLocalPath = path.resolve(process.cwd(), '.env.local'); |
| 7 | if (fs.existsSync(envLocalPath)) { |
| 8 | dotenv.config({ path: envLocalPath }); |
| 9 | } else { |
| 10 | dotenv.config(); |
| 11 | } |
| 12 | |
| 13 | const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL; |
| 14 | const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY; |
| 15 | |
| 16 | if (!supabaseUrl || !supabaseServiceKey) { |
| 17 | console.error('Missing NEXT_PUBLIC_SUPABASE_URL or SUPABASE_SERVICE_ROLE_KEY in .env.local'); |
| 18 | process.exit(1); |
| 19 | } |
| 20 | |
| 21 | const supabase = createClient(supabaseUrl, supabaseServiceKey, { |
| 22 | auth: { persistSession: false }, |
| 23 | }); |
| 24 | |
| 25 | const GENERIC_TAGS = new Set([ |
| 26 | 'ai', |
| 27 | 'artificial intelligence', |
| 28 | 'general ai', |
| 29 | 'technology', |
| 30 | 'tech', |
| 31 | 'news', |
| 32 | 'updates', |
| 33 | ]); |
| 34 | |
| 35 | const TAXONOMY = [ |
| 36 | { name: 'Large Language Models', icon: 'Brain', keywords: ['llm', 'large language model', 'gpt-4', 'gpt-5', 'claude', 'gemini', 'mistral', 'llama', 'foundation model'] }, |
| 37 | { name: 'Natural Language Processing', icon: 'Languages', keywords: ['nlp', 'natural language', 'token', 'text processing', 'semantic search'] }, |
| 38 | { name: 'Computer Vision', icon: 'Eye', keywords: ['computer vision', 'image recognition', 'object detection', 'segmentation', 'vision model'] }, |
| 39 | { name: 'Robotics', icon: 'Bot', keywords: ['robot', 'robotics', 'humanoid', 'automation hardware', 'manipulation'] }, |
| 40 | { name: 'AI Agents', icon: 'Bot', keywords: ['agent', 'autonomous agent', 'agentic', 'multi-agent', 'tool use'] }, |
| 41 | { name: 'Prompt Engineering', icon: 'MessageSquare', keywords: ['prompt', 'prompting', 'system prompt', 'chain-of-thought', 'instruction tuning'] }, |
| 42 | { name: 'Generative AI', icon: 'Sparkles', keywords: ['generative ai', 'genai', 'generation', 'content generation', 'diffusion', 'sora'] }, |
| 43 | { name: 'Multimodal AI', icon: 'Layers', keywords: ['multimodal', 'text and image', 'audio and video', 'vision-language'] }, |
| 44 | { name: 'Speech Recognition', icon: 'Mic', keywords: ['speech-to-text', 'asr', 'voice recognition', 'transcription'] }, |
| 45 | { name: 'Text-to-Speech', icon: 'Volume2', keywords: ['text-to-speech', 'tts', 'voice synthesis', 'speech synthesis'] }, |
| 46 | { name: 'AI Coding', icon: 'Code2', keywords: ['code generation', 'coding assistant', 'copilot', 'developer assistant', 'software engineering ai'] }, |
| 47 | { name: 'Developer Tools', icon: 'Wrench', keywords: ['sdk', 'api', 'framework', 'developer tool', 'platform', 'cli'] }, |
| 48 | { name: 'MLOps', icon: 'GitBranch', keywords: ['mlops', 'deployment', 'model serving', 'model monitoring', 'pipeline', 'orchestration'] }, |
| 49 | { name: 'Data Analysis', icon: 'BarChart3', keywords: ['analytics', 'data analysis', 'bi', 'insights', 'dashboard'] }, |
| 50 | { name: 'Vector Databases', icon: 'Database', keywords: ['vector database', 'embedding store', 'pinecone', 'weaviate', 'chroma', 'pgvector'] }, |
| 51 | { name: 'Retrieval-Augmented Generation', icon: 'Search', keywords: ['rag', 'retrieval-augmented generation', 'retrieval augmented generation', 'knowledge retrieval'] }, |
| 52 | { name: 'Fine-Tuning', icon: 'SlidersHorizontal', keywords: ['fine-tuning', 'fine tuning', 'sft', 'rlhf', 'adapters', 'lora'] }, |
| 53 | { name: 'Open Source AI', icon: 'Code', keywords: ['open source', 'open-weight', 'github model', 'community model'] }, |
| 54 | { name: 'Model Evaluation', icon: 'ClipboardCheck', keywords: ['benchmark', 'evaluation', 'evals', 'hallucination', 'accuracy testing'] }, |
| 55 | { name: 'AI Safety', icon: 'Shield', keywords: ['ai safety', 'alignment', 'red team', 'guardrails', 'risk mitigation'] }, |
| 56 | { name: 'AI Ethics', icon: 'Scale', keywords: ['ethics', 'bias', 'fairness', 'responsible ai', 'transparency'] }, |
| 57 | { name: 'AI Governance', icon: 'Building2', keywords: ['governance', 'policy', 'compliance framework', 'accountability'] }, |
| 58 | { name: 'AI Regulation', icon: 'Gavel', keywords: ['regulation', 'regulatory', 'law', 'legal compliance', 'eu ai act', 'ftc'] }, |
| 59 | { name: 'Healthcare AI', icon: 'HeartPulse', keywords: ['healthcare', 'medical', 'clinical', 'diagnostic', 'hospital'] }, |
| 60 | { name: 'Finance AI', icon: 'Landmark', keywords: ['finance', 'fintech', 'trading', 'banking', 'risk modeling'] }, |
| 61 | { name: 'Education AI', icon: 'GraduationCap', keywords: ['education', 'learning', 'tutoring', 'edtech', 'student'] }, |
| 62 | { name: 'Marketing AI', icon: 'Megaphone', keywords: ['marketing', 'ad copy', 'campaign', 'seo', 'social media'] }, |
| 63 | { name: 'Enterprise AI', icon: 'Briefcase', keywords: ['enterprise', 'b2b', 'workflow automation', 'business operations'] }, |
| 64 | { name: 'Customer Support AI', icon: 'Headphones', keywords: ['customer support', 'support bot', 'helpdesk', 'ticket automation'] }, |
| 65 | { name: 'Deep Learning', icon: 'Network', keywords: ['deep learning', 'neural network', 'transformer', 'cnn', 'rnn'] }, |
| 66 | { name: 'Reinforcement Learning', icon: 'Gamepad2', keywords: ['reinforcement learning', 'rl', 'policy gradient', 'reward model'] }, |
| 67 | { name: 'Autonomous Vehicles', icon: 'Car', keywords: ['autonomous vehicle', 'self-driving', 'autopilot'] }, |
| 68 | { name: 'Edge AI', icon: 'Cpu', keywords: ['edge ai', 'on-device', 'edge inference', 'mobile inference'] }, |
| 69 | { name: 'AI Hardware', icon: 'Cpu', keywords: ['gpu', 'npu', 'accelerator', 'chip', 'inference hardware'] }, |
| 70 | { name: 'Synthetic Media', icon: 'Image', keywords: ['synthetic media', 'deepfake', 'ai image', 'ai video', 'image generation'] }, |
| 71 | { name: 'AI Startups', icon: 'Rocket', keywords: ['startup', 'funding', 'seed round', 'series a', 'vc'] }, |
| 72 | { name: 'AI Research', icon: 'FlaskConical', keywords: ['research', 'paper', 'arxiv', 'study', 'novel method'] }, |
| 73 | ]; |
| 74 | |
| 75 | const FALLBACK_TAGS = ['Generative AI', 'Developer Tools', 'AI Research', 'Enterprise AI', 'AI Agents']; |
| 76 | |
| 77 | const tableCandidates = { |
| 78 | news: ['news', 'news_stories'], |
| 79 | postsJunction: ['post_categories', 'posts_categories', 'blog_posts_categories'], |
| 80 | newsJunction: ['news_categories'], |
| 81 | }; |
| 82 | |
| 83 | function slugify(input) { |
| 84 | return String(input || '') |
| 85 | .toLowerCase() |
| 86 | .replace(/[^a-z0-9]+/g, '-') |
| 87 | .replace(/(^-|-$)/g, ''); |
| 88 | } |
| 89 | |
| 90 | function isGenericTag(tagName) { |
| 91 | return GENERIC_TAGS.has(String(tagName || '').trim().toLowerCase()); |
| 92 | } |
| 93 | |
| 94 | async function detectTable(candidates) { |
| 95 | for (const table of candidates) { |
| 96 | const { error } = await supabase.from(table).select('*').limit(1); |
| 97 | if (!error) return table; |
| 98 | const msg = String(error.message || '').toLowerCase(); |
| 99 | if (msg.includes('does not exist') || msg.includes('relation') || msg.includes('schema cache')) { |
| 100 | continue; |
| 101 | } |
| 102 | } |
| 103 | return null; |
| 104 | } |
| 105 | |
| 106 | function countKeywordMatches(text, keyword) { |
| 107 | if (!keyword) return 0; |
| 108 | const escaped = keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); |
| 109 | const regex = new RegExp(`\\b${escaped}\\b`, 'gi'); |
| 110 | const matches = text.match(regex); |
| 111 | return matches ? matches.length : 0; |
| 112 | } |
| 113 | |
| 114 | function inferTagNames(item, existingCategoryNames) { |
| 115 | const title = String(item.title || '').toLowerCase(); |
| 116 | const body = `${item.summary || ''}\n${item.content || ''}`.toLowerCase().slice(0, 35000); |
| 117 | const combined = `${title}\n${body}`; |
| 118 | const scoreMap = new Map(); |
| 119 | |
| 120 | for (const def of TAXONOMY) { |
| 121 | let score = 0; |
| 122 | for (const keyword of def.keywords) { |
| 123 | const titleHits = countKeywordMatches(title, keyword); |
| 124 | const bodyHits = countKeywordMatches(body, keyword); |
| 125 | score += titleHits * 4 + bodyHits; |
| 126 | } |
| 127 | if (score > 0) scoreMap.set(def.name, score); |
| 128 | } |
| 129 | |
| 130 | for (const existingName of existingCategoryNames) { |
| 131 | if (isGenericTag(existingName)) continue; |
| 132 | const current = scoreMap.get(existingName) || 0; |
| 133 | scoreMap.set(existingName, current + 3); |
| 134 | } |
| 135 | |
| 136 | const sorted = [...scoreMap.entries()].sort((a, b) => b[1] - a[1]); |
| 137 | const selected = []; |
| 138 | |
| 139 | for (const [name] of sorted) { |
| 140 | if (!selected.includes(name)) selected.push(name); |
| 141 | if (selected.length >= 5) break; |
| 142 | } |
| 143 | |
| 144 | for (const existingName of existingCategoryNames) { |
| 145 | if (selected.length >= 5) break; |
| 146 | if (isGenericTag(existingName)) continue; |
| 147 | if (!selected.includes(existingName)) selected.push(existingName); |
| 148 | } |
| 149 | |
| 150 | for (const fallback of FALLBACK_TAGS) { |
| 151 | if (selected.length >= 3) break; |
| 152 | if (!selected.includes(fallback)) selected.push(fallback); |
| 153 | } |
| 154 | |
| 155 | if (selected.length === 0) { |
| 156 | selected.push('Generative AI', 'Developer Tools', 'AI Research'); |
| 157 | } |
| 158 | |
| 159 | return selected.slice(0, 5); |
| 160 | } |
| 161 | |
| 162 | async function fetchAllRows(table, fields) { |
| 163 | const all = []; |
| 164 | const pageSize = 1000; |
| 165 | let from = 0; |
| 166 | |
| 167 | while (true) { |
| 168 | const to = from + pageSize - 1; |
| 169 | const { data, error } = await supabase.from(table).select(fields).range(from, to); |
| 170 | if (error) throw new Error(`Failed querying ${table}: ${error.message}`); |
| 171 | if (!data || data.length === 0) break; |
| 172 | all.push(...data); |
| 173 | if (data.length < pageSize) break; |
| 174 | from += pageSize; |
| 175 | } |
| 176 | |
| 177 | return all; |
| 178 | } |
| 179 | |
| 180 | async function fetchWithFieldFallbacks(table, fieldOptions) { |
| 181 | let lastError = null; |
| 182 | for (const fields of fieldOptions) { |
| 183 | try { |
| 184 | const rows = await fetchAllRows(table, fields); |
| 185 | return rows; |
| 186 | } catch (error) { |
| 187 | lastError = error; |
| 188 | } |
| 189 | } |
| 190 | throw lastError || new Error(`Failed querying ${table}`); |
| 191 | } |
| 192 | |
| 193 | async function ensureCategory(name, categoriesByName, categoriesById, stats) { |
| 194 | const key = name.toLowerCase(); |
| 195 | const existing = categoriesByName.get(key); |
| 196 | if (existing) return existing; |
| 197 | |
| 198 | const def = TAXONOMY.find((t) => t.name.toLowerCase() === key); |
| 199 | const icon = def?.icon || 'Tag'; |
| 200 | const slug = slugify(name); |
| 201 | const description = `${name} resources, news, and analysis`; |
| 202 | const now = new Date().toISOString(); |
| 203 | |
| 204 | const { data, error } = await supabase |
| 205 | .from('categories') |
| 206 | .insert({ name, slug, icon, description, created_at: now, updated_at: now }) |
| 207 | .select('id, name, slug, icon, description') |
| 208 | .single(); |
| 209 | |
| 210 | if (error) { |
| 211 | throw new Error(`Failed creating category "${name}": ${error.message}`); |
| 212 | } |
| 213 | |
| 214 | categoriesByName.set(key, data); |
| 215 | categoriesById.set(data.id, data); |
| 216 | stats.categoriesCreated += 1; |
| 217 | console.log(`+ Created category: ${name} (id=${data.id}, icon=${icon}, slug=${slug})`); |
| 218 | return data; |
| 219 | } |
| 220 | |
| 221 | async function syncItemCategories({ |
| 222 | item, |
| 223 | itemType, |
| 224 | contentTable, |
| 225 | junctionTable, |
| 226 | itemKey, |
| 227 | categoriesByName, |
| 228 | categoriesById, |
| 229 | existingLinksByItemId, |
| 230 | stats, |
| 231 | }) { |
| 232 | const existingLinks = existingLinksByItemId.get(item.id) || []; |
| 233 | const existingNames = existingLinks |
| 234 | .map((x) => categoriesById.get(x.category_id)?.name) |
| 235 | .filter(Boolean); |
| 236 | const inferredNames = inferTagNames(item, existingNames); |
| 237 | |
| 238 | const targetCategories = []; |
| 239 | for (const name of inferredNames) { |
| 240 | const category = await ensureCategory(name, categoriesByName, categoriesById, stats); |
| 241 | targetCategories.push(category); |
| 242 | } |
| 243 | |
| 244 | const targetIds = new Set(targetCategories.map((c) => c.id)); |
| 245 | const targetIdList = [...targetIds]; |
| 246 | const primaryId = targetIdList[0]; |
| 247 | |
| 248 | const existingIdSet = new Set(existingLinks.map((x) => x.category_id)); |
| 249 | const existingById = new Map(existingLinks.map((x) => [x.category_id, x])); |
| 250 | const existingNamesById = new Map(existingLinks.map((x) => [x.category_id, (categoriesById.get(x.category_id)?.name || '').toLowerCase()])); |
| 251 | |
| 252 | const toAdd = targetIdList.filter((id) => !existingIdSet.has(id)); |
| 253 | const toRemove = [...existingIdSet].filter((id) => { |
| 254 | if (targetIds.has(id)) return false; |
| 255 | const existingName = existingNamesById.get(id) || ''; |
| 256 | return isGenericTag(existingName) || true; |
| 257 | }); |
| 258 | |
| 259 | if (toAdd.length === 0 && toRemove.length === 0 && existingLinks.some((x) => x.is_primary && x.category_id === primaryId)) { |
| 260 | return; |
| 261 | } |
| 262 | |
| 263 | console.log(`\n[${itemType}] ${item.title}`); |
| 264 | console.log(`- slug: ${item.slug || 'n/a'}`); |
| 265 | console.log(`- existing: ${existingNames.length ? existingNames.join(', ') : '(none)'}`); |
| 266 | console.log(`- target: ${targetCategories.map((c) => c.name).join(', ')}`); |
| 267 | |
| 268 | if (toRemove.length > 0) { |
| 269 | const { error } = await supabase |
| 270 | .from(junctionTable) |
| 271 | .delete() |
| 272 | .eq(itemKey, item.id) |
| 273 | .in('category_id', toRemove); |
| 274 | if (error) throw new Error(`Failed removing categories from ${junctionTable}: ${error.message}`); |
| 275 | stats.linksRemoved += toRemove.length; |
| 276 | console.log(`- removed category ids: ${toRemove.join(', ')}`); |
| 277 | } |
| 278 | |
| 279 | if (toAdd.length > 0) { |
| 280 | const rows = toAdd.map((categoryId) => ({ |
| 281 | [itemKey]: item.id, |
| 282 | category_id: categoryId, |
| 283 | is_primary: categoryId === primaryId, |
| 284 | })); |
| 285 | |
| 286 | const { error } = await supabase.from(junctionTable).insert(rows); |
| 287 | if (error) throw new Error(`Failed adding categories to ${junctionTable}: ${error.message}`); |
| 288 | stats.linksAdded += toAdd.length; |
| 289 | console.log(`- added category ids: ${toAdd.join(', ')}`); |
| 290 | } |
| 291 | |
| 292 | const { error: clearPrimaryError } = await supabase |
| 293 | .from(junctionTable) |
| 294 | .update({ is_primary: false }) |
| 295 | .eq(itemKey, item.id); |
| 296 | if (clearPrimaryError) throw new Error(`Failed clearing primary flags: ${clearPrimaryError.message}`); |
| 297 | |
| 298 | const { error: setPrimaryError } = await supabase |
| 299 | .from(junctionTable) |
| 300 | .update({ is_primary: true }) |
| 301 | .eq(itemKey, item.id) |
| 302 | .eq('category_id', primaryId); |
| 303 | if (setPrimaryError) throw new Error(`Failed setting primary flag: ${setPrimaryError.message}`); |
| 304 | |
| 305 | const { error: updateItemError } = await supabase.from(contentTable).update({ primary_category_id: primaryId }).eq('id', item.id); |
| 306 | if (updateItemError) { |
| 307 | const { error: retryError } = await supabase |
| 308 | .from(contentTable) |
| 309 | .update({ primary_category_id: primaryId }) |
| 310 | .eq('id', item.id); |
| 311 | if (retryError) throw new Error(`Failed updating ${contentTable}.primary_category_id: ${retryError.message}`); |
| 312 | } |
| 313 | |
| 314 | stats.itemsUpdated += 1; |
| 315 | console.log(`- primary category id set: ${primaryId}`); |
| 316 | } |
| 317 | |
| 318 | async function main() { |
| 319 | const startedAt = new Date(); |
| 320 | const stats = { |
| 321 | categoriesCreated: 0, |
| 322 | linksAdded: 0, |
| 323 | linksRemoved: 0, |
| 324 | itemsUpdated: 0, |
| 325 | }; |
| 326 | |
| 327 | const newsTable = await detectTable(tableCandidates.news); |
| 328 | const postsJunctionTable = await detectTable(tableCandidates.postsJunction); |
| 329 | const newsJunctionTable = await detectTable(tableCandidates.newsJunction); |
| 330 | |
| 331 | if (!newsTable) throw new Error(`Could not find news table from: ${tableCandidates.news.join(', ')}`); |
| 332 | if (!postsJunctionTable) throw new Error(`Could not find posts junction table from: ${tableCandidates.postsJunction.join(', ')}`); |
| 333 | if (!newsJunctionTable) throw new Error(`Could not find news junction table from: ${tableCandidates.newsJunction.join(', ')}`); |
| 334 | |
| 335 | const postsItemKey = postsJunctionTable === 'blog_posts_categories' ? 'blog_post_id' : 'post_id'; |
| 336 | const newsItemKey = 'news_id'; |
| 337 | |
| 338 | console.log('Detected tables:'); |
| 339 | console.log(`- news: ${newsTable}`); |
| 340 | console.log(`- posts junction: ${postsJunctionTable} (${postsItemKey})`); |
| 341 | console.log(`- news junction: ${newsJunctionTable} (${newsItemKey})`); |
| 342 | |
| 343 | const [categories, posts, news, postLinks, newsLinks] = await Promise.all([ |
| 344 | fetchAllRows('categories', 'id, name, slug, icon, description'), |
| 345 | fetchWithFieldFallbacks('posts', [ |
| 346 | 'id, title, content, slug, summary, primary_category_id', |
| 347 | 'id, title, content, slug, primary_category_id', |
| 348 | 'id, title, content, slug', |
| 349 | ]), |
| 350 | fetchWithFieldFallbacks(newsTable, [ |
| 351 | 'id, title, content, slug, primary_category_id', |
| 352 | 'id, title, content, slug', |
| 353 | ]), |
| 354 | fetchAllRows(postsJunctionTable, `${postsItemKey}, category_id, is_primary`), |
| 355 | fetchAllRows(newsJunctionTable, `${newsItemKey}, category_id, is_primary`), |
| 356 | ]); |
| 357 | |
| 358 | const categoriesByName = new Map(categories.map((c) => [String(c.name).toLowerCase(), c])); |
| 359 | const categoriesById = new Map(categories.map((c) => [c.id, c])); |
| 360 | |
| 361 | const postLinksByPostId = new Map(); |
| 362 | for (const link of postLinks) { |
| 363 | const key = link[postsItemKey]; |
| 364 | if (!key) continue; |
| 365 | if (!postLinksByPostId.has(key)) postLinksByPostId.set(key, []); |
| 366 | postLinksByPostId.get(key).push(link); |
| 367 | } |
| 368 | |
| 369 | const newsLinksByNewsId = new Map(); |
| 370 | for (const link of newsLinks) { |
| 371 | const key = link[newsItemKey]; |
| 372 | if (!key) continue; |
| 373 | if (!newsLinksByNewsId.has(key)) newsLinksByNewsId.set(key, []); |
| 374 | newsLinksByNewsId.get(key).push(link); |
| 375 | } |
| 376 | |
| 377 | console.log('\nFetched records:'); |
| 378 | console.log(`- categories: ${categories.length}`); |
| 379 | console.log(`- posts: ${posts.length}`); |
| 380 | console.log(`- news: ${news.length}`); |
| 381 | console.log(`- post links: ${postLinks.length}`); |
| 382 | console.log(`- news links: ${newsLinks.length}`); |
| 383 | |
| 384 | for (const post of posts) { |
| 385 | await syncItemCategories({ |
| 386 | item: post, |
| 387 | itemType: 'Post', |
| 388 | contentTable: 'posts', |
| 389 | junctionTable: postsJunctionTable, |
| 390 | itemKey: postsItemKey, |
| 391 | categoriesByName, |
| 392 | categoriesById, |
| 393 | existingLinksByItemId: postLinksByPostId, |
| 394 | stats, |
| 395 | }); |
| 396 | } |
| 397 | |
| 398 | for (const story of news) { |
| 399 | await syncItemCategories({ |
| 400 | item: story, |
| 401 | itemType: 'News', |
| 402 | contentTable: newsTable, |
| 403 | junctionTable: newsJunctionTable, |
| 404 | itemKey: newsItemKey, |
| 405 | categoriesByName, |
| 406 | categoriesById, |
| 407 | existingLinksByItemId: newsLinksByNewsId, |
| 408 | stats, |
| 409 | }); |
| 410 | } |
| 411 | |
| 412 | const endedAt = new Date(); |
| 413 | console.log('\nTag audit complete'); |
| 414 | console.log(`- started: ${startedAt.toISOString()}`); |
| 415 | console.log(`- ended: ${endedAt.toISOString()}`); |
| 416 | console.log(`- categories created: ${stats.categoriesCreated}`); |
| 417 | console.log(`- links added: ${stats.linksAdded}`); |
| 418 | console.log(`- links removed: ${stats.linksRemoved}`); |
| 419 | console.log(`- items updated: ${stats.itemsUpdated}`); |
| 420 | } |
| 421 | |
| 422 | main().catch((error) => { |
| 423 | console.error('\nTag audit failed:'); |
| 424 | console.error(error); |
| 425 | process.exit(1); |
| 426 | }); |