File size: 5,640 Bytes
25e4412
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
"""Job worker: `python -m stemdeck.worker <job_id>`. Runs in its own process so a crash, an

out-of-memory error or a cancel (process kill) can never take the API server down."""

from __future__ import annotations

import logging
import os
import sys

from sqlmodel import Session

from stemdeck.audio_io import AudioError
from stemdeck.db import get_engine
from stemdeck.gpulock import GpuLock
from stemdeck.logging_setup import setup_logging
from stemdeck.models import Job, Song, utcnow
from stemdeck.pipeline.separator import SeparationError
from stemdeck.settings import details_hint, get_config, get_settings
from stemdeck.youtube import YouTubeError

log = logging.getLogger("stemdeck.worker")


def _prepare_environment() -> None:
    import truststore

    truststore.inject_into_ssl()  # verify downloads with the OS trust store
    settings = get_settings()
    os.environ.setdefault("TORCH_HOME", str(settings.models_dir / "torch"))
    # Only move the download cache: HF_HOME would also move the token that `hf auth login` writes.
    os.environ.setdefault("HF_HUB_CACHE", str(settings.models_dir / "huggingface"))


STARTABLE = frozenset({"queued", "running"})  # 'running' = claimed by the job runner just before launch
RUNNING = frozenset({"running"})


def _mark(job_id: str, only_if: frozenset[str], **fields: object) -> Job | None:
    """Update the job only while its status is one of `only_if`, so a job that was cancelled (or marked

    interrupted) meanwhile is never brought back to life or overwritten. Returns None when nothing was written."""
    with Session(get_engine()) as session:
        job = session.get(Job, job_id)
        if job is None or job.status not in only_if:
            return None
        for key, value in fields.items():
            setattr(job, key, value)
        session.add(job)
        session.commit()
        session.refresh(job)
        return job


def _fail(job_id: str, message: str) -> None:
    job = _mark(job_id, RUNNING, status="failed", stage="failed", error=message, finished_at=utcnow(), eta_sec=None)
    if job is not None and job.type == "split":
        with Session(get_engine()) as session:
            song = session.get(Song, job.song_id)
            if song is not None:
                song.status = "failed"
                session.add(song)
                session.commit()


def run(job_id: str) -> int:
    from stemdeck.device import detect_in_process
    from stemdeck.pipeline.extract import run_extract
    from stemdeck.pipeline.split import JobContext, run_split

    job = _mark(job_id, STARTABLE, status="running", started_at=utcnow(), pid=os.getpid(), error=None)
    if job is None:
        log.error("job %s not found, or no longer waiting to run (cancelled or failed meanwhile)", job_id)
        return 2
    try:
        device = detect_in_process()
        ctx = JobContext(job_id=job.id, song_id=job.song_id, settings=get_settings(), config=get_config(),
                         device=device)
        log.info("job %s (%s) on %s, params=%s", job.id, job.type, device, job.params)
        if job.type == "split":
            with Session(get_engine()) as session:
                song = session.get(Song, job.song_id)
                if song is not None:
                    song.status = "processing"
                    session.add(song)
                    session.commit()
            source_url = job.params.get("source_url")
            run_split(ctx, str(job.params.get("quality", "fast")), str(source_url) if source_url else None)
        elif job.type == "extract":
            run_extract(ctx, str(job.params["extractor"]), job.params.get("source_stem"),  # type: ignore[arg-type]
                        job.params.get("prompt"))  # type: ignore[arg-type]
        else:
            raise SeparationError(f"Unknown job type {job.type}")
    except (AudioError, SeparationError, YouTubeError) as exc:
        log.warning("job %s failed: %s", job_id, exc)
        _fail(job_id, str(exc))
        return 1
    except Exception as exc:  # noqa: BLE001 - last-resort handler; details go to the log
        log.exception("job %s crashed", job_id)
        _fail(job_id, f"Something went wrong while processing ({type(exc).__name__}). You can retry. "
                      f"{details_hint('worker.log')}")
        return 1
    if _mark(job_id, RUNNING, status="done", stage="done", progress=1.0, stage_progress=1.0, eta_sec=0.0,
             finished_at=utcnow(), message=None) is None:
        log.info("job %s finished but was cancelled meanwhile; keeping the cancelled status", job_id)
    return 0


def main() -> None:
    setup_logging("worker.log")
    _prepare_environment()
    if len(sys.argv) != 2:
        raise SystemExit("usage: python -m stemdeck.worker <job_id>")
    job_id = sys.argv[1]
    # Another StemDeck server on this computer (your own app next to the public site) may be using the GPU.
    # The lock is released by the OS when this process exits.
    GpuLock(get_settings().gpu_lock_file).acquire(on_wait=lambda: _mark(
        job_id, STARTABLE, message="Waiting for the GPU: another song on this computer is being processed."))
    code = run(job_id)
    # The outcome is already in the database. Exit hard: after a CUDA error (e.g. out of memory) the CUDA
    # context can be "sticky" and normal interpreter shutdown hangs forever in driver teardown.
    logging.shutdown()
    sys.stdout.flush()
    sys.stderr.flush()
    os._exit(code)


if __name__ == "__main__":
    main()