2Btainment commited on
Commit
457e012
·
verified ·
1 Parent(s): 068bbb5

fix(health): wakeable worker probe, live model status, registry/README

Browse files

- Add studio/adapters/health.py (SLEEPING/BUILDING wakeable)
- Wire HealthCache into minimax/2baudio/stable-audio/audioldm2/ace-step
- Live UI model status + dropdown suffixes via studio/model_status.py
- Refresh schemas/model-registry.yaml header; expand Space README
- Drop committed .pytest_cache/.ruff_cache/egg-info artifacts

README.md CHANGED
@@ -21,33 +21,34 @@ Gradio-Shell für **Generieren → Hören → Rüberschalten → Mastern**.
21
  | MiniMax Music 3 | `MiniMaxAI/MiniMax-Music3` | Vocals & strukturierte Lyrics, bis 180 s |
22
  | 2B Audio Small | `2Btainment/2baudio` | instrumental bevorzugt, bis 20 s |
23
  | 2B Audio Medium | `2Btainment/2baudio` | instrumental bevorzugt, bis 30 s |
24
- | Stable Audio Open | `2Btainment/stable-audio-open` | instrumental, bis 47 s |
25
- | AudioLDM 2 | `2Btainment/audioldm2` | instrumental, bis 20 s |
 
26
 
27
- Die Shell läuft als leichter HF-Space; die Modelle laufen als getrennte ZeroGPU-Worker.
28
- Nicht erreichbare Worker werden im Dropdown automatisch als nicht verfügbar markiert.
29
 
30
  ## Master-Ebene (ONUS)
31
 
32
- - **Lokal:** voller Funktionsumfang inkl. ONUS-Mastering (Purity, Profile, A/B).
33
- - **HF-Space:** Master-Ebene ist deaktiviert (`STUDIO_SPACE_MODE` wird automatisch
34
- gesetzt, sobald `HF_SPACE_ID` existiert). ONUS läuft nur auf dem Studio-Rechner.
35
 
36
  ## Secrets
37
 
38
  | Name | Wert |
39
  |---|---|
40
- | `HF_TOKEN` | Hugging-Face-Token (für private/gated Worker) |
41
  | `TWO_B_AUDIO_SPACE_ID` | optional, Default `2Btainment/2baudio` |
42
  | `MINIMAX_SPACE_ID` | optional, Default `MiniMaxAI/MiniMax-Music3` |
43
  | `STABLE_AUDIO_SPACE_ID` | optional, Default `2Btainment/stable-audio-open` |
44
  | `AUDIOLDM2_SPACE_ID` | optional, Default `2Btainment/audioldm2` |
45
- | `GEMINI_API_KEY` | optional, aktiviert den LLM-Agenten (Producer + Master) |
46
- | `AGENT_MODEL_ID` | optional, HF-Inference-Modell für den Producer-Agenten |
 
47
 
48
  ## Lokal starten
49
 
50
  ```bash
51
  uv sync --extra dev
52
  STUDIO_PORT=7861 uv run python app.py
53
- ```
 
21
  | MiniMax Music 3 | `MiniMaxAI/MiniMax-Music3` | Vocals & strukturierte Lyrics, bis 180 s |
22
  | 2B Audio Small | `2Btainment/2baudio` | instrumental bevorzugt, bis 20 s |
23
  | 2B Audio Medium | `2Btainment/2baudio` | instrumental bevorzugt, bis 30 s |
24
+ | Stable Audio Open | `2Btainment/stable-audio-open` | instrumental, bis 47 s (**privat** → `HF_TOKEN`) |
25
+ | AudioLDM 2 | `2Btainment/audioldm2` | instrumental, bis 20 s (**privat** → `HF_TOKEN`) |
26
+ | ACE-Step | `2Btainment/ace-step` | Vocals/Lyrics, bis 600 s |
27
 
28
+ Die Shell läuft als leichter HF-Space (`cpu-basic`); die Modelle laufen als getrennte ZeroGPU-Worker.
29
+ Schlafende Worker werden beim Generate geweckt. Nicht erreichbare/defekte Worker erscheinen im Dropdown als Status-Suffix.
30
 
31
  ## Master-Ebene (ONUS)
32
 
33
+ - **Lokal:** voller Funktionsumfang inkl. ONUS-Mastering.
34
+ - **HF-Space:** Master-Ebene deaktiviert (`STUDIO_SPACE_MODE=1` automatisch bei `HF_SPACE_ID`).
 
35
 
36
  ## Secrets
37
 
38
  | Name | Wert |
39
  |---|---|
40
+ | `HF_TOKEN` | Pflicht für private Worker (stable-audio-open, audioldm2) und empfohlen allgemein |
41
  | `TWO_B_AUDIO_SPACE_ID` | optional, Default `2Btainment/2baudio` |
42
  | `MINIMAX_SPACE_ID` | optional, Default `MiniMaxAI/MiniMax-Music3` |
