Files
clicktrack/app/api/analyze/route.ts
AJ Avezzano 5e686fc9c4 feat: MusicBrainz BPM enrichment + improved AI prompts
- lookupRecordingWithTags, extractBpmFromTags, extractTimeSigFromTags, getMusicBrainzRecording added to MB client
- upsertSong preserves existing BPM via COALESCE on conflict
- updateSongBpm helper for async enrichment writes
- AnalysisInput gains confirmedBpm / confirmedTimeSigNum fields
- POST /api/analyze fetches confirmed BPM from DB then MB tags before generation
- All three AI providers use confirmedBpm as authoritative and build enriched userMessage
- POST /api/tracks auto-registration now fetches tags via getMusicBrainzRecording
- Updated User-Agent and MB client fallback URL to Gitea

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 19:25:04 -04:00

154 lines
4.9 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { getProvider, getAvailableProviders } from "@/lib/analysis/providers/registry";
import { validateCTP } from "@/lib/ctp/validate";
import { getSongByMbid, updateSongBpm } from "@/lib/db/client";
import { lookupRecordingWithTags, extractBpmFromTags, extractTimeSigFromTags } from "@/lib/musicbrainz/client";
// ─── Request schema ───────────────────────────────────────────────────────────
const AnalyzeRequestSchema = z.object({
bpm: z.number().min(20).max(400),
duration: z.number().positive(),
title: z.string().min(1).max(256).optional(),
artist: z.string().min(1).max(256).optional(),
mbid: z.string().uuid().optional().nullable(),
contributed_by: z.string().min(1).max(64).optional(),
provider: z.string().optional(),
ollamaModel: z.string().optional(),
});
/**
* POST /api/analyze
*
* Accepts BPM detection results from the browser and uses the selected provider
* to generate a draft CTP document for human review.
*
* Body (JSON):
* { bpm, duration, title?, artist?, mbid?, contributed_by?, provider?, ollamaModel? }
*
* Returns:
* { ctp: CTPDocument, warnings: string[] }
*/
export async function POST(req: NextRequest) {
let body: unknown;
try {
body = await req.json();
} catch {
return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
}
const parsed = AnalyzeRequestSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json(
{ error: "Invalid request", details: parsed.error.flatten() },
{ status: 400 }
);
}
const { bpm, duration, title, artist, mbid, contributed_by, provider: providerId, ollamaModel } =
parsed.data;
// Validate Ollama-specific requirement
if (providerId === "ollama" && (!ollamaModel || ollamaModel.trim() === "")) {
return NextResponse.json(
{ error: "ollamaModel is required when using the Ollama provider" },
{ status: 400 }
);
}
// Resolve provider
let provider;
if (providerId) {
try {
provider = await getProvider(providerId);
} catch (err) {
return NextResponse.json(
{ error: err instanceof Error ? err.message : String(err) },
{ status: 400 }
);
}
} else {
const available = await getAvailableProviders();
provider = available[0];
if (!provider) {
return NextResponse.json(
{ error: "No analysis providers are currently available" },
{ status: 503 }
);
}
}
// ── BPM enrichment ────────────────────────────────────────────────────────
// If the song has an MBID, try to supply the AI with a confirmed BPM from
// MusicBrainz community tags. Best-effort: any failure is silently ignored.
let confirmedBpm: number | null = null;
let confirmedTimeSigNum: number | null = null;
if (mbid) {
// 1. Check the DB first — may already have a stored BPM from a prior lookup
try {
const storedSong = await getSongByMbid(mbid);
if (storedSong?.acousticbrainz_bpm) {
confirmedBpm = storedSong.acousticbrainz_bpm;
confirmedTimeSigNum = storedSong.acousticbrainz_time_sig_num ?? null;
}
} catch {
// ignore DB errors
}
// 2. If no stored BPM, fetch from MusicBrainz tags
if (!confirmedBpm) {
try {
const rec = await lookupRecordingWithTags(mbid);
const tagBpm = rec.tags ? extractBpmFromTags(rec.tags) : null;
const tagTimeSig = rec.tags ? extractTimeSigFromTags(rec.tags) : null;
if (tagBpm) {
confirmedBpm = tagBpm;
confirmedTimeSigNum = tagTimeSig;
// Persist for next time — fire-and-forget
updateSongBpm(mbid, tagBpm, tagTimeSig).catch(() => {});
}
} catch {
// MusicBrainz unavailable or rate-limited — proceed without confirmed BPM
}
}
}
const input = {
bpm,
duration,
title,
artist,
mbid: mbid ?? null,
contributed_by: contributed_by ?? "anonymous",
ollamaModel,
confirmedBpm,
confirmedTimeSigNum,
};
let ctpDoc;
try {
ctpDoc = await provider.generateCTP(input);
} catch (err) {
console.error(`[analyze] Provider '${provider.label}' failed:`, err);
return NextResponse.json(
{
error: `Provider '${provider.label}' failed: ${err instanceof Error ? err.message : String(err)}`,
},
{ status: 502 }
);
}
// Validate the output against the CTP schema
const validation = validateCTP(ctpDoc);
const warnings: string[] = [];
if (!validation.success) {
warnings.push(...validation.errors.issues.map((i) => `${i.path.join(".")}: ${i.message}`));
}
return NextResponse.json({ ctp: ctpDoc, warnings });
}