"""Convert AutoEQ to eqMac preset format."""

import json
import os
import shutil
import sys
from hashlib import sha1
from pathlib import Path
from typing import List

from git import Remote, Repo


def fetch_autoeq_results() -> Path:
    autoeq_git = "https://github.com/jaakkopasanen/AutoEq.git"

    autoeq_path = Path(__file__).with_name(".data") / "autoeq"
    autoeq_path_git = autoeq_path / ".git"

    try:
        assert autoeq_path_git.is_dir()

        repo = Repo(str(autoeq_path))
        assert len(repo.remotes) == 1

        origin: Remote = repo.remotes[0]
        print("Updating AutoEQ to origin/master...", file=sys.stderr)
        origin.fetch()
        repo.create_head("master", origin.refs.master)
        repo.heads.master.set_tracking_branch(origin.refs.master)
        repo.heads.master.checkout()
        repo.git.reset(str(origin), hard=True)

    except AssertionError:
        if autoeq_path.is_dir():
            autoeq_path.rmdir()
        else:
            autoeq_path.unlink(missing_ok=True)
        print(f"Cloning from {autoeq_git} (wait patiently)...", file=sys.stderr)
        Repo.clone_from(autoeq_git, str(autoeq_path))

    return autoeq_path


def find_devices(autoeq_path: Path):
    """Find and convert all FixedBandEQ files."""

    for dirpath, dirnames, filenames in os.walk(autoeq_path):
        for filename in filenames:
            if not filename.endswith("FixedBandEQ.txt"):
                continue
            yield Path(dirpath) / filename


def parse_fixedband_eq_file(autoeq_file: Path) -> List[dict]:
    with autoeq_file.open(mode="r") as f:
        preamp: float = 0
        bands: List[float] = []
        for line in f.readlines():
            parts = line.strip().split()
            if parts[0] == "Preamp:":
                preamp = float(parts[1])
            elif parts[0] == "Filter":
                bands.append(float(parts[8]))

    device_name = autoeq_file.parent.name
    device_id = sha1(device_name.encode()).hexdigest()
    return [
        {
            "name": device_name,
            "id": device_id,
            "isDefault": False,
            "gains": {
                "global": preamp,
                "bands": bands,
            },
        }
    ]


def main():
    autoeq_path = fetch_autoeq_results()
    results_path = Path(__file__).with_name("results")
    shutil.rmtree(results_path, ignore_errors=True)

    print(f"Converting AutoEQ presets to eqMac in {results_path}", file=sys.stderr)
    for autoeq_file in find_devices(autoeq_path):
        eqmac_preset = parse_fixedband_eq_file(autoeq_file)
        eqmac_preset_dir = results_path / eqmac_preset[0]["name"]
        eqmac_preset_file = eqmac_preset_dir / f"{eqmac_preset[0]['name']}.json"
        eqmac_preset_dir.mkdir(parents=True, exist_ok=True)
        with open(eqmac_preset_file, mode="w") as f:
            print(json.dumps(eqmac_preset), file=f)


if __name__ == "__main__":
    main()

"""Convert AutoEQ to eqMac preset format."""

import json
import os
import shutil
import sys
from hashlib import sha1
from pathlib import Path
from typing import List

from git import Remote, Repo


def fetch_autoeq_results() -> Path:
    autoeq_git = "https://github.com/jaakkopasanen/AutoEq.git"

    autoeq_path = Path(__file__).with_name(".data") / "autoeq"
    autoeq_path_git = autoeq_path / ".git"

    try:
        assert autoeq_path_git.is_dir()

        repo = Repo(str(autoeq_path))
        assert len(repo.remotes) == 1

        origin: Remote = repo.remotes[0]
        print("Updating AutoEQ to origin/master...", file=sys.stderr)
        origin.fetch()
        repo.create_head("master", origin.refs.master)
        repo.heads.master.set_tracking_branch(origin.refs.master)
        repo.heads.master.checkout()
        repo.git.reset(str(origin), hard=True)

    except AssertionError:
        if autoeq_path.is_dir():
            autoeq_path.rmdir()
        else:
            autoeq_path.unlink(missing_ok=True)
        print(f"Cloning from {autoeq_git} (wait patiently)...", file=sys.stderr)
        Repo.clone_from(autoeq_git, str(autoeq_path))

    return autoeq_path


def find_devices(autoeq_path: Path):
    """Find and convert all FixedBandEQ files."""

    for dirpath, dirnames, filenames in os.walk(autoeq_path):
        for filename in filenames:
            if not filename.endswith("FixedBandEQ.txt"):
                continue
            yield Path(dirpath) / filename


def parse_fixedband_eq_file(autoeq_file: Path) -> List[dict]:
    with autoeq_file.open(mode="r") as f:
        preamp: float = 0
        bands: List[float] = []
        for line in f.readlines():
            parts = line.strip().split()
            if parts[0] == "Preamp:":
                preamp = float(parts[1])
            elif parts[0] == "Filter":
                bands.append(float(parts[8]))

    device_name = autoeq_file.parent.name
    device_id = sha1(device_name.encode()).hexdigest()
    return [
        {
            "name": device_name,
            "id": device_id,
            "isDefault": False,
            "gains": {
                "global": preamp,
                "bands": bands,
            },
        }
    ]


def main():
    autoeq_path = fetch_autoeq_results()
    results_path = Path(__file__).with_name("results")
    shutil.rmtree(results_path, ignore_errors=True)

    print(f"Converting AutoEQ presets to eqMac in {results_path}", file=sys.stderr)
    for autoeq_file in find_devices(autoeq_path):
        eqmac_preset = parse_fixedband_eq_file(autoeq_file)
        eqmac_preset_dir = results_path / eqmac_preset[0]["name"]
        eqmac_preset_file = eqmac_preset_dir / f"{eqmac_preset[0]['name']}.json"
        eqmac_preset_dir.mkdir(parents=True, exist_ok=True)
        with open(eqmac_preset_file, mode="w") as f:
            print(json.dumps(eqmac_preset), file=f)


if __name__ == "__main__":
    main()

Convert AutoEQ to eqMac preset format. Find and convert all FixedBandEQ files.