43
  | `STABLE_AUDIO_SPACE_ID` | optional, Default `2Btainment/stable-audio-open` |
44
  | `AUDIOLDM2_SPACE_ID` | optional, Default `2Btainment/audioldm2` |
45
+ | `ACE_STEP_SPACE_ID` | optional, Default `2Btainment/ace-step` |
46
+ | `GEMINI_API_KEY` | optional, Producer-Agent |
47
+ | `AGENT_MODEL_ID` | optional, HF-Inference-Modell für den Agenten |
48
 
49
  ## Lokal starten
50
 
51
  ```bash
52
  uv sync --extra dev
53
  STUDIO_PORT=7861 uv run python app.py
54
+ ```
schemas/model-registry.yaml CHANGED
@@ -1,13 +1,13 @@
1
- # 2B-Studio model registry — Entwurf, nicht produktiv verdrahtet.
2
- # UI: EINE flache Modelauswahl. group ist nur intern (welcher Worker).
3
 
4
  version: 1
5
- updated: 2026-08-24
6
 
7
  ui:
8
  control: single_dropdown
9
  label: Modelauswahl
10
- note: MiniMax steht in derselben Liste wie die 2baudio-Modelle.
11
 
12
  groups:
13
  minimax:
@@ -59,7 +59,7 @@ models:
59
 
60
  - id: 2b-musicgen-medium
61
  group: 2b-audio
62
- label: 2B Audio
63
  weights: facebook/musicgen-medium
64
  space_ref: 2Btainment/2baudio
65
  adapter: musicgen_2baudio
 
1
+ # 2B-Studio model registry — PRODUKTIV verdrahtet über studio.registry.load_registry().
2
+ # UI: EINE flache Modelauswahl. group steuert nur den Adapter/Worker.
3
 
4
  version: 1
5
+ updated: 2026-09-30
6
 
7
  ui:
8
  control: single_dropdown
9
  label: Modelauswahl
10
+ note: MiniMax, 2B Audio, Stable Audio, AudioLDM2 und ACE-Step in einer Liste.
11
 
12
  groups:
13
  minimax:
 
59
 
60
  - id: 2b-musicgen-medium
61
  group: 2b-audio
62
+ label: 2B Audio Medium
63
  weights: facebook/musicgen-medium
64
  space_ref: 2Btainment/2baudio
65
  adapter: musicgen_2baudio
studio/adapters/ace_step.py CHANGED
@@ -1,9 +1,7 @@
1
  from __future__ import annotations
2
 
3
- import json
4
  import os
5
  import time
6
- import urllib.request
7
  from collections.abc import Callable
8
  from pathlib import Path
9
  from typing import Any
@@ -17,7 +15,7 @@ from studio.adapters.base import (
17
  WorkerTimeoutError,
18
  WorkerUnavailableError,
19
  )
20
- from studio.adapters.minimax import huggingface_token
21
  from studio.audio_analysis import analyze_wav
22
  from studio.audio_io import ensure_browser_wav, resolve_audio_path
23
  from studio.registry import ModelEntry
@@ -47,7 +45,7 @@ class AceStepAdapter:
47
  self._client_factory = client_factory
48
  self._healthcheck = healthcheck
49
  self._client: Any | None = None
50
- self._health_cache: tuple[float, bool] | None = None
51
 
52
  @property
53
  def model_ids(self) -> tuple[str, ...]:
@@ -71,30 +69,16 @@ class AceStepAdapter:
71
  def health(self) -> bool:
72
  if self._healthcheck is not None:
73
  return self._healthcheck()
74
- now = time.monotonic()
75
- if self._health_cache and now - self._health_cache[0] < 30:
76
- return self._health_cache[1]
77
- try:
78
- url = f"https://huggingface.co/api/spaces/{self.space_id}"
79
- headers = {"User-Agent": "2B-Studio/0.1"}
80
- token = huggingface_token()
81
- if token:
82
- headers["Authorization"] = f"Bearer {token}"
83
- request = urllib.request.Request(url, headers=headers)
84
- with urllib.request.urlopen(request, timeout=10) as response:
85
- payload = json.loads(response.read().decode("utf-8"))
86
- healthy = payload.get("runtime", {}).get("stage") == "RUNNING"
87
- except Exception:
88
- healthy = False
89
- self._health_cache = (now, healthy)
90
- return healthy
91
 
92
  def generate(self, request: GenerateRequest) -> Track:
93
  if request.model_id not in self._models:
94
  raise ValueError(f"AceStepAdapter unterstützt {request.model_id!r} nicht.")
95
- if not self.health():
 
96
  raise WorkerUnavailableError(
97
- f"Der Worker {self.space_id} ist momentan nicht erreichbar."
 
98
  )
99
 
100
  seed = int(request.advanced.get("seed", 0))
 
1
  from __future__ import annotations
2
 
 
3
  import os
4
  import time
 
