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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
/**
 * ML Bridge - Node.js interface to Python ML processor
 * 
 * Calls Python scripts via subprocess for:
 * - Stem separation (Demucs)
 * - Audio fingerprinting (Chromaprint)
 * - Embedding generation (CLAP)
 */

import { spawn } from "child_process";
import path from "path";
import { fileURLToPath } from "url";
import fs from "fs/promises";

// Get directory name in ESM
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// Path to ML processor
const ML_DIR = path.resolve(__dirname, "../ml");
const PROCESSOR_PATH = path.join(ML_DIR, "processor.py");

// Types for ML operations
export interface StemResult {
  type: "vocals" | "drums" | "bass" | "other" | "guitar" | "piano";
  path: string;
  duration: number | null;
}

export interface StemSeparationResult {
  success: boolean;
  stems?: StemResult[];
  model?: string;
  output_dir?: string;
  error?: string;
}

export interface FingerprintResult {
  success: boolean;
  fingerprint?: string;
  duration?: number;
  algorithm?: string;
  version?: string;
  error?: string;
}

export interface EmbeddingResult {
  success: boolean;
  embedding?: number[];
  dimension?: number;
  model?: string;
  error?: string;
}

export interface ProcessAllResult {
  success: boolean;
  stems?: Array<{
    type: string;
    path: string;
    duration: number | null;
    fingerprint: string | null;
    fingerprint_error?: string;
    embedding: number[] | null;
    embedding_model?: string;
    embedding_error?: string;
  }>;
  error?: string;
}

export interface HealthCheckResult {
  success: boolean;
  demucs: boolean;
  chromaprint: boolean;
  clap: boolean;
  faiss?: boolean;
  demucs_version?: string;
  chromaprint_version?: string;
  clap_source?: string;
  faiss_version?: string;
  errors: string[];
}

/**
 * Get Python command to use
 * Prefers PYTHON_PATH env var, then conda env, then system python
 */
function getPythonCommand(): string {
  // Allow explicit override via env var
  if (process.env.PYTHON_PATH) {
    return process.env.PYTHON_PATH;
  }
  
  // Default to system python
  return process.platform === "win32" ? "python" : "python3";
}

/**
 * Execute Python processor with given operation and arguments
 */
async function execPython<T>(
  operation: string,
  args: Record<string, unknown>,
  timeoutMs: number = 600000 // 10 minute default
): Promise<T> {
  return new Promise((resolve, reject) => {
    const argsJson = JSON.stringify(args);
    
    const pythonCmd = getPythonCommand();
    
    const proc = spawn(pythonCmd, [PROCESSOR_PATH, operation, argsJson], {
      cwd: ML_DIR,
      env: {
        ...process.env,
        PYTHONUNBUFFERED: "1", // Ensure immediate output
      },
    });

    let stdout = "";
    let stderr = "";
    let timedOut = false;

    // Set timeout
    const timeout = setTimeout(() => {
      timedOut = true;
      proc.kill("SIGTERM");
      reject(new Error(`ML operation timed out after ${timeoutMs}ms`));
    }, timeoutMs);

    proc.stdout.on("data", (data) => {
      stdout += data.toString();
    });

    proc.stderr.on("data", (data) => {
      stderr += data.toString();
    });

    proc.on("error", (err) => {
      clearTimeout(timeout);
      if (err.message.includes("ENOENT")) {
        reject(new Error(`Python not found. Ensure python3 is installed and in PATH.`));
      } else {
        reject(err);
      }
    });

    proc.on("close", (code) => {
      clearTimeout(timeout);
      
      if (timedOut) return; // Already rejected
      
      if (code !== 0) {
        // Try to parse error from stdout (processor outputs JSON even on error)
        try {
          const result = JSON.parse(stdout);
          if (!result.success && result.error) {
            reject(new Error(result.error));
            return;
          }
        } catch {
          // Ignore parse error
        }
        reject(new Error(`ML operation failed (exit code ${code}): ${stderr || stdout}`));
        return;
      }

      try {
        const result = JSON.parse(stdout);
        resolve(result as T);
      } catch (e) {
        // Truncate output to avoid flooding logs with embeddings
        const truncated = stdout.length > 500 ? stdout.slice(0, 500) + "..." : stdout;
        reject(new Error(`Failed to parse ML result: ${e}. Output (truncated): ${truncated}`));
      }
    });
  });
}

/**
 * Check if ML dependencies are available
 */
export async function checkMLHealth(): Promise<HealthCheckResult> {
  try {
    return await execPython<HealthCheckResult>("health", {}, 30000);
  } catch (error) {
    return {
      success: false,
      demucs: false,
      chromaprint: false,
      clap: false,
      errors: [error instanceof Error ? error.message : String(error)],
    };
  }
}

