laion-tunes / migrate_add_language.py
ChristophSchuhmann's picture
Upload batch: migrate_add_language.py, search_index/build_manifest.json, update_indices.py, README.md, search_index/build_stdout.log...
7a55d08 verified
#!/usr/bin/env python3
"""
Migration: Add language detection and instrumental flag to the search index.
Runs langdetect on parakeet_transcription to determine language.
Marks tracks as instrumental if has_lyrics=0 AND transcription is short/empty.
"""
import sqlite3
import sys
import time
from datetime import timedelta
from langdetect import detect, LangDetectException
DB_PATH = "/home/deployer/laion/music/laion-tunes-final/search_index/metadata.db"
BATCH_SIZE = 5000
def migrate():
conn = sqlite3.connect(DB_PATH)
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA synchronous=NORMAL")
# Add columns if not exist
cols = [row[1] for row in conn.execute("PRAGMA table_info(tracks)")]
if "language" not in cols:
conn.execute("ALTER TABLE tracks ADD COLUMN language TEXT DEFAULT ''")
print("Added 'language' column")
if "is_instrumental" not in cols:
conn.execute("ALTER TABLE tracks ADD COLUMN is_instrumental INTEGER DEFAULT 0")
print("Added 'is_instrumental' column")
conn.commit()
# Create index for language
conn.execute("CREATE INDEX IF NOT EXISTS idx_language ON tracks(language)")
conn.execute("CREATE INDEX IF NOT EXISTS idx_instrumental ON tracks(is_instrumental)")
conn.commit()
# Step 1: Mark instrumental tracks
# Instrumental = has_lyrics=0 AND (transcription is NULL or short)
print("Marking instrumental tracks...")
conn.execute("""
UPDATE tracks SET is_instrumental = 1
WHERE has_lyrics = 0
AND (parakeet_transcription IS NULL OR LENGTH(parakeet_transcription) < 10)
""")
# Also mark tracks where lyrics exist but are very short (likely "[Instrumental]" tags)
conn.execute("""
UPDATE tracks SET is_instrumental = 1
WHERE has_lyrics = 1
AND (parakeet_transcription IS NULL OR LENGTH(parakeet_transcription) < 10)
AND is_instrumental = 0
""")
conn.commit()
instr_count = conn.execute("SELECT COUNT(*) FROM tracks WHERE is_instrumental=1").fetchone()[0]
print(f" Instrumental: {instr_count:,}")
# Step 2: Detect language from transcriptions
total = conn.execute(
"SELECT COUNT(*) FROM tracks WHERE has_transcription=1 AND (language IS NULL OR language='')"
).fetchone()[0]
print(f"Detecting language for {total:,} transcriptions...")
t0 = time.time()
processed = 0
offset = 0
while True:
rows = conn.execute(
"SELECT row_id, parakeet_transcription FROM tracks "
"WHERE has_transcription=1 AND (language IS NULL OR language='') "
"LIMIT ? OFFSET ?",
(BATCH_SIZE, offset)
).fetchall()
if not rows:
break
updates = []
for row_id, text in rows:
if not text or len(text.strip()) < 10:
updates.append(("unknown", row_id))
continue
try:
# Use first 300 chars for speed
lang = detect(text[:300])
updates.append((lang, row_id))
except LangDetectException:
updates.append(("unknown", row_id))
conn.executemany("UPDATE tracks SET language=? WHERE row_id=?", updates)
conn.commit()
processed += len(rows)
offset += BATCH_SIZE
elapsed = time.time() - t0
rate = processed / elapsed if elapsed > 0 else 0
remaining = (total - processed) / rate if rate > 0 else 0
print(f" {processed:,}/{total:,} ({processed*100//total}%) "
f"{rate:.0f}/s ETA: {timedelta(seconds=int(remaining))}")
# Step 3: For tracks without transcription, try langdetect on tags or title
# (less reliable but better than nothing)
no_lang = conn.execute(
"SELECT COUNT(*) FROM tracks WHERE (language IS NULL OR language='') AND has_transcription=0"
).fetchone()[0]
print(f"\nTracks without language (no transcription): {no_lang:,}")
print("Setting these to 'unknown'...")
conn.execute("UPDATE tracks SET language='unknown' WHERE language IS NULL OR language=''")
conn.commit()
# Print language distribution
print("\nLanguage distribution:")
for row in conn.execute(
"SELECT language, COUNT(*) as cnt FROM tracks GROUP BY language ORDER BY cnt DESC LIMIT 20"
):
print(f" {row[0]:>10}: {row[1]:>8,}")
print(f"\nDone in {timedelta(seconds=int(time.time() - t0))}")
conn.close()
if __name__ == "__main__":
migrate()