5
  from collections.abc import Callable
6
  from pathlib import Path
7
  from typing import Any
 
15
  WorkerTimeoutError,
16
  WorkerUnavailableError,
17
  )
18
+ from studio.adapters.health import HealthCache, huggingface_token
19
  from studio.audio_analysis import analyze_wav
20
  from studio.audio_io import ensure_browser_wav, resolve_audio_path
21
  from studio.registry import ModelEntry
 
45
  self._client_factory = client_factory
46
  self._healthcheck = healthcheck
47
  self._client: Any | None = None
48
+ self._health = HealthCache(ttl_s=30.0)
49
 
50
  @property
51
  def model_ids(self) -> tuple[str, ...]:
 
69
  def health(self) -> bool:
70
  if self._healthcheck is not None:
71
  return self._healthcheck()
72
+ return self._health.ok(self.space_id)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
 
74
  def generate(self, request: GenerateRequest) -> Track:
75
  if request.model_id not in self._models:
76
  raise ValueError(f"AceStepAdapter unterstützt {request.model_id!r} nicht.")
77
+ probe = self._health.get(self.space_id)
78
+ if not probe["ok"]:
79
  raise WorkerUnavailableError(
80
+ f"Worker {self.space_id} nicht bereit"
81
+ f" ({probe.get('label')}: {probe.get('error')})."
82
  )
83
 
84
  seed = int(request.advanced.get("seed", 0))
studio/adapters/audioldm2.py CHANGED
@@ -1,10 +1,8 @@
1
  from __future__ import annotations
2
 
3
- import json
4
  import os
5
  import random
6
  import time
7
- import urllib.request
8
  from collections.abc import Callable
9
  from pathlib import Path
10
  from typing import Any
@@ -18,7 +16,7 @@ from studio.adapters.base import (
18
  WorkerTimeoutError,
19
  WorkerUnavailableError,
20
  )
21
- from studio.adapters.minimax import huggingface_token
22
  from studio.audio_analysis import analyze_wav
23
  from studio.audio_io import ensure_browser_wav, resolve_audio_path
24
  from studio.registry import ModelEntry
@@ -50,7 +48,7 @@ class AudioLDM2Adapter:
50
  self._client_factory = client_factory
51
  self._healthcheck = healthcheck
52
  self._client: Any | None = None
53
- self._health_cache: tuple[float, bool] | None = None
54
 
55
  @property
56
  def model_ids(self) -> tuple[str, ...]:
@@ -74,30 +72,16 @@ class AudioLDM2Adapter:
74
  def health(self) -> bool:
75
  if self._healthcheck is not None:
76
  return self._healthcheck()
77
- now = time.monotonic()
78
- if self._health_cache and now - self._health_cache[0] < 30:
79
- return self._health_cache[1]
80
- try:
81
- url = f"https://huggingface.co/api/spaces/{self.space_id}"
82
- headers = {"User-Agent": "2B-Studio/0.1"}
83
- token = huggingface_token()
84
- if token:
85
- headers["Authorization"] = f"Bearer {token}"
86
- request = urllib.request.Request(url, headers=headers)
87
- with urllib.request.urlopen(request, timeout=10) as response:
88
- payload = json.loads(response.read().decode("utf-8"))
89
- healthy = payload.get("runtime", {}).get("stage") == "RUNNING"
90
- except Exception:
91
- healthy = False
92
- self._health_cache = (now, healthy)
93
- return healthy
94
 
95
  def generate(self, request: GenerateRequest) -> Track:
96
  if request.model_id not in self._models:
97
  raise ValueError(f"AudioLDM2Adapter unterstützt {request.model_id!r} nicht.")
98
- if not self.health():
 
99
  raise WorkerUnavailableError(
100
- f"Der Worker {self.space_id} ist momentan nicht erreichbar."
 
101
  )
102
 
103
  seed = int(request.advanced.get("seed", 0))
 
1
  from __future__ import annotations
2
 
 
3
  import os
4
  import random
5
  import time
 
6
  from collections.abc import Callable
7
  from pathlib import Path
8
  from typing import Any
 
16
  WorkerTimeoutError,
17
  WorkerUnavailableError,
18
  )
19
+ from studio.adapters.health import HealthCache, huggingface_token
20
  from studio.audio_analysis import analyze_wav
21
  from studio.audio_io import ensure_browser_wav, resolve_audio_path
22
  from studio.registry import ModelEntry
 
48
  self._client_factory = client_factory
49
  self._healthcheck = healthcheck
50
  self._client: Any | None = None
51
+ self._health = HealthCache(ttl_s=30.0)
52
 
53
  @property
54
  def model_ids(self) -> tuple[str, ...]:
 
72
  def health(self) -> bool:
73
  if self._healthcheck is not None:
74
  return self._healthcheck()
75
+ return self._health.ok(self.space_id)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
 
77
  def generate(self, request: GenerateRequest) -> Track:
