spotify-genres/genres/util.py
2023-11-14 13:30:44 +01:00

50 lines
1.4 KiB
Python

import os
import sys
import yaml
from pathlib import Path
from typing import Dict
import model
GENRE_DIR = Path(os.path.dirname(os.path.abspath(__file__)))
GENRE_FILE = GENRE_DIR / "everynoise_genres.json"
METADATA_DIR = GENRE_DIR / ".." / "metadata"
TRANSLATION_DIR = GENRE_DIR / ".." / "translations"
TRANSLATION_FILE = TRANSLATION_DIR / "_main.json"
TRANSLATION_FILE_EN = TRANSLATION_DIR / "en.json"
SCHEMA_DIR = GENRE_DIR / ".." / "schema"
SCHEMA_TREE = SCHEMA_DIR / "genre_tree.json"
SCHEMA_DB = SCHEMA_DIR / "genre_db.json"
def remove_prefix(s: str, prefix: str) -> str:
if s.startswith(prefix):
return s[len(prefix):]
else:
raise Exception(f"{s} does not start with {prefix}")
def read_meta() -> Dict[str, model.GenreMetadata]:
metadata = dict()
for filename in os.listdir(METADATA_DIR):
md_path = METADATA_DIR / filename
with md_path.open("r") as f:
data = yaml.safe_load(f)
stored_genres = model.load_genre_dict(data)
metadata.update(stored_genres)
print(f"{len(metadata)} genres loaded", file=sys.stderr)
return metadata
def read_meta_n(n: int) -> Dict[str, model.GenreMetadata]:
"""Read metadata from a specific file (numbers 0-26)"""
if n == 0:
md_path = METADATA_DIR / "0.yaml"
else:
md_path = METADATA_DIR / f"{chr(96 + n)}.yaml"
with md_path.open("r") as f:
data = yaml.safe_load(f)
return model.load_genre_dict(data)