All files / web/scripts generateTopicTaxonomy.ts

0% Statements 0/433
0% Branches 0/1
0% Functions 0/1
0% Lines 0/433

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
#!/usr/bin/env npx tsx
import dotenv from 'dotenv'
dotenv.config({ path: '.env.local' })
dotenv.config() // .env as fallback

/**
 * Generate topic taxonomy for cluster labeling.
 *
 * Generates ~200 topic labels at multiple specificity levels:
 * - Broad labels (e.g., "Mathematics", "Science") for diverse clusters
 * - Domain labels (e.g., "Fractions", "Grammar") for medium groupings
 * - Topic labels (e.g., "Fraction Addition", "Verb Tenses") for specific matches
 *
 * Labels are informed by word frequencies from existing flowcharts.
 *
 * Usage:
 *   npx tsx scripts/generateTopicTaxonomy.ts          # Generate from scratch
 *   npx tsx scripts/generateTopicTaxonomy.ts --expand  # Add new labels to existing taxonomy
 */

import { writeFileSync, readFileSync, existsSync } from 'fs'
import { join } from 'path'
import Database from 'better-sqlite3'
import { LLMClient } from '@soroban/llm-client'
import { z } from 'zod'
import { EMBEDDING_MODEL, EMBEDDING_DIMENSIONS } from '../src/lib/flowcharts/embedding'

const OUTPUT_DIR = join(__dirname, '../src/lib/flowcharts')
const JSON_PATH = join(OUTPUT_DIR, 'topic-taxonomy.json')
const BIN_PATH = join(OUTPUT_DIR, 'topic-taxonomy.bin')
const DB_PATH = join(__dirname, '../data/sqlite.db')

interface TaxonomyIndex {
  version: string
  model: string
  labels: string[]
}

// Common stop words to exclude from frequency analysis
const STOP_WORDS = new Set([
  'the',
  'a',
  'an',
  'and',
  'or',
  'but',
  'in',
  'on',
  'at',
  'to',
  'for',
  'of',
  'with',
  'by',
  'from',
  'as',
  'is',
  'was',
  'are',
  'were',
  'been',
  'be',
  'have',
  'has',
  'had',
  'do',
  'does',
  'did',
  'will',
  'would',
  'could',
  'should',
  'may',
  'might',
  'must',
  'shall',
  'can',
  'need',
  'dare',
  'ought',
  'used',
  'it',
  'its',
  'this',
  'that',
  'these',
  'those',
  'i',
  'you',
  'he',
  'she',
  'we',
  'they',
  'what',
  'which',
  'who',
  'whom',
  'whose',
  'where',
  'when',
  'why',
  'how',
  'all',
  'each',
  'every',
  'both',
  'few',
  'more',
  'most',
  'other',
  'some',
  'such',
  'no',
  'nor',
  'not',
  'only',
  'own',
  'same',
  'so',
  'than',
  'too',
  'very',
  'just',
  'also',
  'now',
  'here',
  'there',
  'then',
  'once',
  'if',
  'unless',
  'until',
  'while',
  'although',
  'because',
  'since',
  'about',
  'into',
  'through',
  'during',
  'before',
  'after',
  'above',
  'below',
  'between',
  'under',
  'again',
  'further',
  'any',
  'up',
  'down',
  'out',
  'off',
  'over',
  'students',
  'learn',
  'using',
  'use',
  'step',
  'steps',
  'practice',
  'understand',
  'like',
  'different',
  'various',
  'based',
  'given',
  'find',
  'solve',
  'work',
])

/**
 * Extract word frequencies from flowchart content
 */
function extractWordFrequencies(texts: string[]): Map<string, number> {
  const frequencies = new Map<string, number>()

  for (const text of texts) {
    // Split on non-word characters, lowercase, filter
    const words = text
      .toLowerCase()
      .split(/[^a-z]+/)
      .filter((w) => w.length > 2 && !STOP_WORDS.has(w))

    for (const word of words) {
      frequencies.set(word, (frequencies.get(word) || 0) + 1)
    }
  }

  return frequencies
}

/**
 * Format top word frequencies for the prompt
 */
function formatWordFrequencies(frequencies: Map<string, number>, limit: number = 50): string {
  const sorted = [...frequencies.entries()].sort((a, b) => b[1] - a[1]).slice(0, limit)

  if (sorted.length === 0) {
    return '(No existing flowcharts found)'
  }

  return sorted.map(([word, count]) => `${word} (${count})`).join(', ')
}