78
  if request.model_id not in self._models:
79
  raise ValueError(f"AudioLDM2Adapter unterstützt {request.model_id!r} nicht.")
80
+ probe = self._health.get(self.space_id)
81
+ if not probe["ok"]:
82
  raise WorkerUnavailableError(
83
+ f"Worker {self.space_id} nicht bereit"
84
+ f" ({probe.get('label')}: {probe.get('error')})."
85
  )
86
 
87
  seed = int(request.advanced.get("seed", 0))
studio/adapters/health.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared Space worker health for 2B-Studio adapters.
2
+
3
+ Copy to: studio/adapters/health.py
4
+
5
+ Wakeable stages must count as healthy so the first Client.submit can cold-start
6
+ ZeroGPU workers. Only ERROR/RUNTIME_ERROR/missing should hard-fail before submit.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import os
12
+ import time
13
+ import urllib.error
14
+ import urllib.request
15
+ from typing import Any
16
+
17
+ # Stages where a subsequent gradio_client call is expected to succeed or wake the Space.
18
+ WAKEABLE = {
19
+ "RUNNING",
20
+ "SLEEPING",
21
+ "BUILDING",
22
+ "APP_STARTING",
23
+ "RUNTIME_STARTING",
24
+ "PAUSED", # some accounts; client may still resume
25
+ }
26
+
27
+ HARD_FAIL = {
28
+ "RUNTIME_ERROR",
29
+ "CONFIG_ERROR",
30
+ "NO_APP_FILE",
31
+ "BUILD_ERROR",
32
+ }
33
+
34
+
35
+ def huggingface_token() -> str | None:
36
+ env_token = os.environ.get("HF_TOKEN", "").strip()
37
+ if env_token:
38
+ return env_token
39
+ token_file = __import__("pathlib").Path.home() / ".cache" / "huggingface" / "token"
40
+ if token_file.is_file():
41
+ value = token_file.read_text(encoding="utf-8").strip()
42
+ return value or None
43
+ return None
44
+
45
+
46
+ def probe_space(space_id: str, *, timeout_s: float = 10.0) -> dict[str, Any]:
47
+ """Return structured health for UI + adapters."""
48
+ url = f"https://huggingface.co/api/spaces/{space_id}"
49
+ headers = {"User-Agent": "2B-Studio/0.2"}
50
+ token = huggingface_token()
51
+ if token:
52
+ headers["Authorization"] = f"Bearer {token}"
53
+ try:
54
+ request = urllib.request.Request(url, headers=headers)
55
+ with urllib.request.urlopen(request, timeout=timeout_s) as response:
56
+ payload = json.loads(response.read().decode("utf-8"))
57
+ except urllib.error.HTTPError as error:
58
+ return {
59
+ "ok": False,
60
+ "space_id": space_id,
61
+ "stage": None,
62
+ "label": "unauthorized" if error.code == 401 else f"http-{error.code}",
63
+ "wakeable": False,
64
+ "error": f"HTTP {error.code}",
65
+ }
66
+ except Exception as error: # noqa: BLE001
67
+ return {
68
+ "ok": False,
69
+ "space_id": space_id,
70
+ "stage": None,
71
+ "label": "unreachable",
72
+ "wakeable": False,
73
+ "error": str(error)[:160],
74
+ }
75
+
76
+ runtime = payload.get("runtime") or {}
77
+ stage = runtime.get("stage")
78
+ private = bool(payload.get("private"))
79
+ if stage in HARD_FAIL:
80
+ label = "broken"
81
+ ok = False
82
+ wakeable = False
83
+ elif stage in WAKEABLE:
84
+ label = "live" if stage == "RUNNING" else "sleeping"
85
+ ok = True
86
+ wakeable = True
87
+ elif stage is None and private and not token:
88
+ label = "private-needs-token"
89
+ ok = False
90
+ wakeable = False
91
+ else:
92
+ label = (stage or "unknown").lower()
93
+ ok = False
94
+ wakeable = False
95
+
96
+ return {
97
+ "ok": ok,
98
+ "space_id": space_id,
99
+ "stage": stage,
100
+ "label": label,
101
+ "wakeable": wakeable,
102
+ "private": private,
103
+ "hardware": (runtime.get("hardware") or {}).get("current"),
104
+ "error": None if ok else f"stage={stage}",
105
+ }
106
+
107
+
108
+ class HealthCache:
109
+ def __init__(self, ttl_s: float = 30.0) -> None:
110
+ self.ttl_s = ttl_s
111
+ self._cache: dict[str, tuple[float, dict[str, Any]]] = {}
112
+
113
+ def get(self, space_id: str) -> dict[str, Any]:
114
+ now = time.monotonic()
115
+ hit = self._cache.get(space_id)
116
+ if hit and now - hit[0] < self.ttl_s:
117
+ return hit[1]
118
+ result = probe_space(space_id)
119
+ self._cache[space_id] = (now, result)
120
+ return result
121
+
122
+ def ok(self, space_id: str) -> bool:
123
+ return bool(self.get(space_id).get("ok"))
studio/adapters/minimax.py CHANGED
@@ -1,9 +1,7 @@
1
  from __future__ import annotations