/**
 * Separate audio into stems using Demucs
 */
export async function separateStems(
  inputPath: string,
  outputDir: string,
  model: string = "htdemucs"
): Promise<StemSeparationResult> {
  // Verify input file exists
  try {
    await fs.access(inputPath);
  } catch {
    return {
      success: false,
      error: `Input file not found: ${inputPath}`,
    };
  }

  // Create output directory
  await fs.mkdir(outputDir, { recursive: true });

  return execPython<StemSeparationResult>("separate", {
    input_path: inputPath,
    output_dir: outputDir,
    model,
  });
}

/**
 * Generate audio fingerprint using Chromaprint
 */
export async function generateFingerprint(
  audioPath: string
): Promise<FingerprintResult> {
  return execPython<FingerprintResult>("fingerprint", {
    audio_path: audioPath,
  }, 120000); // 2 minute timeout for fingerprinting
}

/**
 * Generate audio embedding using CLAP
 */
export async function generateEmbedding(
  audioPath: string,
  model: string = "laion/larger_clap_music"
): Promise<EmbeddingResult> {
  return execPython<EmbeddingResult>("embed", {
    audio_path: audioPath,
    model,
  }, 300000); // 5 minute timeout for embedding
}

export interface ChunkEmbedding {
  start_time: number;
  end_time: number;
  embedding: number[];
  dimension: number;
}

export interface ChunkEmbeddingsResult {
  success: boolean;
  chunks?: ChunkEmbedding[];
  total_duration?: number;
  chunk_count?: number;
  error?: string;
}

/**
 * Generate chunk-based embeddings for an audio file
 * This splits the audio into overlapping windows and generates
 * an embedding for each chunk, enabling section-level matching.
 */
export async function generateChunkEmbeddings(
  audioPath: string,
  chunkDuration: number = 10.0,
  chunkOverlap: number = 5.0,
  model: string = "laion/larger_clap_music"
): Promise<ChunkEmbeddingsResult> {
  return execPython<ChunkEmbeddingsResult>("embed_chunks", {
    audio_path: audioPath,
    chunk_duration: chunkDuration,
    chunk_overlap: chunkOverlap,
    model,
  }, 600000); // 10 minute timeout for chunk embedding (longer audio)
}

/**
 * Process audio through full pipeline: separate -> fingerprint -> embed
 */
export async function processFullPipeline(
  inputPath: string,
  outputDir: string
): Promise<ProcessAllResult> {
  return execPython<ProcessAllResult>("process_all", {
    input_path: inputPath,
    output_dir: outputDir,
  }, 900000); // 15 minute timeout for full pipeline
}

/**
 * Check if Python ML environment is available
 */
export async function isPythonAvailable(): Promise<boolean> {
  return new Promise((resolve) => {
    const pythonCmd = process.platform === "win32" ? "python" : "python3";
    const proc = spawn(pythonCmd, ["--version"]);
    
    proc.on("error", () => resolve(false));
    proc.on("close", (code) => resolve(code === 0));
  });
}

/**
 * Check if processor.py exists
 */
export async function isProcessorAvailable(): Promise<boolean> {
  try {
    await fs.access(PROCESSOR_PATH);
    return true;
  } catch {
    return false;
  }
}

/**
 * Generic call to Python processor for any operation
 * Used for FAISS operations and other extensible functionality
 */
export async function callPythonProcessor<T = Record<string, unknown>>(
  operation: string,
  args: Record<string, unknown>,
  timeoutMs: number = 60000
): Promise<T> {
  return execPython<T>(operation, args, timeoutMs);
}

// ============== Fingerprint-based matching (Chromaprint) ==============

export interface ChunkFingerprint {
  start_time: number;
  end_time: number;
  fingerprint: string;
}

export interface ChunkFingerprintsResult {
  success: boolean;
  chunks?: ChunkFingerprint[];
  total_duration?: number;
  chunk_count?: number;
  error?: string;
}

/**
 * Generate fingerprints for audio chunks
 * Unlike CLAP embeddings, Chromaprint fingerprints give:
 * - 100% match for same audio
 * - ~2-3% match for different audio
 */
export async function generateChunkFingerprints(
  audioPath: string,
  chunkDuration: number = 10.0,
  chunkOverlap: number = 5.0
): Promise<ChunkFingerprintsResult> {
  return execPython<ChunkFingerprintsResult>("fingerprint_chunks", {
    audio_path: audioPath,
    chunk_duration: chunkDuration,
    chunk_overlap: chunkOverlap,
  }, 600000);
}