/**
 * Load flowchart content from the database
 */
function loadFlowchartContent(): string[] {
  if (!existsSync(DB_PATH)) {
    console.log('Database not found, skipping content analysis')
    return []
  }

  const sqlite = new Database(DB_PATH)

  // Use raw SQL to avoid Drizzle schema resolution issues in scripts
  const flowcharts = sqlite
    .prepare(
      `SELECT title, description
       FROM teacher_flowcharts
       WHERE status = 'published'`
    )
    .all() as Array<{ title: string | null; description: string | null }>

  sqlite.close()

  const texts: string[] = []
  for (const fc of flowcharts) {
    if (fc.title) texts.push(fc.title)
    if (fc.description) texts.push(fc.description)
  }

  console.log(`Loaded ${flowcharts.length} published flowcharts`)
  return texts
}

async function generateLabels(existingLabels: string[], wordFreqHint: string): Promise<string[]> {
  const llm = new LLMClient()

  const avoidClause =
    existingLabels.length > 0
      ? `\n\nIMPORTANT: Do NOT include any of these existing labels (or close synonyms):\n${existingLabels.map((l) => `- ${l}`).join('\n')}`
      : ''

  const response = await llm.call({
    prompt: `Generate a comprehensive list of topic labels for categorizing educational flowcharts. The labels should cover the FULL spectrum of education from kindergarten through graduate/professional level, with multiple levels of specificity.

## Specificity Tiers (generate labels at ALL levels):

**Tier 1 - Broad subjects (~20 labels):**
Very broad categories that can group diverse content. Examples: "Mathematics", "Language Arts", "Science", "Social Studies", "Arts & Music", "Life Skills", "Technology", "Engineering", "Medicine"

**Tier 2 - Domains (~50 labels):**
Subject domains that group related topics. Examples: "Fractions", "Linear Algebra", "Organic Chemistry", "Grammar", "Physics", "Machine Learning", "Music Theory"

**Tier 3 - Specific topics (~130 labels):**
Focused topics for specific content. Examples: "Fraction Addition", "Matrix Operations", "Cramer's Rule", "Verb Tenses", "Newton's Laws", "Neural Networks"

## Content hints from existing flowcharts:
Here are the most common terms from existing flowcharts in the system:
${wordFreqHint}

Use these to ensure coverage of topics that actually exist, including any niche topics.

## Requirements:
- Each label should be 2-5 words (broader labels can be 1-2 words)
- Use Title Case
- Cover the FULL educational spectrum: elementary, middle school, high school, undergraduate, graduate, professional
- Avoid redundancy — each label should cover a distinct topic area
- IMPORTANT: Include broad labels! When content is diverse, a cluster needs a broad label like "Mathematics" rather than being unlabeled.

## Topic coverage (ensure all levels are represented):

**Mathematics:**
- Elementary: counting, place value, basic operations, fractions, decimals, percentages, basic geometry, measurement
- Middle/High School: algebra, linear equations, quadratic equations, polynomials, trigonometry, statistics, probability
- Advanced: linear algebra, matrices, determinants, systems of equations, calculus, differential equations, abstract algebra, number theory, topology, real analysis

**Language Arts:**
- Elementary: phonics, reading comprehension, vocabulary, grammar, parts of speech, sentence structure, punctuation, spelling
- Middle/High School: essay writing, literary analysis, rhetoric, research papers, citations
- Advanced: linguistics, semantics, discourse analysis, technical writing

**Science:**
- Elementary/Middle: scientific method, life science, physical science, earth science, ecosystems
- High School: biology, chemistry, physics, environmental science
- Advanced: molecular biology, organic chemistry, quantum mechanics, thermodynamics, astrophysics, neuroscience

**Engineering & Technology:**
- Fundamentals: basic coding, algorithms, data structures, circuits
- Advanced: machine learning, computer architecture, signal processing, control systems, aerospace, materials science

**Social Studies & Humanities:**
- History, geography, civics, economics, philosophy, psychology, sociology, anthropology

**Professional/Applied:**
- Medicine, law, business, finance, accounting, project management

**Arts & Other:**
- Music theory, art techniques, physical education, health, nutrition, practical life skills

Return approximately 200 labels total across all tiers.${avoidClause}`,
    schema: z.object({
      labels: z.array(z.string()).min(150).max(250),
    }),
    model: 'gpt-4o-mini',
  })

  return response.data.labels
}