2
 
3
- import json
4
  import os
5
  import time
6
- import urllib.request
7
  from collections.abc import Callable
8
  from pathlib import Path
9
  from typing import Any
@@ -23,16 +21,7 @@ from studio.registry import ModelEntry
23
  from studio.state import Track
24
 
25
 
26
- def huggingface_token() -> str | None:
27
- env_token = os.environ.get("HF_TOKEN", "").strip()
28
- if env_token:
29
- return env_token
30
- token_file = Path.home() / ".cache" / "huggingface" / "token"
31
- if token_file.is_file():
32
- value = token_file.read_text(encoding="utf-8").strip()
33
- return value or None
34
- return None
35
-
36
 
37
  class MiniMaxAdapter:
38
  """Gradio client for MiniMax Music 3 via a configured Space worker."""
@@ -59,7 +48,7 @@ class MiniMaxAdapter:
59
  self._client_factory = client_factory
60
  self._healthcheck = healthcheck
61
  self._client: Any | None = None
62
- self._health_cache: tuple[float, bool] | None = None
63
 
64
  @property
65
  def model_ids(self) -> tuple[str, ...]:
@@ -87,24 +76,10 @@ class MiniMaxAdapter:
87
  def health(self) -> bool:
88
  if self._healthcheck is not None:
89
  return self._healthcheck()
90
- now = time.monotonic()
91
- if self._health_cache and now - self._health_cache[0] < 30:
92
- return self._health_cache[1]
93
  if not huggingface_token():
94
- self._health_cache = (now, False)
95
  return False
96
- try:
97
- url = f"https://huggingface.co/api/spaces/{self.space_id}"
98
- request = urllib.request.Request(url, headers={"User-Agent": "2B-Studio/0.1"})
99
- with urllib.request.urlopen(request, timeout=10) as response:
100
- payload = json.loads(response.read().decode("utf-8"))
101
- healthy = payload.get("runtime", {}).get("stage") == "RUNNING"
102
- except Exception:
103
- healthy = False
104
- self._health_cache = (now, healthy)
105
- return healthy
106
-
107
- @staticmethod
108
  def _studio_state(request: GenerateRequest) -> dict[str, Any]:
109
  instrumental = request.lyrics.strip().casefold() in {"", "[instrumental]"}
110
  studio = request.advanced.get("studio") if isinstance(request.advanced, dict) else {}
@@ -136,9 +111,11 @@ class MiniMaxAdapter:
136
  def generate(self, request: GenerateRequest) -> Track:
137
  if request.model_id not in self._models:
138
  raise ValueError(f"MiniMaxAdapter unterstützt {request.model_id!r} nicht.")
139
- if not self.health():
 
140
  raise WorkerUnavailableError(
141
- f"MiniMax-Worker {self.space_id} ist nicht bereit oder nicht authentifiziert."
 
142
  )
143
 
144
  seed = int(request.advanced.get("seed", 0))
 
1
  from __future__ import annotations
2
 
 
3
  import os
4
  import time
 
5
  from collections.abc import Callable
6
  from pathlib import Path
7
  from typing import Any
 
21
  from studio.state import Track
22
 
23
 
24
+ from studio.adapters.health import HealthCache, huggingface_token
 
 
 
 
 
 
 
 
 
25
 
26
  class MiniMaxAdapter:
27
  """Gradio client for MiniMax Music 3 via a configured Space worker."""
 
48
  self._client_factory = client_factory
49
  self._healthcheck = healthcheck
50
  self._client: Any | None = None
51
+ self._health = HealthCache(ttl_s=30.0)
52
 
53
  @property
54
  def model_ids(self) -> tuple[str, ...]:
 
76
  def health(self) -> bool:
77
  if self._healthcheck is not None:
78
  return self._healthcheck()
 
 
 
79
  if not huggingface_token():
 
80
  return False
81
+ return self._health.ok(self.space_id)
82
+
 
 
 
 
 
 
 
 
 
 
83
  def _studio_state(request: GenerateRequest) -> dict[str, Any]:
84
  instrumental = request.lyrics.strip().casefold() in {"", "[instrumental]"}
85
  studio = request.advanced.get("studio") if isinstance(request.advanced, dict) else {}
 
111
  def generate(self, request: GenerateRequest) -> Track:
112
  if request.model_id not in self._models:
113
  raise ValueError(f"MiniMaxAdapter unterstützt {request.model_id!r} nicht.")
114
+ probe = self._health.get(self.space_id)
115
+ if not huggingface_token() or not probe["ok"]:
116
  raise WorkerUnavailableError(
117
+ f"MiniMax-Worker {self.space_id} nicht bereit"
118
+ f" ({probe.get('label')}: {probe.get('error')})."
119
  )
