Complete X-VC, YuE2 audio remix and ClearVoice integration

This commit is contained in:
Mikei386 committed 2026-10-05 22:09:13 +02:00
1 parent 83cd31878c
commit b99abaea25
52 files changed
+1973 -122

No files matched your search

+65 -49
View File
@@ -1,58 +1,74 @@
# Alter Athena Router und Athena Deck
Stand 01.10.2026. Vergleich der aktuellen Quellen und dokumentierten Prüfungen;
keine neue vollständige Live-Abnahme sämtlicher Funktionen. Installierte alte
Container bedeuten keine Anbindung an Deck. Kategorien und Docker-Listen allein
sind kein ausführbarer Worker.
Stand: 05.10.2026. Lesender Abgleich der alten Quellen, der laufenden Deck-
Installation, gespeicherter Profile und vorhandener/stillgelegter Container.
Der ursprüngliche Bestands-/Quellvergleich wurde um die Migration von X-VC,
YuE2 Audio Remix und ClearVoice sowie deren interne GPU-Abnahme ergänzt.
Es ist keine vollständige funktionale Abnahme aller übrigen Alt-Funktionen.
Der Athena MCP Operator ist auf Nutzerwunsch aus dem Migrationsumfang entfernt.
| Funktion | Athena Deck | Offener Umfang |
## Noch nicht übernommen
| Funktion des alten Systems | Stand in Athena Deck | Nachweis / Umfang |
|---|---|---|
| Chat, Profilwechsel, Streaming, Tools, Vision | vorhanden | weitere Client-/Modellkombinationen prüfen |
| Kontext, Slots, GPU-Split, Batch, KV-Quantisierung, MTP | vorhanden | Modellabhängigkeit beachten |
| Bildgenerierung und bis vier Referenzbilder | vorhanden | Referenzbildpfad nicht universell für alle Familien |
| Qwen PE-T2I/PE-I2I Prompt Enhancer | vorhanden | modellabhängige Auswahl und Speicherbedarf |
| TTS, STT und warme/dynamische Audio-Policy | vorhanden | nicht jede Sprachmodellfamilie ausführbar |
| LTX Original + DeskWEB, exklusiver Videomodus | vorhanden, Basisgeneration geprüft | Extend/Retake, Audio, LoRAs und alle Desktop-Erweiterungen nicht vollständig geprüft |
| Dashboard, History, Themes | vorhanden | kein neuer vollständiger Migrationsaudit |
| Modellkatalog, Komponenten, Downloads, automatische Speicheranpassung | vorhanden | Kompatibilitätsrezepte nicht universell |
| ACE-Step Musikstudio | fehlt als Deck-Worker | Laufzeit, Profile/API, GPU-Modus und Oberfläche |
| YuE2 Musikgenerierung | vorhanden: audio.cpp, Musikmodus, Ladypoly | weitere Modelle/Funktionen separat anbinden |
| BS-RoFormer, MelBand und Demucs Trennung | vorhanden: native Laufzeit, Profile, Web-GUI | weitere Familien separat prüfen |
| OmniVoice Voice Studio | fehlt | eigene Worker-/UI-Anbindung |
| X-VC Voice Changer | fehlt | eigene Worker-/UI-Anbindung |
| Applio/RVC Konvertierung und Training | fehlt | eigene Worker-/UI-Anbindung |
| TRELLIS.2 3D | fehlt | eigene Laufzeit, GPU-Modus und Oberfläche |
| EmbeddingGemma / Embeddings | fehlt im Deck-Endpunkt | Embedding-Worker und Route |
| Realtime Voice / WebRTC / OpenClaw Talk | fehlt in Deck | Brücke, Echtzeitaudio und Clientintegration |
| Responses API | fehlt in Deck | /v1/responses-Kompatibilität |
| PCM-Streaming für TTS | fehlt in Deck | Streaming-Audiopfad |
| Spezialmodi | LLM, Video, Musik, Audio-Trennung vorhanden | Voice/3D fehlen |
| Markierte zusätzliche Docker-Anwendungen | vorhanden | allein noch keine GPU-Worker-Orchestrierung |
| WireGuard-Einstellungen | nativer Host-/systemd-Dienst installiert, GUI/API/Web-Tools angebunden | echte Peer-Konfiguration und alter Gateway noch nicht migriert; Dual-Stack mit synthetischem Peer geprüft |
| Backup/Restore | implementiert | kompletter Neuaufbau auf leerem Debian nicht durchgetestet; Anwendungsdaten zusätzlicher Studios brauchen Rezepte |
| Nativer Debian-/systemd-Installer | unvollständig | frischer Host, Voraussetzungen und vollständige Abnahme |
| TRELLIS.2 / 3D Studio | fehlt | Alter `mike-ai-trellis-studio` samt Modell-/Ausgabemounts vorhanden, gestoppt. Keine entsprechende Deck-Kategorie, Laufzeit oder Profilanbindung gefunden. |
| Realtime Voice / Sprachdialog-Brücke | fehlt | Alter `athena-realtime-voice`-Dienst und Container vorhanden; kein entsprechender Deck-Dialogdienst. Nicht mit Applios vorhandener Live-Stimmkonvertierung verwechseln. |
| PCM-Sprachstream und weitere TTS-Ausgabeformate | fehlt | Alter Router: `/v1/audio/speech/pcm-stream`, MP3/WAV/PCM. Installiertes Deck: `/v1/audio/speech` akzeptiert WAV; kein gleichwertiger PCM-Streamingpfad. |
| Globale serverseitige Systemrichtlinie | kein Gegenstück gefunden | Alter Router hat `_load_global_system_policy` und `_inject_global_system_policy`. Im Deck-Quellbestand keine entsprechende globale Einspeisung gefunden. Client-Systemprompts ersetzen diese serverweite Funktion nicht. |
| Chatbefehle für Betriebsarten | kein Gegenstück gefunden | Alter Router wertet z. B. `/athena 3d` und weitere Modusbefehle aus. Deck besitzt die Betriebsartensteuerung in GUI/API, aber keine gleichwertige Chatbefehlsauswertung gefunden. |
| Alte Audio-Katalogrouten | andere Schnittstelle | Alt: `/v1/audio/models`, `/v1/audio/voices`. Deck: getrennte `/v1/audio/speech/models` und `/v1/audio/transcriptions/models`; keine alten Aliasrouten gefunden. Relevant für Altclients. |
Empfohlene Reihenfolge: Embeddings und API-Lücken; gemeinsame Steuerung weiterer
GPU-Spezialworker; Musik/Voice/3D je nach Bedarf; native Installation und vollständiger
Restore-Test. LTX-spezifische optionalen Funktionen separat gegen DeskWEB prüfen.
## Bereits übernommen – nicht erneut als fehlend führen
## Stilllegung und native Netzwerk-Anbindung am 01.10.2026
- Chatprofile Fast, Medium, Large, Ultra und Unzensiert sind vorhanden; zusätzlich
Gemma, Lukes Devlab und Holo4. Gespeicherte Einstellungen müssen nicht identisch
mit den historischen Profilen sein; Änderungen waren teilweise ausdrücklich gewünscht.
- Kontext, Slots, GPU-Split, Batch/Microbatch, KV-Cache, MTP, Sampling/Penalties,
Min-p, Presets und getrennte Vision-Projektor-Zuordnung sind implementiert.
- Qwen-/FLUX-Bilder und Referenzbildbearbeitung, Prompt-Enhancer.
- Qwen-TTS, Qwen-ASR/STT und EmbeddingGemma samt Embeddings-Endpunkt.
- YuE2 / LadyPoly sowie ACE-Step 1.5 XL-SFT / eigene Studio-Oberfläche.
- Musik-Audiotrennung mit Profilen und Separator Web; zusätzlich ClearVoice /
MossFormer2_SE_48K für Sprache/Hintergrund mit eigenem Profil und GPU-Auswahl.
- YuE2 Audio-Remix: SheetSage2/MERT-Analyse, bearbeitbarer ABC-Plan und
Weitergabe an audio.cpp; in Deck und LadyPoly bedienbar.
- X-VC Studio: eigene Laufzeit/Gewichte, inaktives Profil, Weboberfläche und
Deck-GPU-Steuerung. Native Konvertierung und Resemble-Restaurierung geprüft.
- VoxCPM2, OmniVoice und Applio/RVC einschließlich der übernommenen eigenen GUI.
Die Voice-Webcontainer einschließlich X-VC und Applio sind vorhanden und laufen.
- Applio-Trainingsdaten/Checkpoints und Stimmen wurden kopiert; historische
UI-Auftragsdaten/Uploads/Ergebnisse sind nicht vollständig automatisch importiert.
- Optionale Responses-Kompatibilität ist implementiert. Sie bleibt eine definierte
Teilmenge, keine vollständige OpenAI-API (siehe RESPONSES_COMPATIBILITY.md).
- LTX DeskWEB, Dashboard, History, Downloads und zusätzliche Docker-Dienste.
- Native WireGuard-Verwaltung und Migration; alter Gateway-Container ist gestoppt.
Alle 33 alten `mike-ai-*`-Container außer `mike-ai-wireguard-gateway` sind
stillgelegt und auf `restart=no` gesetzt. Images, Definitionen und Daten bleiben
für den Vergleich erhalten. Vorherige Zustände und Neustartregeln sind geschützt
unter `/opt/athena-deck-dev/runtime/legacy-services-before-native-wireguard.json`
gesichert. Alte laufende Dienste sind damit keine aktive Rückfallversorgung mehr.
## Nicht als bestätigte Funktionslücke einstufen
`athena-deck-network.service` läuft nativ auf dem Debian-Host. Es verwaltet die
Schnittstelle `wgdeck0`; aktuell ist noch keine echte Peer-Konfiguration importiert
und der neue Tunnel ist deaktiviert. Im lokalen Modus werden die Deck-GUI 8108,
API-Ports 8120–8124 und die explizit registrierten Web-Tools 8118/8127/8128 über
Athenas KIT-LAN-Adresse bereitgestellt. SSH-Verwaltung bleibt unabhängig.
- LTX Extend/Retake, Audio, LoRAs und alle optionalen Desktopfunktionen: keine
vollständige aktuelle Einzelabnahme. Vor Migration weiterer Teile separat prüfen.
- LadyPoly Writer, Cover, LoRA und weitere Samplingfunktionen sind in der neuen
Brücke nicht angebunden. Welche davon im alten System vollständig funktionsfähig
waren, wurde bei diesem Abgleich nicht erneut getestet.
- Konfigurationsbackup ist nicht dasselbe wie Medien-/Trainingsdatenarchiv.
Applio-Nutzdaten brauchen weiterhin ihr gesondertes Archiv. Vollständiger Restore
auf einem leeren Debian-Host und nativer Neuaufbau sind nicht komplett abgenommen;
dies sind Prüflücken, kein Beleg einer fehlenden alten Modellfunktion.
Nachweis: 86 lokale Netzwerk-/API-/Profiltests, 32 isolierte Backup-/Modelltests
(mit Überschneidungen) und realer Dual-Stack-WireGuard-Handshake in zwei Wegwerf-
Netzwerk-Namensräumen. Kein produktiver Peer wurde zum Test verwendet.
GUI über SSH und KIT-LAN: HTTP 200; API ohne Token: HTTP 401; drei Web-Tools: HTTP 200.
Die vollständige Migration des alten Gateways steht noch aus; dieser bleibt aktiv.
Ein kompletter Restore auf leerem Debian ist weiterhin nicht abgenommen.
## Quellen dieses Abgleichs
Alter Router: `/opt/mike-ai/stack/router/ai_profile_router.py`,
`router_profiles.json`, `config/profile-matrix.json`,
`/opt/mike-ai/stem-separator/app.py`, `speech_enhance.py`,
`/opt/mike-ai/yue2-3b/README.md` und Docker-Metadaten.
Neues System: produktive `/opt/athena-deck-dev/runtime/state/profiles.json`,
installierter `/app/endpoint.py` und `/app/profiles.py`, Containerbestand sowie
Repository-Dateien `docs/XVC.md`, `docs/APPLIO.md`, `RESPONSES_COMPATIBILITY.md`
und die Adapterquellen/-Dokumentationen.
Interne GPU-Abnahme: X-VC liefert 16-kHz- und 44,1-kHz-WAV; ClearVoice
trennt auf RTX 3060; SheetSage2 erzeugt aus einer künstlichen Melodie einen
ABC-Plan, den YuE2 auf RTX 5080 zu 4 Sekunden Audio rendert. YuE2 bleibt
danach geladen. Diese technische Prüfung ersetzt keinen musikalischen Hörtest.
Die frühere Liste vom 01.10.2026 ist durch diesen Stand ersetzt.
+3 -2
View File
@@ -101,8 +101,9 @@ class MusicRouter:
def start(self,profile_id,lyrics='',style='',**options):
with self.lock:
target=self._select(profile_id)
if options.get('steps') is None:options.pop('steps')
if target is self.yue and set(options)-{'seed','max_tokens','steps','wait'}:raise ValueError('ACE-Step-Parameter sind für dieses YuE2-Profil nicht unterstützt.')
if options.get('steps') is None:options.pop('steps',None)
if target is self.ace and set(options)&{'abc','cot'}:raise ValueError('ABC-Musikplan wird nur vom YuE2-Adapter unterstützt.')
if target is self.yue and set(options)-{'seed','max_tokens','steps','wait','abc','cot'}:raise ValueError('ACE-Step-Parameter sind für dieses YuE2-Profil nicht unterstützt.')
return target.start(profile_id,lyrics,style,**options)
def load(self,profile_id,wait=False):
with self.lock:return self._select(profile_id).load(profile_id,wait)
+1
View File
@@ -25,6 +25,7 @@ function appearancePage(){
}
async function refresh(){if(refreshing)return;refreshing=true;const page=location.hash.slice(1)||'dashboard';document.querySelectorAll('nav a').forEach(a=>a.classList.toggle('active',a.hash==='#'+page));try{error.textContent='';let html;
if(['separator-runtime','separator-test','separation'].includes(page)){SeparatorUI.render(page!=='separator-runtime');return;}
if(page==='xvc-runtime'){XVCUI.render();return;}
if(page==='applio-runtime'){ApplioUI.render();return;}
if(page==='acestep-runtime'){AceStepUI.render();return;}
if(page==='audio-cpp-runtime'){AudioCppUI.render();return;}
+2 -2
View File
@@ -37,8 +37,8 @@ class Applio:
c.settimeout(10);request=json.loads(c.makefile('rb').readline(8193))
if request!={'action':'reserve'}:raise ValueError('Ungültige Ressourcenanfrage.')
with self.lock:
if self.active:raise ValueError('Applio arbeitet bereits.')
if self.scheduler.gpu_mode!='voice' or not self.selected():raise ValueError('Applio-Profil in Deck aktivieren und Steuerung → Stimmwerkzeuge starten.')
if self.active:raise ValueError(getattr(self,'label','Applio')+' arbeitet bereits.')
if self.scheduler.gpu_mode!='voice' or not self.selected():raise ValueError(getattr(self,'label','Applio')+'-Profil in Deck aktivieren und Steuerung → Stimmwerkzeuge starten.')
self.active=True;owned=True
release=self.scheduler.image_reservation(False,kind='voice')
from image_test import probe
+34 -6
View File
@@ -7,7 +7,7 @@ from auth import atomic_write,validate_record
from backup_codec import seal,open_backup
from catalog import repo_id,file_role,KINDS
from profiles import SCHEMAS,CHAT_GPU_DEFAULTS,chat_parameters,FLOAT_PARAMETERS
SETTINGS=('applio-data/settings.json','separator-profiles.json','profiles.json','endpoint.json','audio-policy.json','video/comfy-selection.json','models/huggingface.json','video/comfy-client-token','video/original-work/settings.json')
SETTINGS=('xvc-data/settings.json','applio-data/settings.json','separator-profiles.json','profiles.json','endpoint.json','audio-policy.json','video/comfy-selection.json','models/huggingface.json','video/comfy-client-token','video/original-work/settings.json')
MAX_HISTORY=40*1024**2
VERSION=1
# Exact byte hash verified against official Hub metadata, not a filename heuristic.
@@ -36,7 +36,7 @@ def validate(doc):
repo_id(source['repo'])
if not re.fullmatch('[a-f0-9]{40}',source['revision']) or source['file'].startswith('/') or '..' in PurePosixPath(source['file']).parts or '\\' in source['file'] or any(ord(c)<32 for c in source['file']):raise ValueError('Ungültige Ersatzquelle.')
metadata=m.get('runtime_metadata')
if metadata is not None and metadata!={'architecture':'rvc'}:raise ValueError('Ungültige Applio-Modellmetadaten.')
if metadata is not None and metadata not in ({'architecture':'rvc'},{'architecture':'xvc'}):raise ValueError('Ungültige Stimm-Modellmetadaten.')
ids.add(m['id'])
pids=set();names=set();api_names=set()
for p in profiles:
@@ -94,6 +94,9 @@ def validate(doc):
if not isinstance(hf,dict) or set(hf)!={'token'} or hf['token'] is not None and (not isinstance(hf['token'],str) or not re.fullmatch(r'hf_[A-Za-z0-9]{10,252}',hf['token'])):raise ValueError('Ungültiger Hugging-Face-Zugang.')
if 'video/comfy-client-token' in settings and not re.fullmatch(r'[A-Za-z0-9_-]{32,256}',settings['video/comfy-client-token'].strip()):raise ValueError('Ungültiger Diensttoken.')
if 'video/original-work/settings.json' in settings and (not isinstance(settings['video/original-work/settings.json'],dict) or len(json.dumps(settings['video/original-work/settings.json']))>65536):raise ValueError('Ungültige LTX-Einstellungen.')
if 'xvc-data/settings.json' in settings:
v=settings['xvc-data/settings.json']
if not isinstance(v,dict) or set(v)!={'device'} or v['device'] not in ('3060','5080'):raise ValueError('Ungültige X-VC-GPU.')
if 'applio-data/settings.json' in settings:
v=settings['applio-data/settings.json']
if not isinstance(v,dict) or set(v)!={'device'} or v['device'] not in ('3060','5080'):raise ValueError('Ungültige Applio-GPU.')
@@ -102,7 +105,7 @@ def validate(doc):
validate_profiles(settings['separator-profiles.json'])
validate_record(doc.get('credentials'))
runtimes=doc.get('runtimes')
if not isinstance(runtimes,dict) or set(runtimes)-{'llama','llama_builds','image','tts','enhancers','swarm_nodes','ltx_original','audio_cpp','separator','voxcpm','omnivoice','acestep','applio'} or not {'llama','llama_builds','image','tts','enhancers','swarm_nodes'}<=set(runtimes):raise ValueError('Ungültiges Laufzeitrezept.')
if not isinstance(runtimes,dict) or set(runtimes)-{'llama','llama_builds','image','tts','enhancers','swarm_nodes','ltx_original','audio_cpp','separator','voxcpm','omnivoice','acestep','applio','xvc','music_remix'} or not {'llama','llama_builds','image','tts','enhancers','swarm_nodes'}<=set(runtimes):raise ValueError('Ungültiges Laufzeitrezept.')
if 'separator' in runtimes:
from separator_runtime import MODELS
value=runtimes['separator']
@@ -110,6 +113,8 @@ def validate(doc):
if 'sources' in value:
from separator_runtime import SOURCES
if value['sources']!={name:SOURCES[name] for name in value['models']}:raise ValueError('Audio-Separator-Quellen stimmen nicht mit dem geprüften Rezept überein.')
if 'music_remix' in runtimes and type(runtimes['music_remix']) is not bool:raise ValueError('Ungültige Audio-Remix-Laufzeit.')
if 'xvc' in runtimes and type(runtimes['xvc']) is not bool:raise ValueError('Ungültige X-VC-Laufzeit.')
if 'applio' in runtimes and type(runtimes['applio']) is not bool:raise ValueError('Ungültige Applio-Laufzeit.')
if 'acestep' in runtimes and type(runtimes['acestep']) is not bool:raise ValueError('Ungültige ACE-Step-Laufzeit.')
if 'omnivoice' in runtimes and type(runtimes['omnivoice']) is not bool:raise ValueError('Ungültige OmniVoice-Laufzeit.')
@@ -165,7 +170,7 @@ class Backup:
models=[]
for m in s.catalog.status()['entries']:
item={k:m[k] for k in ('id','repo','revision','file','size','sha256','kind')}
if (m.get('runtime_metadata') or {}).get('architecture')=='rvc':item['runtime_metadata']={'architecture':'rvc'}
if (architecture:=(m.get('runtime_metadata') or {}).get('architecture')) in ('rvc','xvc'):item['runtime_metadata']={'architecture':architecture}
if m['repo'].startswith('local/'):
item['source']='local';item['download_source']=m.get('download_source') or LOCAL_SOURCES.get(m['sha256'])
models.append(item)
@@ -181,9 +186,17 @@ class Backup:
network=s.network.call('backup-export')
else:warnings.append('Deck-Netzwerkmodul deaktiviert; fremder WireGuard-Gateway wird nicht gesichert.')
document=dict(format='athena-deck',version=VERSION,created_at=time.time(),settings=settings,models=models,credentials=s.credentials.read(),theme=theme,network=network,services=services,runtime_versions=dict(image=dict(comfy=s.image_runtime.status()['comfy_revision'],gguf=s.image_runtime.status()['gguf_revision']),tts=s.tts_runtime.status()['revision']),runtimes=dict(audio_cpp=bool(getattr(s,'audio_cpp_runtime',None) and s.audio_cpp_runtime.status()['installed']),ltx_original=bool(getattr(s,'ltx_original_runtime',None) and s.ltx_original_runtime.status()['installed']),llama=llama,llama_builds=[dict(commit=b['commit'],backend=b['backend']) for b in state['builds']],image=s.image_runtime.status()['installed'],tts=s.tts_runtime.status()['installed'],enhancers={task:data['revision'] for task in ('t2i','i2i') if (data:=s.prompt_enhancer.installed(task))},swarm_nodes=(self.root/'video/swarm-comfy-nodes').is_dir()),warnings=warnings)
if getattr(s,'remix_runtime',None):
document['runtimes']['music_remix']=s.remix_runtime.status()['installed']
if document['runtimes']['music_remix']:
from remix_runtime import VERSION as REMIX_VERSION
document['runtime_versions']['music_remix']=REMIX_VERSION
if getattr(s,'separator_runtime',None):
from separator_runtime import SOURCES
separator=s.separator_runtime.status();document['runtimes']['separator']=dict(installed=separator['installed'],models=[m['id'] for m in separator['models'] if m['installed']],sources={m['id']:SOURCES[m['id']] for m in separator['models'] if m['installed']});document['runtime_versions']['separator']=separator['version']
if getattr(s,'xvc_runtime',None):
from xvc_runtime import RECIPE_HASH
document['runtimes']['xvc']=s.xvc_runtime.status()['installed'];document['runtime_versions']['xvc']=dict(code=s.xvc_runtime.status()['revision'],assets=RECIPE_HASH)
if getattr(s,'applio_runtime',None):
document['runtimes']['applio']=s.applio_runtime.status()['installed'];document['runtime_versions']['applio']=s.applio_runtime.status()['revision']
if (self.root/'applio-data/logs').exists():document['warnings'].append('Eigene Applio-Stimmen und Trainingsdaten separat sichern. Dieses Konfigurationsbackup enthält sie nicht; nach Restore erst den Applio-Datenbestand zurückspielen.')
@@ -234,6 +247,9 @@ class Backup:
if versions.get('voxcpm'):
from voxcpm_runtime import VERSION as VOXCPM_VERSION
if versions['voxcpm']!=VOXCPM_VERSION:blockers.append('Backup verlangt eine andere VoxCPM-Version. Passende Deck-Version verwenden.')
if versions.get('music_remix'):
from remix_runtime import VERSION as REMIX_VERSION
if versions['music_remix']!=REMIX_VERSION:blockers.append('Backup verlangt eine andere Audio-Remix-Version.')
if versions.get('separator'):
from separator_runtime import VERSION as SEPARATOR_VERSION
if versions['separator']!=SEPARATOR_VERSION:blockers.append('Backup verlangt eine andere Audio-Separator-Version.')
@@ -243,10 +259,13 @@ class Backup:
if versions.get('ltx_original'):
from ltx_original_runtime import DESKTOP_REV,LTX_REV
if versions['ltx_original']!=dict(desktop=DESKTOP_REV,inference=LTX_REV):blockers.append('Backup verlangt eine andere originale LTX-Version. Passende Deck-Version verwenden.')
if versions.get('xvc'):
from xvc_runtime import REVISION as XVC_REVISION,RECIPE_HASH
if versions['xvc']!=dict(code=XVC_REVISION,assets=RECIPE_HASH):blockers.append('Backup verlangt eine andere X-VC-Version oder Komponentenquelle.')
if versions.get('applio'):
from applio_runtime import REVISION as APPLIO_REVISION
if versions['applio']!=APPLIO_REVISION:blockers.append('Backup verlangt eine andere Applio-Version.')
if versions and {k:v for k,v in versions.items() if k not in ('ltx_original','audio_cpp','separator','voxcpm','omnivoice','acestep','applio')}!=dict(image=dict(comfy=s.image_runtime.status()['comfy_revision'],gguf=s.image_runtime.status()['gguf_revision']),tts=s.tts_runtime.status()['revision']):blockers.append('Backup verlangt andere Bild-/TTS-Laufzeitversionen. Passende Deck-Version oder geprüftes Runtime-Upgrade verwenden.')
if versions and {k:v for k,v in versions.items() if k not in ('ltx_original','audio_cpp','separator','voxcpm','omnivoice','acestep','applio','xvc','music_remix')}!=dict(image=dict(comfy=s.image_runtime.status()['comfy_revision'],gguf=s.image_runtime.status()['gguf_revision']),tts=s.tts_runtime.status()['revision']):blockers.append('Backup verlangt andere Bild-/TTS-Laufzeitversionen. Passende Deck-Version oder geprüftes Runtime-Upgrade verwenden.')
for c in doc['services']:
if not c.get('registry') and not c.get('build_recipe'):warnings.append(c['name']+': Image nur lokal vorhanden; Registry-/Buildquelle fehlt.')
ports=s.endpoint.allowed_ports
@@ -271,8 +290,10 @@ class Backup:
if len(set(data['services']))!=len(data['services']) or any(name not in services for name in data['services']):raise ValueError('Unbekannter Zusatzdienst.')
if any(not services[name].get('registry') and not services[name].get('build_recipe') for name in data['services']):raise ValueError('Gewählter Dienst hat keine Wiederherstellungsquelle.')
s=self.server
if getattr(getattr(s,'remix',None),'active',False):raise ValueError('Audio-Remix-Analyse zuerst abschließen.')
if getattr(getattr(s,'xvc',None),'active',False):raise ValueError('X-VC-Auftrag zuerst abschließen.')
if getattr(getattr(s,'applio',None),'active',False):raise ValueError('Applio-Auftrag zuerst abschließen.')
if s.catalog.pending or s.catalog.job and s.catalog.job['state']=='downloading' or s.runtime.busy or any((getattr(o,'job',None) or {}).get('state')=='running' for o in (s.image_runtime,s.tts_runtime,s.ltx_original_runtime,getattr(s,'audio_cpp_runtime',None),getattr(s,'acestep_runtime',None),getattr(s,'applio_runtime',None),getattr(s,'music',None),getattr(s,'separator_runtime',None),getattr(s,'separator_tests',None),s.prompt_enhancer,s.auto_tests,s.chat_tests,s.image_tests,s.tts_tests,s.stt)):raise ValueError('Zuerst laufende Downloads, Builds und Tests abschließen oder abbrechen.')
if s.catalog.pending or s.catalog.job and s.catalog.job['state']=='downloading' or s.runtime.busy or any((getattr(o,'job',None) or {}).get('state')=='running' for o in (s.image_runtime,s.tts_runtime,s.ltx_original_runtime,getattr(s,'audio_cpp_runtime',None),getattr(s,'acestep_runtime',None),getattr(s,'applio_runtime',None),getattr(s,'xvc_runtime',None),getattr(s,'music',None),getattr(s,'remix_runtime',None),getattr(s,'remix',None),getattr(s,'separator_runtime',None),getattr(s,'separator_tests',None),s.prompt_enhancer,s.auto_tests,s.chat_tests,s.image_tests,s.tts_tests,s.stt)):raise ValueError('Zuerst laufende Downloads, Builds und Tests abschließen oder abbrechen.')
self.cancel.clear();self.job=dict(id=secrets.token_hex(16),state='running',phase='Wiederherstellung vorbereiten',completed=0,total=len(doc['models'])+len(data['services'])+5,items=[],started_at=time.time(),theme=doc.get('theme','deck'))
self._save();threading.Thread(target=self._restore,args=(copy.deepcopy(doc),data['services'],data['restore_credentials']),daemon=True).start();self.plan=None
return self.status()
@@ -298,6 +319,8 @@ class Backup:
self._phase('Vorhandene Bild-/Videolaufzeit prüfen oder installieren');s.image_runtime.start();self._wait(s.image_runtime.status)
if r['tts'] and not s.tts_runtime.status()['installed']:
self._phase('TTS-Laufzeit und Zusatzdateien installieren');s.tts_runtime.start();self._wait(s.tts_runtime.status)
if r.get('xvc') and not s.xvc_runtime.status()['installed']:
self._phase('X-VC-Laufzeit und geprüfte Zusatzgewichte installieren');s.xvc_runtime.start();self._wait(s.xvc_runtime.status)
if r.get('applio') and not s.applio_runtime.status()['installed']:
self._phase('Applio-Laufzeit und Basisgewichte installieren');s.applio_runtime.start();self._wait(s.applio_runtime.status)
if r.get('acestep') and not s.acestep_runtime.status()['installed']:
@@ -317,6 +340,8 @@ class Backup:
for name in r['separator']['models']:
if not s.separator_runtime.model_ready(name) or not verify_package(s.separator_runtime.root/'models',name):
self._phase('Audio-Separator-Modellpaket laden');s.separator_runtime.download(name);self._wait(s.separator_runtime.status)
if r.get('music_remix') and not s.remix_runtime.status()['installed']:
self._phase('Audio-Remix-Laufzeit und Modelle installieren');s.remix_runtime.start();self._wait(s.remix_runtime.status)
targets=r['llama_builds']+([r['llama']] if r['llama'] and r['llama'] not in r['llama_builds'] else [])
for target in targets:
state=s.runtime.status();matching=next((b for b in state['builds'] if b['commit']==target['commit'] and b['backend']==target['backend']),None)
@@ -337,6 +362,7 @@ class Backup:
key=secrets.token_urlsafe(32);rollback.write_bytes(seal(before,key));rollback.chmod(0o600)
# Recovery key stays on this server in a separate protected file, never in status responses.
(rollback.with_suffix('.key')).write_text(key);rollback.with_suffix('.key').chmod(0o600)
if getattr(s,'xvc',None):s.xvc.unload_idle()
if getattr(s,'applio',None):s.applio.unload_idle()
s.endpoint.close();s.video.close();s.tts_tests.stop();s.stt.stop()
until=time.monotonic()+30
@@ -434,6 +460,7 @@ class Backup:
if name=='video/comfy-client-token':
path=self.root/name;path.parent.mkdir(parents=True,exist_ok=True);path.write_text(value+'\n');path.chmod(0o600)
else:atomic_write(self.root/name,value)
if getattr(s,'xvc',None):s.xvc.settings=copy.deepcopy(doc['settings'].get('xvc-data/settings.json',{'device':'5080'}))
if getattr(s,'applio',None):s.applio.settings=copy.deepcopy(doc['settings'].get('applio-data/settings.json',{'device':'3060'}))
with s.profiles.lock:
from profiles import migrate_api_ids
@@ -467,6 +494,7 @@ class Backup:
if getattr(self.server,'music',None):self.server.music.stop()
if getattr(self.server,'omnivoice_runtime',None):self.server.omnivoice_runtime.stop()
if getattr(self.server,'voxcpm_runtime',None):self.server.voxcpm_runtime.stop()
if getattr(self.server,'xvc_runtime',None):self.server.xvc_runtime.stop()
if getattr(self.server,'applio_runtime',None):self.server.applio_runtime.stop()
if getattr(self.server,'acestep_runtime',None):self.server.acestep_runtime.stop()
if getattr(self.server,'audio_cpp_runtime',None):self.server.audio_cpp_runtime.stop()
+3 -1
View File
@@ -70,6 +70,8 @@ def file_role(filename):
role,label='auxiliary','ACE-Step-Musik-Sprachmodell'
elif PurePosixPath(name).name in ('model-00002-of-00004.safetensors','model-00003-of-00004.safetensors','model-00004-of-00004.safetensors'):
role,label='auxiliary','Gewichts-Teildatei'
elif name=='xvc.pt':
role,label='model','X-VC-Stimmgewicht'
elif name.endswith('.pth') and not PurePosixPath(name).name.startswith(('g_','d_')) and not any(p in ('pretraineds','predictors','embedders') for p in parts):
role,label='model','Stimmgewicht (PTH)'
elif name.endswith(('.gguf','.safetensors')):
@@ -213,7 +215,7 @@ class Catalog:
name=f['rfilename'];p=PurePosixPath(name)
from acestep_models import ACE_REPO,ACE_BASE_REPO,ACE_FILES,ACE_BASE_FILES
recipe_file=(repo==ACE_REPO and name in ACE_FILES) or (repo==ACE_BASE_REPO and name in ACE_BASE_FILES) or (repo=='k2-fsa/OmniVoice' and name=='chat_template.jinja')
allowed=recipe_file or p.suffix.lower() in ('.gguf','.safetensors','.json','.tiktoken') or (repo=='openbmb/VoxCPM2' and name=='audiovae.pth')
allowed=recipe_file or p.suffix.lower() in ('.gguf','.safetensors','.json','.tiktoken') or (repo=='openbmb/VoxCPM2' and name=='audiovae.pth') or (repo=='chenxie95/X-VC' and name=='xvc.pt')
if p.is_absolute() or '..' in p.parts or not allowed:continue
size=f.get('size',f.get('lfs',{}).get('size'))
if not isinstance(size,int) or size<1:continue
+36
View File
@@ -0,0 +1,36 @@
"""Pinned ClearVoice enhancement; file mode segments long recordings correctly."""
import json,os,subprocess,sys,tempfile
from pathlib import Path
import numpy as np
import soundfile as sf
import torch
from separator_runtime import verify_package,CLEARVOICE
def enhance(model_dir,source,output):
if not verify_package(model_dir,CLEARVOICE):raise ValueError('ClearVoice-Modellpaket-Prüfsumme stimmt nicht.')
if not torch.cuda.is_available():raise ValueError('CUDA nicht verfügbar; kein CPU-Fallback.')
output=Path(output)
with tempfile.TemporaryDirectory(prefix='clearvoice-',dir=output) as temp:
work=Path(temp);(work/'checkpoints').symlink_to((Path(model_dir)/'clearvoice').resolve(),target_is_directory=True)
subprocess.run(['ffmpeg','-nostdin','-hide_banner','-loglevel','error','-y','-i',str(source),'-ar','48000','-c:a','pcm_f32le',str(work/'input.wav')],check=True,timeout=180,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
audio,sr=sf.read(work/'input.wav',dtype='float32',always_2d=True)
previous=Path.cwd()
try:
os.chdir(work)
from clearvoice import ClearVoice
from clearvoice.networks import SpeechModel
from unittest.mock import patch
if torch.cuda.device_count()!=1:raise ValueError('Genau eine von Deck ausgewählte GPU erforderlich.')
# Upstream uses physical nvidia-smi indices; Deck exposes only local CUDA:0.
with patch.object(SpeechModel,'get_free_gpu',return_value=0):model=ClearVoice(task='speech_enhancement',model_names=[CLEARVOICE])
channels=[]
for i in range(audio.shape[1]):
path=work/f'channel-{i}.wav';sf.write(path,audio[:,i],sr,subtype='FLOAT')
clean=np.asarray(model(str(path),False),dtype='float32').squeeze()
if clean.ndim!=1 or not np.isfinite(clean).all():raise ValueError('Ungültige ClearVoice-Ausgabe.')
channels.append(clean)
length=min(len(audio),*(len(c) for c in channels));speech=np.column_stack([c[:length] for c in channels]);background=audio[:length]-speech
finally:os.chdir(previous)
for name,data in [('speech.wav',speech),('rest.wav',background)]:sf.write(output/name,np.clip(data,-1,1),sr,subtype='PCM_16')
(output/'results.json').write_text(json.dumps(['speech.wav','rest.wav']))
if __name__=='__main__':enhance(sys.argv[1],sys.argv[3],sys.argv[4])
+14
View File
@@ -0,0 +1,14 @@
"""Expose only immutable CUDA packages, never another application's full environment."""
import json,subprocess
from pathlib import Path
PREFIXES=('torchgen','functorch','torch','torchaudio','triton','nvidia','cuda','cuda_bindings','cuda_python')
def share_cuda(python,base,shared,command):
roots=json.loads(subprocess.check_output([str(shared),'-c','import json,site;print(json.dumps(site.getsitepackages()))'],text=True))
destination=Path(base)/'cuda-packages';destination.mkdir(exist_ok=True)
for root in roots:
if not Path(root).is_dir():continue
for path in Path(root).iterdir():
if any(path.name==p or path.name.startswith(p+'-') or path.name.startswith(p+'_') for p in PREFIXES):
target=destination/path.name
if not target.exists():target.symlink_to(path.resolve(),target_is_directory=path.is_dir())
command([python,'-c','import site,sys;from pathlib import Path;Path(site.getsitepackages()[0],"deck-shared-cuda.pth").write_text(sys.argv[1]+"\\n")',str(destination)])
+3 -1
View File
@@ -17,9 +17,11 @@ COPY deploy/image-requirements.lock /app/deploy/image-requirements.lock
COPY deploy/acestep-requirements.lock /app/deploy/acestep-requirements.lock
COPY deploy/tts-requirements.lock /app/deploy/tts-requirements.lock
COPY deploy/ltx-original-requirements.lock /app/deploy/ltx-original-requirements.lock
COPY applio.py applio_runtime.py applio_worker.py applio-ui.js acestep_models.py acestep.py acestep_worker.py acestep_runtime.py acestep-ui.js embeddings.py voxcpm_test.py voxcpm_worker.py voxcpm_runtime.py separator_sources.json separator.py separator_runtime.py separator_worker.py music.py audio_cpp_runtime.py ltx_original_runtime.py ltx_original_entry.py video_original.py backup.py backup_codec.py audio_policy.py prompt_enhancer.py prompt_enhancer_worker.py api_compat.py responses_compat.py stt.py execution_setup.py tts_runtime.py tts_test.py tts_worker.py auto_test.py chat_test.py endpoint.py inference.py docker_support.py image_encoder_node.py image_runtime.py image_test.py image_upload.py profiles.py capacity.py server.py runtime.py video.py video_proxy.py video_comfy.py video_comfy_node.py video_comfy_proxy.py catalog.py hub_auth.py auth.py collect_hardware.py dashboard_data.py dashboard_history.py /app/
COPY cuda_overlay.py remix.py remix_runtime.py remix_worker.py remix_sources.json clearvoice_worker.py xvc.py xvc_runtime.py xvc_sources.json xvc-ui.js applio.py applio_runtime.py applio_worker.py applio-ui.js acestep_models.py acestep.py acestep_worker.py acestep_runtime.py acestep-ui.js embeddings.py voxcpm_test.py voxcpm_worker.py voxcpm_runtime.py separator_sources.json separator.py separator_runtime.py separator_worker.py music.py audio_cpp_runtime.py ltx_original_runtime.py ltx_original_entry.py video_original.py backup.py backup_codec.py audio_policy.py prompt_enhancer.py prompt_enhancer_worker.py api_compat.py responses_compat.py stt.py execution_setup.py tts_runtime.py tts_test.py tts_worker.py auto_test.py chat_test.py endpoint.py inference.py docker_support.py image_encoder_node.py image_runtime.py image_test.py image_upload.py profiles.py capacity.py server.py runtime.py video.py video_proxy.py video_comfy.py video_comfy_node.py video_comfy_proxy.py catalog.py hub_auth.py auth.py collect_hardware.py dashboard_data.py dashboard_history.py /app/
COPY voice-ui.js voxcpm-ui.js separator-ui.js music-ui.js audio-cpp-ui.js ltx-original-ui.js backup-ui.js video-ui.js stt-ui.js tts-ui.js auto-test-ui.js chat-test-ui.js endpoint-ui.js docker-ui.js image-test-ui.js profiles-ui.js dashboard-ui.js index.html app.js studio.js runtime-ui.js catalog-ui.js style.css dashboard.css themes.css login.html login.js access-ui.js network-ui.js /app/
COPY deploy/docker_backup.py /app/deploy/docker_backup.py
COPY deploy/xvc-requirements.lock /app/deploy/xvc-requirements.lock
COPY deploy/xvc-web /app/deploy/xvc-web
COPY deploy/applio-requirements.lock /app/deploy/applio-requirements.lock
COPY deploy/applio-web /app/deploy/applio-web
COPY network/__init__.py network/client.py network/config.py network/rpc.py /app/network/
+12 -11
View File
@@ -53,7 +53,7 @@ def export(manager):
try:relative=str(Path(source).relative_to(deck))
except ValueError:pass
mounts.append(dict(index=i,target=m['Destination'],read_only=not m['RW'],deck_path=relative,files=config_files(source,m['Destination']),was_file=Path(source).is_file()))
result.append(dict(name=row['name'],image=c['Image'],registry=registry,application=c.get('Labels',{}).get(APP,''),labels={k:v for k,v in (c.get('Labels') or {}).items() if k.startswith('io.athena-deck.')},env=c.get('Env') or [],entrypoint=c.get('Entrypoint'),cmd=c.get('Cmd'),uid=app_uid(row['id'],c.get('User') or ''),user=c.get('User') or '',workdir=c.get('WorkingDir') or '',network=h['NetworkMode'],ports=h.get('PortBindings') or {},restart=h.get('RestartPolicy',{}).get('Name') or 'no',memory=h.get('Memory') or 0,nanocpus=h.get('NanoCpus') or 0,running=x['State']['Running'],mounts=mounts,build_recipe='swarm-ui' if row['name']=='athena-swarm-ui' else 'ladypoly' if row['name']=='athena-ladypoly' else 'separator-web' if row['name']=='athena-separator-web' else 'applio-web' if row['name']=='athena-applio-web' else 'acestep-web' if row['name']=='athena-acestep-web' else 'voice-web' if row['name'] in ('athena-voxcpm2-web','athena-omnivoice-web') else None,unsupported=bool(h.get('Privileged') or h.get('DeviceRequests') or h.get('Devices') or h.get('CapAdd'))))
result.append(dict(name=row['name'],image=c['Image'],registry=registry,application=c.get('Labels',{}).get(APP,''),labels={k:v for k,v in (c.get('Labels') or {}).items() if k.startswith('io.athena-deck.')},env=c.get('Env') or [],entrypoint=c.get('Entrypoint'),cmd=c.get('Cmd'),uid=app_uid(row['id'],c.get('User') or ''),user=c.get('User') or '',workdir=c.get('WorkingDir') or '',network=h['NetworkMode'],ports=h.get('PortBindings') or {},restart=h.get('RestartPolicy',{}).get('Name') or 'no',memory=h.get('Memory') or 0,nanocpus=h.get('NanoCpus') or 0,running=x['State']['Running'],mounts=mounts,build_recipe='swarm-ui' if row['name']=='athena-swarm-ui' else 'ladypoly' if row['name']=='athena-ladypoly' else 'separator-web' if row['name']=='athena-separator-web' else 'xvc-web' if row['name']=='athena-xvc-web' else 'applio-web' if row['name']=='athena-applio-web' else 'acestep-web' if row['name']=='athena-acestep-web' else 'voice-web' if row['name'] in ('athena-voxcpm2-web','athena-omnivoice-web') else None,unsupported=bool(h.get('Privileged') or h.get('DeviceRequests') or h.get('Devices') or h.get('CapAdd'))))
return {'services':result,'configured':bool(deck)}
def validate(c):
@@ -61,8 +61,8 @@ def validate(c):
if any(c.get('labels',{}).get(k)!=v for k,v in LABELS.items()):raise ValueError('Nur ausdrücklich Deck zugeordnete Anwendungscontainer erlaubt.')
if c.get('unsupported'):raise ValueError('GPU-/privilegierter Container benötigt manuelle Einrichtung.')
if c.get('network') not in ('bridge','default','host'):raise ValueError('Benutzerdefiniertes Docker-Netzwerk benötigt manuelle Einrichtung.')
if c.get('network')=='host' and c['name'] not in ('athena-swarm-ui','ltx-deskweb','athena-ladypoly','athena-separator-web','athena-voxcpm2-web','athena-omnivoice-web','athena-acestep-web','athena-applio-web'):raise ValueError('Host-Netzwerk nur für bekannte Deck-Oberflächen erlaubt.')
recipes={'applio-web':('athena-applio-web','athena-applio-web:3.6.5-deck1'),'acestep-web':('athena-acestep-web','athena-acestep-web:1.0.0'),'separator-web':('athena-separator-web','athena-separator-web:0.1.0'),'swarm-ui':('athena-swarm-ui','athena-swarm-ui:de7b834'),'ladypoly':('athena-ladypoly','athena-ladypoly:3960afc-deck1')}
if c.get('network')=='host' and c['name'] not in ('athena-swarm-ui','ltx-deskweb','athena-ladypoly','athena-separator-web','athena-voxcpm2-web','athena-omnivoice-web','athena-acestep-web','athena-applio-web','athena-xvc-web'):raise ValueError('Host-Netzwerk nur für bekannte Deck-Oberflächen erlaubt.')
recipes={'xvc-web':('athena-xvc-web','athena-xvc-web:0.1.0-deck1'),'applio-web':('athena-applio-web','athena-applio-web:3.6.5-deck1'),'acestep-web':('athena-acestep-web','athena-acestep-web:1.0.0'),'separator-web':('athena-separator-web','athena-separator-web:0.1.0'),'swarm-ui':('athena-swarm-ui','athena-swarm-ui:de7b834'),'ladypoly':('athena-ladypoly','athena-ladypoly:3960afc-deck1')}
if c.get('build_recipe')=='voice-web' and c['name'] in ('athena-voxcpm2-web','athena-omnivoice-web') and c.get('image') in ('athena-voice-web:0.2.1-deck1','athena-voice-web:0.2.1-deck2'):pass
elif c.get('build_recipe') is not None and recipes.get(c['build_recipe'])!=(c['name'],c.get('image')):raise ValueError('Unbekanntes Build-Rezept.')
ref=c.get('registry') or c.get('image','')
@@ -94,12 +94,13 @@ def validate(c):
if m.get('index')!=i or type(m.get('read_only')) is not bool or type(m.get('was_file')) is not bool:raise ValueError('Ungültige Volume-Einstellung.')
rel=m.get('deck_path')
media={'video/original-work/remote-inputs/deskweb':('/data/inputs',False),'video/original-work/outputs':('/data/outputs',True)}
native_xvc=rel=='xvc-data/bridge-key' and c['name']=='athena-xvc-web' and target=='/run/secrets/xvc-bridge' and m['read_only'] and m['was_file']
native_applio=rel=='applio-data/bridge-key' and c['name']=='athena-applio-web' and target=='/run/secrets/applio-bridge' and m['read_only'] and m['was_file']
native_media=rel in media and c['name']=='ltx-deskweb' and (target,m['read_only'])==media[rel] and not m['was_file']
if rel is not None and not native_media and not native_applio and (rel not in ('models','video/comfy-work/models','video/comfy-client-token') or not m['read_only']):raise ValueError('Deck-Volume nicht freigegeben; nur bekannte Modell-/Tokenpfade und LTX-Medienordner erlaubt.')
if rel is not None and not native_media and not native_applio and not native_xvc and (rel not in ('models','video/comfy-work/models','video/comfy-client-token') or not m['read_only']):raise ValueError('Deck-Volume nicht freigegeben; nur bekannte Modell-/Tokenpfade und LTX-Medienordner erlaubt.')
for name,data in m.get('files',{}).items():
allowed=('file','Settings.fds','Backends.fds')
if c['name'] in ('athena-ladypoly','athena-separator-web','athena-voxcpm2-web','athena-omnivoice-web','athena-acestep-web','athena-applio-web') and m['target']=='/data':allowed+=('settings.json','deck-connection.json')
if c['name'] in ('athena-ladypoly','athena-separator-web','athena-voxcpm2-web','athena-omnivoice-web','athena-acestep-web','athena-applio-web','athena-xvc-web') and m['target']=='/data':allowed+=('settings.json','deck-connection.json')
if name not in allowed:raise ValueError('Unbekannte Konfigurationsdatei.')
if not isinstance(data,str) or len(base64.b64decode(data,validate=True))>MAX_FILE:raise ValueError('Ungültige Konfigurationsdatei.')
return c
@@ -117,9 +118,9 @@ def restore(manager,c):
# Never replace or restart an existing service during a restore.
if x['Config']['Image'] not in (c['image'],c.get('registry')):raise ValueError('Vorhandener Container verwendet ein anderes Image; manuell prüfen.')
return {'state':'reused','message':'Vorhandener markierter Container unverändert übernommen.'}
if c['name'] in ('athena-ladypoly','athena-separator-web','athena-voxcpm2-web','athena-omnivoice-web','athena-acestep-web','athena-applio-web'):
with socket.socket() as probe:probe.bind(('127.0.0.1',{'athena-ladypoly':8127,'athena-separator-web':8128,'athena-voxcpm2-web':8129,'athena-omnivoice-web':8130,'athena-acestep-web':8131,'athena-applio-web':8132}[c['name']]))
if c.get('build_recipe') in ('swarm-ui','ladypoly','separator-web','voice-web','acestep-web','applio-web'):
if c['name'] in ('athena-ladypoly','athena-separator-web','athena-voxcpm2-web','athena-omnivoice-web','athena-acestep-web','athena-applio-web','athena-xvc-web'):
with socket.socket() as probe:probe.bind(('127.0.0.1',{'athena-ladypoly':8127,'athena-separator-web':8128,'athena-voxcpm2-web':8129,'athena-omnivoice-web':8130,'athena-acestep-web':8131,'athena-applio-web':8132,'athena-xvc-web':8133}[c['name']]))
if c.get('build_recipe') in ('swarm-ui','ladypoly','separator-web','voice-web','acestep-web','applio-web','xvc-web'):
source=Path(__file__).parent/c['build_recipe']
if not (source/'Dockerfile').is_file():raise ValueError('Gepinntes Swarm-Build-Rezept fehlt im Systemhelfer.')
if c['build_recipe']=='voice-web':
@@ -147,7 +148,7 @@ def restore(manager,c):
if base.is_symlink():raise ValueError('Unsicheres Dienstverzeichnis.')
base.mkdir(parents=True,exist_ok=True,mode=0o700)
args=['create','--name',name,'--network',c['network'],'--restart',c['restart'],'--cap-drop','ALL','--security-opt','no-new-privileges:true','--pids-limit','256']
if c['name'] in ('athena-ladypoly','athena-separator-web','athena-voxcpm2-web','athena-omnivoice-web','athena-acestep-web','athena-applio-web'):
if c['name'] in ('athena-ladypoly','athena-separator-web','athena-voxcpm2-web','athena-omnivoice-web','athena-acestep-web','athena-applio-web','athena-xvc-web'):
args+=['--read-only','--tmpfs','/tmp:rw,noexec,nosuid,size='+('1g' if c['name']=='athena-separator-web' else '128m')+',uid=65534,gid=65534']
if c['memory']:args+=['--memory',str(c['memory'])]
if c['nanocpus']:args+=['--cpus',str(c['nanocpus']/1e9)]
@@ -163,10 +164,10 @@ def restore(manager,c):
source=deck/m['deck_path'] if m['deck_path'] is not None else base/str(i)
if source.is_symlink():raise ValueError('Unsicheres Volume-Verzeichnis.')
if m['deck_path']:
if m['deck_path'] in ('video/comfy-client-token','applio-data/bridge-key') and not source.exists():
if m['deck_path'] in ('video/comfy-client-token','applio-data/bridge-key','xvc-data/bridge-key') and not source.exists():
import secrets
source.parent.mkdir(parents=True,exist_ok=True);source.write_text(secrets.token_urlsafe(48)+'\n');source.chmod(0o600);os.chown(source,65534,65534)
elif m['deck_path'] not in ('video/comfy-client-token','applio-data/bridge-key'):
elif m['deck_path'] not in ('video/comfy-client-token','applio-data/bridge-key','xvc-data/bridge-key'):
source.mkdir(parents=True,exist_ok=True)
if m['deck_path'].startswith('video/original-work/'):
is_input=m['deck_path'].endswith('/deskweb');os.chown(source,1000 if is_input else 65534,65534);source.chmod(0o2770 if is_input else 0o2750)
+36 -3
View File
@@ -18,6 +18,9 @@ LABEL = 'de.casaderoll.athena-deck.standalone'
FILES = ['deploy/applio-requirements.lock','deploy/activate_applio.py','deploy/import_applio.py','deploy/backup_applio_data.py','applio.py','applio_runtime.py','applio_worker.py','applio-ui.js','deploy/activate_acestep.py','acestep_models.py','deploy/import_acestep.py','deploy/acestep-web/Dockerfile','deploy/acestep-web/app.py','deploy/acestep-web/index.html','acestep.py','acestep_worker.py','acestep_runtime.py','acestep-ui.js','deploy/acestep-requirements.lock','deploy/omnivoice-requirements.lock','omnivoice_runtime.py','omnivoice_worker.py','deploy/voice-web/Dockerfile','deploy/voice-web/base.Dockerfile','deploy/voice-web/bridge.py','deploy/patch_yue2_residency.py','embeddings.py','voxcpm_test.py','voxcpm_worker.py','voice-ui.js','voxcpm_runtime.py','voxcpm-ui.js','deploy/voxcpm-requirements.lock','network/native.py','deploy/setup_network_helper.py','separator_sources.json','deploy/separator-web/Dockerfile','deploy/separator-web/app.py','deploy/separator-web/index.html','separator.py','separator_runtime.py','separator_worker.py','separator-ui.js','deploy/ladypoly/Dockerfile','deploy/ladypoly/bridge.py','music.py','music-ui.js','audio_cpp_runtime.py','audio-cpp-ui.js','ltx_original_runtime.py','ltx_original_entry.py','video_original.py','ltx-original-ui.js','deploy/ltx-original-requirements.lock','backup.py','backup_codec.py','backup-ui.js','deploy/docker_backup.py','deploy/swarm-ui/Dockerfile','deploy/swarm-ui/patch-source.py','deploy/swarm-ui/proxy.py','deploy/swarm-ui/entrypoint.py','deploy/Dockerfile.app-update','video_comfy.py','video_comfy_node.py','video_comfy_proxy.py','prompt_enhancer.py','prompt_enhancer_worker.py','image_upload.py','audio_policy.py','deploy/tts-requirements.lock','stt.py','stt-ui.js','api_compat.py','responses_compat.py','execution_setup.py','tts_runtime.py','tts_test.py','tts_worker.py','tts-ui.js','auto_test.py','auto-test-ui.js','chat_test.py','chat-test-ui.js','endpoint.py','inference.py','endpoint-ui.js','docker_support.py','docker-ui.js','deploy/docker_helper.py','deploy/setup_docker_helper.py','image_encoder_node.py','image_runtime.py','image_test.py','image-test-ui.js','profiles.py','profiles-ui.js','capacity.py','runtime.py','runtime-ui.js','video.py','video_proxy.py','video-ui.js','catalog.py','hub_auth.py','catalog-ui.js','server.py','auth.py','collect_hardware.py','dashboard_data.py','dashboard_history.py','dashboard-ui.js','dashboard.css','themes.css','deploy/import_dashboard_history.py','index.html','app.js','studio.js','style.css','login.html','login.js','access-ui.js','network-ui.js','network/__init__.py','network/client.py','network/config.py','network/rpc.py','deploy/Dockerfile','deploy/image-requirements.lock']
FILES += ['xvc.py','xvc_runtime.py','xvc_sources.json','xvc-ui.js','deploy/xvc-requirements.lock','deploy/prepare_xvc.py']
FILES += ['cuda_overlay.py','remix.py','remix_runtime.py','remix_worker.py','remix_sources.json','clearvoice_worker.py','deploy/ladypoly/patch_remix.py']
FILES += sorted(str(p.relative_to(ROOT)) for p in (ROOT/'deploy/xvc-web').rglob('*') if p.is_file() and not {'__pycache__','.pytest_cache'} & set(p.parts))
FILES += sorted(str(p.relative_to(ROOT)) for p in (ROOT/'deploy/applio-web').rglob('*') if p.is_file() and not {'__pycache__','.pytest_cache'} & set(p.parts))
def run(*args, check=True, interactive=False):
@@ -67,7 +70,37 @@ def free_port(port):
raise RuntimeError('Der gewünschte Loopback-Port ist bereits belegt.') from None
def compact_runtime_image(runtime_image):
"""Flatten only image files; never export a running container or its volumes."""
metadata=json.loads(run('docker','image','inspect',runtime_image).stdout)[0]
if len(metadata.get('RootFS',{}).get('Layers',[])) < 100:
return runtime_image
tag='athena-deck-runtime-flat:'+metadata['Id'].split(':')[-1][:16]
if run('docker','image','inspect',tag,check=False).returncode == 0:
return tag
print('Docker-Laufzeitbasis zusammenfassen; Datenvolumes bleiben unangetastet.',flush=True)
container=run('docker','create',metadata['Id']).stdout.strip()
config=metadata['Config'];changes=[]
for value in config.get('Env',[]):changes += ['--change','ENV '+value]
for key in ('Entrypoint','Cmd'):
if config.get(key):changes += ['--change',key.upper()+' '+json.dumps(config[key])]
for key in ('User','WorkingDir'):
if config.get(key):changes += ['--change',('USER' if key=='User' else 'WORKDIR')+' '+config[key]]
for key,value in (config.get('Labels') or {}).items():
changes += ['--change','LABEL '+key+'='+json.dumps(value)]
try:
# /tmp is often a small RAM filesystem on GPU hosts.
with tempfile.TemporaryFile(dir='/var/tmp') as archive:
subprocess.run(['docker','export',container],stdout=archive,check=True)
archive.seek(0)
subprocess.run(['docker','import',*changes,'-',tag],stdin=archive,stdout=subprocess.DEVNULL,check=True)
finally:
run('docker','rm',container,check=False)
return tag
def build(runtime_image=None):
if runtime_image:runtime_image=compact_runtime_image(runtime_image)
digest = hashlib.sha256()
for name in FILES:
digest.update(name.encode());digest.update((ROOT/name).read_bytes())
@@ -111,8 +144,8 @@ def launch(config):
'-p','127.0.0.1:'+str(config['port'])+':8108',
'--health-cmd', 'python3 -c "import urllib.request,json; assert json.load(urllib.request.urlopen(\'http://127.0.0.1:8108/api/v1/auth/status\',timeout=3))[\'initialized\']"',
'--health-interval','30s','--health-timeout','5s','--health-retries','3']
if config['port']==8134 or 8134 in config.get('api_ports',[]):raise RuntimeError('Port 8134 ist für die interne Applio-Brücke reserviert.')
args+=['-p','127.0.0.1:8134:8134']
if config['port'] in (8134,8135) or set(config.get('api_ports',[])) & {8134,8135}:raise RuntimeError('Ports 8134/8135 sind für interne Stimmwerkzeug-Brücken reserviert.')
args+=['-p','127.0.0.1:8134:8134','-p','127.0.0.1:8135:8135']
if config.get('api_ports'):
args+=['-e','DECK_API_BIND=0.0.0.0','-e','DECK_API_PORTS='+','.join(map(str,config['api_ports']))]
for port in config['api_ports']:args+=['-p',f'127.0.0.1:{port}:{port}']
@@ -219,7 +252,7 @@ def update(base, rollback=False, force=False, api_ports=None, reuse_runtime=Fals
backup_name=config['name']+'-previous'
if inspect(backup_name):raise RuntimeError('Rückfall-Containername belegt. Keine Änderung ausgeführt.')
stamp=str(time.time_ns())
shutil.copytree(base/'state',base/'backups'/stamp,ignore=shutil.ignore_patterns('cache','omni-reference-check.py','omni-cache-clean.py','applio-runtime','applio-data','applio-checkout','applio-runtime.py','import_applio.py','applio-migration.log','acestep-runtime','acestep-jobs','acestep-setup-code','acestep-checkout','acestep-source-files','acestep-test-tmp','music-verification','music-test-temp','music-jobs','separator-runtime','separator-tests','voxcpm-runtime','omnivoice-runtime','voice-worker-check','voice-integration-check','voice-setup-code','audio-cpp-runtime','ltx-original-runtime','original-work','tts-runtime','tts-tests','voice-tests','models','runtime','runtime-verification','image-tests','image-verification','image-verification-*','image-runtime','video-runtime','video-verification','video-verification-*','comfy-work','router-verification-*'))
shutil.copytree(base/'state',base/'backups'/stamp,ignore=shutil.ignore_patterns('xvc-runtime','xvc-data','xvc-prepare','cache','omni-reference-check.py','omni-cache-clean.py','applio-runtime','applio-data','applio-checkout','applio-runtime.py','import_applio.py','applio-migration.log','acestep-runtime','acestep-jobs','acestep-setup-code','acestep-checkout','acestep-source-files','acestep-test-tmp','music-verification','music-test-temp','music-jobs','music-remix-runtime','separator-runtime','separator-tests','voxcpm-runtime','omnivoice-runtime','voice-worker-check','voice-integration-check','voice-setup-code','audio-cpp-runtime','ltx-original-runtime','original-work','tts-runtime','tts-tests','voice-tests','models','runtime','runtime-verification','image-tests','image-verification','image-verification-*','image-runtime','video-runtime','video-verification','video-verification-*','comfy-work','router-verification-*'))
was_running=previous['State']['Running']
if was_running:run('docker','stop','--time','15',config['name'])
run('docker','rename',config['name'],backup_name)
+3 -1
View File
@@ -6,8 +6,10 @@ RUN apt-get update && apt-get install -y --no-install-recommends git libsndfile1
&& rm -rf /app/.git \
&& pip install --no-cache-dir fastapi==0.115.12 uvicorn==0.34.2 python-multipart==0.0.20 numpy==2.2.6 soundfile==0.13.1
COPY bridge.py /app/webui/deck_bridge.py
COPY patch_remix.py /tmp/patch_remix.py
RUN python /tmp/patch_remix.py /app/webui
RUN python -c "from pathlib import Path; p=Path('/app/webui/server.py'); s=p.read_text(); s=s.replace('SETTINGS_FILE = Path(__file__).resolve().parent / \"settings.json\"','SETTINGS_FILE = Path(\"/data/settings.json\")'); s=s.replace('from loras import Loras', 'from deck_bridge import Loras'); s=s.replace('if __name__ == \"__main__\":','from deck_bridge import install\ninstall(globals())\n\nif __name__ == \"__main__\":'); p.write_text(s)"
RUN python -c "from pathlib import Path; p=Path('/app/webui/static/index.html'); s=p.read_text().replace('<body>', '<body><div style=\"padding:12px;background:#193249;color:white\">LadyPoly mit Athena Deck · <a style=\"color:#8de8ff\" href=\"/deck-connection\">Deck-Verbindung einrichten</a> · In Deck Musik aktivieren. Worker-Abbruch in Deck.</div>'); s=s.replace('value=\"full\" checked', 'value=\"full\" disabled').replace('value=\"melody\"', 'value=\"melody\" disabled').replace('value=\"off\"', 'value=\"off\" checked'); s=s.replace('</head>', '<style>#engineToggle,#muse,#coverDrawer,#scoreDrawer,#advDrawer,#cancelRun{display:none!important}</style></head>'); p.write_text(s)"
RUN python -c "from pathlib import Path; p=Path('/app/webui/static/index.html'); s=p.read_text().replace('<body>', '<body><div style=\"padding:12px;background:#193249;color:white\">LadyPoly mit Athena Deck · <a style=\"color:#8de8ff\" href=\"/deck-connection\">Deck-Verbindung einrichten</a> · In Deck Musik aktivieren. Worker-Abbruch in Deck.</div>'); s=s.replace('</head>', '<style>#engineToggle,#muse,#advDrawer,#cancelRun{display:none!important}</style></head>'); p.write_text(s)"
ENV PYTHONPATH=/app/src YUE2_HOST=127.0.0.1 YUE2_PORT=8127 YUE2_OUTPUTS=/data/outputs HOME=/data
WORKDIR /app
USER 65534:65534
+29 -13
View File
@@ -1,20 +1,20 @@
"""LadyPoly UI -> authenticated Deck music API. No local model engine."""
import json, os, time, urllib.request, urllib.error
import json, os, time, urllib.request, urllib.error, secrets, asyncio
from pathlib import Path
from fastapi import HTTPException
from fastapi import HTTPException, UploadFile, File, Form
from fastapi.responses import HTMLResponse
from pydantic import BaseModel
CONNECTION = Path('/data/deck-connection.json')
BASE = 'http://127.0.0.1:8120'
def request(path, data=None, connection=None):
def request(path, data=None, connection=None, ctype='application/json', base=BASE):
c = connection or (json.loads(CONNECTION.read_text()) if CONNECTION.exists() else {})
if not c.get('token'): raise RuntimeError('Zuerst unter Deck-Verbindung den API-Token hinterlegen.')
req = urllib.request.Request(BASE + path, data=json.dumps(data).encode() if data is not None else None,
headers={'Authorization': 'Bearer ' + c['token'], 'Content-Type':'application/json'})
req = urllib.request.Request(base + path, data=(data if isinstance(data,bytes) else json.dumps(data).encode()) if data is not None else None,
headers={'Authorization': 'Bearer ' + c['token'], 'Content-Type':ctype})
try:
with urllib.request.urlopen(req, timeout=1850) as response: return response.read()
with urllib.request.urlopen(req, timeout=3650) as response: return response.read()
except urllib.error.HTTPError as exc:
try: message=json.loads(exc.read()).get('error', {}).get('message', 'Deck-Anfrage abgelehnt')
except Exception: message='Deck-Anfrage abgelehnt'
@@ -30,7 +30,7 @@ class Connection(BaseModel):
token: str
model: str
PAGE='''<!doctype html><meta charset="utf-8"><style>body{background:#12151c;color:#eee;font:18px system-ui;max-width:720px;margin:50px auto}input,button{padding:12px;display:block;margin:15px 0;width:90%}a{color:#72d6ff}</style><h1>LadyPoly · Deck-Verbindung</h1><p>In Deck das YuE2-Profil am API-Endpunkt freigeben und den Musik-Modus aktivieren. Hier den API-Token aus „Zugang & API“ und den genauen Profilnamen eingeben.</p><form id="f"><input id="token" type="password" placeholder="Deck API-Token" required autocomplete="off"><input id="model" placeholder="API-Profilname, z. B. YuE2 Studio" required><button>Verbindung prüfen und speichern</button></form><p id="msg"></p><a href="/">LadyPoly öffnen →</a><p>Diese Anbindung unterstützt Liedtext, Stil, Seed und Syntheseschritte. Score, LoRA, eigener Writer und Cover-Generator sind hier noch nicht angebunden. Deck lädt und entlädt die Gewichte.</p><script>f.onsubmit=async e=>{e.preventDefault();msg.textContent='Prüfe …';try{let r=await fetch('/api/deck/connection',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({token:token.value,model:model.value})});let d=await r.json();msg.textContent=r.ok?'Verbunden. Jetzt LadyPoly öffnen.':d.detail;token.value=''}catch(e){msg.textContent='Verbindung fehlgeschlagen'}}</script>'''
PAGE='''<!doctype html><meta charset="utf-8"><style>body{background:#12151c;color:#eee;font:18px system-ui;max-width:720px;margin:50px auto}input,button{padding:12px;display:block;margin:15px 0;width:90%}a{color:#72d6ff}</style><h1>LadyPoly · Deck-Verbindung</h1><p>In Deck das YuE2-Profil am API-Endpunkt freigeben und den Musik-Modus aktivieren. Hier den API-Token aus „Zugang & API“ und den genauen Profilnamen eingeben.</p><form id="f"><input id="token" type="password" placeholder="Deck API-Token" required autocomplete="off"><input id="model" placeholder="API-Profilname, z. B. YuE2 Studio" required><button>Verbindung prüfen und speichern</button></form><p id="msg"></p><a href="/">LadyPoly öffnen →</a><p>Diese Anbindung unterstützt Liedtext, Stil, Seed und Syntheseschritte. Audio-Remix und ABC-Score laufen über Deck. LoRA, eigener Writer und Bild-Cover-Generator sind hier noch nicht angebunden. Deck lädt und entlädt die Gewichte.</p><script>f.onsubmit=async e=>{e.preventDefault();msg.textContent='Prüfe …';try{let r=await fetch('/api/deck/connection',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({token:token.value,model:model.value})});let d=await r.json();msg.textContent=r.ok?'Verbunden. Jetzt LadyPoly öffnen.':d.detail;token.value=''}catch(e){msg.textContent='Verbindung fehlgeschlagen'}}</script>'''
def install(g):
app=g['app'];g['SETTINGS'].song_engine='gguf';g['SETTINGS'].art_auto=False;g['SETTINGS'].stall_timeout=0
@@ -47,26 +47,42 @@ def install(g):
CONNECTION.write_text(json.dumps(c));CONNECTION.chmod(0o600)
return {'ok':True}
def render(job,spec):
if spec.get('abc') or spec.get('cfg_scale') is not None or spec.get('abc_sampling') or spec.get('semantic_sampling') or g['SETTINGS'].loras:
raise RuntimeError('Score, Sampling-Overrides und LoRA sind in der Deck-Anbindung noch nicht verfügbar.')
if spec.get('cfg_scale') is not None or spec.get('abc_sampling') or spec.get('semantic_sampling') or g['SETTINGS'].loras:
raise RuntimeError('Sampling-Overrides und LoRA sind in der Deck-Anbindung noch nicht verfügbar.')
c=json.loads(CONNECTION.read_text()) if CONNECTION.exists() else {}
spec['cot']='off'
spec['cot']=spec.get('cot','off') if spec.get('abc') else 'off'
job.setup='Deck lädt YuE2 und erzeugt Musik · Musik-Modus erforderlich';job.setup_at=time.time();job.push(force=True)
start=time.monotonic()
audio=request('/v1/audio/music',dict(model=c.get('model',''),lyrics=spec['lyrics'],style=spec['style'],seed=spec['seed'],steps=g['SETTINGS'].ode_steps,max_tokens=9000))
audio=request('/v1/audio/music',dict(model=c.get('model',''),lyrics=spec['lyrics'],style=spec['style'],seed=spec['seed'],steps=g['SETTINGS'].ode_steps,max_tokens=9000,**({'abc':spec['abc'],'cot':spec['cot']} if spec.get('abc') else {})))
if job.cancel_flag.is_set():raise InterruptedError('UI-Auftrag abgebrochen. Laufenden Deck-Job in Deck stoppen.')
work=g['OUTPUTS']/('.pending-'+job.id);work.mkdir(parents=True,exist_ok=True)
wav=work/'audio.wav';wav.write_bytes(audio)
return g['GgufSong'](spec,wav,{'e2e_seconds':time.monotonic()-start},'',{'runtime':'Athena Deck audio.cpp','profile':c.get('model')})
return g['GgufSong'](spec,wav,{'e2e_seconds':time.monotonic()-start},spec.get('abc',''),{'runtime':'Athena Deck audio.cpp','profile':c.get('model')})
g['render_gguf']=render;g['render_torch']=render
g['ENGINE'].detail='Remote-Laufzeit in Athena Deck · Musik-Modus erforderlich'
# Replace upstream handlers: its local torch engine is deliberately unused.
app.router.routes[:]=[r for r in app.router.routes if getattr(r,'path','') not in ('/api/cover/status','/api/cover/from-audio')]
@app.get('/api/cover/status')
def cover_status():
try:state=json.loads(request('/api/v1/music-remix',base='http://127.0.0.1:8108'))
except Exception as exc:raise HTTPException(503,str(exc)) from None
return {'sheetsage':{'available':state['installed']},'takes':[{'name':t['name'],'title':t['title'],'has_score':True} for t in g['library']() if t.get('score')]}
@app.post('/api/cover/from-audio')
async def from_audio(file: UploadFile=File(...),melody_only: bool=Form(True)):
audio=await file.read(256*1024**2+1)
if len(audio)>256*1024**2:raise HTTPException(400,'Audio maximal 256 MiB.')
boundary=secrets.token_hex(24)
body=(f'--{boundary}\r\nContent-Disposition: form-data; name="melody_only"\r\n\r\n{str(melody_only).lower()}\r\n--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="input.wav"\r\nContent-Type: application/octet-stream\r\n\r\n'.encode()+audio+f'\r\n--{boundary}--\r\n'.encode())
try:
result=json.loads(await asyncio.to_thread(request,'/api/v1/music-remix/transcribe',body,None,'multipart/form-data; boundary='+boundary,'http://127.0.0.1:8108'));result['source']=Path(file.filename or 'Audio').name;return result
except Exception as exc:raise HTTPException(400,str(exc)) from None
@app.middleware('http')
async def deck_guard(req,call_next):
path=req.url.path
origin=req.headers.get('Origin')
if req.method!='GET' and origin and origin not in ('http://'+req.headers.get('Host',''),'https://'+req.headers.get('Host','')):
return g['JSONResponse']({'detail':'Cross-Origin-Zugriff nicht erlaubt.'},status_code=403)
if req.method!='GET' and not (path in {'/api/generate','/api/deck/connection','/api/unlock'} or (req.method=='DELETE' and path.startswith('/api/library/') and path.count('/')==3)):
if req.method!='GET' and not (path in {'/api/generate','/api/deck/connection','/api/unlock','/api/cover/from-audio','/api/cover/from-take'} or (req.method=='DELETE' and path.startswith('/api/library/') and path.count('/')==3)):
return g['JSONResponse']({'detail':'Laufzeiten, Modelle und Einstellungen werden in Athena Deck verwaltet.'},status_code=409)
response=await call_next(req)
response.headers['Cache-Control']='no-store'
+156
View File
@@ -0,0 +1,156 @@
"""Small Linux integration fixes for the pinned community WebUI.
Keep these transformations explicit and fail the image build if upstream moves
the expected code. That prevents a future upstream update from silently
producing a half-patched console.
"""
from pathlib import Path
import sys
root = Path(sys.argv[1])
app_js = root / "static" / "app.js"
index_html = root / "static" / "index.html"
server_py = root / "server.py"
def replace_once(path: Path, old: str, new: str) -> None:
text = path.read_text(encoding="utf-8")
if text.count(old) != 1:
raise RuntimeError(f"expected exactly one patch marker in {path}: {old[:80]!r}")
path.write_text(text.replace(old, new, 1), encoding="utf-8")
# The published UI calls refreshArt() during startup, but does not define it.
# Athena does not install the Windows-only stable-diffusion.cpp helper, so show
# that state honestly and keep the optional controls inert instead of crashing
# the whole page.
art_marker = ''' $("artDirAdd").addEventListener("click", function () {
'''
art_fix = ''' function refreshArt() {
return api("/api/art/status").then(function (data) {
STATE.art = data;
var installed = !!data.installed;
var supported = !!data.supported;
$("artState").textContent = data.busy || (installed ? "installed" :
(supported ? "not installed" : "not available on Linux"));
$("artState").dataset.s = data.busy ? "busy" : (installed ? "ready" : "missing");
$("artInstall").disabled = !!data.busy || !supported;
$("artInstall").textContent = installed ? "Reinstall" : "Install";
$("setArtAuto").checked = !!data.auto;
$("setArtAuto").disabled = !installed;
$("setArtModel").innerHTML = (data.models || []).length
? data.models.map(function (m) {
return '<option value="' + escape(m.path) + '">' + escape(m.name || m.file) + '</option>';
}).join("")
: '<option value="">no art model available</option>';
if (data.selected) $("setArtModel").value = data.selected;
$("setArtModel").disabled = !installed;
$("artDir").disabled = !supported;
$("artDirAdd").disabled = !supported;
$("artDirs").textContent = supported
? ((data.dirs || []).length ? "Also scanning: " + data.dirs.join(" · ") : "No extra folders configured.")
: "The community release only provides the cover-art installer for Windows; song generation is unaffected.";
$("artCatalog").innerHTML = "";
return data;
}).catch(function (error) {
$("artState").textContent = "unavailable";
$("artInstall").disabled = true;
$("artDirs").textContent = error.message;
});
}
$("artDirAdd").addEventListener("click", function () {
'''
replace_once(app_js, art_marker, art_fix)
# This UI container intentionally has no GPU: Deck owns the remote CUDA worker.
replace_once(app_js, ''' if (!data.hardware.cuda) {
toast("No CUDA device visible — generation needs an NVIDIA GPU with BF16", "bad");
}
''', '')
# The backend already ships a complete SheetSage2 upload endpoint but hides it
# from the published console. Surface it beside the existing take-to-take
# remix controls so uploaded songs can seed a new melody/arrangement.
replace_once(
index_html,
''' <p class="row-hint" id="coverStatus"></p>
</div>
</details>
''',
''' <p class="row-hint" id="coverStatus"></p>
<h4>Remix an uploaded recording</h4>
<p class="hint">SheetSage2 listens to an uploaded song and writes an editable melody
and chord score for YuE2. This is structural transcription, not a sample or a copy of
the original sound. After analysis, choose a new style and generate normally.</p>
<div class="field-row">
<label class="field grow">
<span class="label">Source audio</span>
<input id="coverAudio" type="file" accept=".wav,.flac,.mp3,.m4a,.ogg,.opus,.aac,audio/*" />
</label>
<div class="field reset-cell">
<button type="button" class="btn ghost" id="coverFromAudio">Analyse uploaded melody</button>
</div>
</div>
<label class="check"><input type="checkbox" id="coverAudioMelodyOnly" checked />
<span>Keep the melody, but let the new style rebuild the harmony</span></label>
<p class="row-hint" id="coverAudioStatus">Checking SheetSage2…</p>
</div>
</details>
''',
)
replace_once(
app_js,
''' $("coverStatus").textContent = takes.length
? takes.length + " takes carry a score you can remix."
: "Make a song in Full plan or Melody only mode first; Direct mode keeps no score.";
}).catch(function () {});
''',
''' $("coverStatus").textContent = takes.length
? takes.length + " takes carry a score you can remix."
: "Make a song in Full plan or Melody only mode first; Direct mode keeps no score.";
var sheetsage = data.sheetsage || {};
$("coverFromAudio").disabled = !sheetsage.available;
$("coverAudioStatus").textContent = sheetsage.available
? "SheetSage2 is ready. Analysis temporarily parks YuE2 because both use the GPU."
: "SheetSage2 is not installed yet; uploaded-audio remix is unavailable.";
}).catch(function (error) {
$("coverFromAudio").disabled = true;
$("coverAudioStatus").textContent = error.message;
});
''',
)
replace_once(
app_js,
''' /* -------------------------------------------------------------- compose */
''',
''' $("coverFromAudio").addEventListener("click", function () {
var file = $("coverAudio").files[0];
if (!file) return toast("Choose an audio file first", "bad");
var button = $("coverFromAudio");
var body = new FormData();
body.append("file", file, file.name);
body.append("melody_only", $("coverAudioMelodyOnly").checked ? "true" : "false");
button.disabled = true;
button.textContent = "Analysing…";
$("coverAudioStatus").textContent = "Listening to “" + file.name + "”… this can take several minutes.";
api("/api/cover/from-audio", { method: "POST", body: body }).then(function (data) {
applyCoverScore(data.abc, "Melody analysed from “" + data.source + "” in " + data.seconds + " s. Choose the new style and generate.");
if (!data.melody_only) { var full = document.querySelector('input[name="cot"][value="full"]'); if (full) { full.checked = true; full.dispatchEvent(new Event("change", {bubbles:true})); } }
$("coverAudioStatus").textContent = "Analysis complete in " + data.seconds + " s. The editable score is loaded below.";
}).catch(function (error) {
$("coverAudioStatus").textContent = error.message;
toast(error.message, "bad");
}).then(function () {
button.textContent = "Analyse uploaded melody";
refreshCover();
});
});
/* -------------------------------------------------------------- compose */
''',
)
+13 -3
View File
@@ -21,10 +21,20 @@ class BridgeTest(unittest.TestCase):
self.assertEqual(payload['max_tokens'],9000);self.assertNotIn('abc',payload)
saved=result.save_artifacts(root/'take');self.assertEqual(saved['audio_seconds'],1)
self.assertTrue((root/'take/audio.flac').is_file())
def test_unsupported_score_does_not_start_deck(self):
def test_unsupported_sampling_does_not_start_deck(self):
with patch.object(bridge,'request') as request:
with self.assertRaisesRegex(RuntimeError,'Score'):
server.render_gguf(None,{'abc':'synthetic'})
with self.assertRaisesRegex(RuntimeError,'Sampling'):
server.render_gguf(None,{'cfg_scale':1})
request.assert_not_called()
def test_remix_score_forwarded_and_preserved_in_library(self):
with tempfile.TemporaryDirectory() as temp:
root=Path(temp);connection=root/'connection.json';connection.write_text(json.dumps({'model':'Synthetic Music','token':'synthetic'}))
raw=io.BytesIO()
with wave.open(raw,'wb') as wav:wav.setparams((1,2,48000,0,'NONE','none'));wav.writeframes(bytes(9600))
job=SimpleNamespace(id='synthetic',cancel_flag=SimpleNamespace(is_set=lambda:False),push=lambda **k:None)
abc='X:1\nK:C\nC D E F|';spec=dict(style='pop',lyrics='test',seed=1,abc=abc,cot='melody')
with patch.object(bridge,'CONNECTION',connection),patch.object(server,'OUTPUTS',root),patch.object(bridge,'request',return_value=raw.getvalue()) as request:
result=server.render_gguf(job,spec);self.assertEqual(request.call_args.args[1]['abc'],abc);self.assertEqual(request.call_args.args[1]['cot'],'melody');result.save_artifacts(root/'take');self.assertEqual((root/'take/score.abc').read_text(),abc)
if __name__=='__main__':unittest.main()
+47
View File
@@ -0,0 +1,47 @@
"""Prepare X-VC without starting services; merge its inactive profile only after Deck stops."""
import json,os,secrets,subprocess,sys,time,uuid
from pathlib import Path
sys.path.insert(0,str(Path(__file__).resolve().parent.parent))
from catalog import Catalog
from xvc_runtime import XVCRuntime
def prepare(state):
state=Path(state).resolve();runtime=XVCRuntime(state/'xvc-runtime',None)
python,source=runtime.paths()
# The venv interpreter targets Deck's bundled Python, which lives inside its image.
if not (python.exists() or python.is_symlink()) or not (source/'models/codec/sac/model.py').is_file():raise ValueError('X-VC-Laufzeit zuerst installieren.')
ident=runtime.ensure_library();pending=state/'xvc-profile-pending.json'
if pending.exists():
row=json.loads(pending.read_text())
if row.get('model_id')!=ident or row.get('api_id')!='xvc-studio':raise ValueError('Abweichendes vorbereitetes X-VC-Profil prüfen.')
else:
row=dict(id=uuid.uuid4().hex,revision=1,name='X-VC Studio',api_id='xvc-studio',api_aliases=[],kind='voice',model_id=ident,parameters={},components={},presets=[],prompt_enhancer=None,updated_at=time.time())
pending.write_text(json.dumps(row,indent=2));os.chown(pending,65534,65534)
root=state/'xvc-data';root.mkdir(parents=True,exist_ok=True);os.chown(root,65534,65534)
settings=root/'settings.json'
if not settings.exists():settings.write_text(json.dumps({'device':'5080'}));os.chown(settings,65534,65534)
key=root/'bridge-key'
if not key.exists():key.write_text(secrets.token_urlsafe(48));key.chmod(0o600);os.chown(key,65534,65534)
name='athena-xvc-web';found=subprocess.run(['docker','inspect',name],capture_output=True,text=True)
if found.returncode==0:
row=json.loads(found.stdout)[0];labels=row['Config'].get('Labels') or {}
if labels.get('io.athena-deck.managed')!='true' or labels.get('io.athena-deck.application')!='xvc-web':raise ValueError('Containername anderweitig belegt.')
if row['State']['Running']:raise ValueError('Vorhandene X-VC-UI läuft bereits; Vorbereitung verändert sie nicht.')
else:
subprocess.run(['docker','create','--name',name,'--network','host','--restart','unless-stopped','--label','io.athena-deck.managed=true','--label','io.athena-deck.role=application','--label','io.athena-deck.application=xvc-web','--read-only','--cap-drop','ALL','--security-opt','no-new-privileges:true','--pids-limit','128','--memory','512m','--cpus','1','--tmpfs','/tmp:rw,noexec,nosuid,size=128m,uid=65534,gid=65534','--mount','type=bind,src='+str(key)+',dst=/run/secrets/xvc-bridge,readonly','athena-xvc-web:0.1.0-deck1'],check=True,stdout=subprocess.DEVNULL)
print('X-VC: inaktives Profil vorbereitet, UI-Container gestoppt. Keine Endpunktfreigabe geändert.')
def apply_profile(state,deck='athena-deck-dev'):
from profiles import Profiles
result=subprocess.run(['docker','inspect',deck],capture_output=True,text=True,check=True)
if json.loads(result.stdout)[0]['State']['Running']:raise ValueError('Deck läuft: Profil erst im späteren Wartungsfenster übernehmen.')
state=Path(state);row=json.loads((state/'xvc-profile-pending.json').read_text());profiles=Profiles(state/'profiles.json',Catalog(state/'models'))
existing=next((p for p in profiles.rows if p.get('api_id')==row['api_id']),None)
if existing:
if existing['model_id']!=row['model_id']:raise ValueError('X-VC API-ID bereits anders belegt.')
else:profiles.save(dict(id=None,revision=0,name=row['name'],api_id=row['api_id'],kind='voice',model_id=row['model_id'],parameters={}))
os.chown(state/'profiles.json',65534,65534)
print('Inaktives X-VC-Profil übernommen; Betriebsart und Freigaben unverändert.')
if __name__=='__main__':
if '--apply-profile' in sys.argv:apply_profile(sys.argv[1])
else:prepare(sys.argv[1])
+3 -3
View File
@@ -6,11 +6,11 @@ from email import policy
from email.parser import BytesParser
BASE='http://127.0.0.1:8108'
CONFIG=Path('/data/deck-connection.json')
TARGETS={'vocals':'model_bs_roformer_ep_317_sdr_12.9755.ckpt','drums':'htdemucs_ft.yaml','bass':'htdemucs_ft.yaml','guitar':'htdemucs_6s.yaml','piano':'htdemucs_6s.yaml','other':'htdemucs_6s.yaml'}
TARGETS={'vocals':'model_bs_roformer_ep_317_sdr_12.9755.ckpt','drums':'htdemucs_ft.yaml','bass':'htdemucs_ft.yaml','guitar':'htdemucs_6s.yaml','piano':'htdemucs_6s.yaml','other':'htdemucs_6s.yaml','speech':'MossFormer2_SE_48K'}
def archive_name(target,filename):
if target not in TARGETS:raise ValueError('Unbekannte Zielspur.')
if Path(filename).name=='rest.wav':return 'Instrumental.wav' if target=='vocals' else 'Rest.wav'
return {'vocals':'Vocals','drums':'Drums','bass':'Bass','guitar':'Guitar','piano':'Piano','other':'Other'}[target]+'.wav'
if Path(filename).name=='rest.wav':return 'Instrumental.wav' if target=='vocals' else 'Background.wav' if target=='speech' else 'Rest.wav'
return {'vocals':'Vocals','drums':'Drums','bass':'Bass','guitar':'Guitar','piano':'Piano','other':'Other','speech':'Speech'}[target]+'.wav'
def request(path,body=None,ctype='application/json',token=None):
if token is None:token=json.loads(CONFIG.read_text())['token'] if CONFIG.exists() else ''
if not token:raise ValueError('Zuerst die Deck-Verbindung einrichten.')
+1
View File
@@ -10,6 +10,7 @@
<label class="target"><input type="radio" name="target" value="bass"><b>Bass</b><span>HTDemucs FT</span></label>
<label class="target"><input type="radio" name="target" value="guitar"><b>Gitarre</b><span>HTDemucs 6s<br>experimentell</span></label>
<label class="target"><input type="radio" name="target" value="piano"><b>Piano</b><span>HTDemucs 6s<br>experimentell</span></label>
<label class="target"><input type="radio" name="target" value="speech"><b>Sprache</b><span>ClearVoice MossFormer2<br>Sprache / Hintergrund</span></label>
<label class="target"><input type="radio" name="target" value="other"><b>Sonstiges</b><span>Synths, Streicher etc.<br>gemischte Spur</span></label>
+2 -1
View File
@@ -26,7 +26,7 @@ def main():
for name in ('Dockerfile','patch-source.py','proxy.py','entrypoint.py'):
shutil.copyfile(Path(__file__).parent/'swarm-ui'/name,base/'swarm-ui'/name)
(base/'ladypoly').mkdir(exist_ok=True)
for name in ('Dockerfile','bridge.py'):
for name in ('Dockerfile','bridge.py','patch_remix.py'):
shutil.copyfile(Path(__file__).parent/'ladypoly'/name,base/'ladypoly'/name)
(base/'separator-web').mkdir(exist_ok=True)
for name in ('Dockerfile','app.py','index.html'):
@@ -34,6 +34,7 @@ def main():
(base/'acestep-web').mkdir(exist_ok=True)
for name in ('Dockerfile','app.py','index.html'):
shutil.copyfile(Path(__file__).parent/'acestep-web'/name,base/'acestep-web'/name)
shutil.copytree(Path(__file__).parent/'xvc-web',base/'xvc-web',dirs_exist_ok=True,ignore=shutil.ignore_patterns('__pycache__'))
shutil.copytree(Path(__file__).parent/'applio-web',base/'applio-web',dirs_exist_ok=True,ignore=shutil.ignore_patterns('__pycache__'))
(base/'voice-web').mkdir(exist_ok=True)
for name in ('Dockerfile','base.Dockerfile','bridge.py'):
+152
View File
@@ -0,0 +1,152 @@
absl-py==2.5.0
aiofiles==24.1.0
annotated-doc==0.0.5
annotated-types==0.8.0
antlr4-python3-runtime==4.9.3
anyio==4.15.1
argbind==0.3.9
asttokens==3.0.2
audioread==3.1.0
brotli==1.2.0
certifi==2026.7.22
cffi==2.1.1
charset-normalizer==3.5.2
click==8.5.0
cloudpickle==3.1.2
contourpy==1.3.3
cycler==0.12.1
decorator==5.3.1
descript-audiotools==0.7.2
docstring_parser==0.18.0
einops==0.8.2
einx==0.4.3
executing==2.2.1
fastapi==0.142.2
ffmpy==1.0.0
filelock==3.32.3
fire==0.7.1
flatten-dict==0.5.0
fonttools==4.66.1
frozendict==2.4.7
fsspec==2026.7.0
gradio==5.49.1
gradio_client==1.13.3
groovy==0.1.2
grpcio==1.84.0
h11==0.16.0
hf-xet==1.6.0
httpcore==1.0.9
httpx==0.28.1
huggingface_hub==0.36.2
hydra-core==1.3.7
idna==3.20
importlib_resources==7.1.0
ipython==9.17.1
ipython_pygments_lexers==1.1.1
jedi==0.20.0
Jinja2==3.1.6
joblib==1.6.0
julius==0.2.8
kiwisolver==1.5.1
lazy-loader==0.6
librosa==0.10.1
llvmlite==0.50.0
loguru==0.7.3
Markdown==3.11
markdown-it-py==4.2.0
markdown2==2.5.5
MarkupSafe==3.0.3
matplotlib==3.11.2
matplotlib-inline==0.2.2
mdurl==0.1.2
mpmath==1.3.0
msgpack==1.2.3
narwhals==2.26.0
networkx==3.6.1
numba==0.68.0
numpy==1.26.4
nvidia-cublas-cu12==12.8.4.1
nvidia-cuda-cupti-cu12==12.8.90
nvidia-cuda-nvrtc-cu12==12.8.93
nvidia-cuda-runtime-cu12==12.8.90
nvidia-cudnn-cu12==9.10.2.21
nvidia-cufft-cu12==11.3.3.83
nvidia-cufile-cu12==1.13.1.3
nvidia-curand-cu12==10.3.9.90
nvidia-cusolver-cu12==11.7.3.90
nvidia-cusparse-cu12==12.5.8.93
nvidia-cusparselt-cu12==0.7.1
nvidia-nccl-cu12==2.27.3
nvidia-nvjitlink-cu12==12.8.93
nvidia-nvtx-cu12==12.8.90
omegaconf==2.3.1
opentelemetry-api==1.45.0
orjson==3.12.0
packaging==26.3
pandas==2.3.3
parso==0.8.7
pexpect==4.9.0
pillow==11.3.0
platformdirs==4.12.3
pooch==1.9.0
prompt_toolkit==3.0.53
protobuf==3.19.6
psutil==7.2.2
ptyprocess==0.7.0
pure_eval==0.2.4
pycparser==3.0
pydantic==2.11.10
pydantic_core==2.33.2
pydub==0.25.1
Pygments==2.21.0
pyloudnorm==0.2.0
pyparsing==3.3.3
pystoi==0.4.1
python-dateutil==2.9.0.post0
python-multipart==0.0.32
pytz==2026.5
PyYAML==6.0.3
randomname==0.2.1
regex==2026.9.29
requests==2.34.2
resemble-enhance==0.0.1
rich==14.3.4
ruff==0.16.10
safehttpx==0.1.7
safetensors==0.8.0
scikit-learn==1.9.1
scipy==1.11.4
semantic-version==2.10.0
setuptools==78.1.0
shellingham==1.5.4
six==1.17.0
soundfile==0.12.1
soxr==0.5.0.post1
stack-data==0.6.3
starlette==0.52.1
sympy==1.14.0
tabulate==0.10.0
tensorboard==2.20.0
tensorboard-data-server==0.7.2
termcolor==3.3.0
threadpoolctl==3.7.0
tokenizers==0.22.2
tomlkit==0.13.3
torch==2.8.0+cu128
torch-einops-utils==0.1.35
torch-stoi==0.2.3
torchaudio==2.8.0+cu128
tqdm==4.70.1
traitlets==5.16.1
transformers==4.57.6
triton==3.4.0
typer==0.27.2
typing-inspection==0.4.4
typing_extensions==4.16.0
tzdata==2026.5
urllib3==2.8.0
uvicorn==0.54.0
wcwidth==0.9.2
websockets==15.0.1
Werkzeug==3.1.9
x-transformers==2.31.6
+6
View File
@@ -0,0 +1,6 @@
FROM python:3.12-slim-bookworm
RUN pip install --no-cache-dir fastapi==0.115.12 uvicorn==0.34.2 httpx==0.28.1
WORKDIR /ui
COPY proxy.py ./
USER 65534:65534
CMD ["python","-m","uvicorn","proxy:app","--host","127.0.0.1","--port","8133","--no-access-log"]
+29
View File
@@ -0,0 +1,29 @@
"""Small inference-only replacement for X-VC's training logger.
The upstream logger imports WandB, Matplotlib and TensorBoard at module import
time although model inference only uses the normal logging functions.
"""
import logging
logging.basicConfig(level=logging.INFO)
_logger = logging.getLogger("xvc")
debug = _logger.debug
info = _logger.info
warn = _logger.warning
warning = _logger.warning
error = _logger.error
def init(*_args, **_kwargs):
return None
def write_audio(*_args, **_kwargs):
return None
def write_loss(*_args, **_kwargs):
return None
+264
View File
@@ -0,0 +1,264 @@
"""Local Athena adaptation of the public X-VC Gradio demo."""
import contextlib,json,socket,threading
import logging
import os
import sys
import tempfile
import time
from pathlib import Path
from typing import Tuple
import gradio as gr
import numpy as np
import soundfile as sf
import torch
from omegaconf import OmegaConf
HERE = os.environ["XVC_SOURCE"]
ASSETS = Path(os.environ["XVC_ASSETS"])
sys.path.insert(0, HERE)
from bins.infer_utils import precompute_conditions, run_offline, run_streaming, to_numpy_audio
from models.codec.sac.model import XVC
from utils.audio import audio_highpass_filter, audio_volume_normalize, load_audio
logging.basicConfig(level=logging.INFO)
log = logging.getLogger("xvc-local")
MODEL_REPO = "chenxie95/X-VC"
SPACE_REPO = "hugging-apps/x-vc-voice-conversion"
SPEAKER_SUBDIR = "pretrained/speech_eres2net_sv_en_voxceleb_16k"
SAMPLE_RATE = 16000
ENHANCED_SAMPLE_RATE = 44100
LATENT_HOP_LENGTH = 1280
MAX_SECONDS = 20.0
RESEMBLE_REVISION = "4e3510ce4a8391159f665903544c5150bee7b2cb"
RESEMBLE_RUN_DIR = ASSETS / "enhance/enhancer_stage2"
MODE_OFFLINE = "Offline (höchste Qualität)"
MODE_STREAMING = "Streaming (simulierte Echtzeit)"
def _load_model() -> XVC:
speaker_config = ASSETS / "space" / SPEAKER_SUBDIR / "configuration.json"
checkpoint = ASSETS / "model/xvc.pt"
cfg = OmegaConf.load(os.path.join(HERE, "configs", "xvc.yaml"))
cfg["model"]["generator"].pop("loss_config", None)
cfg["model"].pop("discriminator", None)
cfg["model"]["generator"]["speaker_encoder"]["pretrained_dir"] = os.path.dirname(speaker_config)
for node in (cfg["model"]["generator"]["semantic_encoder"]["encoder"]["from_pretrained"], cfg["model"]["generator"]["semantic_encoder"]["cfg"]):
node["local_ckpt"] = str(ASSETS / "tokenizer")
infer_cfg = os.path.join(tempfile.gettempdir(), "xvc_inference.yaml")
OmegaConf.save(cfg, infer_cfg)
loaded = XVC.load_from_checkpoint(infer_cfg, checkpoint, device=torch.device("cuda"))
loaded.remove_weight_norm()
loaded = loaded.eval().to("cuda")
log.info("X-VC model ready on %s", torch.cuda.get_device_name(0))
return loaded
MODEL = None
LOCK = threading.Lock()
def _prepare_wav(path: str) -> np.ndarray:
wav = load_audio(path, sampling_rate=SAMPLE_RATE, volume_normalize=False)
if wav is None or len(wav) == 0:
raise gr.Error("Die Audiodatei konnte nicht gelesen werden.")
wav = wav[: int(MAX_SECONDS * SAMPLE_RATE)]
wav = audio_volume_normalize(wav)
wav = audio_highpass_filter(wav, SAMPLE_RATE, 40)
remainder = len(wav) % LATENT_HOP_LENGTH
if remainder:
wav = np.pad(wav, (0, LATENT_HOP_LENGTH - remainder), mode="constant")
return wav.astype(np.float32)
def _tensor(wav: np.ndarray) -> torch.Tensor:
return torch.from_numpy(wav).unsqueeze(0).unsqueeze(1).float().to("cuda")
def _write_wav(audio: np.ndarray, sample_rate: int = SAMPLE_RATE, suffix: str = "native-16k") -> str:
output = os.environ["XVC_OUTPUT"]
os.makedirs(output, exist_ok=True)
path = os.path.join(output, f"xvc-{suffix}-{int(time.time() * 1000)}.wav")
sf.write(path, np.clip(np.asarray(audio, dtype=np.float32), -1.0, 1.0), sample_rate, subtype="PCM_16")
return path
@torch.inference_mode()
def _enhance_wav(audio: np.ndarray) -> tuple[str, float]:
if not (RESEMBLE_RUN_DIR / "hparams.yaml").is_file():
raise gr.Error("Resemble-Enhance-Gewichte fehlen; X-VC-Laufzeit unter Laufzeiten prüfen.")
from resemble_enhance.enhancer.inference import enhance
started = time.time()
source = torch.from_numpy(np.asarray(audio, dtype=np.float32).reshape(-1))
restored, sample_rate = enhance(
source,
SAMPLE_RATE,
"cuda",
nfe=32,
solver="midpoint",
lambd=0.1,
tau=0.5,
run_dir=RESEMBLE_RUN_DIR,
)
if int(sample_rate) != ENHANCED_SAMPLE_RATE:
raise RuntimeError(f"Unerwartete Resemble-Enhance-Abtastrate: {sample_rate}")
return _write_wav(restored.cpu().numpy(), int(sample_rate), "enhanced-44k1"), time.time() - started
@torch.inference_mode()
def _convert(
source_audio: str,
reference_audio: str,
enhance_44k1: bool = True,
mode: str = MODE_OFFLINE,
chunk_ms: int = 2400,
current_ms: int = 120,
future_ms: int = 100,
smooth_ms: int = 20,
progress=gr.Progress(track_tqdm=True),
) -> Tuple[str, str | None, str]:
if not source_audio:
raise gr.Error("Bitte eine Quelldatei mit dem zu erhaltenden Inhalt hochladen.")
if not reference_audio:
raise gr.Error("Bitte eine Referenzdatei mit der Zielstimme hochladen.")
source_np = _prepare_wav(source_audio)
reference_np = _prepare_wav(reference_audio)
source_wav = _tensor(source_np)
target_wav = _tensor(reference_np)
seconds = len(source_np) / SAMPLE_RATE
started = time.time()
if mode == MODE_STREAMING:
history_ms = int(chunk_ms) - int(current_ms) - int(smooth_ms) - int(future_ms)
if history_ms < 0:
raise gr.Error("Fenster muss mindestens Current + Lookahead + Crossfade umfassen.")
speaker_condition, frame_condition = precompute_conditions(MODEL, target_wav, target_wav)
recon, latency_ms = run_streaming(
model=MODEL,
source_wav=source_wav,
speaker_condition=speaker_condition,
frame_condition=frame_condition,
sample_rate=SAMPLE_RATE,
chunk_ms=int(chunk_ms),
current_ms=int(current_ms),
future_ms=int(future_ms),
smooth_ms=int(smooth_ms),
)
elapsed = time.time() - started
latency = np.asarray(latency_ms, dtype=np.float64)
report = (
f"**Streaming** · {len(latency)} Chunks · Mittel **{latency.mean():.0f} ms**, "
f"P95 **{np.percentile(latency, 95):.0f} ms** · insgesamt {elapsed:.2f} s "
f"für {seconds:.2f} s Audio (RTF {elapsed / seconds:.2f})"
)
else:
recon = run_offline(MODEL, source_wav, target_wav, target_wav)
elapsed = time.time() - started
report = (
f"**Offline** · {seconds:.2f} s Audio in {elapsed:.2f} s "
f"(RTF {elapsed / seconds:.2f})"
)
recon_np = to_numpy_audio(recon)
native_path = _write_wav(recon_np)
enhanced_path = None
if enhance_44k1:
del source_wav, target_wav, recon
torch.cuda.empty_cache()
enhanced_path, enhancement_seconds = _enhance_wav(recon_np)
report += (
f" · Resemble Enhance **{enhancement_seconds:.2f} s**, "
f"Ausgabe **44,1 kHz** (rekonstruierte Bandbreite)"
)
return native_path, enhanced_path, report
def convert(source_audio: str, reference_audio: str, enhance_44k1: bool = True, mode: str = MODE_OFFLINE, chunk_ms: int = 2400, current_ms: int = 120, future_ms: int = 100, smooth_ms: int = 20, progress=gr.Progress(track_tqdm=True)):
global MODEL
with LOCK:
connection = socket.socket(socket.AF_UNIX)
try:
connection.connect(os.environ["XVC_LEASE_SOCKET"])
connection.sendall(b'{"action":"reserve"}\n')
with connection.makefile("rb") as stream:
reply = json.loads(stream.readline(8193))
if not reply.get("ok"):
raise gr.Error(reply.get("error", "Deck-Ressourcen nicht verfügbar."))
if reply["gpu"] != os.environ["CUDA_VISIBLE_DEVICES"]:
raise gr.Error("GPU-Auswahl hat sich geändert; X-VC erneut öffnen.")
if MODEL is None:
MODEL = _load_model()
return _convert(source_audio, reference_audio, enhance_44k1, mode, chunk_ms, current_ms, future_ms, smooth_ms, progress)
finally:
connection.close()
CSS = "#col-container { max-width: 1100px; margin: 0 auto; }"
HEADER = """# X-VC — Voice Changer
Die **Quelle** liefert Text, Aussprache und Timing. Die **Referenz** liefert die
Zielstimme. X-VC arbeitet Audio-zu-Audio ohne Transkript oder Training.
[Paper](https://arxiv.org/abs/2604.12456) · [Modell](https://huggingface.co/chenxie95/X-VC) ·
[Code](https://github.com/Jerrister/X-VC)
"""
with gr.Blocks(title="X-VC Voice Changer", theme=gr.themes.Citrus(), css=CSS) as demo:
with gr.Column(elem_id="col-container"):
gr.Markdown(HEADER)
with gr.Row():
source = gr.Audio(label="Quelle — Inhalt und Sprechweise", type="filepath", sources=["upload", "microphone"])
reference = gr.Audio(label="Referenz — gewünschte Zielstimme", type="filepath", sources=["upload", "microphone"])
run = gr.Button("Stimme umwandeln", variant="primary")
enhance_44k1 = gr.Checkbox(
value=True,
label="Zusätzlich mit Resemble Enhance auf 44,1 kHz restaurieren",
info="Rekonstruiert fehlende Höhen per KI; das native 16-kHz-Ergebnis bleibt zum Vergleich erhalten.",
)
with gr.Row():
output_native = gr.Audio(label="X-VC Original · 16 kHz", type="filepath", autoplay=False)
output_enhanced = gr.Audio(label="Enhanced · 44,1 kHz", type="filepath", autoplay=False)
report = gr.Markdown()
with gr.Accordion("Erweiterte Einstellungen", open=False):
mode = gr.Radio([MODE_OFFLINE, MODE_STREAMING], value=MODE_OFFLINE, label="Verarbeitungsmodus")
with gr.Row():
current_ms = gr.Slider(40, 640, value=120, step=40, label="Aktueller Chunk (ms)")
chunk_ms = gr.Slider(800, 4800, value=2400, step=200, label="Gesamtfenster (ms)")
with gr.Row():
future_ms = gr.Slider(0, 400, value=100, step=20, label="Lookahead (ms)")
smooth_ms = gr.Slider(0, 100, value=20, step=10, label="Crossfade (ms)")
gr.Markdown(
"Die ersten 20 Sekunden jeder Datei werden verarbeitet. X-VC bleibt nativ bei 16 kHz; "
"die optionale zweite Datei rekonstruiert die Sprachbandbreite auf 44,1 kHz."
)
run.click(
convert,
inputs=[source, reference, enhance_44k1, mode, chunk_ms, current_ms, future_ms, smooth_ms],
outputs=[output_native, output_enhanced, report],
api_name="convert",
)
if __name__ == "__main__":
import secrets
import uvicorn
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
app = FastAPI()
@app.middleware("http")
async def protect(request: Request, call_next):
key = Path(os.environ["XVC_BRIDGE_KEY_FILE"]).read_text().strip()
if not secrets.compare_digest(request.headers.get("X-XVC-Bridge", ""), key):
return JSONResponse({"detail": "Deck-Brücke erforderlich."}, status_code=403)
return await call_next(request)
@app.get("/health")
def health():return {"status": "ready", "model_loaded": MODEL is not None}
app = gr.mount_gradio_app(app, demo.queue(default_concurrency_limit=1), path="/", allowed_paths=[os.environ["XVC_OUTPUT"]])
uvicorn.run(app, host="0.0.0.0", port=8135, access_log=False)
+40
View File
@@ -0,0 +1,40 @@
"""Remove training-only imports from Resemble Enhance's inference path."""
from pathlib import Path
import resemble_enhance
root = Path(resemble_enhance.__file__).parent
replacements = {
root / "enhancer" / "inference.py": {
"from .train import Enhancer, HParams": (
"from .enhancer import Enhancer\nfrom .hparams import HParams"
),
},
root / "denoiser" / "inference.py": {
"from .train import Denoiser, HParams": (
"from .denoiser import Denoiser\nfrom .hparams import HParams"
),
},
root / "enhancer" / "enhancer.py": {
"from ..utils.distributed import global_leader_only\n"
"from ..utils.train_loop import TrainLoop": (
"def global_leader_only(fn):\n"
" return fn\n\n"
"class TrainLoop:\n"
" @classmethod\n"
" def get_running_loop(cls):\n"
" return None"
),
},
}
for path, edits in replacements.items():
text = path.read_text(encoding="utf-8")
for old, new in edits.items():
if old not in text:
raise RuntimeError(f"Expected Resemble Enhance source not found in {path}: {old!r}")
text = text.replace(old, new, 1)
path.write_text(text, encoding="utf-8")
+24
View File
@@ -0,0 +1,24 @@
"""CPU-only forwarding UI; the native Deck backend owns model and GPU access."""
from pathlib import Path
import httpx
from fastapi import FastAPI,Request
from fastapi.responses import JSONResponse,StreamingResponse
from starlette.background import BackgroundTask
app=FastAPI();KEY=Path('/run/secrets/xvc-bridge')
@app.api_route('/{path:path}',methods=['GET','POST','PUT','DELETE','PATCH','HEAD','OPTIONS'])
async def proxy(path:str,request:Request):
if request.method not in ('GET','HEAD','OPTIONS'):
origin=request.headers.get('origin','');host=request.headers.get('host','')
if origin.split('://',1)[-1]!=host and request.headers.get('X-XVC-UI')!='1':return JSONResponse({'detail':'Same-origin control required.'},status_code=403)
if int(request.headers.get('content-length','0'))>512*1024**2:return JSONResponse({'detail':'Upload zu groß.'},status_code=413)
client=httpx.AsyncClient(timeout=180)
try:
headers={'X-XVC-Bridge':KEY.read_text().strip(),'Host':request.headers.get('host','127.0.0.1:8133')}
if request.headers.get('content-type'):headers['Content-Type']=request.headers['content-type']
req=client.build_request(request.method,'http://127.0.0.1:8135/'+path,params=request.query_params,headers=headers,content=request.stream())
response=await client.send(req,stream=True)
async def close():await response.aclose();await client.aclose()
safe={k:v for k,v in response.headers.items() if k in ('content-type','content-length','location','content-disposition')};safe['Cache-Control']='no-store'
return StreamingResponse(response.aiter_raw(),status_code=response.status_code,headers=safe,background=BackgroundTask(close))
except (OSError,httpx.HTTPError):
await client.aclose();return JSONResponse({'detail':'X-VC ist vorbereitet, aber noch nicht gestartet. In Deck ein X-VC-Profil aktivieren und Stimmwerkzeuge starten.'},status_code=503)
+1
View File
@@ -3,6 +3,7 @@ window.DockerUI=(()=>{
const apps={
'athena-voxcpm2-web':{title:'VoxCPM2 Studio',description:'Stimme erzeugen, gestalten und klonen; Ausführung über Decks Stimmworker.',port:8129,hint:'VoxCPM2-Profil in Deck aktivieren und Stimmwerkzeuge starten.'},
'athena-omnivoice-web':{title:'OmniVoice Studio',description:'Bisherige OmniVoice-Weboberfläche; GPU-Aufträge laufen über Deck.',port:8130,hint:'OmniVoice-Profil in Deck aktivieren und Stimmwerkzeuge starten. Beim Klonen Referenztranskript eingeben.'},
'athena-xvc-web':{title:'X-VC Studio',description:'Vorhandene Sprachaufnahme in eine Referenzstimme umwandeln; optional Klang mit Resemble Enhance verbessern. Native Ausführung durch Deck.',port:8133,hint:'X-VC-Profil aktivieren und Stimmwerkzeuge starten; GPU unter Laufzeiten → X-VC einstellen.'},
'athena-applio-web':{title:'Applio Studio',description:'Unsere eigene Oberfläche für RVC-Stimmumwandlung, Live und eigenes Stimmtraining. Native Applio-3.6.5-Laufzeit in Deck.',port:8132,hint:'Applio-Profil aktivieren und Stimmwerkzeuge starten; GPU unter Laufzeiten → Applio einstellen.'},
'athena-acestep-web':{title:'ACE-Step Studio',description:'Musik und Songs mit ACE-Step XL-SFT und dem 1.7B-Musik-Sprachmodell; Ausführung und Gewichte in Deck.',port:8131,hint:'ACE-Step-Profil freigeben und in der Steuerung Musik starten.'},
'athena-ladypoly':{title:'LadyPoly YuE2',description:'Weboberfläche für Decks Musiklaufzeit.',port:8127,hint:'In der Steuerung Musik starten. Deck-Verbindung in LadyPoly einrichten.'},
+55
View File
@@ -0,0 +1,55 @@
# YuE2 Audio Remix und ClearVoice
YuE2 Audio Remix nutzt die vorhandene LadyPoly-UI und den vorhandenen
YuE2-audio.cpp-Worker. Kein zusätzlicher UI-/GPU-Container ist notwendig.
## Audio Remix
- SheetSage2: `m-a-p/SheetSage2`, Revision
`eab522a8168e8b8b8c4856bf8609cd86198f01fe`.
- Backbone: `m-a-p/MERT-v2-FullSong`, Revision
`d8ba1c745e733b3908ce6ad16ebeb17ac7600a42`.
- Quellen und SHA-256 aller Dateien: `remix_sources.json`.
- Eigene Python-Umgebung mit Transformers 4.45.2; CUDA-Pakete aus der
Separator-Laufzeit werden gezielt geteilt. Fehlt diese, installiert der
Restore eine eigene CUDA-PyTorch-Laufzeit.
- In Deck unter Musik: „YuE2 Audio Remix“. In LadyPoly: „Remix a take“ →
„Remix an uploaded recording“. Analyse lädt MERT/SheetSage2 auf die 5080,
nachdem Deck die exklusive Musik-Freigabe erteilt und YuE2 entladen hat.
- Bei einem Notenrasterfehler an einer harten Aufnahmegrenze wird nur die
Analyse einmal mit zwei Sekunden stillem Ausklang wiederholt. Die Originaldatei
bleibt unverändert; der Musikplan kann entsprechend eine Schluss-Pause enthalten.
- Den erstellten ABC-Musikplan prüfen/bearbeiten; Modus `melody` für neue
Begleitung oder `full` für Melodie und Harmonie. Danach Stil und Songtext
eingeben und generieren. YuE2 bleibt zwischen Generierungen geladen.
- Analyse rekonstruiert musikalische Struktur; sie erhält weder exakt den
ursprünglichen Klang noch die Originalstimme.
- WAV/FLAC/MP3 und andere FFmpeg-lesbare Formate, maximal 256 MiB/20 Minuten.
Hochgeladenes Audio und Zwischenresultate werden nach der Analyse gelöscht.
- Bearer-geschützter Upload: POST `/api/v1/music-remix/transcribe` mit
Multipart `file`, optional `melody_only=true|false`. Status:
GET `/api/v1/music-remix`. Installation verlangt Deck-Adminzugriff.
- Musik-Endpunkt `/v1/audio/music`: zusätzlich `abc` und `cot=melody|full`.
ACE-Step bleibt ein unabhängiger Adapter und akzeptiert diese Felder nicht.
## ClearVoice
- Modell: `alibabasglab/MossFormer2_SE_48K`, Revision
`eff8c97925c8bec812af707814b3e5d777fd4503`.
- Paket: `clearvoice==0.1.2`, separate NumPy-1.26.4-Umgebung. Der bestehende
audio-separator behält seine eigenen NumPy-/RoFormer-Abhängigkeiten.
- In Audio-Trennung ein eigenes Profil mit Aktivierung/GPU-Auswahl.
Auf Athena wird die RTX 3060 voreingestellt. Kein stiller GPU-/CPU-Fallback.
- In Separator Web „Sprache“ auswählen. ZIP: `Speech.wav` und
`Background.wav`. Hintergrund ist das Residuum der Originalaufnahme;
ClearVoice ist Sprachverbesserung, keine verlustfreie Quellentrennung.
- 48-kHz-Ausgabe, kanalweise Dateiverarbeitung für Mono/Stereo und lange
Aufnahmen. Damit wird die problematische direkte Array-Verarbeitung bei
Aufnahmen über 20 Sekunden vermieden.
- Modellquellen/Hashes, Profileinstellungen und Installationsrezepte werden
im Konfigurationsbackup gespeichert bzw. durch feste Deck-Rezepte
rekonstruiert. Medienresultate gehören nicht zum Konfigurationsbackup.
Originaldokumentation:
https://huggingface.co/m-a-p/SheetSage2
https://github.com/modelscope/ClearerVoice-Studio/tree/main/clearvoice
+61
View File
@@ -0,0 +1,61 @@
# X-VC voice conversion
Official source: https://github.com/Jerrister/X-VC at
`49df8c591eafc48b096e466d96f9839f9c0dd739`.
Official weights: https://huggingface.co/chenxie95/X-VC at
`9e54747d8c4d1ef544b903e2300a4ba040dcc126`.
`xvc_sources.json` pins all ten model, tokenizer, speaker-encoder and
Resemble Enhance assets, including size and upstream checksums.
The verified downloads total 7,206,037,113 bytes (6.71 GiB).
`deploy/xvc-requirements.lock` records the CPU-import-tested environment.
Resemble Enhance's training-only imports are removed, as in our old UI;
its old DeepSpeed/Torch dependency pins are intentionally not installed.
## Architecture
The previous X-VC Gradio interface is retained. It converts source audio to
a reference voice without training or a transcript. Native output is 16 kHz;
optional Resemble Enhance produces a second 44.1-kHz output. The previous UI's
20-second input limit is retained and displayed. Streaming mode is simulated
chunked conversion, not a live microphone session.
`athena-xvc-web:0.1.0-deck1` is a rootless CPU-only forwarding container on
host loopback port 8133. It forwards Gradio uploads, queue events and results
to native Deck backend 8135 using a private bridge key. Backend 8135 must
never be added to public network relays. Add only 8133 to the native network
helper's service-port policy during the approved deployment.
The native backend owns the GPU weights. No model is loaded on UI import or
startup. Conversion requires an enabled X-VC voice profile AND Deck's voice
mode, acquires the shared GPU lease, and checks the selected GPU UUID.
Weights stay resident between conversions; mode/profile/device changes
terminate the native process and restart the empty UI backend. Default GPU
is RTX 5080; RTX 3060 is selectable but not yet verified for conversion.
## Prepared, not activated (2026-10-05)
On Athena the isolated runtime and all assets are installed; the main library
entry points to its real Hugging Face source using a relative symlink.
The UI container exists in `created`/stopped state. The candidate profile is
`xvc-profile-pending.json`, named `X-VC Studio`, API ID `xvc-studio`.
The live profile list, endpoint activation, GPU mode and existing Deck image
have not been changed. No conversion, GPU test or UI server has been started.
CPU import passed with `MODEL is None` and no initialized CUDA context.
After authorization, stop Deck and run `deploy/prepare_xvc.py STATE
--apply-profile` from the new full checkout. It refuses a running Deck and
merges only the single inactive profile into the current profile list.
Deploy the prepared application update (private port 8135 included), update
the helper recipes, relay public UI port 8133, and start the UI container.
Enable X-VC under voice profiles and select voice mode only when ready to test.
The GPU conversion test is deliberately pending until then.
## Recovery
The configuration backup stores X-VC GPU selection, inactive/active profile
state, original main-weight source, exact code/assets recipe identity and the
stopped/running UI container state. Restore reinstalls the native package,
redownloads every pinned component and verifies upstream checksums, then
rebuilds the CPU forwarding container. Bridge-key mounts have a specific
allowlist. Reference uploads and generated results are not configuration
backup content; archive those separately if needed.
+5 -3
View File
@@ -93,6 +93,7 @@ class Endpoint:
if not row:raise ValueError('Profil nicht gefunden.')
if data['enabled'] and not row['runnable']:raise ValueError('Profil nicht ausführbar: '+' '.join(row['blockers']))
if row['kind']=='voice' and getattr(self,'applio',None):self.applio.unload_idle()
if row['kind']=='voice' and getattr(self,'xvc',None):self.xvc.unload_idle()
with self.lock:
if row['kind']=='voice' and self.voxcpm:
job=self.voxcpm.status().get('job') or {}
@@ -170,7 +171,8 @@ class Endpoint:
if not (p['enabled'] and p['runnable'] and p['kind']==kind):continue
if kind=='voice':
from applio import applio_model
if applio_model(p.get('model')):continue
from xvc import xvc_model
if applio_model(p.get('model')) or xvc_model(p.get('model')):continue
row=dict(id='athena-image' if kind=='image' else p.get('api_id',p['name']),name=p['name'],display_name=p['name'],object='model',created=int(p['updated_at']),owned_by='athena-deck')
if kind=='chat':
params=p.get('parameters',{})
@@ -375,9 +377,9 @@ class APIHandler(BaseHTTPRequestHandler):
def music_generation(self,ep,data):
if ep.scheduler.gpu_mode!='music':raise APIError('Bitte in der Übersicht auf Musik umschalten.',503,'music_mode_required')
if not ep.music:raise APIError('Musikworker nicht eingerichtet.',501)
if set(data)-{'model','lyrics','style','seed','max_tokens','steps','duration_seconds','guidance','thinking','instrumental','bpm','language'}:raise APIError('Nicht unterstützte Musikfelder.')
if set(data)-{'model','lyrics','style','seed','max_tokens','steps','duration_seconds','guidance','thinking','instrumental','bpm','language','abc','cot'}:raise APIError('Nicht unterstützte Musikfelder.')
profile=ep.find_profile(data.get('model'),'music')
try:job=ep.music.start(profile['id'],data.get('lyrics',''),data.get('style'),seed=data.get('seed',1234),max_tokens=data.get('max_tokens',400),steps=data.get('steps'),wait=True,**{k:data[k] for k in ('duration_seconds','guidance','thinking','instrumental','bpm','language') if k in data})
try:job=ep.music.start(profile['id'],data.get('lyrics',''),data.get('style'),seed=data.get('seed',1234),max_tokens=data.get('max_tokens',400),steps=data.get('steps'),wait=True,**{k:data[k] for k in ('duration_seconds','guidance','thinking','instrumental','bpm','language','abc','cot') if k in data})
except ValueError as exc:raise APIError(str(exc)) from None
end=time.monotonic()+1850
while time.monotonic()<end:
+9
View File
@@ -12,6 +12,10 @@ def _assess(model, installed, profile=None):
if not file_role(filename)['profile_eligible']:
result.update(state='component',label='Zusatzdatei',message='Diese Datei wird einem kompatiblen Modellprofil zugeordnet und benötigt keine eigene Laufzeit.')
return result
from xvc import xvc_model
if xvc_model(model):
result.update(family='X-VC',evidence='Offizielles X-VC-Gewicht',runtime='X-VC · Python/PyTorch',route='#xvc-runtime',installed=bool(installed.get('xvc')),state='ready' if installed.get('xvc') else 'setup',label='X-VC erkannt',message='Quellaufnahme und Referenzstimme in der X-VC-Oberfläche verwenden. Die Laufzeit richtet alle Zusatzgewichte ein; keine einzelnen VAE-/Projektor-Zuordnungen.')
return result
from applio import applio_model
if applio_model(model):
result.update(family='Applio / RVC',evidence='Geprüfter RVC-Checkpoint',runtime='Applio · Python/PyTorch',route='#applio-runtime',installed=bool(installed.get('applio')),state='ready' if installed.get('applio') else 'setup',label='RVC-Stimmgewicht',message='Stimmumwandlung und Training in unserer Applio-Oberfläche. Kein Textencoder, VAE oder Vision-Projektor erforderlich. Basisgewichte werden mit der Laufzeit eingerichtet.')
@@ -71,6 +75,11 @@ def _assess_candidates(model, installed, profile=None):
meta=model.get('runtime_metadata') or {};family=str(meta.get('architecture') or '').lower()
def add(id,label,key,route,reason,maintained=True):
result['candidates'].append(dict(id=id,label=label,installed=bool(installed.get(key)),route=route,installation_available=maintained,evidence=reason))
from xvc import xvc_model
if xvc_model(model):
add('xvc','X-VC · Python/PyTorch','xvc','#xvc-runtime','Offizielles X-VC-Paket mit geprüftem Deck-Worker')
if profile:result.update(state='ready' if profile.get('runnable') else 'profile_incomplete',blockers=profile.get('blockers',[]))
return result
from applio import applio_model
if applio_model(model):
add('applio','Applio / RVC · Python/PyTorch','applio','#applio-runtime','Geprüfter RVC-Checkpoint und Deck-Worker')
+1 -1
View File
@@ -1 +1 @@
<!doctype html><html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Athena Deck</title><link rel="stylesheet" href="/style.css"><link rel="stylesheet" href="/dashboard.css"><link rel="stylesheet" href="/themes.css"><script src="/network-ui.js" defer></script><script src="/access-ui.js" defer></script><script src="/catalog-ui.js" defer></script><script src="/runtime-ui.js" defer></script><script src="/profiles-ui.js" defer></script><script src="/auto-test-ui.js" defer></script><script src="/chat-test-ui.js" defer></script><script src="/image-test-ui.js" defer></script><script src="/docker-ui.js" defer></script><script src="/stt-ui.js" defer></script><script src="/tts-ui.js" defer></script><script src="/voxcpm-ui.js" defer></script><script src="/voice-ui.js" defer></script><script src="/studio.js" defer></script><script src="/separator-ui.js" defer></script><script src="/music-ui.js" defer></script><script src="/applio-ui.js" defer></script><script src="/acestep-ui.js" defer></script><script src="/audio-cpp-ui.js" defer></script><script src="/ltx-original-ui.js" defer></script><script src="/video-ui.js" defer></script><script src="/endpoint-ui.js" defer></script><script src="/dashboard-ui.js" defer></script><script src="/backup-ui.js" defer></script><script src="/app.js" defer></script></head><body><aside><a class="brand" href="#dashboard"><span>Α</span> ATHENA <b>DECK</b></a><p class="eyebrow">WORKSPACE / ATHENA</p><nav aria-label="Hauptnavigation"><p class="nav-heading">Übersicht</p><a href="#dashboard">Dashboard</a><a href="#home">Steuerung</a><p class="nav-heading">KI-Werkzeuge</p><a href="#chat">Chat &amp; Sprachmodelle</a><a href="#embeddings">Embeddings</a><a href="#image">Bildgenerierung</a><a href="#music">Musikgenerierung</a><a href="#separation">Audio-Trennung</a><a href="#audio">Sprachausgabe (TTS)</a><a href="#stt">Spracherkennung (STT)</a><a href="#voice">Stimmwerkzeuge</a><a href="#video">Videogenerierung</a><p class="nav-heading">Anwendungen</p><a href="#services">Weitere Dienste</a><p class="nav-heading">Einstellungen</p><a href="#runtimes">Laufzeiten</a><a href="#endpoint">Endpunkt</a><a href="#network">Netzwerk</a><a href="#access">Zugang &amp; API-Token</a><a href="#appearance">Darstellung</a><a href="#backup">Backup &amp; Wiederherstellung</a></nav><footer><i></i> Isolierte Entwicklungsumgebung<p>Eigener Modell-Router<br>Hardware · nur lesend</p></footer></aside><main><header><span>ATHENA CONTROL SURFACE</span><span class="pill">v0.7 · Router</span></header><div id="view"></div><p id="error" role="alert"></p></main></body></html>
<!doctype html><html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Athena Deck</title><link rel="stylesheet" href="/style.css"><link rel="stylesheet" href="/dashboard.css"><link rel="stylesheet" href="/themes.css"><script src="/network-ui.js" defer></script><script src="/access-ui.js" defer></script><script src="/catalog-ui.js" defer></script><script src="/runtime-ui.js" defer></script><script src="/profiles-ui.js" defer></script><script src="/auto-test-ui.js" defer></script><script src="/chat-test-ui.js" defer></script><script src="/image-test-ui.js" defer></script><script src="/docker-ui.js" defer></script><script src="/stt-ui.js" defer></script><script src="/tts-ui.js" defer></script><script src="/voxcpm-ui.js" defer></script><script src="/voice-ui.js" defer></script><script src="/studio.js" defer></script><script src="/separator-ui.js" defer></script><script src="/music-ui.js" defer></script><script src="/xvc-ui.js"></script><script src="/applio-ui.js" defer></script><script src="/acestep-ui.js" defer></script><script src="/audio-cpp-ui.js" defer></script><script src="/ltx-original-ui.js" defer></script><script src="/video-ui.js" defer></script><script src="/endpoint-ui.js" defer></script><script src="/dashboard-ui.js" defer></script><script src="/backup-ui.js" defer></script><script src="/app.js" defer></script></head><body><aside><a class="brand" href="#dashboard"><span>Α</span> ATHENA <b>DECK</b></a><p class="eyebrow">WORKSPACE / ATHENA</p><nav aria-label="Hauptnavigation"><p class="nav-heading">Übersicht</p><a href="#dashboard">Dashboard</a><a href="#home">Steuerung</a><p class="nav-heading">KI-Werkzeuge</p><a href="#chat">Chat &amp; Sprachmodelle</a><a href="#embeddings">Embeddings</a><a href="#image">Bildgenerierung</a><a href="#music">Musikgenerierung</a><a href="#separation">Audio-Trennung</a><a href="#audio">Sprachausgabe (TTS)</a><a href="#stt">Spracherkennung (STT)</a><a href="#voice">Stimmwerkzeuge</a><a href="#video">Videogenerierung</a><p class="nav-heading">Anwendungen</p><a href="#services">Weitere Dienste</a><p class="nav-heading">Einstellungen</p><a href="#runtimes">Laufzeiten</a><a href="#endpoint">Endpunkt</a><a href="#network">Netzwerk</a><a href="#access">Zugang &amp; API-Token</a><a href="#appearance">Darstellung</a><a href="#backup">Backup &amp; Wiederherstellung</a></nav><footer><i></i> Isolierte Entwicklungsumgebung<p>Eigener Modell-Router<br>Hardware · nur lesend</p></footer></aside><main><header><span>ATHENA CONTROL SURFACE</span><span class="pill">v0.7 · Router</span></header><div id="view"></div><p id="error" role="alert"></p></main></body></html>
+6 -4
View File
@@ -1,14 +1,16 @@
window.MusicUI=(()=>{
const e=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
async function api(path,data){const r=await fetch('/api/v1/'+path,data===undefined?{}:{method:'POST',headers:{'Content-Type':'application/json','X-Athena-Deck':'1'},body:JSON.stringify(data)});const x=await r.json();if(!r.ok)throw Error(x.error||'Musikanfrage fehlgeschlagen');return x;}
function html(){return '<section id="music-test" class="card"><h2>Musik ausprobieren</h2><p>YuE2 über audio.cpp oder ACE-Step XL-SFT mit 1.7B-Musik-Sprachmodell. Parameter richten sich nach dem gewählten Profil.</p><p id="music-state" role="status"></p><p id="music-error" role="alert"></p><div id="music-progress"></div><form id="music-form"><label>Profil<select id="music-profile" required></select></label><label>Musikstil<textarea id="music-style" maxlength="2000" required placeholder="English, acoustic pop, warm vocals, gentle guitar"></textarea></label><label>Songtext<textarea id="music-lyrics" maxlength="8000" rows="6" required placeholder="[Verse] … [Chorus] …"></textarea></label><label>Maximale Länge (Sekunden)<input type="number" id="music-duration" min="2" max="360" step="1" value="16" required></label><p id="music-length-hint" class="small">Bis etwa 16 Sekunden · 400 semantische Tokens. YuE2 verwendet hier ungefähr 25 Tokens pro Sekunde.</p><details><summary>Erweiterte Testparameter</summary><label>Maximale semantische Tokens<input type="number" id="music-tokens" min="32" max="9000" value="400"></label><label><span id="music-steps-label">NAR-Schritte</span><input type="number" id="music-steps" min="1" max="32" value="8"></label><div id="music-ace-options" hidden><label>Guidance<input type="number" id="music-guidance" min="0" max="20" step="0.1" value="7"></label><label><input type="checkbox" id="music-thinking" checked> Musik-Sprachmodell verwenden (Thinking)</label><label><input type="checkbox" id="music-instrumental"> Instrumental ohne Gesang</label><label>Gesangssprache<input id="music-language" value="unknown" maxlength="16" placeholder="de, en oder unknown"></label><label>BPM (leer = automatisch)<input type="number" id="music-bpm" min="30" max="300"></label></div><label>Seed<input type="number" id="music-seed" min="0" max="2147483647" value="1234"></label></details><button type="button" class="secondary" id="music-load">Modell laden</button><button id="music-start">Musik erzeugen</button><button type="button" class="secondary" id="music-cancel">Abbrechen</button></form><div id="music-result"></div><p>RTX 5080 bevorzugt. Deck-Aufträge werden koordiniert. Das gewählte Modell bleibt zwischen Songs geladen, bis du die Betriebsart wechselst. Text und Stil werden nicht dauerhaft gespeichert.</p></section>';}
function html(){return '<section id="music-test" class="card"><h2>Musik ausprobieren</h2><p>YuE2 über audio.cpp oder ACE-Step XL-SFT mit 1.7B-Musik-Sprachmodell. Parameter richten sich nach dem gewählten Profil.</p><p id="music-state" role="status"></p><p id="music-error" role="alert"></p><div id="music-progress"></div><form id="music-form"><label>Profil<select id="music-profile" required></select></label><label>Musikstil<textarea id="music-style" maxlength="2000" required placeholder="English, acoustic pop, warm vocals, gentle guitar"></textarea></label><label>Songtext<textarea id="music-lyrics" maxlength="8000" rows="6" required placeholder="[Verse] … [Chorus] …"></textarea></label><label>Maximale Länge (Sekunden)<input type="number" id="music-duration" min="2" max="360" step="1" value="16" required></label><p id="music-length-hint" class="small">Bis etwa 16 Sekunden · 400 semantische Tokens. YuE2 verwendet hier ungefähr 25 Tokens pro Sekunde.</p><details><summary>Erweiterte Testparameter</summary><label>Maximale semantische Tokens<input type="number" id="music-tokens" min="32" max="9000" value="400"></label><label><span id="music-steps-label">NAR-Schritte</span><input type="number" id="music-steps" min="1" max="32" value="8"></label><div id="music-ace-options" hidden><label>Guidance<input type="number" id="music-guidance" min="0" max="20" step="0.1" value="7"></label><label><input type="checkbox" id="music-thinking" checked> Musik-Sprachmodell verwenden (Thinking)</label><label><input type="checkbox" id="music-instrumental"> Instrumental ohne Gesang</label><label>Gesangssprache<input id="music-language" value="unknown" maxlength="16" placeholder="de, en oder unknown"></label><label>BPM (leer = automatisch)<input type="number" id="music-bpm" min="30" max="300"></label></div><label>Seed<input type="number" id="music-seed" min="0" max="2147483647" value="1234"></label></details><details id="music-remix-controls"><summary>YuE2 Audio Remix</summary><p>Audio analysieren, den Musikplan bearbeiten und mit neuem Stil erzeugen. Keine Kopie der Originalaufnahme.</p><p id="music-remix-state"></p><button type="button" id="music-remix-install">Remix-Komponenten einrichten</button><label>Audio<input id="music-remix-file" type="file" accept="audio/*"></label><button type="button" id="music-remix-analyze">Musikplan aus Audio erstellen</button><label>ABC-Musikplan<textarea id="music-abc" maxlength="20000" rows="6"></textarea></label><label>Plan verwenden<select id="music-cot"><option value="off">Kein Plan</option><option value="melody">Melodie · neue Begleitung</option><option value="full">Melodie und Harmonie</option></select></label></details><button type="button" class="secondary" id="music-load">Modell laden</button><button id="music-start">Musik erzeugen</button><button type="button" class="secondary" id="music-cancel">Abbrechen</button></form><div id="music-result"></div><p>RTX 5080 bevorzugt. Deck-Aufträge werden koordiniert. Das gewählte Modell bleibt zwischen Songs geladen, bis du die Betriebsart wechselst. Text und Stil werden nicht dauerhaft gespeichert.</p></section>';}
function bind(){const root=document.querySelector('#music-test'),el=id=>root.querySelector('#'+id);let ready=false,busy=false,resultId=null,profiles=[],ace=false;
async function poll(){if(!root.isConnected)return;try{const s=await api('music');if(!root.isConnected)return;const j=s.job,running=j?.state==='running';el('music-state').textContent=(s.mode!=='music'?'Bitte in der Übersicht auf Musik umschalten.':j?.phase||'Profil wählen und Musikstil sowie Songtext eingeben.')+(running?' · '+Math.round((Date.now()/1000)-j.started_at)+' s':'');el('music-progress').innerHTML=running?'<progress aria-label="Musikgenerierung läuft"></progress>':'';el('music-start').disabled=busy||running||!ready||s.mode!=='music';el('music-load').disabled=busy||running||!ready||s.mode!=='music';el('music-cancel').disabled=!running;if(!busy&&j?.state==='complete'&&j.id!==resultId){resultId=j.id;el('music-result').innerHTML=`<h3>Ergebnis · ${e(j.duration_seconds)} Sekunden</h3><audio controls src="/api/v1/music/audio?id=${e(j.id)}"></audio><p><a download="athena-musik.wav" href="/api/v1/music/audio?id=${e(j.id)}">WAV herunterladen</a></p>`;}if(j?.state==='failed')el('music-error').textContent=j.phase;}catch(x){if(root.isConnected)el('music-error').textContent=x.message;}if(root.isConnected)setTimeout(poll,1500);}
async function poll(){if(!root.isConnected)return;try{const s=await api('music');if(!root.isConnected)return;const remix=await api('music-remix');el('music-remix-state').textContent=remix.job?.state==='running'?remix.job.phase:remix.installed?'Audio-Remix bereit':'SheetSage2 und MERT noch nicht eingerichtet';el('music-remix-install').disabled=remix.installed||remix.job?.state==='running';el('music-remix-analyze').disabled=busy||remix.active||!remix.installed||s.mode!=='music';const j=s.job,running=j?.state==='running';el('music-state').textContent=(s.mode!=='music'?'Bitte in der Übersicht auf Musik umschalten.':j?.phase||'Profil wählen und Musikstil sowie Songtext eingeben.')+(running?' · '+Math.round((Date.now()/1000)-j.started_at)+' s':'');el('music-progress').innerHTML=running?'<progress aria-label="Musikgenerierung läuft"></progress>':'';el('music-start').disabled=busy||running||!ready||s.mode!=='music';el('music-load').disabled=busy||running||!ready||s.mode!=='music';el('music-cancel').disabled=!running;if(!busy&&j?.state==='complete'&&j.id!==resultId){resultId=j.id;el('music-result').innerHTML=`<h3>Ergebnis · ${e(j.duration_seconds)} Sekunden</h3><audio controls src="/api/v1/music/audio?id=${e(j.id)}"></audio><p><a download="athena-musik.wav" href="/api/v1/music/audio?id=${e(j.id)}">WAV herunterladen</a></p>`;}if(j?.state==='failed')el('music-error').textContent=j.phase;}catch(x){if(root.isConnected)el('music-error').textContent=x.message;}if(root.isConnected)setTimeout(poll,1500);}
function updateLength(fromTokens=false){if(ace){el('music-length-hint').textContent='Zieldauer in Sekunden · ACE-Step XL-SFT: 50 Schritte und Guidance 7 als Ausgangspunkt.';return;}const tokens=fromTokens?Number(el('music-tokens').value):Math.round(Number(el('music-duration').value)*25);if(!fromTokens)el('music-tokens').value=tokens;else el('music-duration').value=(tokens/25).toFixed(2);el('music-length-hint').textContent=`Bis etwa ${(tokens/25).toFixed(2)} Sekunden · ${tokens} semantische Tokens. Das Modell kann früher enden.`;}
el('music-duration').step='0.04';el('music-duration').min='1.28';el('music-duration').oninput=()=>updateLength();el('music-tokens').oninput=()=>updateLength(true);
api('profiles').then(s=>{if(!root.isConnected)return;profiles=s.profiles.filter(p=>p.kind==='music'&&p.runnable);ready=profiles.length>0;el('music-profile').innerHTML=profiles.map(p=>`<option value="${e(p.id)}">${e(p.name)}</option>`).join('')||'<option value="">Zuerst Profil und Komponenten einrichten</option>';selectFamily();}).catch(x=>el('music-error').textContent=x.message);
function selectFamily(){ace=profiles.find(p=>p.id===el('music-profile').value)?.model?.repo==='ACE-Step/acestep-v15-xl-sft';el('music-ace-options').hidden=!ace;el('music-tokens').parentElement.hidden=ace;el('music-steps-label').textContent=ace?'Diffusionsschritte':'NAR-Schritte';el('music-steps').max=ace?200:32;el('music-steps').value=ace?50:8;el('music-duration').min=ace?10:1.28;el('music-duration').max=ace?600:360;el('music-duration').step=ace?1:.04;el('music-duration').value=ace?30:16;el('music-lyrics').required=!ace;updateLength();}
function selectFamily(){ace=profiles.find(p=>p.id===el('music-profile').value)?.model?.repo==='ACE-Step/acestep-v15-xl-sft';el('music-ace-options').hidden=!ace;el('music-remix-controls').hidden=ace;el('music-tokens').parentElement.hidden=ace;el('music-steps-label').textContent=ace?'Diffusionsschritte':'NAR-Schritte';el('music-steps').max=ace?200:32;el('music-steps').value=ace?50:8;el('music-duration').min=ace?10:1.28;el('music-duration').max=ace?600:360;el('music-duration').step=ace?1:.04;el('music-duration').value=ace?30:16;el('music-lyrics').required=!ace;updateLength();}
el('music-remix-install').onclick=()=>api('music-remix/install',{}).catch(x=>el('music-error').textContent=x.message);
el('music-remix-analyze').onclick=async()=>{const file=el('music-remix-file').files[0];if(!file){el('music-error').textContent='Audiodatei auswählen.';return;}busy=true;el('music-error').textContent='';try{const body=new FormData();body.append('file',file);body.append('melody_only',el('music-cot').value==='full'?'false':'true');const r=await fetch('/api/v1/music-remix/transcribe',{method:'POST',headers:{'X-Athena-Deck':'1'},body});const d=await r.json();if(!r.ok)throw Error(d.error||'Analyse fehlgeschlagen');el('music-abc').value=d.abc;el('music-cot').value=d.melody_only?'melody':'full';}catch(x){el('music-error').textContent=x.message;}finally{busy=false;}};
el('music-profile').onchange=selectFamily;
el('music-load').onclick=()=>api('music/load',{profile_id:el('music-profile').value}).catch(x=>el('music-error').textContent=x.message);el('music-form').onsubmit=async event=>{event.preventDefault();busy=true;el('music-start').disabled=true;el('music-error').textContent='';el('music-result').replaceChildren();resultId=null;try{await api('music/start',{profile_id:el('music-profile').value,lyrics:el('music-lyrics').value,style:el('music-style').value,seed:Number(el('music-seed').value),max_tokens:Number(el('music-tokens').value),steps:Number(el('music-steps').value),...(ace?{duration_seconds:Number(el('music-duration').value),guidance:Number(el('music-guidance').value),thinking:el('music-thinking').checked,instrumental:el('music-instrumental').checked,bpm:el('music-bpm').value?Number(el('music-bpm').value):null,language:el('music-language').value}:{})});}catch(x){el('music-error').textContent=x.message;}finally{busy=false;}};el('music-cancel').onclick=()=>api('music/cancel',{}).catch(x=>el('music-error').textContent=x.message);poll();}
el('music-load').onclick=()=>api('music/load',{profile_id:el('music-profile').value}).catch(x=>el('music-error').textContent=x.message);el('music-form').onsubmit=async event=>{event.preventDefault();busy=true;el('music-start').disabled=true;el('music-error').textContent='';el('music-result').replaceChildren();resultId=null;try{await api('music/start',{profile_id:el('music-profile').value,lyrics:el('music-lyrics').value,style:el('music-style').value,seed:Number(el('music-seed').value),max_tokens:Number(el('music-tokens').value),steps:Number(el('music-steps').value),...(ace?{duration_seconds:Number(el('music-duration').value),guidance:Number(el('music-guidance').value),thinking:el('music-thinking').checked,instrumental:el('music-instrumental').checked,bpm:el('music-bpm').value?Number(el('music-bpm').value):null,language:el('music-language').value}:(el('music-abc').value&&el('music-cot').value!=='off'?{abc:el('music-abc').value,cot:el('music-cot').value}:{}))});}catch(x){el('music-error').textContent=x.message;}finally{busy=false;}};el('music-cancel').onclick=()=>api('music/cancel',{}).catch(x=>el('music-error').textContent=x.message);poll();}
return {html,bind};
})();
+9 -6
View File
@@ -16,15 +16,17 @@ class Music:
return result
def status(self):
with self.lock:return dict(job=dict(self.job) if self.job else None,loaded=bool(self.session_ready and self.process and self.process.poll() is None),profile_id=self.session_key[0] if self.session_key else None,mode=self.scheduler.gpu_mode,runtime_installed=self.runtime.status()['installed'])
def start(self,profile_id,lyrics,style,seed=1234,max_tokens=400,steps=8,wait=False):
def start(self,profile_id,lyrics,style,seed=1234,max_tokens=400,steps=8,wait=False,abc=None,cot='off'):
if not isinstance(lyrics,str) or not 1<=len(lyrics.strip())<=8000:raise ValueError('Songtext mit 1–8000 Zeichen eingeben.')
if not isinstance(style,str) or not 1<=len(style.strip())<=2000:raise ValueError('Musikstil mit 1–2000 Zeichen eingeben.')
for value,lo,hi in ((seed,0,2**31-1),(max_tokens,32,9000),(steps,1,32)):
if type(value) is not int or not lo<=value<=hi:raise ValueError('Ungültige Musikparameter.')
return self._start_job(profile_id,lyrics,style,seed,max_tokens,steps,wait)
if cot not in ('off','melody','full'):raise ValueError('Score-Modus: off, melody oder full.')
if abc is not None and (not isinstance(abc,str) or not 1<=len(abc)<=20000 or cot=='off'):raise ValueError('ABC-Score mit maximal 20000 Zeichen und Modus melody/full erforderlich.')
return self._start_job(profile_id,lyrics,style,seed,max_tokens,steps,wait,abc,cot)
def load(self,profile_id,wait=False):
return self._start_job(profile_id,None,None,1234,400,8,wait)
def _start_job(self,profile_id,lyrics,style,seed,max_tokens,steps,wait):
def _start_job(self,profile_id,lyrics,style,seed,max_tokens,steps,wait,abc=None,cot='off'):
if self.scheduler.gpu_mode!='music':raise ValueError('Bitte in der Übersicht auf Musik umschalten.')
with self.lock:
if self.job and self.job['state']=='running':raise ValueError('Musikauftrag läuft bereits.')
@@ -32,7 +34,7 @@ class Music:
if not p or not p['runnable']:raise ValueError('Musikprofil noch nicht vollständig eingerichtet.')
self.cancel.clear();self.root.mkdir(parents=True,exist_ok=True,mode=0o700)
self.job=dict(id=uuid.uuid4().hex,state='running',phase='Wartet auf Deck-GPU-Freigabe',profile_id=profile_id,started_at=time.time(),max_tokens=max_tokens)
threading.Thread(target=self._run,args=(p,lyrics,style,seed,max_tokens,steps,wait),daemon=True).start();return dict(self.job)
threading.Thread(target=self._run,args=(p,lyrics,style,seed,max_tokens,steps,wait)+((abc,cot) if abc or cot!='off' else ()),daemon=True).start();return dict(self.job)
def _request(self,path,data=None,timeout=5):
conn=http.client.HTTPConnection('127.0.0.1',self.port,timeout=timeout)
try:
@@ -91,7 +93,7 @@ class Music:
if time.monotonic()>deadline:raise ValueError('YuE2 konnte nicht rechtzeitig geladen werden.')
self.cancel.wait(.25)
raise InterruptedError()
def _run(self,p,lyrics,style,seed,max_tokens,steps,wait):
def _run(self,p,lyrics,style,seed,max_tokens,steps,wait,abc=None,cot='off'):
release=None;state='failed';phase='Musikgenerierung fehlgeschlagen.';directory=self.root/self.job['id']
try:
release=self.scheduler.image_reservation(wait=wait,kind="music")
@@ -102,7 +104,8 @@ class Music:
state='ready';phase='YuE2 geladen · bereit für weitere Songs';return
directory.mkdir(mode=0o700)
with self.lock:self.job['phase']='YuE2 erzeugt Musik · Modell bleibt geladen'
request=dict(model='deck-yue2',request=dict(lyrics=lyrics,options={'style':style,'cot':'off','semantic_min_tokens':'0','semantic_max_tokens':str(max_tokens),'num_inference_steps':str(steps),'seed':str(seed)}))
request=dict(model='deck-yue2',request=dict(lyrics=lyrics,options={'style':style,'cot':cot,'semantic_min_tokens':'0','semantic_max_tokens':str(max_tokens),'num_inference_steps':str(steps),'seed':str(seed)}))
if abc:request['request']['options']['abc']=abc
result=self._request('/v1/tasks/run',request,timeout=1800)
if self.cancel.is_set():raise InterruptedError()
audio=base64.b64decode(result['audio'],validate=True)
+4
View File
@@ -227,6 +227,8 @@ class Profiles:
try:self._component(p['model'],role,p.get('components',{}).get(role))
except ValueError:p['blockers'].append(info['label']+' fehlt oder ist noch nicht zugeordnet.')
if applio_model(p.get('model')):p['blockers']=getattr(self,'applio_blockers',lambda p:['Applio-Worker fehlt.'])(p)
from xvc import xvc_model
if xvc_model(p.get('model')):p['blockers']=getattr(self,'xvc_blockers',lambda p:['X-VC-Worker fehlt.'])(p)
if p['kind']=='video' and self.video_blockers and p.get('model'):p['blockers']=self.video_blockers(p)
if p['kind']=='audio' and self.tts_blockers and p.get('model') and not voice_recipe(p['model']):p['blockers']=self.tts_blockers(p)
if p['kind']=='music' and getattr(self,'music_blockers',None) and p.get('model'):p['blockers']=self.music_blockers(p)
@@ -348,6 +350,8 @@ class Profiles:
return item
def components(self,model_id,extra_repo=None):
model=self.catalog.entry(model_id)
from xvc import xvc_model
if xvc_model(model):return dict(supported=True,requirements=[],source='https://huggingface.co/chenxie95/X-VC',license='mit',runtime='X-VC · Python/PyTorch',runtime_route='#xvc-runtime',runtime_installed=not bool(getattr(self,'xvc_blockers',lambda p:['Laufzeit fehlt'])({'model':model})),worker_available=True,no_components=True,message='Audio-zu-Audio-Stimmumwandlung. X-VC, Sprach-Tokenizer, Sprecherencoder und optionales Resemble Enhance werden als geprüftes Paket mit der Laufzeit installiert. Kein VAE oder Vision-Projektor erforderlich.')
from applio import applio_model
if applio_model(model):return dict(supported=True,requirements=[],source=None,license=None,runtime='Applio / RVC · Python/PyTorch',runtime_route='#applio-runtime',runtime_installed=not bool(getattr(self,'applio_blockers',lambda p:['Laufzeit prüfen'])({'model':model})),worker_available=True,no_components=True,message='Lokales RVC-Stimmgewicht aus unserer bisherigen Applio-Oberfläche. Index und Trainingsstände bleiben im Applio-Datenbestand. Offizielle Basisgewichte werden mit der Laufzeit eingerichtet. Eigene Stimme separat sichern; kein verifizierter öffentlicher Downloadlink.')
from embeddings import supported
+50
View File
@@ -0,0 +1,50 @@
"""Audio-to-score jobs use Deck's music GPU lease and delete temporary input."""
import os,signal,subprocess,tempfile,threading,time
from pathlib import Path
from image_test import probe
class Remix:
def __init__(self,root,runtime,music,scheduler):
self.root=Path(root);self.runtime=runtime;self.music=music;self.scheduler=scheduler;self.lock=threading.Lock();self.process=None;self.active=False
def status(self):return dict(self.runtime.status(),active=self.active)
def transcribe(self,audio,melody_only=True):
if type(melody_only) is not bool:raise ValueError('melody_only muss boolesch sein.')
if not isinstance(audio,bytes) or not 44<=len(audio)<=256*1024**2:raise ValueError('Audiodatei fehlt oder ist größer als 256 MiB.')
if not self.runtime.status()['installed']:raise ValueError('YuE2 Audio Remix zuerst in Deck einrichten.')
if self.scheduler.gpu_mode!='music':raise ValueError('Bitte in Deck auf Musik umschalten.')
if not self.lock.acquire(blocking=False):raise ValueError('Audio-Remix-Analyse läuft bereits.')
release=None
try:
release=self.scheduler.image_reservation(kind='music');self.active=True
self.music.close() # Only after exclusive admission: analysis needs the same GPU.
gpu=next((g for g in probe() if 'RTX 5080' in g['name'] and not g['processes'] and g['free_mib']>6000),None)
if not gpu:raise ValueError('RTX 5080 nicht ausreichend frei. Fremde Prozesse bleiben unverändert.')
self.root.mkdir(parents=True,exist_ok=True)
with tempfile.TemporaryDirectory(prefix='analysis-',dir=self.root) as temp:
work=Path(temp);(work/'input').write_bytes(audio)
result=subprocess.run(['ffmpeg','-nostdin','-hide_banner','-loglevel','error','-y','-i',str(work/'input'),'-t','1201','-ac','1','-ar','24000','-c:a','pcm_s16le',str(work/'input.wav')],capture_output=True,timeout=180)
if result.returncode:raise ValueError('Audiodatei konnte nicht gelesen werden.')
import wave
with wave.open(str(work/'input.wav')) as wav:
if not 0<wav.getnframes()/wav.getframerate()<=1200:raise ValueError('Audio-Remix: maximal 20 Minuten pro Aufnahme.')
python,models=self.runtime.paths();started=time.monotonic()
with (work/'worker.log').open('wb') as log:
self.process=subprocess.Popen([str(python),str(Path(__file__).with_name('remix_worker.py')),str(models),str(work/'input.wav'),str(work/'output'),'true' if melody_only else 'false'],stdout=log,stderr=log,start_new_session=True,env=dict(os.environ,CUDA_VISIBLE_DEVICES=gpu['uuid'],HF_HUB_OFFLINE='1',TRANSFORMERS_OFFLINE='1',HF_HUB_DISABLE_TELEMETRY='1',OMP_NUM_THREADS='4'))
try:code=self.process.wait(timeout=3600)
except subprocess.TimeoutExpired:self.stop();raise ValueError('Audio-Remix-Analyse hat das Zeitlimit überschritten.') from None
if code:
error=(work/'worker.log').read_text(errors='replace')[-4000:]
raise ValueError('Remix-GPU-Speicher reicht nicht.' if 'out of memory' in error.lower() else 'SheetSage2-Analyse fehlgeschlagen ('+next((line.split(':',1)[0][:80] for line in reversed(error.splitlines()) if line and not line.startswith((' ','Traceback'))),'Worker-Fehler')+'). Laufzeit und Modellpaket prüfen.')
abc=(work/'output/score.abc').read_text()
if not 1<=len(abc)<=20000:raise ValueError('Musikplan zu umfangreich oder leer.')
return dict(abc=abc,melody_only=melody_only,seconds=round(time.monotonic()-started,1))
finally:
self.stop();self.active=False
if release:release()
self.lock.release()
def stop(self):
p=self.process
if p and p.poll() is None:
try:os.killpg(p.pid,signal.SIGTERM);p.wait(5)
except subprocess.TimeoutExpired:os.killpg(p.pid,signal.SIGKILL);p.wait()
except ProcessLookupError:pass
self.process=None
+50
View File
@@ -0,0 +1,50 @@
"""Pinned SheetSage2/MERT transcription environment for the existing YuE2 UI."""
import hashlib,json,os,shutil,site,sys,urllib.request
from pathlib import Path
from ltx_original_runtime import LTXOriginalRuntime
SOURCES=json.loads(Path(__file__).with_name('remix_sources.json').read_text())
VERSION='SheetSage2-eab522a + MERT-d8ba1c7'
class RemixRuntime(LTXOriginalRuntime):
name='YuE2 Audio Remix'
def __init__(self,root,separator):super().__init__(root,None);self.separator=separator
def paths(self):
try:
ident=json.loads((self.root/'active.json').read_text())['id']
if len(ident)==32 and all(c in '0123456789abcdef' for c in ident):
base=self.root/ident
if (base/'ready').is_file():return base/'python/bin/python',base/'models'
except (OSError,ValueError,KeyError):pass
return self.root/'missing-python',self.root/'missing-models'
def status(self):
python,models=self.paths()
return dict(installed=python.is_file() and (models/'SheetSage2/model.safetensors').is_file() and (models/'MERT-v2-FullSong/model.safetensors').is_file(),version=VERSION,required_disk_gib=8,job=dict(self.job) if self.job else None,sources=SOURCES)
def _run(self):
base=self.root/self.job['id'];state='failed';phase='Remix-Einrichtung fehlgeschlagen.'
try:
base.mkdir(mode=0o700);models=base/'models';models.mkdir();python=base/'python/bin/python'
self._phase('Remix · isolierte Python-Umgebung');self._command([sys.executable,'-m','venv',base/'python'])
shared=self.separator.paths()[0]
if shared.is_file():
from cuda_overlay import share_cuda
share_cuda(python,base,shared,self._command)
else:self._command([python,'-m','pip','install','--no-cache-dir','torch==2.11.0','torchaudio==2.11.0','--index-url','https://download.pytorch.org/whl/cu128'])
self._phase('SheetSage2-Abhängigkeiten');self._command([python,'-m','pip','install','--no-cache-dir','transformers==4.45.2','huggingface-hub==0.36.0','safetensors==0.5.3','numpy==1.26.4','scipy==1.13.1','mir_eval==0.8.2','pretty_midi==0.2.10','mido==1.3.3','soundfile==0.13.1','setuptools==78.1.1','torch==2.11.0','torchaudio==2.11.0'])
self._command([python,'-m','pip','check'])
for recipe in SOURCES.values():
for item in recipe['files']:
self._phase('Remix-Modellpaket: '+item['file']);dest=models/item['file'];dest.parent.mkdir(parents=True,exist_ok=True);h=hashlib.sha256();size=0
with urllib.request.urlopen(item['urls'][0],timeout=90) as response,dest.open('wb') as out:
while chunk:=response.read(1024**2):
if self.cancel.is_set():raise InterruptedError()
size+=len(chunk)
if size>4*1024**3:raise ValueError('Modellquelldatei zu groß.')
h.update(chunk);out.write(chunk)
if h.hexdigest()!=item['sha256']:raise ValueError('Prüfsumme stimmt nicht: '+item['file'])
self._command([python,'-c','import torch,transformers,soundfile;assert torch.version.cuda;assert transformers.__version__=="4.45.2"'])
(base/'ready').write_text(VERSION);tmp=self.root/'active.tmp';tmp.write_text(json.dumps({'id':base.name}));tmp.replace(self.root/'active.json')
state='complete';phase='Audio Remix bereit · SheetSage2 und MERT installiert'
except InterruptedError:state='cancelled';phase='Remix-Einrichtung abgebrochen.'
except Exception as exc:phase=str(exc)
finally:
if state!='complete':shutil.rmtree(base,ignore_errors=True)
with self.lock:self.process=None;self.job.update(state=state,phase=phase);self._save()
+301
View File
@@ -0,0 +1,301 @@
{
"SheetSage2": {
"repo": "m-a-p/SheetSage2",
"revision": "eab522a8168e8b8b8c4856bf8609cd86198f01fe",
"files": [
{
"file": "SheetSage2/LICENSE",
"sha256": "73593d6cad4ca80f3ab1448a4908f92ab802dfffe029561e3b12fa7d07c8b87c",
"urls": [
"https://huggingface.co/m-a-p/SheetSage2/resolve/eab522a8168e8b8b8c4856bf8609cd86198f01fe/LICENSE"
]
},
{
"file": "SheetSage2/README.md",
"sha256": "30c377847af4131b84c9725ab0c6f39538709b974c9fa9001d38092c8962803d",
"urls": [
"https://huggingface.co/m-a-p/SheetSage2/resolve/eab522a8168e8b8b8c4856bf8609cd86198f01fe/README.md"
]
},
{
"file": "SheetSage2/THIRD_PARTY_NOTICES.md",
"sha256": "ab8b195c2c1475f254a04181a9841db2f2581c579b95858c78ee0040eb495a29",
"urls": [
"https://huggingface.co/m-a-p/SheetSage2/resolve/eab522a8168e8b8b8c4856bf8609cd86198f01fe/THIRD_PARTY_NOTICES.md"
]
},
{
"file": "SheetSage2/__init__.py",
"sha256": "19539a965cabf22d08231688efc15547d005e6345745f48684c2f02d010f82fd",
"urls": [
"https://huggingface.co/m-a-p/SheetSage2/resolve/eab522a8168e8b8b8c4856bf8609cd86198f01fe/__init__.py"
]
},
{
"file": "SheetSage2/audio_sheetsage2.py",
"sha256": "ecce56e7bb8a08cbca9eb27a74d9aeff17f55e80efcc7c48f7436440f610ccc1",
"urls": [
"https://huggingface.co/m-a-p/SheetSage2/resolve/eab522a8168e8b8b8c4856bf8609cd86198f01fe/audio_sheetsage2.py"
]
},
{
"file": "SheetSage2/benchmark_results.json",
"sha256": "a906aef48611247325433a8f6270159f3d58b626a46b48d55d8197c68091cc5a",
"urls": [
"https://huggingface.co/m-a-p/SheetSage2/resolve/eab522a8168e8b8b8c4856bf8609cd86198f01fe/benchmark_results.json"
]
},
{
"file": "SheetSage2/config.json",
"sha256": "a986e63f5d831ecb823c11d19cfb371d763f25ae2e614ec9acd714c0b8bb87fd",
"urls": [
"https://huggingface.co/m-a-p/SheetSage2/resolve/eab522a8168e8b8b8c4856bf8609cd86198f01fe/config.json"
]
},
{
"file": "SheetSage2/configuration_mert2.py",
"sha256": "77b53ec9d7ee31a599d744fb006e812c7eeaf7390deb46e2f460cf8c17b00bd6",
"urls": [
"https://huggingface.co/m-a-p/SheetSage2/resolve/eab522a8168e8b8b8c4856bf8609cd86198f01fe/configuration_mert2.py"
]
},
{
"file": "SheetSage2/configuration_sheetsage2.py",
"sha256": "36d174331b3721d984608252830179bf3516d77b7225f413acc85bdf5efb3bec",
"urls": [
"https://huggingface.co/m-a-p/SheetSage2/resolve/eab522a8168e8b8b8c4856bf8609cd86198f01fe/configuration_sheetsage2.py"
]
},
{
"file": "SheetSage2/durations_sheetsage2.py",
"sha256": "abbc297b70b63a86f8509b1db74d0e85d7b46dcb83867cf33741c43f9d49db83",
"urls": [
"https://huggingface.co/m-a-p/SheetSage2/resolve/eab522a8168e8b8b8c4856bf8609cd86198f01fe/durations_sheetsage2.py"
]
},
{
"file": "SheetSage2/exports_sheetsage2.py",
"sha256": "8c50cf9f71a4dc0dea13a9a4341345f7f9e02844fb32631888cb0f7b7bb6e815",
"urls": [
"https://huggingface.co/m-a-p/SheetSage2/resolve/eab522a8168e8b8b8c4856bf8609cd86198f01fe/exports_sheetsage2.py"
]
},
{
"file": "SheetSage2/generation_sheetsage2.py",
"sha256": "b58dbbfaebfba2a441a79b8c36183f0e4956acdd3aaf7c655c559933b4c20afd",
"urls": [
"https://huggingface.co/m-a-p/SheetSage2/resolve/eab522a8168e8b8b8c4856bf8609cd86198f01fe/generation_sheetsage2.py"
]
},
{
"file": "SheetSage2/infer.py",
"sha256": "20e6b23c910bfdecf012a8ee8d45efcb31cb6cb21351da5921d95fb877e70de6",
"urls": [
"https://huggingface.co/m-a-p/SheetSage2/resolve/eab522a8168e8b8b8c4856bf8609cd86198f01fe/infer.py"
]
},
{
"file": "SheetSage2/io_sheetsage2.py",
"sha256": "afb5b4d4a52b513b11cfdad40e7b9d2286dd4ff6585b89688dbb31b3d5376da6",
"urls": [
"https://huggingface.co/m-a-p/SheetSage2/resolve/eab522a8168e8b8b8c4856bf8609cd86198f01fe/io_sheetsage2.py"
]
},
{
"file": "SheetSage2/labels_sheetsage2.py",
"sha256": "4a80870695dd91da6070e7d8d0ce6b50f3bf71c3f629417a86cf12f4ef4f97e0",
"urls": [
"https://huggingface.co/m-a-p/SheetSage2/resolve/eab522a8168e8b8b8c4856bf8609cd86198f01fe/labels_sheetsage2.py"
]
},
{
"file": "SheetSage2/midi_sheetsage2.py",
"sha256": "32f80d13592c669e56683ebb4c415f13bf8278c8ad1fe43afa500347bed35099",
"urls": [
"https://huggingface.co/m-a-p/SheetSage2/resolve/eab522a8168e8b8b8c4856bf8609cd86198f01fe/midi_sheetsage2.py"
]
},
{
"file": "SheetSage2/model.safetensors",
"sha256": "b235f68091a5f5b644000f2b5acb57d1e70432aca2b34ab1b9cf27236e1f4274",
"urls": [
"https://huggingface.co/m-a-p/SheetSage2/resolve/eab522a8168e8b8b8c4856bf8609cd86198f01fe/model.safetensors"
]
},
{
"file": "SheetSage2/modeling_mert2.py",
"sha256": "b1a3174e5649c4b26b0c90d8626f0adacfbbba111a58ed3bb72ad651945a2f5c",
"urls": [
"https://huggingface.co/m-a-p/SheetSage2/resolve/eab522a8168e8b8b8c4856bf8609cd86198f01fe/modeling_mert2.py"
]
},
{
"file": "SheetSage2/modeling_sheetsage2.py",
"sha256": "df36bec866e4bd1f0a08e79369405c9a1bd86214a1c48559e75e3e567f43bbc4",
"urls": [
"https://huggingface.co/m-a-p/SheetSage2/resolve/eab522a8168e8b8b8c4856bf8609cd86198f01fe/modeling_sheetsage2.py"
]
},
{
"file": "SheetSage2/notation_sheetsage2.py",
"sha256": "f75f0e8b268cd9e9c622d791d3fd77d2e68ad355a4e67018c7e15aeb2bc05af7",
"urls": [
"https://huggingface.co/m-a-p/SheetSage2/resolve/eab522a8168e8b8b8c4856bf8609cd86198f01fe/notation_sheetsage2.py"
]
},
{
"file": "SheetSage2/pipeline_sheetsage2.py",
"sha256": "0ae572554ca375323e2aa4ea1fb25ba27e7f4d520c0ba5b101d74930c0a66c33",
"urls": [
"https://huggingface.co/m-a-p/SheetSage2/resolve/eab522a8168e8b8b8c4856bf8609cd86198f01fe/pipeline_sheetsage2.py"
]
},
{
"file": "SheetSage2/processing_sheetsage2.py",
"sha256": "b8dfa9f344ea7efab3ac9ec61f4c3bd0345f7a65d39a5c2c8b8a803689fdc393",
"urls": [
"https://huggingface.co/m-a-p/SheetSage2/resolve/eab522a8168e8b8b8c4856bf8609cd86198f01fe/processing_sheetsage2.py"
]
},
{
"file": "SheetSage2/processor_config.json",
"sha256": "1eed73513a74029fe74c71faba70f8cff002ae7be23ac1c926125846d1b29817",
"urls": [
"https://huggingface.co/m-a-p/SheetSage2/resolve/eab522a8168e8b8b8c4856bf8609cd86198f01fe/processor_config.json"
]
},
{
"file": "SheetSage2/render.py",
"sha256": "446b18e0ba7250c8584c14bda241f8d063083cd10b1432de82c3cf56736af9de",
"urls": [
"https://huggingface.co/m-a-p/SheetSage2/resolve/eab522a8168e8b8b8c4856bf8609cd86198f01fe/render.py"
]
},
{
"file": "SheetSage2/rendering_sheetsage2.py",
"sha256": "ddbcaf314139d67727cb5df6840d7d60d671d5c67f6b185a26b840df1e2d9288",
"urls": [
"https://huggingface.co/m-a-p/SheetSage2/resolve/eab522a8168e8b8b8c4856bf8609cd86198f01fe/rendering_sheetsage2.py"
]
},
{
"file": "SheetSage2/requirements-render.txt",
"sha256": "17990cc03ded2e6041b1ee4afcb3c0af3577cba534a4537685776c76fe0642c1",
"urls": [
"https://huggingface.co/m-a-p/SheetSage2/resolve/eab522a8168e8b8b8c4856bf8609cd86198f01fe/requirements-render.txt"
]
},
{
"file": "SheetSage2/requirements.txt",
"sha256": "fc3172be36722d75ae679ec9ffcf100baaa3d6ce4b6fdfefa9b24608810fc6a2",
"urls": [
"https://huggingface.co/m-a-p/SheetSage2/resolve/eab522a8168e8b8b8c4856bf8609cd86198f01fe/requirements.txt"
]
},
{
"file": "SheetSage2/schema_sheetsage2.py",
"sha256": "3ee069f0d4dcfb8080f730c43676318d471ab6b3cfef86c6c225aa63a9db182f",
"urls": [
"https://huggingface.co/m-a-p/SheetSage2/resolve/eab522a8168e8b8b8c4856bf8609cd86198f01fe/schema_sheetsage2.py"
]
},
{
"file": "SheetSage2/setup_render.py",
"sha256": "8ee1004067f8e50443005a761d86435337f6ee71eeabf447d543eb5f3ad5561d",
"urls": [
"https://huggingface.co/m-a-p/SheetSage2/resolve/eab522a8168e8b8b8c4856bf8609cd86198f01fe/setup_render.py"
]
},
{
"file": "SheetSage2/tensors_sheetsage2.py",
"sha256": "51f72b51ed5a22c751d5adf915198490b1a95ec8959fcf9a38ee71b4444fc8b3",
"urls": [
"https://huggingface.co/m-a-p/SheetSage2/resolve/eab522a8168e8b8b8c4856bf8609cd86198f01fe/tensors_sheetsage2.py"
]
},
{
"file": "SheetSage2/tokenization_sheetsage2.py",
"sha256": "b8cc6792eda99994ab7e1be4e7afcd8760fe7f25ad2886639306cc1dfe63b75d",
"urls": [
"https://huggingface.co/m-a-p/SheetSage2/resolve/eab522a8168e8b8b8c4856bf8609cd86198f01fe/tokenization_sheetsage2.py"
]
}
]
},
"MERT-v2-FullSong": {
"repo": "m-a-p/MERT-v2-FullSong",
"revision": "d8ba1c745e733b3908ce6ad16ebeb17ac7600a42",
"files": [
{
"file": "MERT-v2-FullSong/LICENSE",
"sha256": "73593d6cad4ca80f3ab1448a4908f92ab802dfffe029561e3b12fa7d07c8b87c",
"urls": [
"https://huggingface.co/m-a-p/MERT-v2-FullSong/resolve/d8ba1c745e733b3908ce6ad16ebeb17ac7600a42/LICENSE"
]
},
{
"file": "MERT-v2-FullSong/README.md",
"sha256": "2b025166f640a0416b5544f4c3775aced46bf0c467af4ef7b302d52496335da6",
"urls": [
"https://huggingface.co/m-a-p/MERT-v2-FullSong/resolve/d8ba1c745e733b3908ce6ad16ebeb17ac7600a42/README.md"
]
},
{
"file": "MERT-v2-FullSong/THIRD_PARTY_NOTICES.md",
"sha256": "ce8fd578969f1bdad9a0be5e20cab0251dc4253bd4dbfaa9abeb1c11d68bafdc",
"urls": [
"https://huggingface.co/m-a-p/MERT-v2-FullSong/resolve/d8ba1c745e733b3908ce6ad16ebeb17ac7600a42/THIRD_PARTY_NOTICES.md"
]
},
{
"file": "MERT-v2-FullSong/config.json",
"sha256": "f2e194895f58be3ddba327255db129ff0e3bee550cc0ecf08e4d22d79ce3bca3",
"urls": [
"https://huggingface.co/m-a-p/MERT-v2-FullSong/resolve/d8ba1c745e733b3908ce6ad16ebeb17ac7600a42/config.json"
]
},
{
"file": "MERT-v2-FullSong/configuration_mert2.py",
"sha256": "77b53ec9d7ee31a599d744fb006e812c7eeaf7390deb46e2f460cf8c17b00bd6",
"urls": [
"https://huggingface.co/m-a-p/MERT-v2-FullSong/resolve/d8ba1c745e733b3908ce6ad16ebeb17ac7600a42/configuration_mert2.py"
]
},
{
"file": "MERT-v2-FullSong/marble_results.json",
"sha256": "ced741a3d9684b551a2569c2206ba86911addd07a42df72d65b74e4288d4bd0e",
"urls": [
"https://huggingface.co/m-a-p/MERT-v2-FullSong/resolve/d8ba1c745e733b3908ce6ad16ebeb17ac7600a42/marble_results.json"
]
},
{
"file": "MERT-v2-FullSong/model.safetensors",
"sha256": "e6dd2ab187d6dd62b6521cd7d8f932e237acf0c5757745a7232082e28391350d",
"urls": [
"https://huggingface.co/m-a-p/MERT-v2-FullSong/resolve/d8ba1c745e733b3908ce6ad16ebeb17ac7600a42/model.safetensors"
]
},
{
"file": "MERT-v2-FullSong/modeling_mert2.py",
"sha256": "b1a3174e5649c4b26b0c90d8626f0adacfbbba111a58ed3bb72ad651945a2f5c",
"urls": [
"https://huggingface.co/m-a-p/MERT-v2-FullSong/resolve/d8ba1c745e733b3908ce6ad16ebeb17ac7600a42/modeling_mert2.py"
]
},
{
"file": "MERT-v2-FullSong/preprocessor_config.json",
"sha256": "fc7337f113b71062b8efd03f8a43a07aa769ce85c6a53fdc0b3bb90c299fe63f",
"urls": [
"https://huggingface.co/m-a-p/MERT-v2-FullSong/resolve/d8ba1c745e733b3908ce6ad16ebeb17ac7600a42/preprocessor_config.json"
]
},
{
"file": "MERT-v2-FullSong/weights_manifest.json",
"sha256": "413e2ddfa71ae5bb364bfd15364e221249111e14c2f0843ea6162afb776a8300",
"urls": [
"https://huggingface.co/m-a-p/MERT-v2-FullSong/resolve/d8ba1c745e733b3908ce6ad16ebeb17ac7600a42/weights_manifest.json"
]
}
]
}
}
+20
View File
@@ -0,0 +1,20 @@
"""Offline GPU transcription. Decode with FFmpeg, avoiding torchaudio FFmpeg ABI coupling."""
import json,sys
from pathlib import Path
import numpy as np,soundfile as sf,torch
from transformers import AutoModel
if not torch.cuda.is_available():raise RuntimeError('CUDA fehlt; kein CPU-Fallback.')
models,input_file,output,melody=sys.argv[1:5]
audio,sr=sf.read(input_file,dtype='float32',always_2d=True)
model=AutoModel.from_pretrained(str(Path(models)/'SheetSage2'),base_model_path=str(Path(models)/'MERT-v2-FullSong'),trust_remote_code=True,local_files_only=True).eval().to('cuda')
waveform=audio.mean(axis=1)
with torch.inference_mode():
try:result=model.transcribe(waveform,sampling_rate=sr,output_dir=output,melody_only=melody=='true')
except RuntimeError as exc:
# SheetSage2 can quantize a note at a hard file boundary to an unrepresentable
# tiny duration. Retry that specific notation failure with analysis-only silence.
if 'cannot be represented on the decoded subbeat grid' not in str(exc):raise
result=model.transcribe(np.pad(waveform,(0,2*sr)),sampling_rate=sr,output_dir=output,melody_only=melody=='true')
abc=result['abc']
if not isinstance(abc,str) or not abc.strip():raise RuntimeError('Keine Musiknotation erzeugt.')
(Path(output)/'score.abc').write_text(abc)
+3 -3
View File
@@ -42,7 +42,7 @@ class SeparatorTests:
def start(self,model,audio,target=None,full=False):
if isinstance(model,str) and model in MODELS and not self.profiles()[model]['enabled']:raise ValueError('Dieses Audio-Trennprofil ist deaktiviert. Unter Profile aktivieren.')
if full and self.scheduler.gpu_mode!='separator':raise ValueError('Bitte unter Steuerung Audio-Trennung starten.')
targets={'vocals':'model_bs_roformer_ep_317_sdr_12.9755.ckpt','drums':'htdemucs_ft.yaml','bass':'htdemucs_ft.yaml','guitar':'htdemucs_6s.yaml','piano':'htdemucs_6s.yaml','other':'htdemucs_6s.yaml'}
targets={'vocals':'model_bs_roformer_ep_317_sdr_12.9755.ckpt','drums':'htdemucs_ft.yaml','bass':'htdemucs_ft.yaml','guitar':'htdemucs_6s.yaml','piano':'htdemucs_6s.yaml','other':'htdemucs_6s.yaml','speech':'MossFormer2_SE_48K'}
if target is not None and targets.get(target)!=model:raise ValueError('Zielspur und Modellpaket passen nicht zusammen.')
if not isinstance(model,str) or model not in MODELS or not self.runtime.status()['installed'] or not self.runtime.model_ready(model):raise ValueError('Laufzeit und Modellpaket zuerst unter Audio Separator einrichten.')
if not isinstance(audio,bytes) or not 44<=len(audio)<=(256 if full else 8)*1024**2:raise ValueError('WAV überschreitet die erlaubte Upload-Größe.')
@@ -65,7 +65,7 @@ class SeparatorTests:
with self.lock:
if self.cancel.is_set():raise InterruptedError()
self.job.update(phase='Modell laden und Audio trennen',gpu=gpu['name'])
self.process=subprocess.Popen([str(self.runtime.paths()[0]),str(Path(__file__).with_name('separator_worker.py')),str(self.runtime.root/'models'),model,str(directory/'input.wav'),str(directory),getattr(self,'target',None) or ''],stdout=subprocess.DEVNULL,stderr=diagnostics,start_new_session=True,env=dict(os.environ,CUDA_VISIBLE_DEVICES=gpu['uuid'],OMP_NUM_THREADS='6'))
self.process=subprocess.Popen([str(self.runtime.worker_python(model)),str(Path(__file__).with_name('clearvoice_worker.py' if model=='MossFormer2_SE_48K' else 'separator_worker.py')),str(self.runtime.root/'models'),model,str(directory/'input.wav'),str(directory),getattr(self,'target',None) or ''],stdout=subprocess.DEVNULL,stderr=diagnostics,start_new_session=True,env=dict(os.environ,CUDA_VISIBLE_DEVICES=gpu['uuid'],OMP_NUM_THREADS='6'))
# Drain diagnostics into a bounded temporary file rather than retaining user data.
deadline=time.monotonic()+(7200 if getattr(self,'full',False) else 600)
while self.process.poll() is None:
@@ -73,7 +73,7 @@ class SeparatorTests:
if time.monotonic()>deadline:raise ValueError('Trennauftrag überschreitet das Zeitlimit.')
with self.lock:self.job['elapsed_seconds']=round(time.time()-self.job['started_at'])
diagnostics.close();error=(directory/'worker.tmp').read_bytes()[-65536:].decode(errors='replace')
if self.process.returncode:raise ValueError('GPU-Speicher reicht nicht (OOM).' if 'out of memory' in error.lower() else 'Audio Separator hat den Test abgebrochen. Modellpaket und Laufzeit prüfen.')
if self.process.returncode:raise ValueError('GPU-Speicher reicht nicht (OOM).' if 'out of memory' in error.lower() else 'Audio Separator hat den Test abgebrochen ('+next((line.split(':',1)[0][:80] for line in reversed(error.splitlines()) if line and not line.startswith((' ','Traceback'))),'Worker-Fehler')+'). Laufzeit und Modellpaket prüfen.')
names=json.loads((directory/'results.json').read_text())
if not names or any(Path(n).name!=n or not n.endswith('.wav') or not (directory/n).is_file() for n in names):raise ValueError('Ungültige Ergebnisdateien.')
with self.lock:self.job['files']=[dict(index=i,name=n) for i,n in enumerate(names)]
+21 -2
View File
@@ -14,11 +14,13 @@ def verify_package(directory,name):
for chunk in iter(lambda:stream.read(1024**2),b''):digest.update(chunk)
if digest.hexdigest()!=item['sha256']:return False
return True
CLEARVOICE='MossFormer2_SE_48K'
MODELS={
'vocals_mel_band_roformer.ckpt':('MelBand RoFormer · Gesang / Instrumental','vocals_mel_band_roformer.yaml'),
'model_bs_roformer_ep_317_sdr_12.9755.ckpt':('BS-RoFormer · Gesang / Instrumental','model_bs_roformer_ep_317_sdr_12.9755.yaml'),
'htdemucs_ft.yaml':('Demucs FT · Gesang / Schlagzeug / Bass / Rest','htdemucs_ft.yaml'),
'htdemucs_6s.yaml':('Demucs 6s · zusätzlich Gitarre / Piano','htdemucs_6s.yaml')}
'htdemucs_6s.yaml':('Demucs 6s · zusätzlich Gitarre / Piano','htdemucs_6s.yaml'),
CLEARVOICE:('ClearVoice · Sprache / Hintergrund','clearvoice/MossFormer2_SE_48K/last_best_checkpoint')}
class SeparatorRuntime(LTXOriginalRuntime):
name='Audio Separator'
def __init__(self,root):super().__init__(root,None)
@@ -30,11 +32,26 @@ class SeparatorRuntime(LTXOriginalRuntime):
base=self.root/ident
if (base/'ready').is_file():return base/'python/bin/python',base
return self.root/'missing-python',self.root/'missing-runtime'
def worker_python(self,name):
if name==CLEARVOICE:return self.paths()[1]/'clearvoice-python/bin/python'
return self.paths()[0]
def ensure_clearvoice(self):
python,base=self.paths();target=base/'clearvoice-python/bin/python'
if target.is_file() and (base/'clearvoice-ready').is_file():return
self._phase('ClearVoice · eigene Python-Umgebung mit geteilter CUDA-Laufzeit')
self._command([python,'-m','venv',base/'clearvoice-python'])
from cuda_overlay import share_cuda
share_cuda(target,base/'clearvoice-python',python,self._command)
self._command([target,'-m','pip','install','--no-cache-dir','clearvoice==0.1.2','numpy==1.26.4','huggingface-hub==0.36.0','torch==2.11.0','torchaudio==2.11.0','torchvision==0.26.0'])
self._command([target,'-m','pip','check'])
self._command([target,'-c','import torch,clearvoice,numpy;assert torch.version.cuda;assert numpy.__version__=="1.26.4"'])
(base/'clearvoice-ready').write_text('clearvoice==0.1.2\n numpy==1.26.4')
def status(self):
python,base=self.paths()
return dict(installed=python.is_file() and (base/'ready').is_file(),version=VERSION,required_disk_gib=15,job=dict(self.job) if self.job else None,models=[dict(id=name,name=label,configuration=config,source=SOURCES[name],installed=self.model_ready(name)) for name,(label,config) in MODELS.items()])
def model_ready(self,name):
if name not in MODELS:return False
if name==CLEARVOICE and not (self.paths()[1]/'clearvoice-ready').is_file():return False
directory=self.root/'models';marker=directory/(name+'.ready')
try:
recorded=json.loads(marker.read_text())
@@ -60,10 +77,12 @@ class SeparatorRuntime(LTXOriginalRuntime):
base=self.root/self.job['id'];state='failed';phase='Einrichtung fehlgeschlagen.';model=getattr(self,'requested_model',None)
try:
if model:
if model==CLEARVOICE:self.ensure_clearvoice()
directory=base;directory.mkdir(mode=0o700)
import urllib.request
for item in SOURCES[model]['files']:
self._phase('Modellpaket: '+item['file'])
(directory/item['file']).parent.mkdir(parents=True,exist_ok=True)
succeeded=False
for url in item['urls']:
try:
@@ -87,7 +106,7 @@ class SeparatorRuntime(LTXOriginalRuntime):
digest=hashlib.sha256()
with (directory/f).open('rb') as source:
for chunk in iter(lambda:source.read(1024**2),b''):digest.update(chunk)
hashes[f]=digest.hexdigest();(directory/f).replace(destination/f)
hashes[f]=digest.hexdigest();(destination/f).parent.mkdir(parents=True,exist_ok=True);(directory/f).replace(destination/f)
(destination/(model+'.ready')).write_text(json.dumps(hashes))
state='complete';phase='Modell und passende Konfiguration heruntergeladen. Kein Modell geladen.'
else:
+21
View File
@@ -109,5 +109,26 @@
]
}
]
},
"MossFormer2_SE_48K": {
"recipe_version": 1,
"publisher": "Alibaba Speech Lab",
"homepage": "https://huggingface.co/alibabasglab/MossFormer2_SE_48K",
"files": [
{
"file": "clearvoice/MossFormer2_SE_48K/last_best_checkpoint",
"sha256": "315744c841441f8831cb2f896e06102b4d864776bf272febaa30c639c903e1c0",
"urls": [
"https://huggingface.co/alibabasglab/MossFormer2_SE_48K/resolve/eff8c97925c8bec812af707814b3e5d777fd4503/last_best_checkpoint"
]
},
{
"file": "clearvoice/MossFormer2_SE_48K/last_best_checkpoint.pt",
"sha256": "03692b9f773bbd6bb43b9c5a41f96b1e28affd66e13796b7bec66ad3d8b227c6",
"urls": [
"https://huggingface.co/alibabasglab/MossFormer2_SE_48K/resolve/eff8c97925c8bec812af707814b3e5d777fd4503/last_best_checkpoint.pt"
]
}
]
}
}
+38 -6
View File
@@ -95,6 +95,8 @@ class Server(ThreadingHTTPServer):
self.profiles.voxcpm_runtime_ready=lambda:self.voxcpm_runtime.status()['installed']
from applio_runtime import ApplioRuntime
self.applio_runtime=ApplioRuntime(self.catalog.root.parent/'applio-runtime',self.image_runtime)
from xvc_runtime import XVCRuntime
self.xvc_runtime=XVCRuntime(self.catalog.root.parent/'xvc-runtime',self.image_runtime)
self.tts_runtime=TTSRuntime(self.catalog.root.parent/'tts-runtime')
self.tts_tests=TTSTests(self.catalog.root.parent/'tts-tests',self.profiles,self.tts_runtime)
self.profiles.tts_blockers=self.tts_tests.blockers
@@ -139,14 +141,18 @@ class Server(ThreadingHTTPServer):
self.applio=Applio(self.catalog.root.parent/'applio-data',self.applio_runtime,self.scheduler,self.profiles,lambda:self.endpoint.config['enabled_profiles'])
self.profiles.applio_blockers=self.applio.blockers
self.endpoint.applio=self.applio
from xvc import XVC
self.xvc=XVC(self.catalog.root.parent/'xvc-data',self.xvc_runtime,self.scheduler,self.profiles,lambda:self.endpoint.config['enabled_profiles'])
self.profiles.xvc_blockers=self.xvc.blockers;self.endpoint.xvc=self.xvc
self.xvc.ensure()
def evict_voice():
self.voxcpm_tests.unload_idle();self.applio.unload_idle()
self.voxcpm_tests.unload_idle();self.applio.unload_idle();self.xvc.unload_idle()
self.scheduler.evict_voice=evict_voice
self.applio.ensure()
self.chat_tests=ChatTests(self.profiles,self.worker,self.scheduler)
self.auto_tests=AutoTests(self.catalog.root.parent/'auto-tests.json',self.profiles,self.worker,self.scheduler)
def stop_gpu_work():
self.voxcpm_tests.stop();self.separator_tests.stop();self.music.close();self.auto_tests.stop();self.chat_tests.stop();self.image_tests.stop();self.prompt_enhancer.stop_preview();self.tts_tests.stop();self.worker.stop()
self.remix.stop();self.voxcpm_tests.stop();self.separator_tests.stop();self.music.close();self.auto_tests.stop();self.chat_tests.stop();self.image_tests.stop();self.prompt_enhancer.stop_preview();self.tts_tests.stop();self.worker.stop()
from video_original import VideoRuntimes
from ltx_original_runtime import LTXOriginalRuntime
from audio_cpp_runtime import AudioCppRuntime
@@ -160,6 +166,10 @@ class Server(ThreadingHTTPServer):
self.music=MusicRouter(Music(self.catalog.root.parent/'music-jobs',self.profiles,self.catalog,self.audio_cpp_runtime,self.scheduler),AceStep(self.catalog.root.parent/'acestep-jobs',self.profiles,self.catalog,self.acestep_runtime,self.scheduler))
self.profiles.music_blockers=self.music.blockers
self.endpoint.music=self.music
from remix_runtime import RemixRuntime
from remix import Remix
self.remix_runtime=RemixRuntime(self.catalog.root.parent/'music-remix-runtime',self.separator_runtime)
self.remix=Remix(self.catalog.root.parent/'music-remix-jobs',self.remix_runtime,self.music,self.scheduler)
from profiles import audio_package_recipe
self.profiles.runtime_recipe=lambda model:audio_package_recipe(model,self.audio_cpp_runtime.paths()[1])
self.ltx_original_runtime=LTXOriginalRuntime(self.catalog.root.parent/'ltx-original-runtime',self.image_runtime)
@@ -205,6 +215,7 @@ class Server(ThreadingHTTPServer):
threading.Thread(target=preload_music,daemon=True).start()
def server_close(self):
if getattr(self,'xvc',None):self.xvc.stop()
if getattr(self,'applio',None):self.applio.stop()
super().server_close()
@@ -243,7 +254,7 @@ class Handler(BaseHTTPRequestHandler):
return secrets.compare_digest(actual,record['api_token_hash'])
def token_route(self):
return (self.command == 'GET' and (self.path in ('/api/v1/status','/api/v1/hardware','/api/v1/separator-runtime','/api/v1/separator-tests','/api/v1/voice','/api/v1/voice/profiles') or urlsplit(self.path).path in ('/api/v1/separator-tests/audio','/api/v1/voice/audio'))) or (self.command=='POST' and self.path in ('/api/v1/separator-jobs/start','/api/v1/separator-tests/cancel','/api/v1/voice/start','/api/v1/voice/cancel'))
return (self.command == 'GET' and (self.path in ('/api/v1/status','/api/v1/hardware','/api/v1/separator-runtime','/api/v1/separator-tests','/api/v1/voice','/api/v1/voice/profiles','/api/v1/music-remix') or urlsplit(self.path).path in ('/api/v1/separator-tests/audio','/api/v1/voice/audio'))) or (self.command=='POST' and self.path in ('/api/v1/separator-jobs/start','/api/v1/separator-tests/cancel','/api/v1/voice/start','/api/v1/voice/cancel','/api/v1/music-remix/transcribe'))
def session_token(self):
try:
@@ -361,7 +372,7 @@ class Handler(BaseHTTPRequestHandler):
'video':video_runtime.status().get('installed',False),
'acestep':self.server.acestep_runtime.status()['installed'],
'audio_cpp':self.server.audio_cpp_runtime.status()['installed'],
'applio':self.server.applio_runtime.status()['installed'],'omnivoice':self.server.omnivoice_runtime.status()['installed'],'voxcpm':self.server.voxcpm_runtime.status()['installed'],'music_worker':True,'separator':self.server.separator_runtime.status()['installed']}
'xvc':self.server.xvc_runtime.status()['installed'],'applio':self.server.applio_runtime.status()['installed'],'omnivoice':self.server.omnivoice_runtime.status()['installed'],'voxcpm':self.server.voxcpm_runtime.status()['installed'],'music_worker':True,'separator':self.server.separator_runtime.status()['installed']}
def execution_setup(self, model, profile=None, installed=None):
return execution_assess(model, self.execution_runtime_snapshot() if installed is None else installed, profile)
@@ -377,7 +388,7 @@ class Handler(BaseHTTPRequestHandler):
return self.respond({'error':'Anmeldung erforderlich.'},401)
if not self.authenticated() and self.path == '/':
return self.respond((ROOT/'login.html').read_bytes(), mime='text/html; charset=utf-8')
routes = {'/applio-ui.js':('applio-ui.js','text/javascript'),'/acestep-ui.js':('acestep-ui.js','text/javascript'),'/voice-ui.js':('voice-ui.js','text/javascript'),'/voxcpm-ui.js':('voxcpm-ui.js','text/javascript'),'/separator-ui.js':('separator-ui.js','text/javascript'),'/music-ui.js':('music-ui.js','text/javascript'),'/audio-cpp-ui.js':('audio-cpp-ui.js','text/javascript'),'/ltx-original-ui.js':('ltx-original-ui.js','text/javascript'),'/backup-ui.js':('backup-ui.js','text/javascript'),'/dashboard-ui.js':('dashboard-ui.js','text/javascript'),'/dashboard.css':('dashboard.css','text/css'),'/themes.css':('themes.css','text/css'),'/video-ui.js':('video-ui.js','text/javascript'),'/stt-ui.js':('stt-ui.js','text/javascript'),'/tts-ui.js':('tts-ui.js','text/javascript'),'/auto-test-ui.js':('auto-test-ui.js','text/javascript'),'/chat-test-ui.js':('chat-test-ui.js','text/javascript'),'/endpoint-ui.js':('endpoint-ui.js','text/javascript'),'/docker-ui.js': ('docker-ui.js','text/javascript'), '/': ('index.html', 'text/html; charset=utf-8'), '/app.js': ('app.js', 'text/javascript'), '/style.css': ('style.css', 'text/css'), '/network-ui.js': ('network-ui.js', 'text/javascript'), '/access-ui.js': ('access-ui.js', 'text/javascript'), '/studio.js': ('studio.js', 'text/javascript'), '/catalog-ui.js': ('catalog-ui.js','text/javascript'), '/runtime-ui.js': ('runtime-ui.js','text/javascript'), '/profiles-ui.js': ('profiles-ui.js','text/javascript'), '/image-test-ui.js': ('image-test-ui.js','text/javascript')}
routes = {'/xvc-ui.js':('xvc-ui.js','text/javascript'),'/applio-ui.js':('applio-ui.js','text/javascript'),'/acestep-ui.js':('acestep-ui.js','text/javascript'),'/voice-ui.js':('voice-ui.js','text/javascript'),'/voxcpm-ui.js':('voxcpm-ui.js','text/javascript'),'/separator-ui.js':('separator-ui.js','text/javascript'),'/music-ui.js':('music-ui.js','text/javascript'),'/audio-cpp-ui.js':('audio-cpp-ui.js','text/javascript'),'/ltx-original-ui.js':('ltx-original-ui.js','text/javascript'),'/backup-ui.js':('backup-ui.js','text/javascript'),'/dashboard-ui.js':('dashboard-ui.js','text/javascript'),'/dashboard.css':('dashboard.css','text/css'),'/themes.css':('themes.css','text/css'),'/video-ui.js':('video-ui.js','text/javascript'),'/stt-ui.js':('stt-ui.js','text/javascript'),'/tts-ui.js':('tts-ui.js','text/javascript'),'/auto-test-ui.js':('auto-test-ui.js','text/javascript'),'/chat-test-ui.js':('chat-test-ui.js','text/javascript'),'/endpoint-ui.js':('endpoint-ui.js','text/javascript'),'/docker-ui.js': ('docker-ui.js','text/javascript'), '/': ('index.html', 'text/html; charset=utf-8'), '/app.js': ('app.js', 'text/javascript'), '/style.css': ('style.css', 'text/css'), '/network-ui.js': ('network-ui.js', 'text/javascript'), '/access-ui.js': ('access-ui.js', 'text/javascript'), '/studio.js': ('studio.js', 'text/javascript'), '/catalog-ui.js': ('catalog-ui.js','text/javascript'), '/runtime-ui.js': ('runtime-ui.js','text/javascript'), '/profiles-ui.js': ('profiles-ui.js','text/javascript'), '/image-test-ui.js': ('image-test-ui.js','text/javascript')}
if self.path in routes:
name, mime = routes[self.path]
return self.respond((ROOT/name).read_bytes(), mime=mime)
@@ -401,10 +412,14 @@ class Handler(BaseHTTPRequestHandler):
if urlsplit(self.path).path == '/api/v1/tts/audio':
try:return self.respond(self.server.tts_tests.audio(parse_qs(urlsplit(self.path).query).get('id',[''])[0]),mime='audio/wav')
except (OSError,ValueError):return self.respond({'error':'Audio nicht verfügbar.'},404)
if self.path == '/api/v1/music-remix':return self.respond(self.server.remix.status())
if self.path == '/api/v1/music':return self.respond(self.server.music.status())
if urlsplit(self.path).path == '/api/v1/music/audio':
try:return self.respond(self.server.music.audio(parse_qs(urlsplit(self.path).query).get('id',[''])[0]),mime='audio/wav')
except (OSError,ValueError):return self.respond({'error':'Musik nicht verfügbar.'},404)
if self.path == '/api/v1/xvc':return self.respond(self.server.xvc.status())
if self.path == '/api/v1/xvc-runtime':return self.respond(self.server.xvc_runtime.status())
if self.path == '/api/v1/xvc-runtime/log':return self.respond(self.server.xvc_runtime.log())
if self.path == '/api/v1/applio':return self.respond(self.server.applio.status())
if self.path == '/api/v1/applio-runtime':return self.respond(self.server.applio_runtime.status())
if self.path == '/api/v1/applio-runtime/log':return self.respond(self.server.applio_runtime.log())
@@ -614,6 +629,13 @@ class Handler(BaseHTTPRequestHandler):
if self.path == '/api/v1/separator-profiles/save':
try:return self.respond(self.server.separator_tests.configure(self.read_json()))
except (ValueError,OSError) as exc:return self.respond({'error':str(exc)},400)
if self.path in ('/api/v1/xvc-runtime/install','/api/v1/xvc-runtime/cancel','/api/v1/xvc/configure'):
try:
data=self.read_json()
if self.path.endswith('/configure'):return self.respond(self.server.xvc.configure(data))
if data:raise ValueError('Keine Installationsparameter erwartet.')
return self.respond(self.server.xvc_runtime.stop() if self.path.endswith('/cancel') else self.server.xvc_runtime.start())
except ValueError as exc:return self.respond({'error':str(exc)},400)
if self.path in ('/api/v1/applio-runtime/install','/api/v1/applio-runtime/cancel','/api/v1/applio/configure'):
try:
data=self.read_json()
@@ -695,6 +717,16 @@ class Handler(BaseHTTPRequestHandler):
return self.respond(self.server.stt.setup() if self.path.endswith('/setup') else self.server.stt.stop())
except ValueError as exc:return self.respond({'error':str(exc)},400)
except Exception:return self.respond({'error':'STT-Aktion fehlgeschlagen.'},503)
if self.path in ('/api/v1/music-remix/install','/api/v1/music-remix/cancel','/api/v1/music-remix/transcribe'):
try:
if self.path.endswith('/transcribe'):
fields,audio=read_upload(self,validate=False,allowed_fields=('melody_only',),max_audio=256*1024**2)
if fields.get('melody_only','true') not in ('true','false'):raise ValueError('Ungültiger Score-Modus.')
return self.respond(self.server.remix.transcribe(audio,fields.get('melody_only','true')=='true'))
if self.read_json():raise ValueError('Keine Installationsparameter erwartet.')
if self.path.endswith('/cancel'):self.server.remix.stop();return self.respond(self.server.remix_runtime.stop())
return self.respond(self.server.remix_runtime.start())
except ValueError as exc:return self.respond({'error':str(exc)},400)
if self.path in ('/api/v1/music/start','/api/v1/music/load','/api/v1/music/cancel'):
try:
data=self.read_json()
@@ -875,7 +907,7 @@ def main():
server.tts_runtime.stop();server.voxcpm_runtime.stop();server.omnivoice_runtime.stop()
server.image_runtime.stop()
server.ltx_original_runtime.stop()
server.separator_tests.stop();server.separator_runtime.stop();server.music.close();server.acestep_runtime.stop();server.audio_cpp_runtime.stop()
server.remix.stop();server.remix_runtime.stop();server.separator_tests.stop();server.separator_runtime.stop();server.music.close();server.acestep_runtime.stop();server.audio_cpp_runtime.stop()
server.prompt_enhancer.stop()
server.image_tests.stop()
server.runtime.stop()
+1
View File
@@ -42,6 +42,7 @@ const Studio=(()=>{
['Docker Engine','Weitere Dienste','docker-runtime','/api/v1/docker','Optionale Container-Umgebung. Erstinstallation über den Systemhelfer; vorhandenes Docker wird nicht automatisch aktualisiert.'],
['VoxCPM','Stimmwerkzeuge','voxcpm-runtime','/api/v1/voxcpm-runtime','Originale VoxCPM-Python-Laufzeit installieren. Vorhandene CUDA-Pakete wiederverwenden; Modellkomponenten separat. Sprachausgabe und Stimmklonen unter Stimmwerkzeuge testen.'],
['OmniVoice','Stimmwerkzeuge','omnivoice-runtime','/api/v1/omnivoice-runtime','Originale OmniVoice-Laufzeit für Voice Design und Klonen. Profile und Komponenten in Stimmwerkzeuge.'],
['X-VC','Stimmwerkzeuge','xvc-runtime','/api/v1/xvc-runtime','Audio-zu-Audio-Stimmumwandlung; native Laufzeit mit Resemble Enhance und bisheriger Oberfläche.'],
['Applio / RVC','Stimmwerkzeuge','applio-runtime','/api/v1/applio-runtime','Unsere eigene Oberfläche für Stimmen umwandeln, Live und Training. Native Applio-3.6.5-Laufzeit; GPU wird durch Deck gesteuert.'],
['Audio Separator','Audio-Trennung','separator-runtime','/api/v1/separator-runtime','Native CUDA-Laufzeit für BS-Roformer, MelBand und Demucs FT/6s. Vollständige Modellpakete mit überprüften Originalquellen und Prüfsummen.']
];
+4
View File
@@ -51,6 +51,10 @@ class AceTests(unittest.TestCase):
router.load('p');yue.close.assert_called_once();router.load('p');ace.close.assert_not_called()
ace.job={'state':'running'}
with self.assertRaises(ValueError):router.load('p')
def test_remix_fields_do_not_leak_into_ace_adapter(self):
p=self.profile();yue=Mock(job=None);ace=Mock(job=None);yue.profiles.status.return_value=dict(profiles=[p]);router=MusicRouter(yue,ace)
with self.assertRaisesRegex(ValueError,'YuE2'):router.start('p','test','pop',abc='X:1',cot='melody')
ace.start.assert_not_called()
def test_cross_repo_components_have_independent_pinned_revision(self):
with tempfile.TemporaryDirectory() as root:
catalog=Mock();profiles=Profiles(Path(root)/'profiles.json',catalog);model=self.profile()['model'];role='ace_base_0';info=ACE_COMPONENTS[role]
+49
View File
@@ -0,0 +1,49 @@
import io,json,tempfile,unittest,wave
from pathlib import Path
from unittest.mock import Mock,patch
from remix import Remix
from separator import SeparatorTests
from separator_runtime import CLEARVOICE,MODELS
from music import Music
from test_music import MusicTests
class MigrationTests(unittest.TestCase):
def test_update_package_contains_worker_dependencies(self):
from deploy.install import FILES
self.assertFalse({'cuda_overlay.py','remix.py','remix_runtime.py','remix_worker.py','remix_sources.json','clearvoice_worker.py','deploy/ladypoly/patch_remix.py'}-set(FILES))
def test_image_compaction_failure_cleans_only_temporary_container(self):
from deploy.install import compact_runtime_image
import subprocess
metadata={'Id':'sha256:1234567890abcdef','RootFS':{'Layers':['layer']*488},'Config':{'Env':['HOME=/tmp'],'Cmd':['python3','server.py'],'User':'65534:65534','WorkingDir':'/app'}}
responses=[Mock(stdout=json.dumps([metadata])),Mock(returncode=1),Mock(stdout='temporary-container\n'),Mock(returncode=0)]
with patch('deploy.install.tempfile.TemporaryFile',return_value=io.BytesIO()),patch('deploy.install.run',side_effect=responses) as run,patch('deploy.install.subprocess.run',side_effect=[None,subprocess.CalledProcessError(1,'docker import')]):
with self.assertRaises(subprocess.CalledProcessError):compact_runtime_image('production-image')
self.assertEqual(run.call_args.args,('docker','rm','temporary-container'))
self.assertFalse(any('stop' in call.args or 'export' in call.args for call in run.call_args_list))
def test_remix_score_forwarded_and_native_session_reused(self):
with tempfile.TemporaryDirectory() as root:
m,release,p=MusicTests().make(root)
with patch('music.probe',return_value=[dict(name='RTX 5080',uuid='GPU-test',free_mib=16000,processes=0)]):
with patch.object(m,'_request',wraps=m._request) as request:
job=m.start('p','Remix','pop',max_tokens=32,steps=1,abc='X:1\nK:C\nC D E F|',cot='melody');MusicTests().wait(m)
payload=next(c.args[1] for c in request.call_args_list if c.args[0]=='/v1/tasks/run')
self.assertEqual(payload['request']['options']['cot'],'melody');self.assertIn('K:C',payload['request']['options']['abc'])
self.assertEqual(m.status()['job']['state'],'complete');release.assert_called_once();m.close()
def test_off_mode_score_and_invalid_score_rejected(self):
with tempfile.TemporaryDirectory() as root:
m,_,_=MusicTests().make(root)
for abc,cot in [('X:1','off'),('', 'melody'),('x'*20001,'melody'),('X:1','unknown')]:
with self.assertRaises(ValueError):m.start('p','test','pop',abc=abc,cot=cot)
def test_remix_busy_does_not_evict_music(self):
r=Remix('/tmp/unused',Mock(),Mock(),Mock());r.runtime.status.return_value={'installed':True};r.scheduler.gpu_mode='music';r.scheduler.image_reservation.side_effect=ValueError('busy')
with self.assertRaisesRegex(ValueError,'busy'):r.transcribe(bytes(44))
r.music.close.assert_not_called();self.assertFalse(r.active);self.assertTrue(r.lock.acquire(False));r.lock.release()
def test_clearvoice_target_maps_to_supported_package(self):
self.assertIn(CLEARVOICE,MODELS)
with tempfile.TemporaryDirectory() as root:
runtime=Mock();runtime.status.return_value={'installed':True};runtime.model_ready.return_value=True;worker=SeparatorTests(root,runtime,Mock());worker.scheduler.gpu_mode='separator'
data=io.BytesIO()
with wave.open(data,'wb') as w:w.setparams((1,2,16000,0,'NONE','none'));w.writeframes(bytes(320))
with patch('separator.threading.Thread'):
worker.start(CLEARVOICE,data.getvalue(),target='speech',full=True)
worker.job=None
with self.assertRaises(ValueError):worker.start(CLEARVOICE,data.getvalue(),target='vocals',full=True)
+16
View File
@@ -42,6 +42,22 @@ class RestoreTests(unittest.TestCase):
self.server.acestep_runtime.start=Mock();self.server.backup._wait=Mock()
self.server.backup.job=dict(state='running',items=[],completed=0,phase='ACE-Step-Test')
self.server.backup._runtimes(doc);self.server.acestep_runtime.start.assert_called_once();self.server.backup.job['state']='complete'
def test_remix_runtime_recipe_and_restore(self):
from remix_runtime import VERSION
self.server.remix_runtime.status=Mock(return_value=dict(installed=True,version=VERSION,job=None))
doc=self.server.backup.snapshot(include_history=False);validate(doc)
self.assertTrue(doc['runtimes']['music_remix']);self.assertEqual(doc['runtime_versions']['music_remix'],VERSION)
self.server.remix_runtime.status=Mock(return_value=dict(installed=False,version=VERSION,job=None))
self.server.remix_runtime.start=Mock();self.server.backup._wait=Mock();self.server.backup.job=dict(state='running',items=[],completed=0,phase='Remix-Test')
self.server.backup._runtimes(doc);self.server.remix_runtime.start.assert_called_once();self.server.backup.job['state']='complete'
def test_xvc_runtime_recipe_reinstalls_verified_components(self):
from xvc_runtime import REVISION,RECIPE_HASH
self.server.xvc_runtime.status=Mock(return_value=dict(installed=True,revision=REVISION,job=None))
doc=self.server.backup.snapshot(include_history=False);validate(doc)
self.assertEqual(doc['runtime_versions']['xvc'],dict(code=REVISION,assets=RECIPE_HASH))
self.assertTrue(doc['runtimes']['xvc'])
self.server.xvc_runtime.status=Mock(return_value=dict(installed=False,revision=REVISION,job=None));self.server.xvc_runtime.start=Mock();self.server.backup._wait=Mock()
self.server.backup.job=dict(state='running',items=[],completed=0,phase='Test');self.server.backup._runtimes(doc);self.server.xvc_runtime.start.assert_called_once();self.server.backup.job['state']='complete'
def test_private_rvc_metadata_survives_backup_and_has_no_fake_download(self):
ident=self.model();path=self.root/'models'/ident/'entry.json';entry=json.loads(path.read_text());entry.update(repo='local/mikes-applio',revision=entry['sha256'],kind='voice',file='voice.pth',runtime_metadata={'architecture':'rvc','tags':['private-trained-voice']});path.write_text(json.dumps(entry));(path.parent/'model.gguf').rename(path.parent/'model.pth')
doc=self.server.backup.snapshot(include_history=False);model=doc['models'][0]
+43
View File
@@ -0,0 +1,43 @@
import copy,hashlib,json,tempfile,time,unittest
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import patch
from test_applio import Tests as LeaseTests
from xvc import XVC,xvc_model
from xvc_runtime import ASSETS,REVISION,MODEL_REVISION,REPO,RECIPE_HASH
from execution_setup import assess
class Tests(LeaseTests):
def setUp(self):
super().setUp();self.a.stop()
self.profile.update(name='X-VC',model=dict(repo=REPO,file='xvc.pt',kind='voice',runtime_metadata={'architecture':'xvc'}))
self.a=XVC(Path(self.tmp.name),self.runtime,self.scheduler,self.profiles,lambda:self.active)
self.a.settings={'device':'3060'}
def test_real_profile_is_runnable_only_after_runtime_ready(self):
from catalog import Catalog
from profiles import Profiles
root=Path(self.tmp.name);catalog=Catalog(root/'models');ident=hashlib.sha256((REPO+MODEL_REVISION+'xvc.pt').encode()).hexdigest();folder=catalog.root/ident;folder.mkdir(parents=True)
(folder/'model.pt').write_bytes(b'test');(folder/'entry.json').write_text(json.dumps(dict(repo=REPO,revision=MODEL_REVISION,file='xvc.pt',kind='voice',size=4,sha256='b'*64,runtime_metadata={'architecture':'xvc'})))
profiles=Profiles(root/'profiles.json',catalog);profiles.save(dict(id=None,revision=0,name='X-VC Studio',api_id='xvc-studio',kind='voice',model_id=ident,parameters={}))
profiles.xvc_blockers=lambda p:['Laufzeit fehlt'];self.assertFalse(profiles.status()['profiles'][0]['runnable'])
profiles.xvc_blockers=lambda p:[];self.assertTrue(profiles.status()['profiles'][0]['runnable'])
def test_rvc_recognition_does_not_guess_every_pth(self):
self.assertTrue(xvc_model(self.profile['model']));self.assertFalse(xvc_model(dict(kind='voice',file='xvc.pt')))
result=assess(self.profile['model'],{'xvc':True});self.assertEqual(result['setup_steps'][1]['state'],'complete');self.assertEqual(result['components'],[])
def test_assets_have_fixed_verified_sources(self):
self.assertEqual(len(ASSETS),10)
for item in ASSETS:
self.assertEqual(len(item['revision']),40);self.assertGreater(item['size'],0);self.assertTrue(item['sha256'] or item['git_sha1'])
self.assertNotIn('..',Path(item['target']).parts)
self.assertEqual(len(RECIPE_HASH),64)
def test_apply_profile_refuses_running_deck(self):
from deploy.prepare_xvc import apply_profile
with patch('deploy.prepare_xvc.subprocess.run',return_value=SimpleNamespace(stdout=json.dumps([{'State':{'Running':True}}]))):
with self.assertRaisesRegex(ValueError,'Deck läuft'):apply_profile(self.tmp.name)
def test_container_backup_preserves_stopped_ui_and_rejects_unsafe_mount(self):
from deploy.docker_backup import validate
c=dict(name='athena-xvc-web',image='athena-xvc-web:0.1.0-deck1',registry=None,application='xvc-web',labels={'io.athena-deck.managed':'true','io.athena-deck.role':'application','io.athena-deck.application':'xvc-web'},env=[],entrypoint=None,cmd=None,user='65534:65534',uid=65534,workdir='/ui',network='host',ports={},restart='unless-stopped',memory=512*1024**2,nanocpus=10**9,running=False,build_recipe='xvc-web',unsupported=False,mounts=[dict(index=0,target='/run/secrets/xvc-bridge',read_only=True,deck_path='xvc-data/bridge-key',was_file=True,files={})])
self.assertFalse(validate(c)['running']);bad=copy.deepcopy(c);bad['mounts'][0]['read_only']=False
with self.assertRaises(ValueError):validate(bad)
if __name__=='__main__':unittest.main()
+1 -1
View File
@@ -1,6 +1,6 @@
window.VoiceUI=(()=>{
const e=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
function html(){return `<section id="voice-panel" class="card"><h2>Stimme ausprobieren · VoxCPM2 / OmniVoice</h2><p>Text erzeugt Sprache. Mit optionaler WAV-Referenz übernimmt das Modell deren Stimme. OmniVoice benötigt dazu den gesprochenen Text; ein leeres Transkriptfeld wird mit der vorhandenen Spracherkennung automatisch ergänzt.</p><p>Für RVC-Stimmumwandlung und eigenes Training: <a class="link" href="${e(DeckLinks.url(8132,'/'))}" target="_blank" rel="noopener">Applio Studio öffnen →</a></p><p id="voice-status" role="status"></p><progress id="voice-progress" hidden aria-label="Stimmgenerierung"></progress><p id="voice-error" role="alert"></p><form id="voice-form"><label>Profil<select name="profile_id" id="voice-profile" required></select></label><label>Text<textarea name="text" rows="5" maxlength="1000" required></textarea></label><label>Referenzstimme (optional, WAV, ab 1 Sekunde, bis 512 MiB; automatische PCM-16-Konvertierung)<input name="file" type="file" accept="audio/wav,.wav"></label><label>Transkript der Referenz (optional; leer = automatisch erkennen)<textarea name="reference_text" maxlength="64000"></textarea></label><label><input name="preprocess_prompt" type="checkbox" checked>OmniVoice: Referenz automatisch aufbereiten</label><p class="small">Ohne Transkript wählt OmniVoice aus langen Aufnahmen automatisch einen kurzen Ausschnitt. Mit eigenem Transkript bleibt die gesamte Aufnahme erhalten.</p><label>Stil / Stimme (OmniVoice)<input name="instruct" maxlength="1000"></label><div class="form-grid"><label>GPU<select name="device"><option value="3060">RTX 3060</option><option value="5080">RTX 5080</option></select></label><label>Guidance<input name="cfg" type="number" min="0.5" max="5" step="0.1" value="2"></label><label>Schritte<input name="steps" type="number" min="1" max="50" value="10"></label><label>Seed<input name="seed" type="number" min="0" max="2147483647" value="42"></label></div><button id="voice-start">Stimme erzeugen</button><button id="voice-cancel" type="button" class="secondary" disabled>Abbrechen</button></form><div id="voice-result"></div><p class="small">Im LLM- oder Stimmwerkzeuge-Modus verfügbar. Deck entlädt sein LLM vor der Stimmgenerierung und lädt es bei der nächsten Chat-Anfrage wieder. Das Stimmmodell bleibt für weitere Texte geladen und wird beim Profil-, GPU- oder Betriebsartwechsel entladen. Referenzdatei wird nach dem Auftrag gelöscht; Text wird nicht gespeichert.</p></section>`;}
function html(){return `<section id="voice-panel" class="card"><h2>Stimme ausprobieren · VoxCPM2 / OmniVoice</h2><p>Text erzeugt Sprache. Mit optionaler WAV-Referenz übernimmt das Modell deren Stimme. OmniVoice benötigt dazu den gesprochenen Text; ein leeres Transkriptfeld wird mit der vorhandenen Spracherkennung automatisch ergänzt.</p><p>Für RVC-Stimmumwandlung und eigenes Training: <a class="link" href="${e(DeckLinks.url(8132,'/'))}" target="_blank" rel="noopener">Applio Studio öffnen →</a> · <a class="link" href="${e(DeckLinks.url(8133,'/'))}" target="_blank" rel="noopener">X-VC Studio öffnen →</a></p><p id="voice-status" role="status"></p><progress id="voice-progress" hidden aria-label="Stimmgenerierung"></progress><p id="voice-error" role="alert"></p><form id="voice-form"><label>Profil<select name="profile_id" id="voice-profile" required></select></label><label>Text<textarea name="text" rows="5" maxlength="1000" required></textarea></label><label>Referenzstimme (optional, WAV, ab 1 Sekunde, bis 512 MiB; automatische PCM-16-Konvertierung)<input name="file" type="file" accept="audio/wav,.wav"></label><label>Transkript der Referenz (optional; leer = automatisch erkennen)<textarea name="reference_text" maxlength="64000"></textarea></label><label><input name="preprocess_prompt" type="checkbox" checked>OmniVoice: Referenz automatisch aufbereiten</label><p class="small">Ohne Transkript wählt OmniVoice aus langen Aufnahmen automatisch einen kurzen Ausschnitt. Mit eigenem Transkript bleibt die gesamte Aufnahme erhalten.</p><label>Stil / Stimme (OmniVoice)<input name="instruct" maxlength="1000"></label><div class="form-grid"><label>GPU<select name="device"><option value="3060">RTX 3060</option><option value="5080">RTX 5080</option></select></label><label>Guidance<input name="cfg" type="number" min="0.5" max="5" step="0.1" value="2"></label><label>Schritte<input name="steps" type="number" min="1" max="50" value="10"></label><label>Seed<input name="seed" type="number" min="0" max="2147483647" value="42"></label></div><button id="voice-start">Stimme erzeugen</button><button id="voice-cancel" type="button" class="secondary" disabled>Abbrechen</button></form><div id="voice-result"></div><p class="small">Im LLM- oder Stimmwerkzeuge-Modus verfügbar. Deck entlädt sein LLM vor der Stimmgenerierung und lädt es bei der nächsten Chat-Anfrage wieder. Das Stimmmodell bleibt für weitere Texte geladen und wird beim Profil-, GPU- oder Betriebsartwechsel entladen. Referenzdatei wird nach dem Auftrag gelöscht; Text wird nicht gespeichert.</p></section>`;}
function bind(){const root=document.querySelector('#voice-panel');if(!root)return;const el=id=>root.querySelector('#'+id);let busy=false,lastResult='',ready=false;
async function api(path='',body){const r=await fetch('/api/v1/voice'+path,body===undefined?{}:{method:'POST',headers:body instanceof FormData?{'X-Athena-Deck':'1'}:{'X-Athena-Deck':'1','Content-Type':'application/json'},body:body instanceof FormData?body:JSON.stringify(body)});const d=await r.json();if(!r.ok)throw Error(d.error||'Stimmgenerierung fehlgeschlagen');return d;}
async function refresh(){try{const d=await api();if(!root.isConnected)return;const j=d.job;el('voice-status').textContent=(j?.phase||'Profil wählen und Text eingeben.')+(j?.gpu?' · '+j.gpu:'');el('voice-progress').hidden=j?.state!=='running';el('voice-start').disabled=busy||!ready||!['llm','voice'].includes(d.mode)||j?.state==='running';el('voice-cancel').disabled=j?.state!=='running';if(j?.state==='complete'&&j.id!==lastResult){lastResult=j.id;el('voice-result').innerHTML=`<h3>Ergebnis · ${Number(j.duration).toFixed(1)} Sekunden</h3><audio controls src="/api/v1/voice/audio?id=${e(j.id)}"></audio><p><a class="link" download="athena-stimme.wav" href="/api/v1/voice/audio?id=${e(j.id)}">WAV herunterladen</a></p>`;}}catch(err){if(root.isConnected)el('voice-error').textContent=err.message;}finally{if(root.isConnected)setTimeout(refresh,2000);}}
+10
View File
@@ -0,0 +1,10 @@
window.XVCUI=(()=>{
function render(){const view=document.querySelector('#view');if(view.querySelector('#xvc-page'))return;
view.innerHTML='<div id="xvc-page"><h1>X-VC</h1><p>Vorhandene Sprachaufnahmen anhand einer Referenzstimme umwandeln. Unsere bisherige Oberfläche bleibt erhalten; die native Laufzeit und GPU steuert Athena Deck.</p><section class="card"><h2>X-VC einrichten</h2><p id="ap-status"></p><button id="ap-install">Laufzeit und Basisgewichte installieren</button><button id="ap-cancel" class="secondary">Installation abbrechen</button><details><summary>Installationsausgabe</summary><pre id="ap-log" style="white-space:pre-wrap;max-height:300px;overflow:auto"></pre></details></section><section class="card"><h2>Ausführung</h2><label>GPU für X-VC<select id="ap-device"><option value="3060">RTX 3060</option><option value="5080">RTX 5080</option></select></label><button id="ap-save">GPU speichern</button><p id="ap-state"></p><a id="ap-link" class="link" target="_blank" rel="noopener">Unsere X-VC-Oberfläche öffnen →</a><p>Vor einem Auftrag X-VC in Stimmwerkzeuge → Profile aktivieren und Steuerung → Stimmwerkzeuge starten. Immer nur ein Stimmwerkzeug-Profil aktiv.</p><p>Gewichte und Zusatzkomponenten werden aus ihren fest hinterlegten Originalquellen wiederhergestellt. Eigene Referenzaufnahmen und Ergebnisse separat sichern.</p></section><p id="ap-error" role="alert"></p></div>';
const root=view.firstChild,el=id=>root.querySelector('#'+id);el('ap-link').href=DeckLinks.url(8133,'/');let dirty=false;el('ap-device').onchange=()=>dirty=true;
async function api(path,data){const r=await fetch('/api/v1/'+path,data?{method:'POST',headers:{'Content-Type':'application/json','X-Athena-Deck':'1'},body:JSON.stringify(data)}:{});const d=await r.json();if(!r.ok)throw Error(d.error||'Aktion fehlgeschlagen.');return d;}
async function poll(){if(!root.isConnected)return;try{const s=await api('xvc-runtime'),a=await api('xvc');if(!root.isConnected)return;el('ap-status').textContent=s.job?.phase||(s.installed?'X-VC installiert.':'Laufzeit fehlt.');el('ap-install').disabled=s.installed||s.job?.state==='running';el('ap-cancel').disabled=s.job?.state!=='running';el('ap-state').textContent=a.active?'X-VC-Auftrag läuft.':a.selected_profile?'Aktives Profil: '+a.selected_profile:'Noch kein X-VC-Profil aktiv.';if(!dirty)el('ap-device').value=a.device;if(s.job)el('ap-log').textContent=(await api('xvc-runtime/log')).text;}catch(e){el('ap-error').textContent=e.message;}if(root.isConnected)setTimeout(poll,3000);}
for(const [id,path] of [['ap-install','xvc-runtime/install'],['ap-cancel','xvc-runtime/cancel']])el(id).onclick=async()=>{try{await api(path,{});}catch(e){el('ap-error').textContent=e.message;}};
el('ap-save').onclick=async()=>{try{await api('xvc/configure',{device:el('ap-device').value});dirty=false;}catch(e){el('ap-error').textContent=e.message;}};poll();
}return {render};
})();
+45
View File
@@ -0,0 +1,45 @@
"""Native X-VC UI backend, sharing Deck's voice-mode admission protocol."""
import json,os,signal,subprocess
from pathlib import Path
from applio import Applio
def xvc_model(model):return bool(model and model.get('kind')=='voice' and model.get('repo')=='chenxie95/X-VC' and model.get('file')=='xvc.pt' and (model.get('runtime_metadata') or {}).get('architecture')=='xvc')
class XVC(Applio):
label="X-VC"
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
if not self.settings_path.exists():self.settings={'device':'5080'}
def selected(self):return next((p for p in self.profiles.status()['profiles'] if xvc_model(p.get('model')) and p['id'] in self.enabled() and p['runnable']),None)
def blockers(self,p):return [] if self.runtime.status()['installed'] else ['X-VC-Laufzeit unter Laufzeiten installieren.']
def status(self):
installed=self.runtime.status()['installed']
if installed:self.ensure()
selected=self.selected()
return dict(installed=installed,device=self.settings['device'],active=self.active,backend_running=bool(self.process and self.process.poll() is None),selected_profile=selected['name'] if selected else None)
def unload_idle(self):
if self.active:raise ValueError('X-VC-Auftrag läuft; Wechsel erst danach möglich.')
if self.process and self.process.poll() is None:
try:os.killpg(self.process.pid,signal.SIGTERM);self.process.wait(10)
except subprocess.TimeoutExpired:os.killpg(self.process.pid,signal.SIGKILL);self.process.wait()
except ProcessLookupError:pass
self.process=None
self.ensure() # fresh CPU-only UI process; no weights load before the next lease
def configure(self,data):
if set(data)!={'device'} or data['device'] not in ('3060','5080'):raise ValueError('RTX 3060 oder RTX 5080 auswählen.')
with self.lock:
if self.active:raise ValueError('X-VC-Auftrag läuft; GPU erst danach ändern.')
self.settings=dict(data);temp=self.settings_path.with_suffix('.tmp');temp.write_text(json.dumps(data));temp.replace(self.settings_path)
self.unload_idle()
return self.status()
def ensure(self):
with self.lock:
if self.process and self.process.poll() is None:return
python,source=self.runtime.paths()
if not python.is_file():return
from image_test import probe
gpu=next((g for g in probe() if self.settings['device'] in g['name']),None)
if not gpu:return
for name in ('results','uploads','tmp'):(self.root/name).mkdir(exist_ok=True)
env={k:v for k,v in os.environ.items() if not k.startswith(('HF_','DECK_'))}
env.update(XVC_SOURCE=str(source),XVC_ASSETS=str(source.parent/'assets'),XVC_OUTPUT=str(self.root/'results'),XVC_LEASE_SOCKET=str(self.socket),XVC_BRIDGE_KEY_FILE=str(self.root/'bridge-key'),CUDA_VISIBLE_DEVICES=gpu['uuid'],HF_HUB_OFFLINE='1',HF_HUB_DISABLE_TELEMETRY='1',GRADIO_ANALYTICS_ENABLED='False',GRADIO_TEMP_DIR=str(self.root/'uploads'),TMPDIR=str(self.root/'tmp'),OMP_NUM_THREADS='4',PYTHONPATH=str(source))
script=Path(__file__).parent/'deploy/xvc-web/native_ui.py';log=(self.root/'backend.log').open('a')
self.process=subprocess.Popen([str(python),'/app/applio_worker.py','--exec',str(python),str(script)],cwd=source,env=env,stdout=log,stderr=log,start_new_session=True);log.close()
+69
View File
@@ -0,0 +1,69 @@
"""X-VC inference environment and immutable, verified model sources; setup is CPU-only."""
import hashlib,json,os,shutil,sys,time,urllib.request
from pathlib import Path
from ltx_original_runtime import LTXOriginalRuntime
REVISION='49df8c591eafc48b096e466d96f9839f9c0dd739'
MODEL_REVISION='9e54747d8c4d1ef544b903e2300a4ba040dcc126'
REPO='chenxie95/X-VC'
ASSETS=json.loads(Path(__file__).with_name('xvc_sources.json').read_text())
RECIPE_HASH=hashlib.sha256(json.dumps(ASSETS,sort_keys=True).encode()).hexdigest()
class XVCRuntime(LTXOriginalRuntime):
name='X-VC'
def paths(self):
try:
ident=json.loads((self.root/'active.json').read_text())['id'];base=self.root/ident
if len(ident)==32 and all(c in '0123456789abcdef' for c in ident) and (base/'ready').read_text().strip()==REVISION:return base/'python/bin/python',base/'source'
except (OSError,ValueError,KeyError):pass
return self.root/'missing-python',self.root/'missing-source'
def status(self):
python,source=self.paths()
return dict(installed=python.is_file() and (source/'models/codec/sac/model.py').is_file(),revision=REVISION,model_revision=MODEL_REVISION,recipe_hash=RECIPE_HASH,job=dict(self.job) if self.job else None,required_disk_gib=25,origin=REPO,worker_available=True,message='Audio-zu-Audio-Stimmumwandlung mit optionalem Resemble Enhance. Installation lädt alle Komponenten; sie startet kein Modell.')
def ensure_library(self):
_,source=self.paths();base=source.parent;main=next(x for x in ASSETS if x['file']=='xvc.pt');ident=hashlib.sha256((REPO+MODEL_REVISION+'xvc.pt').encode()).hexdigest();folder=self.root.parent/'models'/ident;folder.mkdir(parents=True,exist_ok=True)
target=folder/'model.pt'
asset=base/'assets'/main['target'];relative=os.path.relpath(asset,folder)
if target.is_symlink():
old=os.readlink(target)
if old not in (relative,str(asset),'/var/lib/deck/xvc-runtime/'+base.name+'/assets/'+main['target']):raise ValueError('X-VC-Bibliothekslink zeigt auf eine fremde Datei.')
if old!=relative:target.unlink();target.symlink_to(relative)
elif not target.exists():target.symlink_to(relative)
entry=dict(repo=REPO,revision=MODEL_REVISION,file='xvc.pt',kind='voice',size=main['size'],sha256=main['sha256'],upstream_hash_verified=True,downloaded_at=time.time(),runtime_metadata={'architecture':'xvc'})
(folder/'entry.json').write_text(json.dumps(entry));return ident
def _run(self):
base=self.root/self.job['id'];state='failed';phase='X-VC-Einrichtung fehlgeschlagen.'
try:
base.mkdir(mode=0o700);tmp=base/'tmp';tmp.mkdir();source=base/'source'
env=dict(os.environ,CUDA_VISIBLE_DEVICES='',TMPDIR=str(tmp),PIP_NO_INPUT='1',PIP_DISABLE_PIP_VERSION_CHECK='1',GIT_TERMINAL_PROMPT='0')
self._phase('Offiziellen X-VC-Quellcode beziehen')
for args in (['git','init',source],['git','-C',source,'fetch','--depth','1','https://github.com/Jerrister/X-VC.git',REVISION],['git','-C',source,'checkout','--detach','FETCH_HEAD']):self._command(args,env)
shared=self.image_runtime.paths()[0] if self.image_runtime else Path('/missing')
self._command([shared if shared.is_file() else sys.executable,'-m','venv',base/'python'],env);python=base/'python/bin/python'
self._phase('Isolierte X-VC-Abhängigkeiten installieren; keine GPU-Ausführung')
self._command([python,'-m','pip','install','--no-cache-dir','torch==2.8.0','torchaudio==2.8.0','--index-url','https://download.pytorch.org/whl/cu128'],env)
lock=Path(__file__).parent/'deploy/xvc-requirements.lock'
requirements=['gradio==5.49.1','huggingface_hub>=0.34,<1','transformers>=4.44,<5','hydra-core>=1.3,<2','omegaconf>=2.3,<3','x-transformers>=1.40,<3','einops>=0.8,<1','einx>=0.3,<1','numpy==1.26.4','scipy==1.11.4','soundfile==0.12.1','soxr>=0.5,<1','tqdm>=4.66,<5','librosa==0.10.1','descript-audiotools==0.7.2','matplotlib>=3.8,<4','pandas>=2.1,<3','rich>=13,<15','tabulate>=0.9,<1','uvicorn','httpx','websockets']
self._command([python,'-m','pip','install','--no-cache-dir',*(['-c',lock] if lock.exists() else []),*requirements],env)
self._command([python,'-m','pip','install','--no-cache-dir','--no-deps','resemble-enhance==0.0.1'],env)
ui=Path(__file__).parent/'deploy/xvc-web'
self._command([python,ui/'patch_resemble_enhance.py'],env);shutil.copyfile(ui/'inference_log.py',source/'utils/log.py')
self._phase('X-VC und alle Zusatzgewichte mit Prüfsummen herunterladen')
for item in ASSETS:
if self.cancel.is_set():raise InterruptedError()
dest=base/'assets'/item['target'];dest.parent.mkdir(parents=True,exist_ok=True)
prefix='https://huggingface.co/'+('spaces/' if item['repo_type']=='space' else '')+item['repo']+'/resolve/'+item['revision']+'/'
sha=hashlib.sha256();git=hashlib.sha1(('blob '+str(item['size'])+'\0').encode())
with urllib.request.urlopen(prefix+item['file'],timeout=90) as response,dest.open('wb') as output:
while chunk:=response.read(4*1024**2):
if self.cancel.is_set():raise InterruptedError()
output.write(chunk);sha.update(chunk);git.update(chunk)
if dest.stat().st_size!=item['size'] or (sha.hexdigest()!=item['sha256'] if item['sha256'] else git.hexdigest()!=item['git_sha1']):raise ValueError('X-VC-Komponenten-Prüfsumme falsch: '+item['file'])
(base/'asset-sources.json').write_text(json.dumps(ASSETS,indent=2))
# Inference intentionally omits Resemble's obsolete training dependencies.
self._command([python,'-c','import torch,transformers,gradio,hydra,soundfile,librosa,audiotools; import resemble_enhance.enhancer.inference; assert not torch.cuda.is_available()'],env)
self._command([python,'-m','pip','freeze'],env)
(base/'ready').write_text(REVISION);marker=self.root/'active.tmp';marker.write_text(json.dumps({'id':base.name}));marker.replace(self.root/'active.json');self.ensure_library();state='complete';phase='X-VC vorbereitet · nicht gestartet, kein Profil aktiviert'
except InterruptedError:state='cancelled';phase='X-VC-Einrichtung abgebrochen.'
except Exception as exc:phase=str(exc)
finally:
if state!='complete':shutil.rmtree(base,ignore_errors=True)
with self.lock:self.process=None;self.job.update(state=state,phase=phase,finished_at=time.time());self._save()
+102
View File
@@ -0,0 +1,102 @@
[
{
"repo": "chenxie95/X-VC",
"repo_type": "model",
"revision": "9e54747d8c4d1ef544b903e2300a4ba040dcc126",
"file": "xvc.pt",
"target": "model/xvc.pt",
"size": 5007756915,
"sha256": "1ba0ca3187d2a6753a1529db18c5490e5cb20c8874dc067b92935ff39cfed687",
"git_sha1": "11e2845425a87bddcaee3f7236a2a83927580058"
},
{
"repo": "chenxie95/X-VC",
"repo_type": "model",
"revision": "9e54747d8c4d1ef544b903e2300a4ba040dcc126",
"file": "config.json",
"target": "model/config.json",
"size": 404,
"sha256": null,
"git_sha1": "4e3cdf7eafb64aa8cabea3020d15d56bde0030ee"
},
{
"repo": "hugging-apps/x-vc-voice-conversion",
"repo_type": "space",
"revision": "d761cd6421e85376b2656dfefd8471d7f35a42be",
"file": "pretrained/speech_eres2net_sv_en_voxceleb_16k/configuration.json",
"target": "space/pretrained/speech_eres2net_sv_en_voxceleb_16k/configuration.json",
"size": 405,
"sha256": null,
"git_sha1": "14480b73420bf5c54cafaf245ada218b797e21c5"
},
{
"repo": "hugging-apps/x-vc-voice-conversion",
"repo_type": "space",
"revision": "d761cd6421e85376b2656dfefd8471d7f35a42be",
"file": "pretrained/speech_eres2net_sv_en_voxceleb_16k/pretrained_eres2net.ckpt",
"target": "space/pretrained/speech_eres2net_sv_en_voxceleb_16k/pretrained_eres2net.ckpt",
"size": 26725867,
"sha256": "d8941f5952e31820173c8854562cb6d7897aaa58cd65c18f30d5a2e52d30847d",
"git_sha1": "2f57ca80c420ac89122747968262a60d862f2911"
},
{
"repo": "zai-org/glm-4-voice-tokenizer",
"repo_type": "model",
"revision": "a5f2404e63c84e92f5238908e1706316324ebafa",
"file": "config.json",
"target": "tokenizer/config.json",
"size": 1746,
"sha256": null,
"git_sha1": "d5765b0940b8fe62ba00b7ed5ee5892a56a78f70"
},
{
"repo": "zai-org/glm-4-voice-tokenizer",
"repo_type": "model",
"revision": "a5f2404e63c84e92f5238908e1706316324ebafa",
"file": "model.safetensors",
"target": "tokenizer/model.safetensors",
"size": 1458374480,
"sha256": "2800bd503f52b51e45f0c53cfd5c31dcfe8ef7f13d22b396aa3d53e0280dd1e4",
"git_sha1": "defda19da829f14713b1b4c1fa537745c6bdecfd"
},
{
"repo": "zai-org/glm-4-voice-tokenizer",
"repo_type": "model",
"revision": "a5f2404e63c84e92f5238908e1706316324ebafa",
"file": "preprocessor_config.json",
"target": "tokenizer/preprocessor_config.json",
"size": 340,
"sha256": null,
"git_sha1": "931c77a740890c46365c7ae0c9d350ba3cca908f"
},
{
"repo": "ResembleAI/resemble-enhance",
"repo_type": "model",
"revision": "4e3510ce4a8391159f665903544c5150bee7b2cb",
"file": "enhancer_stage2/ds/G/default/mp_rank_00_model_states.pt",
"target": "enhance/enhancer_stage2/ds/G/default/mp_rank_00_model_states.pt",
"size": 713176232,
"sha256": "f9d035f318de3e6d919bc70cf7ad7d32b4fe92ec5cbe0b30029a27f5db07d9d6",
"git_sha1": "a73468ffd3b1959b6734c4a2501485398230051d"
},
{
"repo": "ResembleAI/resemble-enhance",
"repo_type": "model",
"revision": "4e3510ce4a8391159f665903544c5150bee7b2cb",
"file": "enhancer_stage2/ds/G/latest",
"target": "enhance/enhancer_stage2/ds/G/latest",
"size": 7,
"sha256": null,
"git_sha1": "331d858ce9b12fa6720414196a9dd6e0b6a0faaa"
},
{
"repo": "ResembleAI/resemble-enhance",
"repo_type": "model",
"revision": "4e3510ce4a8391159f665903544c5150bee7b2cb",
"file": "enhancer_stage2/hparams.yaml",
"target": "enhance/enhancer_stage2/hparams.yaml",
"size": 717,
"sha256": null,
"git_sha1": "0946d9553860e839892e9fe1a3433b364952a93c"
}
]