diff --git a/karaokatalog/Song.py b/karaokatalog/Song.py index 8b7515f..1abc90f 100644 --- a/karaokatalog/Song.py +++ b/karaokatalog/Song.py @@ -5,6 +5,8 @@ from dataclasses import dataclass from pathlib import Path from typing import Self +from karaokatalog.parse_song_txt import parse_song_txt + type Title = str type Artist = str @@ -43,8 +45,7 @@ class Song: @classmethod def from_song_txt(cls, song_txt: Path) -> Self | None: - with song_txt.open(encoding="utf-8", errors="ignore") as f: - tags = dict(_parse_tag_line(line) for line in f if line.startswith("#")) + tags = parse_song_txt(song_txt) title = tags.get("TITLE") artist = tags.get("ARTIST") @@ -65,26 +66,9 @@ class Song: song_txt=song_txt, ) - -def _parse_tag_line(tag_line: str) -> tuple[str, str | None]: - """ - Parse a tag line of the format: - - #KEY:Value - - or - - #KEY: - - Returns a tuple of (key, value), where the value might be None. - """ - - key_and_potentially_value = tuple( - tag_line.strip().removeprefix("#").split(":", maxsplit=1) - ) - - return ( - key_and_potentially_value - if len(key_and_potentially_value) == 2 - else (key_and_potentially_value[0], None) - ) + def as_dict(self) -> dict[str, str]: + return { + "title": self.title, + "artist": self.artist, + # TODO More fields + } diff --git a/karaokatalog/parse_song_txt.py b/karaokatalog/parse_song_txt.py new file mode 100644 index 0000000..edb2839 --- /dev/null +++ b/karaokatalog/parse_song_txt.py @@ -0,0 +1,33 @@ +from pathlib import Path +from typing import Any + + +def _parse_tag_line(tag_line: str) -> tuple[str, str | None]: + """ + Parse a tag line of the format: + + #KEY:Value + + or + + #KEY: + + Returns a tuple of (key, value), where the value might be None. + """ + + key_and_potentially_value = tuple( + tag_line.strip().removeprefix("#").split(":", maxsplit=1) + ) + + return ( + key_and_potentially_value + if len(key_and_potentially_value) == 2 + else (key_and_potentially_value[0], None) + ) + + +def parse_song_txt(song_txt: Path) -> dict[str, Any]: + with song_txt.open(encoding="utf-8", errors="ignore") as f: + tags = dict(_parse_tag_line(line) for line in f if line.startswith("#")) + + return tags