120
 
121
  seed = int(request.advanced.get("seed", 0))
studio/adapters/stable_audio_open.py CHANGED
@@ -1,10 +1,8 @@
1
  from __future__ import annotations
2
 
3
- import json
4
  import os
5
  import random
6
  import time
7
- import urllib.request
8
  from collections.abc import Callable
9
  from pathlib import Path
10
  from typing import Any
@@ -18,7 +16,7 @@ from studio.adapters.base import (
18
  WorkerTimeoutError,
19
  WorkerUnavailableError,
20
  )
21
- from studio.adapters.minimax import huggingface_token
22
  from studio.audio_analysis import analyze_wav
23
  from studio.audio_io import ensure_browser_wav, resolve_audio_path
24
  from studio.registry import ModelEntry
@@ -50,7 +48,7 @@ class StableAudioOpenAdapter:
50
  self._client_factory = client_factory
51
  self._healthcheck = healthcheck
52
  self._client: Any | None = None
53
- self._health_cache: tuple[float, bool] | None = None
54
 
55
  @property
56
  def model_ids(self) -> tuple[str, ...]:
@@ -74,30 +72,16 @@ class StableAudioOpenAdapter:
74
  def health(self) -> bool:
75
  if self._healthcheck is not None:
76
  return self._healthcheck()
77
- now = time.monotonic()
78
- if self._health_cache and now - self._health_cache[0] < 30:
79
- return self._health_cache[1]
80
- try:
81
- url = f"https://huggingface.co/api/spaces/{self.space_id}"
82
- headers = {"User-Agent": "2B-Studio/0.1"}
83
- token = huggingface_token()
84
- if token:
85
- headers["Authorization"] = f"Bearer {token}"
86
- request = urllib.request.Request(url, headers=headers)
87
- with urllib.request.urlopen(request, timeout=10) as response:
88
- payload = json.loads(response.read().decode("utf-8"))
89
- healthy = payload.get("runtime", {}).get("stage") == "RUNNING"
90
- except Exception:
91
- healthy = False
92
- self._health_cache = (now, healthy)
93
- return healthy
94
 
95
  def generate(self, request: GenerateRequest) -> Track:
96
  if request.model_id not in self._models:
97
  raise ValueError(f"StableAudioOpenAdapter unterstützt {request.model_id!r} nicht.")
98
- if not self.health():
 
99
  raise WorkerUnavailableError(
100
- f"Der Worker {self.space_id} ist momentan nicht erreichbar."
 
101
  )
102
 
103
  seed = int(request.advanced.get("seed", 0))
 
1
  from __future__ import annotations
2
 
 
3
  import os
4
  import random
5
  import time
 
6
  from collections.abc import Callable
7
  from pathlib import Path
8
  from typing import Any
 
16
  WorkerTimeoutError,
17
  WorkerUnavailableError,
18
  )
19
+ from studio.adapters.health import HealthCache, huggingface_token
20
  from studio.audio_analysis import analyze_wav
21
  from studio.audio_io import ensure_browser_wav, resolve_audio_path
22
  from studio.registry import ModelEntry
 
48
  self._client_factory = client_factory
49
  self._healthcheck = healthcheck
50
  self._client: Any | None = None
51
+ self._health = HealthCache(ttl_s=30.0)
52
 
53
  @property
54
  def model_ids(self) -> tuple[str, ...]:
 
72
  def health(self) -> bool:
73
  if self._healthcheck is not None:
74
  return self._healthcheck()
75
+ return self._health.ok(self.space_id)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
 
77
  def generate(self, request: GenerateRequest) -> Track:
78
  if request.model_id not in self._models:
79
  raise ValueError(f"StableAudioOpenAdapter unterstützt {request.model_id!r} nicht.")
80
+ probe = self._health.get(self.space_id)
81
+ if not probe["ok"]:
82
  raise WorkerUnavailableError(
83
+ f"Worker {self.space_id} nicht bereit"
84
+ f" ({probe.get('label')}: {probe.get('error')})."
85
  )
86
 
87
  seed = int(request.advanced.get("seed", 0))
studio/adapters/two_b_audio.py CHANGED
@@ -4,7 +4,6 @@ import json
4
  import os
5
  import random
6
  import time
7
- import urllib.request
8
  from collections.abc import Callable
9
  from pathlib import Path
10
  from typing import Any
@@ -12,6 +11,7 @@ from uuid import uuid4
12
 
13
  from gradio_client import Client
