mirror of
https://github.com/rommapp/romm.git
synced 2026-11-30 02:22:44 +01:00
test(tools): generate soundtracks with the rest of the test data
Folds the standalone soundtrack seeder into generate_test_data.py, where the rest of the fake library is built: a share of roms (--soundtrack-share, default 8%) now get tagged audio files plus their track_meta rows, so the music endpoints and the jukebox have something to read. Two pre-existing bugs in that script surfaced while verifying this, both of which made it fail outright on MariaDB: - bulk_insert used executemany, whose MariaDB bulk path silently drops all but the first row when a column mixes NULL and non-NULL across the batch. Every rom batch inserted one rom, and the rom_files insert then failed the foreign key. Multi-VALUES statements per chunk keep the speed without it. - with rows actually landing, the small title pools collide on the unique (platform_id, fs_name) index, so repeats are now disambiguated. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -2,8 +2,8 @@
|
||||
"""Generate a large, prod-like RomM library for load and UI testing.
|
||||
|
||||
Builds platforms, users, devices, firmware, roms (with per-provider fake
|
||||
metadata), rom files, saves, states, screenshots, notes, play stats,
|
||||
collections and sync data, then bulk-inserts everything.
|
||||
metadata), rom files, tagged soundtracks, saves, states, screenshots, notes,
|
||||
play stats, collections and sync data, then bulk-inserts everything.
|
||||
|
||||
Run from the backend directory:
|
||||
|
||||
@@ -68,6 +68,7 @@ from models.rom import ( # noqa: E402
|
||||
RomNote,
|
||||
RomUser,
|
||||
RomUserStatus,
|
||||
TrackMeta,
|
||||
compute_name_sort_key,
|
||||
)
|
||||
from models.sync_session import SyncSession, SyncSessionStatus # noqa: E402
|
||||
@@ -77,6 +78,54 @@ from models.user import Role, User # noqa: E402
|
||||
# Static data pools used to fabricate believable metadata.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
# Soundtrack tags. Track titles are generic enough to sit under any game;
|
||||
# composers are fabricated so no real person is attributed to fake data.
|
||||
TRACK_TITLES = [
|
||||
"Title Screen",
|
||||
"Opening",
|
||||
"Main Theme",
|
||||
"Overworld",
|
||||
"Field",
|
||||
"Town",
|
||||
"Cave",
|
||||
"Underwater",
|
||||
"Battle",
|
||||
"Boss Battle",
|
||||
"Final Boss",
|
||||
"Victory",
|
||||
"Game Over",
|
||||
"Shop",
|
||||
"Character Select",
|
||||
"Stage 1",
|
||||
"Stage 2",
|
||||
"Stage 3",
|
||||
"Credits",
|
||||
"Ending",
|
||||
]
|
||||
|
||||
COMPOSERS = [
|
||||
"A. Brightwater",
|
||||
"H. Vance",
|
||||
"K. Solberg",
|
||||
"M. Ferreira",
|
||||
"N. Okabe",
|
||||
"R. Lindqvist",
|
||||
"S. Delacroix",
|
||||
"T. Mbeki",
|
||||
"V. Antonov",
|
||||
"Y. Castellanos",
|
||||
]
|
||||
|
||||
TRACK_GENRES = [
|
||||
"Chiptune",
|
||||
"Orchestral",
|
||||
"Ambient",
|
||||
"Rock",
|
||||
"Jazz",
|
||||
"Electronic",
|
||||
"Synthwave",
|
||||
]
|
||||
|
||||
TITLE_PREFIXES = [
|
||||
"Super",
|
||||
"Legend of",
|
||||
@@ -665,12 +714,19 @@ def rand_past(rng: random.Random, now: datetime, max_days: int = 730) -> datetim
|
||||
return now - timedelta(days=rng.randint(0, max_days), seconds=rng.randint(0, 86400))
|
||||
|
||||
|
||||
def bulk_insert(conn, model, rows: list[dict[str, Any]], chunk: int = 5000) -> None:
|
||||
def bulk_insert(conn, model, rows: list[dict[str, Any]], chunk: int = 1000) -> None:
|
||||
"""Insert rows as multi-VALUES statements.
|
||||
|
||||
Not `executemany`: MariaDB Connector/Python's bulk path silently drops all
|
||||
but the first row when a column mixes NULL and non-NULL across the batch,
|
||||
which most of these tables do (optional provider ids, hashes, covers).
|
||||
One statement per chunk keeps the speed without that failure mode.
|
||||
"""
|
||||
if not rows:
|
||||
return
|
||||
table = model.__table__
|
||||
for i in range(0, len(rows), chunk):
|
||||
conn.execute(table.insert(), rows[i : i + chunk])
|
||||
conn.execute(table.insert().values(rows[i : i + chunk]))
|
||||
|
||||
|
||||
def main() -> int:
|
||||
@@ -698,6 +754,18 @@ def main() -> int:
|
||||
default=40,
|
||||
help="Number of user collections (default: 40)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--soundtrack-share",
|
||||
type=float,
|
||||
default=0.08,
|
||||
help="Fraction of roms that get a soundtrack (default: 0.08)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--tracks-per-soundtrack",
|
||||
type=int,
|
||||
default=12,
|
||||
help="Upper bound on tracks per soundtracked rom (default: 12)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--play-sessions",
|
||||
type=int,
|
||||
@@ -807,10 +875,14 @@ def main() -> int:
|
||||
ids = Ids(starts)
|
||||
|
||||
counts: dict[str, int] = {k: 0 for k in id_tables}
|
||||
counts.update({"devices": 0, "collections_roms": 0, "device_save_sync": 0})
|
||||
counts.update(
|
||||
{"devices": 0, "collections_roms": 0, "device_save_sync": 0, "track_meta": 0}
|
||||
)
|
||||
# Tracks the last standalone rom per platform so a fraction of later roms
|
||||
# can reuse its igdb_id, surfacing them as regional siblings via the view.
|
||||
sibling_seed: dict[int, dict[str, Any]] = {}
|
||||
# Guards the unique (platform_id, fs_name) index across every batch.
|
||||
fs_names_by_platform: dict[int, set[str]] = {}
|
||||
|
||||
# ----------------------------- platforms -------------------------------
|
||||
platform_rows = []
|
||||
@@ -970,6 +1042,7 @@ def main() -> int:
|
||||
for batch_start in range(0, args.roms, args.batch_size):
|
||||
batch_end = min(batch_start + args.batch_size, args.roms)
|
||||
rom_rows, file_rows, ru_rows = [], [], []
|
||||
track_rows: list[dict[str, Any]] = []
|
||||
save_rows, state_rows, shot_rows, note_rows = [], [], [], []
|
||||
dss_rows: list[dict[str, Any]] = []
|
||||
|
||||
@@ -996,6 +1069,15 @@ def main() -> int:
|
||||
if f["revision"]:
|
||||
tags += f" ({f['revision']})"
|
||||
fs_name = f"{f['title']}{tags}.{ext}"[:445]
|
||||
# `roms` is uniquely indexed on (platform_id, fs_name) and the title
|
||||
# pools are small enough to collide, so disambiguate repeats.
|
||||
used_names = fs_names_by_platform.setdefault(platform["id"], set())
|
||||
if fs_name in used_names:
|
||||
dedupe = 2
|
||||
while f"{f['title']}{tags} (v{dedupe}).{ext}"[:445] in used_names:
|
||||
dedupe += 1
|
||||
fs_name = f"{f['title']}{tags} (v{dedupe}).{ext}"[:445]
|
||||
used_names.add(fs_name)
|
||||
parts = compute_file_name_parts(fs_name)
|
||||
multi_disc = rng.random() < 0.08
|
||||
size = rng.randint(256 * 1024, 8 * 1024 * 1024 * 1024)
|
||||
@@ -1130,6 +1212,58 @@ def main() -> int:
|
||||
"updated_at": created,
|
||||
}
|
||||
)
|
||||
# Soundtrack: a share of roms ship tagged audio next to the game,
|
||||
# which is what the /api/music endpoints and the Jukebox read.
|
||||
if rng.random() < args.soundtrack_share:
|
||||
album = f"{f['title']} Original Soundtrack"
|
||||
composer = rng.choice(COMPOSERS)
|
||||
track_genre = rng.choice(TRACK_GENRES)
|
||||
year = f.get("year")
|
||||
n_tracks = rng.randint(3, max(3, args.tracks_per_soundtrack))
|
||||
for number, title in enumerate(
|
||||
rng.sample(TRACK_TITLES, k=min(n_tracks, len(TRACK_TITLES))),
|
||||
start=1,
|
||||
):
|
||||
fid = ids.take("rom_files")
|
||||
file_rows.append(
|
||||
{
|
||||
"id": fid,
|
||||
"rom_id": rid,
|
||||
"file_name": f"{number:02d} - {title}.mp3",
|
||||
"file_path": f"{platform['slug']}/roms/{f['slug']}/soundtrack",
|
||||
"file_size_bytes": rng.randint(1_500_000, 9_000_000),
|
||||
"last_modified": created.timestamp(),
|
||||
"crc_hash": None,
|
||||
"md5_hash": None,
|
||||
"sha1_hash": None,
|
||||
"ra_hash": None,
|
||||
"chd_sha1_hash": None,
|
||||
"archive_members": None,
|
||||
"category": RomFileCategory.SOUNDTRACK,
|
||||
"missing_from_fs": False,
|
||||
"created_at": created,
|
||||
"updated_at": created,
|
||||
}
|
||||
)
|
||||
track_rows.append(
|
||||
{
|
||||
"rom_file_id": fid,
|
||||
"rom_id": rid,
|
||||
"title": title,
|
||||
"artist": composer,
|
||||
"album": album,
|
||||
"genre": track_genre,
|
||||
"year": year,
|
||||
"track": number,
|
||||
"disc": 1,
|
||||
"duration_seconds": float(rng.randint(45, 320)),
|
||||
"has_embedded_cover": rng.random() < 0.3,
|
||||
"cover_path": None,
|
||||
"created_at": created,
|
||||
"updated_at": created,
|
||||
}
|
||||
)
|
||||
|
||||
if rng.random() < 0.15:
|
||||
fid = ids.take("rom_files")
|
||||
man_name = f"{f['title']} (Manual).pdf"
|
||||
@@ -1303,6 +1437,7 @@ def main() -> int:
|
||||
with sync_engine.begin() as conn:
|
||||
bulk_insert(conn, Rom, rom_rows)
|
||||
bulk_insert(conn, RomFile, file_rows)
|
||||
bulk_insert(conn, TrackMeta, track_rows)
|
||||
bulk_insert(conn, RomUser, ru_rows)
|
||||
bulk_insert(conn, Save, save_rows)
|
||||
bulk_insert(conn, State, state_rows)
|
||||
@@ -1312,6 +1447,7 @@ def main() -> int:
|
||||
|
||||
counts["roms"] += len(rom_rows)
|
||||
counts["rom_files"] += len(file_rows)
|
||||
counts["track_meta"] += len(track_rows)
|
||||
counts["rom_user"] += len(ru_rows)
|
||||
counts["saves"] += len(save_rows)
|
||||
counts["states"] += len(state_rows)
|
||||
@@ -1479,6 +1615,7 @@ def _wipe(conn) -> None:
|
||||
"screenshots",
|
||||
"states",
|
||||
"saves",
|
||||
"track_meta",
|
||||
"rom_files",
|
||||
"roms",
|
||||
"firmware",
|
||||
|
||||
@@ -1,125 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Seed a small soundtrack library so the jukebox can be exercised by hand.
|
||||
|
||||
Creates a few platforms, games (with game genres and release years) and
|
||||
soundtrack files carrying track metadata, which is what the /api/music
|
||||
endpoints and the v2 Jukebox read.
|
||||
|
||||
Run from the backend directory, pointed at a throwaway database:
|
||||
|
||||
DB_NAME=romm_dev uv run tools/seed_soundtracks.py
|
||||
|
||||
This is a TEST tool: never point it at a real library.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import random
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
|
||||
|
||||
from handler.database import ( # noqa: E402
|
||||
db_platform_handler,
|
||||
db_rom_handler,
|
||||
db_user_handler,
|
||||
)
|
||||
from models.platform import Platform # noqa: E402
|
||||
from models.rom import Rom, RomFile, RomFileCategory, TrackMeta # noqa: E402
|
||||
from models.user import Role # noqa: E402
|
||||
|
||||
PLATFORMS = [
|
||||
("genesis", "Sega Genesis"),
|
||||
("snes", "Super Nintendo"),
|
||||
("psx", "PlayStation"),
|
||||
]
|
||||
|
||||
GAMES = [
|
||||
("Sonic the Hedgehog", "genesis", 1991, ["Platform", "Action"], "Nakamura"),
|
||||
("Streets of Rage", "genesis", 1991, ["Beat 'em up"], "Koshiro"),
|
||||
("Chrono Trigger", "snes", 1995, ["Role-playing (RPG)"], "Mitsuda"),
|
||||
("Super Metroid", "snes", 1994, ["Platform", "Adventure"], "Yamamoto"),
|
||||
("Final Fantasy VII", "psx", 1997, ["Role-playing (RPG)"], "Uematsu"),
|
||||
("Castlevania SotN", "psx", 1997, ["Platform", "Adventure"], "Yamane"),
|
||||
]
|
||||
|
||||
TRACK_NAMES = [
|
||||
"Opening",
|
||||
"Main Theme",
|
||||
"Field",
|
||||
"Battle",
|
||||
"Boss",
|
||||
"Ending",
|
||||
"Credits",
|
||||
]
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument(
|
||||
"--tracks-per-game", type=int, default=5, help="Soundtrack files per game."
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
rng = random.Random(1991)
|
||||
users = db_user_handler.get_users()
|
||||
admin = next((u for u in users if u.role == Role.ADMIN), None) or next(
|
||||
iter(users), None
|
||||
)
|
||||
if admin is None:
|
||||
raise SystemExit("No users found — create one before seeding.")
|
||||
|
||||
by_slug: dict[str, Platform] = {}
|
||||
for slug, name in PLATFORMS:
|
||||
existing = db_platform_handler.get_platform_by_fs_slug(slug)
|
||||
by_slug[slug] = existing or db_platform_handler.add_platform(
|
||||
Platform(name=name, slug=slug, fs_slug=slug)
|
||||
)
|
||||
|
||||
created = 0
|
||||
for name, slug, year, genres, artist in GAMES:
|
||||
platform = by_slug[slug]
|
||||
rom = db_rom_handler.add_rom(
|
||||
Rom(
|
||||
platform_id=platform.id,
|
||||
name=name,
|
||||
slug=name.lower().replace(" ", "-"),
|
||||
fs_name=f"{name}.zip",
|
||||
fs_name_no_tags=name,
|
||||
fs_name_no_ext=name,
|
||||
fs_extension="zip",
|
||||
fs_path=f"{slug}/roms",
|
||||
manual_metadata={"genres": genres},
|
||||
)
|
||||
)
|
||||
db_rom_handler.add_rom_user(rom_id=rom.id, user_id=admin.id)
|
||||
for index in range(args.tracks_per_game):
|
||||
title = TRACK_NAMES[index % len(TRACK_NAMES)]
|
||||
db_rom_handler.add_rom_file(
|
||||
RomFile(
|
||||
rom_id=rom.id,
|
||||
file_name=f"{index + 1:02d} - {title}.mp3",
|
||||
file_path=f"{rom.fs_path}/{name}/soundtrack",
|
||||
file_size_bytes=rng.randint(2_000_000, 8_000_000),
|
||||
category=RomFileCategory.SOUNDTRACK,
|
||||
track_meta=TrackMeta(
|
||||
rom_id=rom.id,
|
||||
title=title,
|
||||
artist=artist,
|
||||
album=f"{name} OST",
|
||||
genre="Game",
|
||||
year=year,
|
||||
track=index + 1,
|
||||
duration_seconds=float(rng.randint(60, 240)),
|
||||
),
|
||||
)
|
||||
)
|
||||
created += 1
|
||||
|
||||
print(f"Seeded {len(GAMES)} games and {created} soundtrack tracks.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user