export interface FingerprintMatch {
  score: number;
  trackId: string;
  stemType?: string;
  title: string;
  artist: string;
  startTime?: number;
  endTime?: number;
}

export interface FingerprintSearchResult {
  matches: FingerprintMatch[];
  message?: string;
}

/**
 * Search fingerprint index for matches
 */
export async function searchFingerprints(
  fingerprint: string,
  k: number = 5,
  threshold: number = 0.3
): Promise<FingerprintSearchResult> {
  return execPython<FingerprintSearchResult>("fp_search", {
    fingerprint,
    k,
    threshold,
  }, 30000);
}

export interface FingerprintIndexStats {
  exists: boolean;
  total: number;
  uniqueTracks: number;
}

/**
 * Get fingerprint index statistics
 */
export async function getFingerprintStats(): Promise<FingerprintIndexStats> {
  return execPython<FingerprintIndexStats>("fp_stats", {}, 10000);
}

// ============== Style-based similarity ==============

export interface StyleFeatures {
  success: boolean;
  feature_vector?: number[];
  dimension?: number;
  tempo?: number;
  error?: string;
}

export interface StyleMatch {
  score: number;
  trackId: string;
  title: string;
  artist: string;
}

export interface StyleSearchResult {
  matches: StyleMatch[];
}

/**
 * Extract musical style features from audio
 */
export async function extractStyleFeatures(
  audioPath: string,
  duration?: number
): Promise<StyleFeatures> {
  return execPython<StyleFeatures>("style_extract", {
    audio_path: audioPath,
    duration,
  }, 120000);
}

export interface StyleChunk {
  start_time: number;
  end_time: number;
  feature_vector: number[];
}

export interface StyleChunksResult {
  success: boolean;
  total_duration?: number;
  chunk_count?: number;
  chunks?: StyleChunk[];
  error?: string;
}

/**
 * Extract chunk-level style features for granular matching
 */
export async function extractStyleChunks(
  audioPath: string,
  chunkDuration: number = 10.0,
  chunkOverlap: number = 5.0
): Promise<StyleChunksResult> {
  return execPython<StyleChunksResult>("style_chunks", {
    audio_path: audioPath,
    chunk_duration: chunkDuration,
    chunk_overlap: chunkOverlap,
  }, 300000);
}

/**
 * Search for tracks with similar musical style
 */
export async function searchStyleSimilar(
  features: number[],
  k: number = 5,
  threshold: number = 0.85
): Promise<StyleSearchResult> {
  return execPython<StyleSearchResult>("style_search", {
    features,
    k,
    threshold,
  }, 30000);
}

export interface StyleIndexStats {
  exists: boolean;
  total: number;
  uniqueTracks: number;
}

/**
 * Get style index statistics
 */
export async function getStyleStats(): Promise<StyleIndexStats> {
  return execPython<StyleIndexStats>("style_stats", {}, 10000);
}

// ============== MERT (Music-specific embeddings) ==============

export interface MertChunk {
  start_time: number;
  end_time: number;
  embedding: number[];
}

export interface MertChunksResult {
  success: boolean;
  total_duration?: number;
  chunk_count?: number;
  chunks?: MertChunk[];
  error?: string;
}

/**
 * Extract MERT chunk embeddings for music-specific similarity
 * MERT gives much better discrimination than generic audio features
 */
export async function extractMertChunks(
  audioPath: string,
  chunkDuration: number = 10.0,
  chunkOverlap: number = 5.0
): Promise<MertChunksResult> {
  return execPython<MertChunksResult>("mert_chunks", {
    audio_path: audioPath,
    chunk_duration: chunkDuration,
    chunk_overlap: chunkOverlap,
  }, 600000); // 10 min timeout
}

export interface MertMatch {
  score: number;
  trackId: string;
  title: string;
  artist: string;
  startTime?: number;
  endTime?: number;
}

export interface MertSearchResult {
  matches: MertMatch[];
}

/**
 * Search MERT index for similar music
 * @param percentile If set (0-100), use dynamic threshold at this percentile
 */
export async function searchMertSimilar(
  embedding: number[],
  k: number = 5,
  threshold?: number,
  percentile?: number
): Promise<MertSearchResult & { threshold_used?: number }> {
  return execPython<MertSearchResult & { threshold_used?: number }>("mert_search", {
    embedding,
    k,
    threshold: threshold ?? 0.75,
    percentile,
  }, 30000);
}

export interface MertIndexStats {
  exists: boolean;
  total: number;
  uniqueTracks: number;
}

/**
 * Get MERT index statistics
 */
export async function getMertStats(): Promise<MertIndexStats> {
  return execPython<MertIndexStats>("mert_stats", {}, 10000);
}