14
 
 
15
  from studio.adapters.base import (
16
  DummyAudioError,
17
  GenerateRequest,
@@ -50,7 +50,7 @@ class TwoBAudioAdapter:
50
  self._client_factory = client_factory
51
  self._healthcheck = healthcheck
52
  self._client: Any | None = None
53
- self._health_cache: tuple[float, bool] | None = None
54
 
55
  @property
56
  def model_ids(self) -> tuple[str, ...]:
@@ -74,27 +74,17 @@ class TwoBAudioAdapter:
74
  def health(self) -> bool:
75
  if self._healthcheck is not None:
76
  return self._healthcheck()
77
- now = time.monotonic()
78
- if self._health_cache and now - self._health_cache[0] < 30:
79
- return self._health_cache[1]
80
- try:
81
- url = f"https://huggingface.co/api/spaces/{self.space_id}"
82
- request = urllib.request.Request(url, headers={"User-Agent": "2B-Studio/0.1"})
83
- with urllib.request.urlopen(request, timeout=10) as response:
84
- payload = json.loads(response.read().decode("utf-8"))
85
- healthy = payload.get("runtime", {}).get("stage") == "RUNNING"
86
- except Exception:
87
- healthy = False
88
- self._health_cache = (now, healthy)
89
- return healthy
90
 
91
  def generate(self, request: GenerateRequest) -> Track:
92
  model = self._models.get(request.model_id)
93
  if model is None:
94
  raise ValueError(f"TwoBAudioAdapter unterstützt {request.model_id!r} nicht.")
95
- if not self.health():
 
96
  raise WorkerUnavailableError(
97
- f"Der Worker {self.space_id} ist momentan nicht erreichbar."
 
98
  )
99
 
100
  seed = int(request.advanced.get("seed", 0))
 
4
  import os
5
  import random
6
  import time
 
7
  from collections.abc import Callable
8
  from pathlib import Path
9
  from typing import Any
 
11
 
12
  from gradio_client import Client
13
 
14
+ from studio.adapters.health import HealthCache
15
  from studio.adapters.base import (
16
  DummyAudioError,
17
  GenerateRequest,
 
50
  self._client_factory = client_factory
51
  self._healthcheck = healthcheck
52
  self._client: Any | None = None
53
+ self._health = HealthCache(ttl_s=30.0)
54
 
55
  @property
56
  def model_ids(self) -> tuple[str, ...]:
 
74
  def health(self) -> bool:
75
  if self._healthcheck is not None:
76
  return self._healthcheck()
77
+ return self._health.ok(self.space_id)
 
 
 
 
 
 
 
 
 
 
 
 
78
 
79
  def generate(self, request: GenerateRequest) -> Track:
80
  model = self._models.get(request.model_id)
81
  if model is None:
82
  raise ValueError(f"TwoBAudioAdapter unterstützt {request.model_id!r} nicht.")
83
+ probe = self._health.get(self.space_id)
84
+ if not probe["ok"]:
85
  raise WorkerUnavailableError(
86
+ f"Worker {self.space_id} nicht bereit"
87
+ f" ({probe.get('label')}: {probe.get('error')})."
88
  )
89
 
90
  seed = int(request.advanced.get("seed", 0))
studio/model_status.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Drop-in helpers for studio/ui.py model status (live probe).
2
+
3
+ Replace _model_status_html usage with model_status_html_live after wiring
4
+ AdapterRouter / HealthCache.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from html import escape
9
+
10
+ from studio.adapters.health import HealthCache, probe_space
11
+ from studio.adapters.router import route_id_for_model
12
+ from studio.registry import ModelRegistry
13
+
14
+ _CACHE = HealthCache(ttl_s=20.0)
15
+
16
+ _LABEL_DE = {
17
+ "live": "Live",
18
+ "sleeping": "Schlafend (wird beim Generate geweckt)",
19
+ "broken": "Defekt",
20
+ "unauthorized": "Privat — HF_TOKEN fehlt/ungültig",
21
+ "private-needs-token": "Privat — HF_TOKEN setzen",
22
+ "unreachable": "Nicht erreichbar",
23
+ }
24
+
25
+
26
+ def model_status_html_live(model_id: str, registry: ModelRegistry) -> str:
27
+ model = registry.get(model_id)
28
+ route_id = route_id_for_model(model)
29
+ space_ref = model.space_ref or "—"
30
+ probe = _CACHE.get(space_ref) if model.space_ref else {
31
+ "ok": False,
32
+ "label": "unreachable",
33
+ "stage": None,
34
+ "hardware": None,
35
+ }
36
+ status = _LABEL_DE.get(str(probe.get("label")), str(probe.get("label")))
37
+ vocals = "Gesang" if model.supports_vocals else "Instrumental"
38
+ lyrics = "Lyrics" if model.supports_lyrics else "keine Lyrics"
39
+ blockers = (
40
+ f" · Worker-Blocker: {', '.join(model.blockers)}" if model.blockers else ""
41
+ )
42
+ hw = probe.get("hardware") or "—"
43
+ return f"""
44
+ <section class="model-status-card">
45
+ <div><strong>{escape(model.label)}</strong><span>{escape(model.route_label)}</span></div>
46
+ <div class="model-status-pills">
47
+ <b>{escape(status)}</b>
48
+ <span>{vocals}</span><span>{lyrics}</span>
49
+ <span>max. {model.max_duration_s} s</span>
50
+ <span>HW {escape(str(hw))}</span>
51
+ </div>
52
+ <small>Worker <code>{escape(space_ref)}</code> · Stage <code>{escape(str(probe.get('stage')))}</code>
53
+ · Route <code>{escape(route_id)}</code> · Adapter <code>{escape(model.adapter)}</code>
54
+ {escape(blockers)}.</small>
55
+ </section>
56
+ """
57
+
58
+
59
+ def refresh_all_model_labels(registry: ModelRegistry) -> list[tuple[str, str]]:
60
+ """Dropdown labels with live suffix: 'MiniMax Music 3 · Live'."""
61
+ out: list[tuple[str, str]] = []
62
+ for model in registry.models:
63
+ probe = probe_space(model.space_ref) if model.space_ref else {"label": "?"}
64
+ suffix = _LABEL_DE.get(str(probe.get("label")), str(probe.get("label")))
65
+ out.append((f"{model.label} · {suffix}", model.id))
66
+ return out
studio/ui.py CHANGED
@@ -22,6 +22,7 @@ from studio.agent import FieldProposal, MasterProposal, ProducerAgent, propose_m
22
  from studio.audio_analysis import AudioAnalysis, analyze_wav
23
  from studio.library import add_track, delete_track, import_wav, library_choices, select_track
24
  from studio.registry import ModelRegistry, load_registry
 
25
  from studio.remix import build_remix_plan
26
  from studio.state import ChatTurn, StudioSession, new_session
27
 
@@ -370,26 +371,7 @@ def _download_update(track: Any | None) -> Any:
370
 
371
 
372
  def _model_status_html(model_id: str, registry: ModelRegistry) -> str:
373
- model = registry.get(model_id)
374
- route_id = route_id_for_model(model)
375
- is_live = route_id.endswith("-real")
376
- vocals = "Gesang" if model.supports_vocals else "Instrumental"
377
- lyrics = "Lyrics" if model.supports_lyrics else "keine Lyrics"
378
- blockers = (
379
- f" · Worker-Blocker: {', '.join(model.blockers)}" if model.blockers else ""
380
- )
381
- return f"""
382
- <section class="model-status-card">
383
- <div><strong>{escape(model.label)}</strong><span>{escape(model.route_label)}</span></div>
384
- <div class="model-status-pills">
385
- <b>Live-Worker</b><span>{vocals}</span><span>{lyrics}</span>
386
- <span>max. {model.max_duration_s} s</span>
387
- </div>
388
- <small>Route <code>{escape(route_id)}</code> über <code>{escape(model.adapter)}</code>.
389
- {"Dummy-Fallback wird strikt als Fehler abgelehnt" if is_live else "Worker nicht erreichbar"}
390
- {escape(blockers)}.</small>
391
- </section>
392
- """
393
 
394
 
395
  def _tuning_for(model_id: str, registry: ModelRegistry) -> dict[str, tuple[float, float, float]]:
@@ -1287,14 +1269,7 @@ def _open_create(session: StudioSession | None) -> tuple[Any, Any, str, StudioSe
1287
  def build_app() -> gr.Blocks:
1288
  registry = load_registry()
1289
  producer_agent = ProducerAgent(registry)
1290
- model_choices = [
1291
- (
1292
- f"{model.label} · "
1293
- f"{'Live' if route_id_for_model(model).endswith('-real') else 'Worker offline'}",
1294
- model.id,
1295
- )
1296
- for model in registry.models
1297
- ]
1298
  lexicon_bindings: list[tuple[gr.Button, str, str]] = []
1299
  recipe_bindings: list[tuple[gr.Button, str]] = []
1300
 
 
22
  from studio.audio_analysis import AudioAnalysis, analyze_wav
23
  from studio.library import add_track, delete_track, import_wav, library_choices, select_track
24
  from studio.registry import ModelRegistry, load_registry
25
+ from studio.model_status import model_status_html_live, refresh_all_model_labels
26
  from studio.remix import build_remix_plan
27
  from studio.state import ChatTurn, StudioSession, new_session
28
 
 
371
 
372
 
373
  def _model_status_html(model_id: str, registry: ModelRegistry) -> str:
374
+ return model_status_html_live(model_id, registry)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
375
 
376
 
377
  def _tuning_for(model_id: str, registry: ModelRegistry) -> dict[str, tuple[float, float, float]]:
 
1269
  def build_app() -> gr.Blocks:
1270
  registry = load_registry()
1271
  producer_agent = ProducerAgent(registry)
1272
+ model_choices = refresh_all_model_labels(registry)
 
 
 
 
 
 
 
1273
  lexicon_bindings: list[tuple[gr.Button, str, str]] = []
1274
  recipe_bindings: list[tuple[gr.Button, str]] = []
1275