function deduplicateLabels(labels: string[]): string[] {
  const seen = new Set<string>()
  const result: string[] = []

  for (const label of labels) {
    const normalized = label.trim()
    const key = normalized.toLowerCase()
    if (!seen.has(key) && normalized.length > 0) {
      seen.add(key)
      result.push(normalized)
    }
  }

  return result
}

async function embedLabels(labels: string[]): Promise<Float32Array[]> {
  const llm = new LLMClient()

  console.log(`Embedding ${labels.length} labels...`)
  const response = await llm.embed({
    input: labels,
    model: EMBEDDING_MODEL,
  })

  return response.embeddings
}

function writeTaxonomy(labels: string[], embeddings: Float32Array[]): void {
  // Write JSON index
  const index: TaxonomyIndex = {
    version: '2.0.0',
    model: EMBEDDING_MODEL,
    labels,
  }
  writeFileSync(JSON_PATH, JSON.stringify(index, null, 2) + '\n')
  console.log(`Wrote ${JSON_PATH} (${labels.length} labels)`)

  // Write binary embeddings (packed Float32Arrays)
  const bytesPerLabel = EMBEDDING_DIMENSIONS * Float32Array.BYTES_PER_ELEMENT
  const totalBytes = labels.length * bytesPerLabel
  const buffer = Buffer.alloc(totalBytes)

  for (let i = 0; i < embeddings.length; i++) {
    const src = Buffer.from(embeddings[i].buffer)
    src.copy(buffer, i * bytesPerLabel)
  }

  writeFileSync(BIN_PATH, buffer)
  console.log(`Wrote ${BIN_PATH} (${totalBytes} bytes)`)
}

async function main() {
  const isExpand = process.argv.includes('--expand')

  // Load existing flowchart content for word frequency analysis
  console.log('Analyzing existing flowchart content...')
  const flowchartTexts = loadFlowchartContent()
  const wordFrequencies = extractWordFrequencies(flowchartTexts)
  const wordFreqHint = formatWordFrequencies(wordFrequencies, 60)
  console.log(`Top terms: ${wordFreqHint.slice(0, 200)}...`)

  let existingLabels: string[] = []
  const existingEmbeddings: Float32Array[] = []

  if (isExpand && existsSync(JSON_PATH) && existsSync(BIN_PATH)) {
    console.log('Loading existing taxonomy for expansion...')
    const index: TaxonomyIndex = JSON.parse(readFileSync(JSON_PATH, 'utf-8'))
    existingLabels = index.labels

    const binBuffer = readFileSync(BIN_PATH)
    const bytesPerLabel = EMBEDDING_DIMENSIONS * Float32Array.BYTES_PER_ELEMENT
    for (let i = 0; i < existingLabels.length; i++) {
      const offset = i * bytesPerLabel
      const slice = binBuffer.subarray(offset, offset + bytesPerLabel)
      const ab = new ArrayBuffer(bytesPerLabel)
      new Uint8Array(ab).set(slice)
      existingEmbeddings.push(new Float32Array(ab))
    }

    console.log(`Existing taxonomy: ${existingLabels.length} labels`)
  }

  // Generate new labels
  console.log('Generating topic labels via LLM...')
  const rawLabels = await generateLabels(existingLabels, wordFreqHint)
  console.log(`Generated ${rawLabels.length} raw labels`)

  // Deduplicate (including against existing labels)
  const allRawLabels = [...existingLabels, ...rawLabels]
  const allLabels = deduplicateLabels(allRawLabels)
  const newLabels = allLabels.slice(existingLabels.length)

  console.log(`After dedup: ${newLabels.length} new labels (${allLabels.length} total)`)

  if (newLabels.length === 0) {
    console.log('No new labels to add.')
    return
  }

  // Embed new labels
  const newEmbeddings = await embedLabels(newLabels)

  // Combine with existing
  const finalLabels = [...existingLabels, ...newLabels]
  const finalEmbeddings = [...existingEmbeddings, ...newEmbeddings]

  // Write output
  writeTaxonomy(finalLabels, finalEmbeddings)

  console.log('\nDone! Generated labels:')
  for (const label of finalLabels) {
    console.log(`  - ${label}`)
  }
}

main().catch((err) => {
  console.error('Failed to generate taxonomy:', err)
  process.exit(1)
})