Add voice control mode, OmniVoice worker and managed voice studios
This commit is contained in:
1 parent
260740994f
commit
5fa8e6de90
33 files changed
+411
-64
No files matched your search
@@ -28,7 +28,8 @@ if(['separator-runtime','separator-test','separation'].includes(page)){Separator
|
||||
if(page==='audio-cpp-runtime'){AudioCppUI.render();return;}
|
||||
if(page==='ltx-original-runtime'){LTXOriginalUI.render();return;}
|
||||
if(['video','video-runtime'].includes(page)){VideoUI.runtime();return;}
|
||||
if(['embeddings','chat','image','audio','stt','music','voice','video','runtime','runtimes','image-runtime','stt-runtime','tts-runtime','voxcpm-runtime','docker-runtime','services'].includes(page)){Studio.render(page);return;}
|
||||
if(page==='voice-test'){Studio.openTest('voice');return;}
|
||||
if(['embeddings','chat','image','audio','stt','music','voice','video','runtime','runtimes','image-runtime','stt-runtime','tts-runtime','voxcpm-runtime','omnivoice-runtime','docker-runtime','services'].includes(page)){Studio.render(page);return;}
|
||||
if(page==='backup'){BackupUI.render();return;}
|
||||
if(page==='access'){await accessPage();return;}
|
||||
if(page==='appearance'){appearancePage();return;}
|
||||
|
||||
@@ -57,7 +57,7 @@ def validate(doc):
|
||||
if kind=='chat' and (params['ubatch']>params['batch'] or params.get('vision_projector') and params['vision_projector'] not in ids):raise ValueError('Ungültige Chat-Zuordnung.')
|
||||
if kind in ('image','video') and (params['width']%64 or params['height']%64):raise ValueError('Ungültige Bildgröße.')
|
||||
components=p.get('components',{})
|
||||
if not isinstance(components,dict) or any((k not in ('text_encoder','vae','video_vae','audio_vae','spatial_upsampler','model_config','generation_config','tokenizer','vae_config','manual_text_encoder','manual_vae','manual_tokenizer','manual_configuration','manual_projector','manual_auxiliary') and not re.fullmatch(r'runtime_file_[0-9]{1,2}',k)) or v not in ids for k,v in components.items()):raise ValueError('Ungültige Komponentenreferenz.')
|
||||
if not isinstance(components,dict) or any((k not in ('text_encoder','vae','video_vae','audio_vae','spatial_upsampler','model_config','generation_config','tokenizer','vae_config','manual_text_encoder','manual_vae','manual_tokenizer','manual_configuration','manual_projector','manual_auxiliary','tokenizer_config','special_tokens','chat_template','audio_tokenizer','audio_config','preprocessor') and not re.fullmatch(r'runtime_file_[0-9]{1,2}',k)) or v not in ids for k,v in components.items()):raise ValueError('Ungültige Komponentenreferenz.')
|
||||
presets=p.get('presets',[])
|
||||
if not isinstance(presets,list) or len(presets)>50:raise ValueError('Ungültige Presets im Backup.')
|
||||
preset_ids=set();preset_names=set()
|
||||
@@ -97,7 +97,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'} 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'} 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']
|
||||
@@ -105,6 +105,7 @@ 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 'omnivoice' in runtimes and type(runtimes['omnivoice']) is not bool:raise ValueError('Ungültige OmniVoice-Laufzeit.')
|
||||
if 'voxcpm' in runtimes and type(runtimes['voxcpm']) is not bool:raise ValueError('Ungültige VoxCPM-Laufzeit.')
|
||||
if 'audio_cpp' in runtimes and type(runtimes['audio_cpp']) is not bool:raise ValueError('Ungültige audio.cpp-Laufzeit.')
|
||||
if 'ltx_original' in runtimes and type(runtimes['ltx_original']) is not bool:raise ValueError('Ungültige LTX-Laufzeit.')
|
||||
@@ -175,6 +176,8 @@ class Backup:
|
||||
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,'omnivoice_runtime',None):
|
||||
document['runtimes']['omnivoice']=s.omnivoice_runtime.status()['installed'];document['runtime_versions']['omnivoice']=s.omnivoice_runtime.status()['version']
|
||||
if getattr(s,'voxcpm_runtime',None):
|
||||
document['runtimes']['voxcpm']=s.voxcpm_runtime.status()['installed'];document['runtime_versions']['voxcpm']=s.voxcpm_runtime.status()['version']
|
||||
if document['runtimes']['audio_cpp']:
|
||||
@@ -209,6 +212,9 @@ class Backup:
|
||||
elif s.network.status().get('enabled') or s.network.status().get('mode')!='lan':blockers.append('Deck-Tunnel vor Netzwerk-Restore im bestätigten LAN-Modus deaktivieren.')
|
||||
if doc['network']['mode']!='lan':warnings.append('Tunnelzugang wird mit Rückfallzeit aktiviert und muss über den Tunnel bestätigt werden.')
|
||||
versions=doc.get('runtime_versions',{})
|
||||
if versions.get('omnivoice'):
|
||||
from omnivoice_runtime import VERSION as OMNIVOICE_VERSION
|
||||
if versions['omnivoice']!=OMNIVOICE_VERSION:blockers.append('Backup verlangt eine andere OmniVoice-Version. Passende Deck-Version verwenden.')
|
||||
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.')
|
||||
@@ -221,7 +227,7 @@ 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 and {k:v for k,v in versions.items() if k not in ('ltx_original','audio_cpp','separator','voxcpm')}!=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')}!=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
|
||||
@@ -274,6 +280,8 @@ class Backup:
|
||||
self._phase('TTS-Laufzeit und Zusatzdateien installieren');s.tts_runtime.start();self._wait(s.tts_runtime.status)
|
||||
if r.get('audio_cpp') and not s.audio_cpp_runtime.status()['installed']:
|
||||
self._phase('audio.cpp-Laufzeit installieren');s.audio_cpp_runtime.start();self._wait(s.audio_cpp_runtime.status)
|
||||
if r.get('omnivoice') and not s.omnivoice_runtime.status()['installed']:
|
||||
self._phase('OmniVoice-Laufzeit installieren');s.omnivoice_runtime.start();self._wait(s.omnivoice_runtime.status)
|
||||
if r.get('voxcpm') and not s.voxcpm_runtime.status()['installed']:
|
||||
self._phase('VoxCPM-Laufzeit installieren');s.voxcpm_runtime.start();self._wait(s.voxcpm_runtime.status)
|
||||
if r.get('ltx_original') and not s.ltx_original_runtime.status()['installed']:
|
||||
@@ -429,6 +437,7 @@ class Backup:
|
||||
if getattr(self.server,'separator_runtime',None):self.server.separator_runtime.stop()
|
||||
if getattr(self.server,'separator_tests',None):self.server.separator_tests.stop()
|
||||
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,'audio_cpp_runtime',None):self.server.audio_cpp_runtime.stop()
|
||||
self.server.prompt_enhancer.stop()
|
||||
|
||||
+1
-1
@@ -52,7 +52,7 @@ def file_role(filename):
|
||||
name=filename.lower();parts=PurePosixPath(name).parts
|
||||
if re.search(r'(?:^|[/_-])mmproj(?:[/_.-]|$)',name):
|
||||
role,label=('audio_projector','Audio-Projektor') if 'qwen3-asr' in name else ('vision_projector','Vision-Projektor')
|
||||
elif 'speech_tokenizer' in parts:
|
||||
elif 'speech_tokenizer' in parts or 'audio_tokenizer' in parts:
|
||||
role,label='auxiliary','Sprach-Tokenizer'
|
||||
elif any(p in ('text_encoder','text_encoders') for p in parts) or re.search(r'(?:^|[/_-])(?:text.encoder|qwen3vl|t5xxl|clip_l|clip_g)(?:[/_.-]|$)',name):
|
||||
role,label='text_encoder','Textencoder'
|
||||
|
||||
@@ -30,3 +30,7 @@ CMD ["python3", "server.py", "--port", "8108"]
|
||||
COPY deploy/voxcpm-requirements.lock /app/deploy/voxcpm-requirements.lock
|
||||
|
||||
COPY deploy/patch_yue2_residency.py /app/deploy/patch_yue2_residency.py
|
||||
|
||||
COPY omnivoice_runtime.py omnivoice_worker.py /app/
|
||||
|
||||
COPY deploy/omnivoice-requirements.lock /app/deploy/omnivoice-requirements.lock
|
||||
@@ -20,3 +20,7 @@ CMD ["python3", "server.py", "--port", "8108"]
|
||||
COPY deploy/voxcpm-requirements.lock /app/deploy/voxcpm-requirements.lock
|
||||
|
||||
COPY deploy/patch_yue2_residency.py /app/deploy/patch_yue2_residency.py
|
||||
|
||||
COPY omnivoice_runtime.py omnivoice_worker.py /app/
|
||||
|
||||
COPY deploy/omnivoice-requirements.lock /app/deploy/omnivoice-requirements.lock
|
||||
+12
-8
@@ -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 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 '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,9 +61,10 @@ 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'):raise ValueError('Host-Netzwerk nur für bekannte Deck-Oberflächen erlaubt.')
|
||||
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'):raise ValueError('Host-Netzwerk nur für bekannte Deck-Oberflächen erlaubt.')
|
||||
recipes={'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') is not None and recipes.get(c['build_recipe'])!=(c['name'],c.get('image')):raise ValueError('Unbekanntes Build-Rezept.')
|
||||
if c.get('build_recipe')=='voice-web' and c['name'] in ('athena-voxcpm2-web','athena-omnivoice-web') and c.get('image')=='athena-voice-web:0.2.1-deck1':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','')
|
||||
if not isinstance(ref,str) or not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._/@:-]{0,300}',ref):raise ValueError('Ungültige Image-Referenz.')
|
||||
if c.get('restart') not in ('no','always','unless-stopped','on-failure'):raise ValueError('Ungültige Neustartregel.')
|
||||
@@ -97,7 +98,7 @@ def validate(c):
|
||||
if rel is not None and not native_media 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') 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') 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
|
||||
@@ -115,11 +116,14 @@ 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'):
|
||||
with socket.socket() as probe:probe.bind(('127.0.0.1',8127 if c['name']=='athena-ladypoly' else 8128))
|
||||
if c.get('build_recipe') in ('swarm-ui','ladypoly','separator-web'):
|
||||
if c['name'] in ('athena-ladypoly','athena-separator-web','athena-voxcpm2-web','athena-omnivoice-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}[c['name']]))
|
||||
if c.get('build_recipe') in ('swarm-ui','ladypoly','separator-web','voice-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':
|
||||
exists=subprocess.run(['/usr/bin/docker','image','inspect','mike-ai/omnivoice-studio:0.2.1'],capture_output=True)
|
||||
if exists.returncode:command(['build','-f',str(source/'base.Dockerfile'),'-t','mike-ai/omnivoice-studio:0.2.1',str(source)],1800)
|
||||
command(['build','-t',c['image'],str(source)],1800)
|
||||
else:
|
||||
if not c.get('registry'):raise ValueError('Lokales Image hat keine Registry-Quelle und kein bekanntes Build-Rezept.')
|
||||
@@ -142,7 +146,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'):
|
||||
if c['name'] in ('athena-ladypoly','athena-separator-web','athena-voxcpm2-web','athena-omnivoice-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)]
|
||||
|
||||
+1
-1
@@ -14,7 +14,7 @@ import urllib.request
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
LABEL = 'de.casaderoll.athena-deck.standalone'
|
||||
FILES = ['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 = ['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']
|
||||
|
||||
|
||||
def run(*args, check=True, interactive=False):
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
# Versions verified with OmniVoice 0.2.1 on Athena, 2026-10-04.
|
||||
omnivoice==0.2.1
|
||||
transformers==5.17.0
|
||||
tokenizers==0.23.2
|
||||
accelerate==1.15.0
|
||||
soundfile==0.14.0
|
||||
numpy==2.5.2
|
||||
torch==2.11.0
|
||||
torchaudio==2.11.0
|
||||
@@ -31,6 +31,9 @@ def main():
|
||||
(base/'separator-web').mkdir(exist_ok=True)
|
||||
for name in ('Dockerfile','app.py','index.html'):
|
||||
shutil.copyfile(Path(__file__).parent/'separator-web'/name,base/'separator-web'/name)
|
||||
(base/'voice-web').mkdir(exist_ok=True)
|
||||
for name in ('Dockerfile','base.Dockerfile','bridge.py'):
|
||||
shutil.copyfile(Path(__file__).parent/'voice-web'/name,base/'voice-web'/name)
|
||||
if args.deck_state:
|
||||
registered=Path(args.deck_state).resolve()
|
||||
if not registered.is_dir():raise SystemExit('Deck-Zustandsverzeichnis fehlt.')
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
# Keep the former OmniVoice web UI and its version. Containers only serve UI;
|
||||
# Deck's native workers own GPU/model execution.
|
||||
FROM mike-ai/omnivoice-studio:0.2.1
|
||||
WORKDIR /ui
|
||||
COPY bridge.py /ui/bridge.py
|
||||
ENV GRADIO_ANALYTICS_ENABLED=False HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 VOICE_PORT=8129 VOICE_FAMILY=openbmb/VoxCPM2
|
||||
ENTRYPOINT ["python", "/ui/bridge.py"]
|
||||
CMD []
|
||||
HEALTHCHECK NONE
|
||||
@@ -0,0 +1,23 @@
|
||||
# Stimmstudios
|
||||
|
||||
VoxCPM2 Studio: `athena-voxcpm2-web`, Port 8129.
|
||||
OmniVoice Studio: `athena-omnivoice-web`, Port 8130.
|
||||
|
||||
Beide sind reine Oberflächen ohne GPU-Freigabe. OmniVoice verwendet die
|
||||
Gradio-Oberfläche der bisherigen Router-Version 0.2.1. VoxCPM2 bietet Text,
|
||||
Voice Design (Beschreibung in Klammern) und Referenzstimmen über Gradio.
|
||||
Aufträge gehen an Decks geschützte `/api/v1/voice/*`-Routen. Das gewünschte
|
||||
Profil muss in Deck freigegeben sein; nur ein Stimmprofil kann aktiv sein.
|
||||
In der Steuerung Stimmwerkzeuge starten. Die zugeordnete native Laufzeit
|
||||
lädt beim Auftrag; anschließend wird das Stimmmodell entladen.
|
||||
OmniVoice-Klonen benötigt das Transkript der Referenz, damit kein zusätzlicher
|
||||
Whisper-Download und keine unkontrollierte ASR-GPU-Ausführung stattfinden.
|
||||
|
||||
`/data/deck-connection.json` enthält den Deck-Verbindungswert, Berechtigung 0600.
|
||||
Die Datei wird vom verschlüsselten Konfigurationsbackup erfasst. Images können
|
||||
mit dem hinterlegten Build-Rezept wiederhergestellt werden. Die Gewichte
|
||||
bleiben in Decks Bibliothek mit Originalquelle und Prüfsummen.
|
||||
|
||||
Container lauschen ausschließlich auf Loopback (Host-Netzwerk). Ports 8129
|
||||
und 8130 im nativen Netzwerkhelfer registrieren; dessen Zugriffspolitik und
|
||||
dynamische WireGuard-Adresse gelten auch für diese Studios.
|
||||
@@ -0,0 +1,7 @@
|
||||
FROM nvidia/cuda:12.8.1-cudnn-runtime-ubuntu24.04
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl ffmpeg libsndfile1 python3 python3-pip python3-venv && rm -rf /var/lib/apt/lists/*
|
||||
RUN python3 -m venv /opt/venv
|
||||
ENV PATH="/opt/venv/bin:${PATH}"
|
||||
RUN python -m pip install --no-cache-dir torch==2.8.0 torchaudio==2.8.0 --index-url https://download.pytorch.org/whl/cu128
|
||||
RUN python -m pip install --no-cache-dir omnivoice==0.2.1 omnivoice-triton==0.1.0 'num2words>=0.5.14'
|
||||
CMD ["omnivoice-demo","--ip","0.0.0.0","--port","8008"]
|
||||
@@ -0,0 +1,83 @@
|
||||
"""UI-only bridge: all GPU execution and profile selection remain in Athena Deck."""
|
||||
import io,json,os,time,urllib.request,urllib.error,wave
|
||||
from pathlib import Path
|
||||
CONFIG=Path('/data/deck-connection.json')
|
||||
BASE='http://127.0.0.1:8108'
|
||||
def request(path,data=None,ctype='application/json'):
|
||||
token=json.loads(CONFIG.read_text()).get('token','') if CONFIG.exists() else ''
|
||||
if not token:raise ValueError('Deck-Verbindung zuerst einrichten.')
|
||||
req=urllib.request.Request(BASE+path,data=data,headers={'Authorization':'Bearer '+token,'Content-Type':ctype})
|
||||
try:
|
||||
with urllib.request.urlopen(req,timeout=90) as r:return r.read()
|
||||
except urllib.error.HTTPError as exc:
|
||||
try:error=json.loads(exc.read()).get('error','Deck-Anfrage abgelehnt')
|
||||
except Exception:error='Deck-Anfrage abgelehnt (HTTP '+str(exc.code)+')'
|
||||
raise ValueError(error if isinstance(error,str) else error.get('message','Deck-Anfrage abgelehnt')) from None
|
||||
|
||||
def connect(token):
|
||||
if not token:raise ValueError('API-Token eingeben.')
|
||||
# Check before persisting; keep token out of output and logs.
|
||||
req=urllib.request.Request(BASE+'/api/v1/voice/profiles',headers={'Authorization':'Bearer '+token})
|
||||
with urllib.request.urlopen(req,timeout=10) as r:
|
||||
if r.status!=200:raise ValueError('Deck-Verbindung nicht bestätigt.')
|
||||
CONFIG.parent.mkdir(parents=True,exist_ok=True);tmp=CONFIG.with_suffix('.tmp');tmp.write_text(json.dumps({'token':token}));tmp.chmod(0o600);tmp.replace(CONFIG)
|
||||
return 'Deck verbunden. In Deck das gewünschte Stimmprofil aktivieren und Stimmwerkzeuge starten.'
|
||||
|
||||
def generate(family,text,device='3060',reference=None,**options):
|
||||
rows=json.loads(request('/api/v1/voice/profiles'))['profiles']
|
||||
p=next((p for p in rows if p['repo']==family and p['enabled'] and p['runnable']),None)
|
||||
if not p:raise ValueError('Dieses Stimmprofil zuerst in Deck aktivieren. Es darf nur ein Stimmprofil aktiv sein.')
|
||||
data=dict(profile_id=p['id'],text=text,device=device,**options)
|
||||
ctype='application/json'
|
||||
if reference:
|
||||
import soundfile as sf
|
||||
arr,rate=sf.read(reference);buf=io.BytesIO();sf.write(buf,arr,rate,format='WAV',subtype='PCM_16');audio=buf.getvalue()
|
||||
boundary='athena-voice-'+os.urandom(12).hex();parts=[]
|
||||
for k,v in data.items():
|
||||
value=str(v).lower() if isinstance(v,bool) else str(v)
|
||||
parts.append(('--'+boundary+'\r\nContent-Disposition: form-data; name="'+k+'"\r\n\r\n'+value+'\r\n').encode())
|
||||
parts.extend([('--'+boundary+'\r\nContent-Disposition: form-data; name="file"; filename="reference.wav"\r\nContent-Type: audio/wav\r\n\r\n').encode(),audio,('\r\n--'+boundary+'--\r\n').encode()]);body=b''.join(parts);ctype='multipart/form-data; boundary='+boundary
|
||||
else:body=json.dumps(data).encode()
|
||||
job=json.loads(request('/api/v1/voice/start',body,ctype));deadline=time.monotonic()+650
|
||||
while time.monotonic()<deadline:
|
||||
current=json.loads(request('/api/v1/voice'))['job']
|
||||
if not current or current['id']!=job['id']:raise ValueError('Auftrag nicht mehr verfügbar.')
|
||||
if current['state']=='complete':
|
||||
import soundfile as sf
|
||||
arr,rate=sf.read(io.BytesIO(request('/api/v1/voice/audio?id='+job['id'])),dtype='int16');return (rate,arr),'Fertig · '+current['gpu']
|
||||
if current['state']!='running':raise ValueError(current['phase'])
|
||||
time.sleep(.5)
|
||||
raise ValueError('Deck-Auftrag dauert länger als erwartet. Status in Deck prüfen.')
|
||||
|
||||
def main():
|
||||
import gradio as gr
|
||||
family=os.environ['VOICE_FAMILY'];port=int(os.environ['VOICE_PORT'])
|
||||
if family=='k2-fsa/OmniVoice':
|
||||
# Reuse the exact OmniVoice demo shipped by the old router, replacing only
|
||||
# generation with Deck requests. No weights or CUDA access in this container.
|
||||
from omnivoice.cli.demo import build_demo
|
||||
from types import SimpleNamespace
|
||||
def gen(text,language,ref_audio,instruct,num_step,guidance_scale,denoise,speed,duration,preprocess_prompt,postprocess_output,mode,ref_text=None):
|
||||
try:return generate(family,text,reference=ref_audio if mode=='clone' else None,reference_text=ref_text or '',language='' if language=='Auto' else language or '',instruct=instruct or '',steps=int(num_step or 32),cfg=float(guidance_scale if guidance_scale is not None else 2),seed=42,speed=float(speed or 1),duration=float(duration or 0),denoise=bool(denoise),preprocess_prompt=bool(preprocess_prompt),postprocess_output=bool(postprocess_output))
|
||||
except Exception as exc:return None,str(exc) if isinstance(exc,ValueError) else 'Deck-Verbindung prüfen.'
|
||||
demo=build_demo(SimpleNamespace(sampling_rate=24000),'Athena Deck · OmniVoice',generate_fn=gen)
|
||||
with demo:
|
||||
with gr.Accordion('Athena Deck-Verbindung',open=not CONFIG.exists()):
|
||||
token=gr.Textbox(label='Deck API-Token',type='password');save=gr.Button('Verbinden');status=gr.Textbox(label='Verbindung',interactive=False);save.click(connect,token,status)
|
||||
else:
|
||||
with gr.Blocks(title='Athena VoxCPM2 Studio') as demo:
|
||||
gr.Markdown('# VoxCPM2 Studio\nSprachausgabe, Voice Design und Stimmklonen. Verarbeitung über Athena Deck. Profil dort aktivieren; Stimmwerkzeuge starten.')
|
||||
with gr.Accordion('Deck-Verbindung',open=not CONFIG.exists()):
|
||||
token=gr.Textbox(label='Deck API-Token',type='password');save=gr.Button('Verbinden');status=gr.Textbox(interactive=False);save.click(connect,token,status)
|
||||
text=gr.Textbox(label='Text (Voice Design: Beschreibung in Klammern voranstellen)',lines=5)
|
||||
ref=gr.Audio(label='Referenzstimme (optional, 1–30 Sekunden)',type='filepath')
|
||||
device=gr.Dropdown(['3060','5080'],value='3060',label='GPU')
|
||||
with gr.Row():
|
||||
cfg=gr.Slider(.5,5,value=2,step=.1,label='Guidance');steps=gr.Slider(1,50,value=10,step=1,label='Schritte');seed=gr.Number(value=42,precision=0,label='Seed')
|
||||
button=gr.Button('Stimme erzeugen',variant='primary');output=gr.Audio(label='Ergebnis');message=gr.Textbox(label='Status',interactive=False)
|
||||
def gen(text,ref,device,cfg,steps,seed):
|
||||
try:return generate(family,text,device,ref,cfg=float(cfg),steps=int(steps),seed=int(seed))
|
||||
except Exception as exc:return None,str(exc) if isinstance(exc,ValueError) else 'Deck-Verbindung prüfen.'
|
||||
button.click(gen,[text,ref,device,cfg,steps,seed],[output,message])
|
||||
demo.queue(default_concurrency_limit=1).launch(server_name='127.0.0.1',server_port=port,show_error=False,allowed_paths=['/tmp'],max_file_size='8mb')
|
||||
if __name__=='__main__':main()
|
||||
@@ -1,6 +1,8 @@
|
||||
window.DockerUI=(()=>{
|
||||
const esc=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||||
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-ladypoly':{title:'LadyPoly YuE2',description:'Weboberfläche für Decks Musiklaufzeit.',port:8127,hint:'In der Steuerung Musik starten. Deck-Verbindung in LadyPoly einrichten.'},
|
||||
'athena-separator-web':{title:'Athena Separator Web',description:'Gesang oder Instrumente herauslösen; Verarbeitung durch Decks native Audio-Separator-Laufzeit.',port:8128,hint:'In der Steuerung Audio-Trennung starten. Modelle unter Audio-Trennung einrichten.'},
|
||||
'ltx-deskweb':{title:'LTX DeskWEB',description:'LTX-Webstudio für Videoerzeugung über Decks originale LTX-Laufzeit.',port:8118,hint:'Videoprofil freigeben und in der Steuerung Video starten.'},
|
||||
|
||||
+3
-3
@@ -5,7 +5,7 @@ window.EndpointUI=(()=>{
|
||||
async function api(path='',data){const r=await fetch('/api/v1/endpoint'+path,data!==undefined?{method:'POST',headers:{'Content-Type':'application/json','X-Athena-Deck':'1'},body:JSON.stringify(data)}:{});const v=await r.json();if(!r.ok)throw Error(v.error||'Endpunkt nicht erreichbar');return v;}
|
||||
function put(el,html){if(el._deckHtml!==html){el.innerHTML=html;el._deckHtml=html;}}
|
||||
function summary(s){return `<div class="grid"><section class="card wide"><div class="card-top"><h2>OpenAI-kompatibler Endpunkt</h2><span class="pill">${e(stateName[s.state])}</span></div><div class="metrics"><div><small>Erreichbarkeit</small><strong>${s.reachable?'Listener bereit':'Nicht erreichbar'}</strong></div><div><small>Lokaler API-Port</small><strong>${s.port}</strong></div><div><small>Laufende / wartende Aufträge</small><strong>${s.scheduler.active_requests} / ${s.scheduler.waiting_requests}</strong></div></div><p><code>${e(s.base_url)}</code> · <a class="link" href="#endpoint">Port und Profile einstellen →</a></p><p>Geladen: ${e(s.worker.profile_name||'Kein Sprachmodell')} · ${e(stateName[s.worker.state]||s.worker.state)}</p>${s.worker.error||s.error?`<p role="alert">${e(s.worker.error||s.error)}</p>`:''}<p>Aktivierte Profile werden angeboten. Erst eine Anfrage lädt das Modell. Wechsel warten auf laufende Antworten; Bildaufträge entladen vorher das eigene Sprachmodell.</p></section>${[['llm','Sprachmodelle'],['image','Bildgenerierung'],['tts','Text → Sprache (TTS)'],['stt','Sprache → Text (STT)'],['music','Musik']].map(([key,label])=>{const c=s.counts[key];return `<section class="card"><h3>${label}</h3><p>${c.supported?`${c.enabled} Profile aktiviert · ${c.available} ausführbar`:'Noch keine eigene Laufzeit eingerichtet'}</p><span class="pill">${c.loaded?'AKTIV IM SPEICHER':c.available?'BEI ANFRAGE LADEN':'NICHT AKTIV'}</span></section>`}).join('')}</div>`;}
|
||||
const modeLabels={llm:'LLM',video:'Video',music:'Musik',separator:'Audio-Trennung'};
|
||||
const modeLabels={llm:'LLM',video:'Video',music:'Musik',separator:'Audio-Trennung',voice:'Stimmwerkzeuge'};
|
||||
function control(s,root){
|
||||
const v=s.video||{},active=v.mode||'llm';
|
||||
if(!selectedMode)selectedMode=active==='switching'?(v.target_mode||'llm'):active;
|
||||
@@ -14,11 +14,11 @@ window.EndpointUI=(()=>{
|
||||
const ready=current&&(selected==='separator'||s.reachable)&&!switching&&(selected!=='video'||v.service?.ready);
|
||||
const loading=current&&selected==='llm'&&s.worker.state==='loading';
|
||||
const address=DeckLinks.url(s.port).replace(/\/$/,'');
|
||||
const routes=selected==='llm'?[['Chat',address+'/v1/chat/completions'],['Modelle',address+'/v1/models']]:selected==='separator'?[['Trennauftrag',DeckLinks.url(8108,'/api/v1/separator-jobs/start')],['Status',DeckLinks.url(8108,'/api/v1/separator-tests')]]:selected==='music'?[['Musik erzeugen',address+'/v1/audio/music'],['Musikmodelle',address+'/v1/audio/music/models']]:[['Video-API',address+'/']];
|
||||
const routes=selected==='llm'?[['Chat',address+'/v1/chat/completions'],['Modelle',address+'/v1/models']]:selected==='separator'?[['Trennauftrag',DeckLinks.url(8108,'/api/v1/separator-jobs/start')],['Status',DeckLinks.url(8108,'/api/v1/separator-tests')]]:selected==='music'?[['Musik erzeugen',address+'/v1/audio/music'],['Musikmodelle',address+'/v1/audio/music/models']]:selected==='voice'?[['Sprache erzeugen',address+'/v1/audio/speech'],['Stimmprofile',address+'/v1/audio/speech/models']]:[['Video-API',address+'/']];
|
||||
const reason=available?'':selected==='video'?'Wähle zuerst ein eingerichtetes Videomodell.':selected==='separator'?'Installiere zuerst die Laufzeit und ein Trennmodellpaket.':'Gib zuerst ein ausführbares Profil am API-Endpunkt frei.';
|
||||
const state=switching?'Wechsel läuft':loading?'Modell wird geladen':ready?'Bereit':current&&s.state==='stopping'?'Wird gestoppt':current&&s.reachable?'Startet':current?'Gestoppt':'Nicht aktiv';
|
||||
put(root.querySelector('#control-modes'),`<div class="control-modes" role="tablist" aria-label="Betriebsart">${Object.entries(modeLabels).map(([id,name])=>`<button role="tab" aria-selected="${selected===id}" data-control-mode="${id}" class="${selected===id?'chosen':'secondary'}" ${busy?'disabled':''}>${name}</button>`).join('')}</div>`);
|
||||
put(root.querySelector('#endpoint-summary'),`<section class="card control-card" role="tabpanel"><div class="control-heading"><h2>${label}</h2><span class="pill">${e(state)}</span></div><p>${active==='switching'?`Wechsel zu ${e(modeLabels[v.target_mode]||v.target_mode)}`:(s.reachable||active==='separator')?`Aktiver Betrieb: ${e(modeLabels[active]||active)}`:'Betrieb gestoppt'}</p><div class="card-actions"><button data-control-start ${busy||!available||ready?'disabled':''}>${label} starten</button><button data-control-stop class="secondary" ${busy||!current||(s.state==='stopped'&&active==='llm')?'disabled':''}>Stoppen</button></div>${switching||loading||pending||s.state==='stopping'?`<div class="video-activity" role="status" aria-live="polite"><strong>${e(switching?v.switch_phase:loading?s.worker.phase||'Modell wird geladen':s.state==='stopping'?'Laufende Aufträge werden beendet':'Start wird angefordert')}</strong><progress aria-label="Fortschritt"></progress></div>`:''}${reason?`<p class="warning">${e(reason)} <a class="link" href="#${selected==='video'?'video':selected==='music'?'music':selected==='separator'?'separation':'chat'}">Einrichten →</a></p>`:''}${(current&&(v.error||s.error||selected==='llm'&&s.worker.error))?`<p class="video-error" role="alert">${e(v.error||s.error||s.worker.error)}</p>`:''}<div class="control-api"><h3>API-Adresse</h3>${routes.map(([name,url])=>`<div><span>${name}</span><code>${e(url)}</code></div>`).join('')}<p class="small">${ready?'Erreichbar':'Erreichbar, sobald dieser Betrieb bereit ist'} · Port ${selected==='separator'?8108:s.port}</p></div>${selected==='separator'?`<p class="small">${v.separator?.models?.filter(m=>m.installed).length||0} Modellpakete bereit · Gewichte laden beim Trennauftrag und werden anschließend entladen.</p><a class="link" href="${e(DeckLinks.url(8128,'/'))}" target="_blank" rel="noopener">Audio-Trennoberfläche öffnen →</a><p><a class="link" href="#separation">Modelle und Aufträge →</a></p>`:selected==='llm'?`<p class="small">${s.counts.llm.available} Chatprofile freigegeben · ${e(s.worker.profile_name||'Gewichte laden bei der ersten Anfrage')}</p>`:selected==='music'?`<p class="small">${e(v.music_profiles?.map(p=>p.name).join(', ')||'Kein Musikprofil freigegeben')} · Gewichte laden bei Anfrage</p>${available?`<a class="link" href="${e(DeckLinks.url(8127,'/'))}" target="_blank" rel="noopener">LadyPoly YuE2 öffnen →</a>${!ready?'<p class="small">Vor dem Generieren Musik starten.</p>':''}`:''}`:`<p class="small">${e(v.service?.name||'Kein Videomodell ausgewählt')} · ${v.runtime_kind==='original'?'LTX Original':'ComfyUI'} · Gewichte laden bei Generierung</p>${ready?`<a class="link" href="${e(v.runtime_kind==='original'?DeckLinks.url(8118,'/'):address+'/')}" target="_blank" rel="noopener">${v.runtime_kind==='original'?'LTX DeskWEB':'ComfyUI'} öffnen →</a>`:''}`}<details class="control-details"><summary>Weitere Dienste & Einstellungen</summary><p>Im LLM-Betrieb stehen auch freigegebene Bild-, TTS- und STT-Profile bereit.</p><p><a class="link" href="#endpoint">Endpunkt und Port einstellen →</a></p><p>${s.scheduler.active_requests} laufende · ${s.scheduler.waiting_requests} wartende Aufträge</p></details></section>`);
|
||||
put(root.querySelector('#endpoint-summary'),`<section class="card control-card" role="tabpanel"><div class="control-heading"><h2>${label}</h2><span class="pill">${e(state)}</span></div><p>${active==='switching'?`Wechsel zu ${e(modeLabels[v.target_mode]||v.target_mode)}`:(s.reachable||active==='separator')?`Aktiver Betrieb: ${e(modeLabels[active]||active)}`:'Betrieb gestoppt'}</p><div class="card-actions"><button data-control-start ${busy||!available||ready?'disabled':''}>${label} starten</button><button data-control-stop class="secondary" ${busy||!current||(s.state==='stopped'&&active==='llm')?'disabled':''}>Stoppen</button></div>${switching||loading||pending||s.state==='stopping'?`<div class="video-activity" role="status" aria-live="polite"><strong>${e(switching?v.switch_phase:loading?s.worker.phase||'Modell wird geladen':s.state==='stopping'?'Laufende Aufträge werden beendet':'Start wird angefordert')}</strong><progress aria-label="Fortschritt"></progress></div>`:''}${reason?`<p class="warning">${e(reason)} <a class="link" href="#${selected==='video'?'video':selected==='music'?'music':selected==='separator'?'separation':selected==='voice'?'voice':'chat'}">Einrichten →</a></p>`:''}${(current&&(v.error||s.error||selected==='llm'&&s.worker.error))?`<p class="video-error" role="alert">${e(v.error||s.error||s.worker.error)}</p>`:''}<div class="control-api"><h3>API-Adresse</h3>${routes.map(([name,url])=>`<div><span>${name}</span><code>${e(url)}</code></div>`).join('')}<p class="small">${ready?'Erreichbar':'Erreichbar, sobald dieser Betrieb bereit ist'} · Port ${selected==='separator'?8108:s.port}</p></div>${selected==='separator'?`<p class="small">${v.separator?.models?.filter(m=>m.installed).length||0} Modellpakete bereit · Gewichte laden beim Trennauftrag und werden anschließend entladen.</p><a class="link" href="${e(DeckLinks.url(8128,'/'))}" target="_blank" rel="noopener">Audio-Trennoberfläche öffnen →</a><p><a class="link" href="#separation">Modelle und Aufträge →</a></p>`:selected==='llm'?`<p class="small">${s.counts.llm.available} Chatprofile freigegeben · ${e(s.worker.profile_name||'Gewichte laden bei der ersten Anfrage')}</p>`:selected==='music'?`<p class="small">${e(v.music_profiles?.map(p=>p.name).join(', ')||'Kein Musikprofil freigegeben')} · Gewichte laden bei Anfrage</p>${available?`<a class="link" href="${e(DeckLinks.url(8127,'/'))}" target="_blank" rel="noopener">LadyPoly YuE2 öffnen →</a>${!ready?'<p class="small">Vor dem Generieren Musik starten.</p>':''}`:''}`:selected==='voice'?`<p class="small">${e(v.voice_profiles?.map(p=>p.name).join(', ')||'Kein Stimmprofil freigegeben')} · Gewichte laden beim Auftrag</p><p><a class="link" href="#voice-test">Stimme ausprobieren →</a></p><p><a class="link" href="${e(DeckLinks.url(8129,'/'))}" target="_blank" rel="noopener">VoxCPM2 Studio →</a> · <a class="link" href="${e(DeckLinks.url(8130,'/'))}" target="_blank" rel="noopener">OmniVoice Studio →</a></p>`:`<p class="small">${e(v.service?.name||'Kein Videomodell ausgewählt')} · ${v.runtime_kind==='original'?'LTX Original':'ComfyUI'} · Gewichte laden bei Generierung</p>${ready?`<a class="link" href="${e(v.runtime_kind==='original'?DeckLinks.url(8118,'/'):address+'/')}" target="_blank" rel="noopener">${v.runtime_kind==='original'?'LTX DeskWEB':'ComfyUI'} öffnen →</a>`:''}`}<details class="control-details"><summary>Weitere Dienste & Einstellungen</summary><p>Im LLM-Betrieb stehen auch freigegebene Bild-, TTS- und STT-Profile bereit.</p><p><a class="link" href="#endpoint">Endpunkt und Port einstellen →</a></p><p>${s.scheduler.active_requests} laufende · ${s.scheduler.waiting_requests} wartende Aufträge</p></details></section>`);
|
||||
root.querySelectorAll('[data-control-mode]').forEach(b=>b.onclick=()=>{selectedMode=b.dataset.controlMode;control(s,root);});
|
||||
root.querySelector('[data-control-start]').onclick=()=>controlAction('start',selected);
|
||||
root.querySelector('[data-control-stop]').onclick=()=>controlAction('stop',selected);
|
||||
|
||||
+14
-7
@@ -61,9 +61,9 @@ class Endpoint:
|
||||
return [dict(p,enabled=p['id'] in enabled) for p in rows if p['kind']!='video']
|
||||
def status(self):
|
||||
rows=self.rows();worker=self.worker.status();job=self.images.status()['job'];counts={}
|
||||
for key,kind in [('llm','chat'),('image','image'),('tts','audio'),('stt','stt'),('music','music')]:
|
||||
for key,kind in [('llm','chat'),('image','image'),('tts','audio'),('stt','stt'),('music','music'),('voice','voice')]:
|
||||
subset=[p for p in rows if p['kind']==kind]
|
||||
counts[key]=dict(enabled=sum(p['enabled'] for p in subset),available=sum(p['enabled'] and p['runnable'] for p in subset),loaded=bool(worker['state']=='ready' and kind=='chat') if kind=='chat' else bool(self.tts and self.tts.status().get('loaded')) if kind=='audio' else bool(self.stt and self.stt.status().get('loaded')) if kind=='stt' else bool(self.music and self.music.status().get('loaded')) if kind=='music' else bool(kind=='image' and job and job['state']=='running'),supported=kind in ('chat','image') or (kind=='audio' and self.tts is not None) or (kind=='stt' and self.stt is not None) or (kind=='music' and self.music is not None))
|
||||
counts[key]=dict(enabled=sum(p['enabled'] for p in subset),available=sum(p['enabled'] and p['runnable'] for p in subset),loaded=bool(worker['state']=='ready' and kind=='chat') if kind=='chat' else bool(self.tts and self.tts.status().get('loaded')) if kind=='audio' else bool(self.stt and self.stt.status().get('loaded')) if kind=='stt' else bool(self.music and self.music.status().get('loaded')) if kind=='music' else bool(self.voxcpm and self.voxcpm.status().get('loaded')) if kind=='voice' else bool(kind=='image' and job and job['state']=='running'),supported=kind in ('chat','image') or (kind=='audio' and self.tts is not None) or (kind=='stt' and self.stt is not None) or (kind=='music' and self.music is not None) or (kind=='voice' and self.voxcpm is not None))
|
||||
scheduler_status=self.scheduler.status()
|
||||
# Video status can call back into endpoint.rows(); never hold our lock
|
||||
# while acquiring another service's lock. Concurrent GUI requests otherwise deadlock.
|
||||
@@ -92,9 +92,12 @@ 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']))
|
||||
with self.lock:
|
||||
if row['kind']=='voice' and self.voxcpm:
|
||||
job=self.voxcpm.status().get('job') or {}
|
||||
if job.get('state')=='running' and (not data['enabled'] or job.get('profile_id')!=row['id']):raise ValueError('Stimmauftrag läuft. Vor dem Profilwechsel abschließen oder abbrechen.')
|
||||
enabled=set(self.config['enabled_profiles'])
|
||||
if data['enabled']:
|
||||
if row['kind']=='image':enabled.difference_update(p['id'] for p in rows if p['kind']=='image')
|
||||
if row['kind'] in ('image','voice'):enabled.difference_update(p['id'] for p in rows if p['kind']==row['kind'])
|
||||
enabled.add(data['id'])
|
||||
else:enabled.discard(data['id'])
|
||||
self.config['enabled_profiles']=sorted(enabled);self.persist()
|
||||
@@ -244,8 +247,9 @@ class APIHandler(BaseHTTPRequestHandler):
|
||||
return self.send(ep.model_properties(name))
|
||||
if self.command=='GET' and parsed.path=='/health':
|
||||
return self.send({'status':'ok','service':'athena-deck-api'})
|
||||
if ep.scheduler.gpu_mode=='voice' and parsed.path not in ('/v1/audio/speech','/v1/audio/speech/models','/v1/embeddings','/v1/embeddings/models'):raise APIError('Stimmwerkzeuge aktiv. Für andere KI-Aufträge die Betriebsart wechseln.',503,'voice_mode_active')
|
||||
if ep.scheduler.gpu_mode=='separator' and self.path not in ('/v1/embeddings','/v1/embeddings/models'):raise APIError('Audio-Trennung aktiv. Für Chat, Bilder oder Musik die Betriebsart wechseln.',503,'separator_mode_active')
|
||||
if ep.video and ep.scheduler.gpu_mode not in ('llm','music') and self.path not in ('/v1/embeddings','/v1/embeddings/models'):
|
||||
if ep.video and ep.scheduler.gpu_mode not in ('llm','music','voice') and self.path not in ('/v1/embeddings','/v1/embeddings/models'):
|
||||
if ep.scheduler.gpu_mode=='switching':raise APIError('Moduswechsel läuft.',503,'mode_switching')
|
||||
video=ep.video.status()
|
||||
if not video.get('service',{}).get('ready'):raise APIError('Video-API noch nicht bereit.',503,'video_not_ready')
|
||||
@@ -266,9 +270,10 @@ class APIHandler(BaseHTTPRequestHandler):
|
||||
if self.command=='GET' and self.path=='/health':return self.send({'status':'ok','service':'athena-deck-api'})
|
||||
if self.video_route(ep):return
|
||||
if self.command!='POST':raise APIError('Route nicht gefunden.',404)
|
||||
if ep.scheduler.gpu_mode=='voice' and parsed.path not in ('/v1/audio/speech','/v1/audio/speech/models','/v1/embeddings','/v1/embeddings/models'):raise APIError('Stimmwerkzeuge aktiv. Für andere KI-Aufträge die Betriebsart wechseln.',503,'voice_mode_active')
|
||||
if ep.scheduler.gpu_mode=='separator' and self.path not in ('/v1/embeddings','/v1/embeddings/models'):raise APIError('Audio-Trennung aktiv. Für Chat, Bilder oder Musik die Betriebsart wechseln.',503,'separator_mode_active')
|
||||
if ep.scheduler.gpu_mode=='music' and self.path not in ('/v1/audio/music','/v1/embeddings'):raise APIError('Musik-Modus aktiv. Für andere KI-Aufträge auf LLM wechseln.',503,'music_mode_active')
|
||||
if ep.video and ep.scheduler.gpu_mode not in ('llm','music') and self.path not in ('/v1/audio/transcriptions','/v1/embeddings'):raise APIError('Video-Modus aktiv; Chat-, Bild- und TTS-Aufträge sind gesperrt. Auf LLM zurückschalten.',503,'video_mode_active')
|
||||
if ep.video and ep.scheduler.gpu_mode not in ('llm','music','voice') and self.path not in ('/v1/audio/transcriptions','/v1/embeddings'):raise APIError('Video-Modus aktiv; Chat-, Bild- und TTS-Aufträge sind gesperrt. Auf LLM zurückschalten.',503,'video_mode_active')
|
||||
if self.path=='/v1/audio/transcriptions':return self.transcription(ep)
|
||||
if self.path=='/v1/images/edits':
|
||||
from image_upload import read_image_upload
|
||||
@@ -332,10 +337,12 @@ class APIHandler(BaseHTTPRequestHandler):
|
||||
voice=next((p for p in ep.rows() if p.get('model') and voice_recipe(p['model']) and data.get('model') in [p.get('api_id',p['name']),p['name'],*p.get('api_aliases',[])] and p['enabled']),None)
|
||||
if voice:
|
||||
profile=ep.find_profile(data.get('model'),voice['kind']);backend=ep.voxcpm
|
||||
if data.get('voice','default')!='default' or data.get('speed',1)!=1:raise APIError('VoxCPM2: voice=default und speed=1 verwenden; Referenzstimme im Deck-Testbereich.')
|
||||
try:job=backend.start(profile['id'],data.get('input'),wait=True)
|
||||
omni=profile['model']['repo']=='k2-fsa/OmniVoice'
|
||||
if data.get('voice','default')!='default' or (not omni and data.get('speed',1)!=1):raise APIError('voice=default verwenden; VoxCPM2 unterstützt hier speed=1. Referenzstimme im Deck-Testbereich.')
|
||||
try:job=backend.start(profile['id'],data.get('input'),steps=32 if omni else 10,**(dict(speed=data.get('speed',1),language=data.get('language','')) if omni else {}),wait=True)
|
||||
except ValueError as exc:raise APIError(str(exc)) from None
|
||||
else:
|
||||
if ep.scheduler.gpu_mode=='voice':raise APIError('Ein aktives Stimmwerkzeug-Profil wählen.',404,'model_not_found')
|
||||
profile=ep.find_profile(data.get('model'),'audio');backend=ep.tts
|
||||
try:job=backend.start(profile['id'],data.get('input'),speaker=data.get('voice','Ryan'),language=data.get('language','Auto'),speed=data.get('speed'),wait=True)
|
||||
except ValueError as exc:raise APIError(str(exc)) from None
|
||||
|
||||
+9
-3
@@ -1,7 +1,7 @@
|
||||
"""Read-only, conservative mapping to Deck's maintained execution adapters."""
|
||||
from catalog import file_role
|
||||
from stt import supported as stt_supported
|
||||
from profiles import image_recipe, image_adapter, video_recipe, voice_recipe
|
||||
from profiles import image_recipe, image_adapter, video_recipe, voice_recipe, omni_recipe
|
||||
from tts_runtime import REPO, REVISION
|
||||
|
||||
def _assess(model, installed, profile=None):
|
||||
@@ -28,6 +28,8 @@ def _assess(model, installed, profile=None):
|
||||
elif kind=='audio' and repo==REPO and filename=='model.safetensors' and model.get('revision')==REVISION:
|
||||
result['family']='Qwen3-TTS CustomVoice'
|
||||
result.update(runtime='Qwen3-TTS CustomVoice',route='#tts-runtime',components=['Vollständiges Modellpaket und Sprach-Tokenizer (im Einrichtungsassistenten enthalten)'])
|
||||
elif omni_recipe(model):
|
||||
result.update(family='OmniVoice',evidence='Offizielles k2-fsa-Modellpaket',state='setup',label='OmniVoice erkannt · Komponenten prüfen',runtime=None,route='#omnivoice-runtime',components=[x['label'] for x in omni_recipe(model).values()])
|
||||
elif voice_recipe(model):
|
||||
result.update(family='VoxCPM2',evidence='Offizielles OpenBMB-Modellpaket',state='setup',label='VoxCPM2 erkannt · Komponenten prüfen',runtime=None,route='#voxcpm-runtime',components=[x['label'] for x in voice_recipe(model).values()],message='Die heruntergeladenen Dateien bilden das Modellpaket. Für die Ausführung fehlt noch die VoxCPM-Python/PyTorch-Laufzeit samt Deck-Worker. audio.cpp und llama.cpp führen diese Safetensors-Datei nicht aus. Textencoder und Vision-Projektor sind nicht separat erforderlich. Unter Komponenten werden die tatsächlich benötigten Dateien angeboten.')
|
||||
elif kind=='chat' and filename.lower().endswith('.gguf'):
|
||||
@@ -65,7 +67,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))
|
||||
if voice_recipe(model):
|
||||
if omni_recipe(model):
|
||||
result.update(family='OmniVoice',runtime='OmniVoice · Python/PyTorch',route='#omnivoice-runtime',installed=bool(installed.get('omnivoice')),state='setup',label='OmniVoice · Komponenten prüfen',message='Originale OmniVoice-Laufzeit mit Deck-Worker. Text- und Audio-Tokenizer derselben Modellversion zuordnen.')
|
||||
add('omnivoice','OmniVoice · Python/PyTorch','omnivoice','#omnivoice-runtime','Originale OmniVoice-Laufzeit mit Audio-Tokenizer',True)
|
||||
if profile:result.update(state='ready' if profile.get('runnable') else 'profile_incomplete',blockers=profile.get('blockers',[]),label='OmniVoice bereit' if profile.get('runnable') else 'OmniVoice einrichten')
|
||||
elif voice_recipe(model):
|
||||
result['installed']=bool(installed.get('voxcpm'));result['message']='VoxCPM-Laufzeit '+('bereits installiert' if result['installed'] else 'fehlt: unter Ausführung einrichten installieren')+'. Komponenten zuordnen, danach unter Stimmwerkzeuge → Testen Sprache erzeugen oder Stimme klonen.'
|
||||
add('voxcpm','VoxCPM · Python/PyTorch','voxcpm','#voxcpm-runtime','Originale VoxCPM-Laufzeit · Sprachausgabe und Stimmklonen',True)
|
||||
if profile:result.update(state='ready' if profile.get('runnable') else 'profile_incomplete',blockers=profile.get('blockers',[]),label='VoxCPM2 bereit' if profile.get('runnable') else 'VoxCPM2 einrichten')
|
||||
@@ -105,7 +111,7 @@ def assess(model, installed, profile=None):
|
||||
result=_assess_candidates(model,installed,profile)
|
||||
if result['state']=='component':return result
|
||||
verified=result['state'] not in ('unsupported','workflow_missing')
|
||||
runtime=(next((c for c in result['candidates'] if c['id'] in ('voxcpm','audio_cpp')),None) or next((c for c in result['candidates'] if c['id']!='category'),None)) if verified else None
|
||||
runtime=(next((c for c in result['candidates'] if c['id'] in ('voxcpm','omnivoice','audio_cpp')),None) or next((c for c in result['candidates'] if c['id']!='category'),None)) if verified else None
|
||||
worker_missing=result['state'] in ('adapter_missing','workflow_missing','unsupported')
|
||||
result['setup_steps']=[
|
||||
dict(label='Modell erkennen',state='complete' if verified else 'blocked',message='Modellfamilie erkannt' if verified else 'Noch kein geprüfter Einrichtungsweg'),
|
||||
|
||||
+1
-1
@@ -60,7 +60,7 @@ class Scheduler:
|
||||
if claimed:
|
||||
with self.cv:self.active-=1;self.cv.notify_all()
|
||||
def image_reservation(self, wait=False,kind='image'):
|
||||
lease=self.lease((kind,),timeout=600 if wait else 0,modes=("music",) if kind=="music" else ("llm","separator") if kind=="separator" else ("llm",))
|
||||
lease=self.lease((kind,),timeout=600 if wait else 0,modes=("music",) if kind=="music" else ("llm","separator") if kind=="separator" else ("llm","voice") if kind=="voice" else ("llm",))
|
||||
lease.__enter__()
|
||||
return lambda:lease.__exit__(None,None,None)
|
||||
def tts_reservation(self,wait=False):
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Owned, GUI-installable OmniVoice runtime; never downloads or loads models."""
|
||||
import json,os,shutil,sys,time
|
||||
from pathlib import Path
|
||||
from ltx_original_runtime import LTXOriginalRuntime
|
||||
VERSION='0.2.1'
|
||||
class OmniVoiceRuntime(LTXOriginalRuntime):
|
||||
name='OmniVoice'
|
||||
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').read_text().strip()==VERSION:return base/'python/bin/python',base
|
||||
except (OSError,ValueError,KeyError):pass
|
||||
return self.root/'missing-python',self.root/'missing-runtime'
|
||||
def status(self):
|
||||
python,base=self.paths();shared=self.image_runtime.paths()[0].is_file() if self.image_runtime else False
|
||||
return dict(installed=python.is_file() and (base/'ready').is_file(),version=VERSION,job=dict(self.job) if self.job else None,required_disk_gib=8 if shared else 25,shared_cuda=shared,worker_available=True,origin='k2-fsa/OmniVoice · offizielles Python-Paket',message='Laufzeitinstallation lädt keine Gewichte. Generierung und Stimmklonen unter Stimmwerkzeuge → Testen.')
|
||||
def start(self):
|
||||
if not shutil.which('ffmpeg'):raise ValueError('FFmpeg fehlt. Systemvoraussetzungen über den Deck-Installer einrichten.')
|
||||
return super().start()
|
||||
def _run(self):
|
||||
base=self.root/self.job['id'];state='failed';phase='OmniVoice-Einrichtung fehlgeschlagen.'
|
||||
try:
|
||||
base.mkdir(mode=0o700);tmp=base/'tmp';tmp.mkdir()
|
||||
# A new environment may reference existing CUDA packages but never alters them.
|
||||
env={k:v for k,v in os.environ.items() if not k.startswith(('HF_','DECK_','LLAMA_'))}
|
||||
env.update(TMPDIR=str(tmp),PIP_NO_INPUT='1',PIP_DISABLE_PIP_VERSION_CHECK='1',HF_HUB_OFFLINE='1',OMP_NUM_THREADS='2')
|
||||
shared=self.image_runtime.paths()[0] if self.image_runtime else Path('/missing')
|
||||
bootstrap=shared if shared.is_file() else Path(sys.executable)
|
||||
self._phase('Eigene OmniVoice-Python-Umgebung erstellen');self._command([bootstrap,'-m','venv',base/'python'],env)
|
||||
python=base/'python/bin/python'
|
||||
self._command([python,'-c','import sys; assert (3,10)<=sys.version_info[:2]<(3,13), "OmniVoice benötigt Python 3.10 bis 3.12"'],env)
|
||||
if shared.is_file():
|
||||
self._phase('Vorhandene CUDA-Pakete lesend wiederverwenden')
|
||||
self._command([python,'-c','import json,site,subprocess,sys;from pathlib import Path;p=json.loads(subprocess.check_output([sys.argv[1],"-c","import json,site;print(json.dumps(site.getsitepackages()))"],text=True));Path(site.getsitepackages()[0],"deck-shared-cuda.pth").write_text("\\n".join(p)+"\\n")',shared],env)
|
||||
self._phase('CUDA-PyTorch prüfen / installieren')
|
||||
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'],env)
|
||||
self._phase('OmniVoice '+VERSION+' und Abhängigkeiten installieren')
|
||||
self._command([python,'-m','pip','install','--no-cache-dir','-c',Path(__file__).parent/'deploy/omnivoice-requirements.lock','omnivoice=='+VERSION],env)
|
||||
self._phase('Paketkonsistenz und OmniVoice-Unterstützung prüfen')
|
||||
self._command([python,'-m','pip','check'],env)
|
||||
self._command([python,'-c','import torch,soundfile;from omnivoice import OmniVoice;assert torch.version.cuda;assert callable(OmniVoice.from_pretrained)'],env)
|
||||
if self.cancel.is_set():raise InterruptedError()
|
||||
(base/'ready').write_text(VERSION);marker=self.root/'active.tmp';marker.write_text(json.dumps(dict(id=base.name)));marker.replace(self.root/'active.json')
|
||||
state='complete';phase='OmniVoice-Laufzeit installiert · kein Modell geladen · unter Stimmwerkzeuge testen'
|
||||
except InterruptedError:state='cancelled';phase='OmniVoice-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()
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Offline OmniVoice worker. Private input/output; no model or credential logging."""
|
||||
import contextlib,json,sys
|
||||
from pathlib import Path
|
||||
|
||||
def main():
|
||||
root=Path(sys.argv[1]);request=json.loads(sys.stdin.read());phase='Modell laden'
|
||||
try:
|
||||
with open('/dev/null','w') as sink,contextlib.redirect_stdout(sink),contextlib.redirect_stderr(sink):
|
||||
import torch,soundfile as sf
|
||||
from omnivoice import OmniVoice,OmniVoiceGenerationConfig
|
||||
torch.manual_seed(request['seed'])
|
||||
model=OmniVoice.from_pretrained(str(root/'model'),device_map='cuda:0',dtype=torch.float16,local_files_only=True,load_asr=False)
|
||||
(root/'phase').write_text('OmniVoice: Stimme wird erzeugt');phase='Stimme erzeugen'
|
||||
kwargs=dict(text=request['text'],language=request.get('language') or None,instruct=request.get('instruct') or None,speed=request.get('speed',1.0),generation_config=OmniVoiceGenerationConfig(num_step=request['steps'],guidance_scale=request['cfg'],denoise=request.get('denoise',True),preprocess_prompt=request.get('preprocess_prompt',True),postprocess_output=request.get('postprocess_output',True)))
|
||||
if request.get('duration'):kwargs['duration']=request['duration']
|
||||
if (root/'reference.wav').exists():kwargs.update(ref_audio=str(root/'reference.wav'),ref_text=request['reference_text'])
|
||||
wave=model.generate(**kwargs)[0];rate=model.sampling_rate
|
||||
sf.write(root/'result.wav',wave,rate,subtype='PCM_16')
|
||||
result=dict(ok=True,sample_rate=rate,duration=len(wave)/rate)
|
||||
except Exception as exc:
|
||||
oom='outofmemory' in type(exc).__name__.lower() or 'out of memory' in str(exc).lower()
|
||||
result=dict(ok=False,error='GPU-Speicher reicht nicht aus. Andere Deck-Modelle entladen oder andere GPU wählen.' if oom else 'OmniVoice: '+phase+' fehlgeschlagen ('+type(exc).__name__+'). Laufzeit und Komponenten prüfen.')
|
||||
(root/'result.json').write_text(json.dumps(result));return 0 if result['ok'] else 1
|
||||
if __name__=='__main__':sys.exit(main())
|
||||
+1
-1
@@ -9,7 +9,7 @@ window.ProfilesUI=(()=>{
|
||||
async function load(){try{const [p,c,h,ep]=await Promise.all([api('profiles'),api('catalog'),['chat','video'].includes(kind)?api('hardware').catch(()=>({gpus:[]})):Promise.resolve({gpus:[]}),api('endpoint')]);entries=c.entries;projectors=c.entries.filter(x=>x.role==='vision_projector'&&x.file.endsWith('.gguf'));enabled=ep.profiles.filter(x=>x.enabled).map(x=>x.id);gpus=h.gpus||[];if(!root.isConnected)return;rows=p.profiles.filter(x=>x.kind===kind);models=c.entries.filter(x=>x.kind===kind&&x.profile_eligible===true);schema=p.schemas[kind];el('profile-new').disabled=!models.length;
|
||||
const openRows=new Set([...root.querySelectorAll('.detail-row[open]')].map(x=>x.dataset.rowId));
|
||||
el('profile-list').innerHTML=rows.map(p=>`<details class="detail-row" data-row-id="${e(p.id)}" ${openRows.has(p.id)?'open':''}><summary class="detail-summary"><strong>${e(p.name)}</strong><span class="small">API-ID: ${e(p.api_id||p.name)}</span><span class="hub-filename">${e(p.model?.file||'Modelldatei nicht verfügbar')}</span><span>${p.parameters.context?`${e(p.parameters.context)} Token · ${e(p.parameters.slots||1)} Slots`:e(p.execution?.runtime||'Laufzeit prüfen')}</span><span>${enabled.includes(p.id)?'API: freigegeben':'API: nicht freigegeben'}<small>${p.runnable?'Bereit · lädt bei Anfrage':'Einrichtung fehlt'}</small></span></summary><div class="detail-body"><p>${Object.entries(p.parameters).map(([k,v])=>`${e(labels[k]||k)}: ${e(['video_device','text_encoder_device'].includes(k)?({auto:'Automatisch · RTX 5080 bevorzugt',same:'Wie Videopipeline'}[v]||gpus.find(g=>g.uuid===v)?.name||v):k==='gpu_reserve_mode'?({auto:'Automatisch',manual:'Manuell',none:'Keine zusätzliche Reserve'}[v]||v):k==='gpu_reserve_mib'?(Object.entries(v).map(([id,n])=>`${gpus.find(g=>g.uuid===id)?.name||id}: ${n} MiB`).join(', ')||'gemäß Reservemodus'):k==='gpu_devices'?(v.length?v.map((id,i)=>`CUDA${i}: ${gpus.find(g=>g.uuid===id)?.name||id}`).join(', '):'Automatisch'):Array.isArray(v)?(v.join(', ')||'Automatisch'):v)}`).join(' · ')}</p>${kind==='image'?`<p>Prompt-Aufwerter: Text-zu-Bild ${p.prompt_enhancer?.t2i?'an':'aus'} · Bildbearbeitung ${p.prompt_enhancer?.i2i?'an':'aus'} · Gerät ${e(p.prompt_enhancer?.device||'auto')}</p>`:''}${CatalogUI.executionHTML(p.execution)}<details><summary>${p.runnable?(kind==='video'?'Laufzeit bereit · Video-Modus in Steuerung aktivieren':'Laufzeit bereit · lädt bei Anfrage'):'Was fehlt zur Ausführung?'}</summary>${p.blockers.map(t=>`<p>${e(t)}</p>`).join('')}</details><div class="card-actions"><label class="endpoint-choice"><input type="checkbox" data-publish="${p.id}" ${enabled.includes(p.id)?'checked':''} ${!p.runnable&&!enabled.includes(p.id)?'disabled':''}> Am API-Endpunkt freigegeben</label><button class="secondary" data-edit="${p.id}">Bearbeiten</button><button class="secondary" data-copy="${p.id}">Duplizieren</button><button class="secondary" data-presets="${p.id}">Presets (${(p.presets||[]).length})</button><button class="secondary" data-delete="${p.id}">Löschen</button><button class="secondary" data-components="${p.id}">Einrichtung & Komponenten</button>${kind==='image'?`<button class="secondary" data-enhancers="${p.id}">Prompt-Aufwerter</button>`:''}</div></div></details>`).join('')||`<section class="empty"><h3>Noch keine Profile</h3><p>${models.length?'Wähle eine heruntergeladene Modelldatei und lege dein erstes Profil an.':'Lade zuerst eine Gewichtsdatei unter Entdecken herunter.'}</p></section>`;
|
||||
el('profile-list').insertAdjacentHTML('afterbegin',`<p>${kind==='image'?'Der feste API-Name athena-image verwendet das hier freigegebene Bildprofil und dessen Auflösung. Höchstens ein Bildprofil ist am API-Endpunkt freigegeben. Ein neuer Haken ersetzt die bisherige Auswahl.':['audio','stt'].includes(kind)?'Eingerichtete Sprachprofile können am API-Endpunkt freigegeben werden.':kind==='chat'?'Mehrere Sprachmodellprofile können gleichzeitig am API-Endpunkt freigegeben sein.':kind==='video'?'Genau ein Videoprofil kann am API-Endpunkt freigegeben sein. Ein neuer Haken ersetzt die bisherige Auswahl. Die Steuerung lädt dieses Profil beim Wechsel auf Video; API-Name: athena-video. Zum Ändern der Freigabe zuerst auf LLM wechseln.':kind==='music'?'Gib ein eingerichtetes Musikprofil frei, um es in der Steuerung verwenden zu können.':kind==='voice'?'Eingerichtete VoxCPM2-Profile können Sprache erzeugen und am Sprach-API-Endpunkt freigegeben werden. Stimmklonen mit WAV-Referenz steht unter Testen.':'Für diesen Bereich ist noch keine ausführbare Laufzeit am Endpunkt angebunden.'} Freigegeben bedeutet nicht bereits in den GPU-Speicher geladen.</p>`);
|
||||
el('profile-list').insertAdjacentHTML('afterbegin',`<p>${kind==='image'?'Der feste API-Name athena-image verwendet das hier freigegebene Bildprofil und dessen Auflösung. Höchstens ein Bildprofil ist am API-Endpunkt freigegeben. Ein neuer Haken ersetzt die bisherige Auswahl.':['audio','stt'].includes(kind)?'Eingerichtete Sprachprofile können am API-Endpunkt freigegeben werden.':kind==='chat'?'Mehrere Sprachmodellprofile können gleichzeitig am API-Endpunkt freigegeben sein.':kind==='video'?'Genau ein Videoprofil kann am API-Endpunkt freigegeben sein. Ein neuer Haken ersetzt die bisherige Auswahl. Die Steuerung lädt dieses Profil beim Wechsel auf Video; API-Name: athena-video. Zum Ändern der Freigabe zuerst auf LLM wechseln.':kind==='voice'?'Genau ein Stimmprofil ist am Endpunkt aktiv. Aktivieren ersetzt die bisherige Auswahl; starten über Steuerung → Stimmwerkzeuge.':kind==='music'?'Gib ein eingerichtetes Musikprofil frei, um es in der Steuerung verwenden zu können.':kind==='voice'?'Eingerichtete VoxCPM2-Profile können Sprache erzeugen und am Sprach-API-Endpunkt freigegeben werden. Stimmklonen mit WAV-Referenz steht unter Testen.':'Für diesen Bereich ist noch keine ausführbare Laufzeit am Endpunkt angebunden.'} Freigegeben bedeutet nicht bereits in den GPU-Speicher geladen.</p>`);
|
||||
root.querySelectorAll('[data-publish]').forEach(b=>b.onchange=async()=>{const checked=b.checked;root.querySelectorAll('[data-publish]').forEach(x=>x.disabled=true);try{await api('endpoint/profile',{id:b.dataset.publish,enabled:checked});await load();message(kind==='video'?'Video-Freigabe gespeichert. Die Steuerung lädt dieses Profil beim Wechsel auf Video.':'Endpunkt-Freigabe gespeichert. Geladen wird erst bei einer API-Anfrage.');}catch(error){await load();message(error.message);}});
|
||||
root.querySelectorAll('[data-delete]').forEach(b=>b.onclick=async()=>{const p=rows.find(p=>p.id===b.dataset.delete);if(!confirm(`Profil „${p.name}“ löschen? Modelldateien und Komponenten bleiben in der Bibliothek.`))return;b.disabled=true;try{await api('profiles/delete',{id:p.id,revision:p.revision});panelSequence++;el('profile-editor').replaceChildren();await load();message('Profil gelöscht. Modelldateien und Komponenten bleiben erhalten.');}catch(error){message(error.message);b.disabled=false;}});
|
||||
root.querySelectorAll('[data-components]').forEach(b=>b.onclick=()=>components(rows.find(p=>p.id===b.dataset.components)));
|
||||
|
||||
+17
-2
@@ -118,8 +118,20 @@ VOXCPM2_COMPONENTS={
|
||||
'tokenizer_config':dict(label='Tokenizer-Einstellungen · gehört zum Wortschatz',files=['tokenizer_config.json']),
|
||||
'special_tokens':dict(label='Spezialtokens · Steuerzeichen des Tokenizers',files=['special_tokens_map.json'])
|
||||
}
|
||||
OMNIVOICE_REPO='k2-fsa/OmniVoice'
|
||||
OMNIVOICE_COMPONENTS={
|
||||
'model_config':dict(label='Modellkonfiguration',files=['config.json']),
|
||||
'tokenizer':dict(label='Text-Tokenizer',files=['tokenizer.json']),
|
||||
'tokenizer_config':dict(label='Tokenizer-Konfiguration',files=['tokenizer_config.json']),
|
||||
'chat_template':dict(label='Textvorlage',files=['chat_template.jinja']),
|
||||
'audio_tokenizer':dict(label='Audio-Tokenizer · Gewichte',files=['audio_tokenizer/model.safetensors']),
|
||||
'audio_config':dict(label='Audio-Tokenizer-Konfiguration',files=['audio_tokenizer/config.json']),
|
||||
'preprocessor':dict(label='Audio-Vorverarbeitung',files=['audio_tokenizer/preprocessor_config.json']),
|
||||
}
|
||||
def omni_recipe(model):
|
||||
return OMNIVOICE_COMPONENTS if model.get('kind')=='voice' and model.get('repo')==OMNIVOICE_REPO and model.get('file')=='model.safetensors' else None
|
||||
def voice_recipe(model):
|
||||
return VOXCPM2_COMPONENTS if model.get('kind') in ('voice','audio') and model.get('repo')==VOXCPM2_REPO and model.get('file')=='model.safetensors' else None
|
||||
return VOXCPM2_COMPONENTS if model.get('kind') in ('voice','audio') and model.get('repo')==VOXCPM2_REPO and model.get('file')=='model.safetensors' else omni_recipe(model)
|
||||
|
||||
def component_recipe(model):
|
||||
return voice_recipe(model) or music_recipe(model) or video_recipe(model) or image_recipe(model)
|
||||
@@ -204,7 +216,9 @@ 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 p.get('model') and voice_recipe(p['model']):
|
||||
p['blockers']=[] if getattr(self,'voxcpm_runtime_ready',lambda:False)() else ['VoxCPM-Laufzeit unter Laufzeiten → VoxCPM installieren.']
|
||||
family='OmniVoice' if omni_recipe(p['model']) else 'VoxCPM'
|
||||
ready=getattr(self,'omnivoice_runtime_ready' if omni_recipe(p['model']) else 'voxcpm_runtime_ready',lambda:False)()
|
||||
p['blockers']=[] if ready else [family+'-Laufzeit unter Laufzeiten installieren.']
|
||||
for role,info in voice_recipe(p['model']).items():
|
||||
try:self._component(p['model'],role,p.get('components',{}).get(role))
|
||||
except ValueError:p['blockers'].append(info['label']+' fehlt oder ist noch nicht zugeordnet.')
|
||||
@@ -342,6 +356,7 @@ class Profiles:
|
||||
except ValueError:pass
|
||||
candidates=[dict(f,repo=source.get('repo',info.get('repo',model['repo'])),revision=source['revision'],gated=source['gated'],auth_configured=source.get('auth_configured',False)) for name in info['files'] for f in source['files'] if f['name']==name]
|
||||
requirements.append(dict(role=role,label=info['label'],available=available,candidates=candidates))
|
||||
if omni_recipe(model):return dict(supported=True,requirements=requirements,source='https://huggingface.co/'+model['repo']+'/blob/'+model['revision']+'/README.md',license=source['license'],runtime='OmniVoice · Python/PyTorch',runtime_installed=bool(getattr(self,'omnivoice_runtime_ready',lambda:False)()),runtime_route='#omnivoice-runtime',worker_available=True,message='Originale OmniVoice-Laufzeit mit Audio- und Text-Tokenizer. Komponenten derselben Quellversion zuordnen. Stimmklonen benötigt Referenz-Audio und dessen Transkript; keine zusätzlichen ASR-Gewichte werden automatisch geladen.')
|
||||
if voice_recipe(model):return dict(supported=True,requirements=requirements,source='https://huggingface.co/'+model['repo']+'/blob/'+model['revision']+'/README.md',license=source['license'],runtime='VoxCPM · eigene Python/PyTorch-Laufzeit',runtime_installed=bool(getattr(self,'voxcpm_runtime_ready',lambda:False)()),runtime_route='#voxcpm-runtime',worker_available=True,message='VoxCPM2 benötigt genau diese fünf Zusatzdateien derselben Quellversion. Ein separater Textencoder und ein Vision-Projektor werden nicht benötigt. tokenizer.json und tokenizer_config.json gehören zusammen, sie sind keine doppelten Modelle. Vorhandene Dateien werden wiederverwendet. Die passende Laufzeit kann unter Einstellungen → Laufzeiten → VoxCPM installiert werden. Nach Zuordnung dieser Dateien unter Stimmwerkzeuge → Testen Sprache erzeugen oder eine WAV-Referenz für Stimmklonen verwenden.')
|
||||
if music_recipe(model):return dict(supported=True,requirements=requirements,source='https://huggingface.co/'+model['repo']+'/blob/'+model['revision']+'/README.md',license=source['license'],runtime='audio.cpp',runtime_route='#audio-cpp-runtime',runtime_installed=bool(getattr(self,'music_runtime_ready',lambda:False)()),message='Passendes YuE2-GGUF-Paket: je eine VAE-Datei und die vier Zusatzdateien derselben Quellversion. F16-VAE ist die erste Downloadempfehlung. Vorhandene Dateien wiederverwenden, fehlende herunterladen und danach zuordnen. Die YuE2-Musikanbindung verwendet diese Dateien über audio.cpp. Speichern startet kein Modell; anschließend Musik → Testen verwenden.')
|
||||
if video:return dict(supported=True,requirements=requirements,source='https://huggingface.co/'+model['repo']+'/blob/'+model['revision']+'/README.md',license=source['license'],runtime='ComfyUI · gemeinsame Bild- und Videolaufzeit',runtime_route='#image-runtime',runtime_installed=bool(getattr(self,'video_runtime_ready',lambda:False)()),message='Geprüftes Dateirezept nach Herstellerdokumentation für die zweistufige Distilled-Pipeline mit fester Bildanzahl. Alle Komponenten stammen aus derselben Version wie dein Transformer. Kein beliebiger Gemma-Encoder; keine Comfy-INT8-Dateien. Optionaler Duration-Head, Temporal-Upsampling und DFR sind nicht Teil dieses Rezepts. Vorhandene ComfyUI-Laufzeit wiederverwenden; Videomodell im Bereich Video aktivieren. Vollständige Dateien sind keine Speicherzusage.')
|
||||
|
||||
@@ -10,6 +10,7 @@ from http.cookies import SimpleCookie, CookieError
|
||||
from auth import CredentialStore, verify_password
|
||||
from catalog import Catalog
|
||||
from voxcpm_runtime import VoxCPMRuntime
|
||||
from omnivoice_runtime import OmniVoiceRuntime
|
||||
from tts_runtime import TTSRuntime
|
||||
from stt import STT,read_upload
|
||||
from audio_policy import AudioPolicy
|
||||
@@ -87,6 +88,8 @@ class Server(ThreadingHTTPServer):
|
||||
self.profiles.prompt_enhancer_ready=lambda task:bool(self.prompt_enhancer.installed(task))
|
||||
self.profiles.image_runtime_ready=lambda:self.image_tests.status()["runtime_installed"]
|
||||
self.voxcpm_runtime=VoxCPMRuntime(self.catalog.root.parent/'voxcpm-runtime',self.image_runtime)
|
||||
self.omnivoice_runtime=OmniVoiceRuntime(self.catalog.root.parent/'omnivoice-runtime',self.image_runtime)
|
||||
self.profiles.omnivoice_runtime_ready=lambda:self.omnivoice_runtime.status()['installed']
|
||||
self.profiles.voxcpm_runtime_ready=lambda:self.voxcpm_runtime.status()['installed']
|
||||
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)
|
||||
@@ -106,6 +109,7 @@ class Server(ThreadingHTTPServer):
|
||||
self.worker=LlamaWorker(self.catalog.root.parent/'llama-worker',self.catalog,self.runtime)
|
||||
self.scheduler=Scheduler(self.worker)
|
||||
self.voxcpm_tests=VoxCPMTests(self.catalog.root.parent/'voice-tests',self.profiles,self.voxcpm_runtime)
|
||||
self.voxcpm_tests.omni_runtime=self.omnivoice_runtime
|
||||
self.voxcpm_tests.acquire=lambda wait=False:self.scheduler.image_reservation(wait,kind='voice')
|
||||
self.separator_runtime=SeparatorRuntime(self.catalog.root.parent/'separator-runtime')
|
||||
self.separator_tests=SeparatorTests(self.catalog.root.parent/'separator-tests',self.separator_runtime,self.scheduler)
|
||||
@@ -144,6 +148,7 @@ class Server(ThreadingHTTPServer):
|
||||
self.video=VideoRuntimes(self.scheduler,stop_gpu_work,self.docker,self.catalog.root.parent/'video',self.catalog,self.profiles,self.image_runtime,original_runtime=self.ltx_original_runtime)
|
||||
self.endpoint.video=self.video
|
||||
self.video.separator_status=lambda:dict(self.separator_runtime.status(),worker=self.separator_tests.status())
|
||||
self.video.voice_profiles=lambda:[dict(id=p['id'],name=p['name']) for p in self.endpoint.rows() if p['kind']=='voice' and p['enabled'] and p['runnable']]
|
||||
self.video.music_profiles=lambda:[dict(id=p['id'],name=p['name']) for p in self.endpoint.rows() if p['kind']=='music' and p['enabled'] and p['runnable']]
|
||||
self.profiles.video_runtime_ready=lambda:self.image_runtime.status().get("installed",False)
|
||||
from dashboard_data import Dashboard
|
||||
@@ -216,7 +221,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') or urlsplit(self.path).path=='/api/v1/separator-tests/audio')) or (self.command=='POST' and self.path in ('/api/v1/separator-jobs/start','/api/v1/separator-tests/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') 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'))
|
||||
|
||||
def session_token(self):
|
||||
try:
|
||||
@@ -333,7 +338,7 @@ class Handler(BaseHTTPRequestHandler):
|
||||
'audio':self.server.tts_runtime.status().get('installed',False),
|
||||
'video':video_runtime.status().get('installed',False),
|
||||
'audio_cpp':self.server.audio_cpp_runtime.status()['installed'],
|
||||
'voxcpm':self.server.voxcpm_runtime.status()['installed'],'music_worker':True,'separator':self.server.separator_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)
|
||||
@@ -363,7 +368,8 @@ class Handler(BaseHTTPRequestHandler):
|
||||
if self.path == '/api/v1/endpoint':return self.respond(self.server.endpoint.status())
|
||||
if self.path == '/api/v1/docker':return self.respond(self.server.docker.status())
|
||||
if self.path == '/api/v1/stt':return self.respond(self.server.stt.status())
|
||||
if self.path == '/api/v1/voice':return self.respond(self.server.voxcpm_tests.status())
|
||||
if self.path == '/api/v1/voice/profiles':return self.respond({'profiles':[dict(id=p['id'],name=p['name'],repo=p['model']['repo'],enabled=p['enabled'],runnable=p['runnable']) for p in self.server.endpoint.rows() if p['kind']=='voice' and p.get('model')]})
|
||||
if self.path == '/api/v1/voice':return self.respond(dict(self.server.voxcpm_tests.status(),mode=self.server.scheduler.gpu_mode))
|
||||
if urlsplit(self.path).path == '/api/v1/voice/audio':
|
||||
try:return self.respond(self.server.voxcpm_tests.audio(parse_qs(urlsplit(self.path).query).get('id',[''])[0]),mime='audio/wav')
|
||||
except (ValueError,OSError) as exc:return self.respond({'error':str(exc)},400)
|
||||
@@ -376,6 +382,8 @@ class Handler(BaseHTTPRequestHandler):
|
||||
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/omnivoice-runtime':return self.respond(self.server.omnivoice_runtime.status())
|
||||
if self.path == '/api/v1/omnivoice-runtime/log':return self.respond(self.server.omnivoice_runtime.log())
|
||||
if self.path == '/api/v1/voxcpm-runtime':return self.respond(self.server.voxcpm_runtime.status())
|
||||
if self.path == '/api/v1/voxcpm-runtime/log':return self.respond(self.server.voxcpm_runtime.log())
|
||||
if self.path == '/api/v1/separator-runtime':return self.respond(self.server.separator_runtime.status())
|
||||
@@ -578,6 +586,11 @@ 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/omnivoice-runtime/install','/api/v1/omnivoice-runtime/cancel'):
|
||||
try:
|
||||
if self.read_json():raise ValueError('Keine Installationsparameter erwartet.')
|
||||
return self.respond(self.server.omnivoice_runtime.stop() if self.path.endswith('/cancel') else self.server.omnivoice_runtime.start())
|
||||
except (ValueError,OSError) as exc:return self.respond({'error':str(exc)},400)
|
||||
if self.path in ('/api/v1/voxcpm-runtime/install','/api/v1/voxcpm-runtime/cancel'):
|
||||
try:
|
||||
if self.read_json():raise ValueError('Keine Parameter erwartet.')
|
||||
@@ -658,13 +671,21 @@ class Handler(BaseHTTPRequestHandler):
|
||||
if self.read_json():raise ValueError('Keine Abbruchparameter erwartet.')
|
||||
return self.respond(self.server.voxcpm_tests.stop())
|
||||
if self.headers.get('Content-Type','').startswith('multipart/form-data'):
|
||||
fields,audio=read_upload(self,validate=False,allowed_fields=('profile_id','text','device','cfg','steps','seed'),max_field=4096)
|
||||
fields,audio=read_upload(self,validate=False,allowed_fields=('profile_id','text','device','cfg','steps','seed','reference_text','language','instruct','speed','duration','denoise','preprocess_prompt','postprocess_output'),max_field=4096)
|
||||
fields['reference']=audio
|
||||
for key in ('steps','seed'):
|
||||
if key in fields:fields[key]=int(fields[key])
|
||||
if 'cfg' in fields:fields['cfg']=float(fields['cfg'])
|
||||
for key in ('cfg','speed','duration'):
|
||||
if key in fields:fields[key]=float(fields[key])
|
||||
for key in ('denoise','preprocess_prompt','postprocess_output'):
|
||||
if key in fields:
|
||||
if fields[key] not in ('true','false'):raise ValueError('Ungültige Audio-Option.')
|
||||
fields[key]=fields[key]=='true'
|
||||
else:fields=self.read_json()
|
||||
if set(fields)-{'profile_id','text','device','cfg','steps','seed','reference'} or not {'profile_id','text'}<=set(fields):raise ValueError('Ungültige VoxCPM2-Anfrage.')
|
||||
if set(fields)-{'profile_id','text','device','cfg','steps','seed','reference_text','language','instruct','speed','duration','denoise','preprocess_prompt','postprocess_output','reference'} or not {'profile_id','text'}<=set(fields):raise ValueError('Ungültige VoxCPM2-Anfrage.')
|
||||
if self.api_token_authenticated():
|
||||
selected=next((p for p in self.server.endpoint.rows() if p['id']==fields['profile_id'] and p['kind']=='voice' and p['enabled']),None)
|
||||
if not selected:raise ValueError('Dieses Stimmprofil ist nicht aktiviert. In Deck das gewünschte Profil freigeben.')
|
||||
return self.respond(self.server.voxcpm_tests.start(**fields))
|
||||
except (ValueError,OSError) as exc:return self.respond({'error':str(exc)},400)
|
||||
if self.path in ('/api/v1/tts/install','/api/v1/tts/install-cancel','/api/v1/tts/assign','/api/v1/tts/start','/api/v1/tts/cancel'):
|
||||
@@ -811,7 +832,7 @@ def main():
|
||||
server.endpoint.close()
|
||||
server.stt.stop()
|
||||
server.voxcpm_tests.stop();server.tts_tests.stop()
|
||||
server.tts_runtime.stop();server.voxcpm_runtime.stop()
|
||||
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.audio_cpp_runtime.stop()
|
||||
|
||||
@@ -2,17 +2,18 @@
|
||||
const Studio=(()=>{
|
||||
let section='discover',category='';
|
||||
const labels={embeddings:'Embeddings',chat:'Chat & Sprachmodelle',image:'Bildgenerierung',audio:'Sprachausgabe (TTS)',stt:'Spracherkennung (STT)',music:'Musikgenerierung',voice:'Stimmwerkzeuge',video:'Videogenerierung'};
|
||||
const audioDescriptions={embeddings:'Text in Vektoren umwandeln – für Gedächtnis, Suche und Dokumente. Entdecken, Downloads und Profile sind verfügbar. EmbeddingGemma 300M QAT Q8_0 verwendet die vorhandene llama.cpp-Laufzeit auf CPU. Profil am Endpunkt freigeben und über /v1/embeddings nutzen. Chat bleibt getrennt.',audio:'Geschriebenen Text vorlesen lassen. Die Suche zeigt Text-to-Speech-Modelle.',stt:'Gesprochene Sprache in Text umwandeln. Die Suche zeigt Spracherkennungsmodelle.',music:'Musik und Klänge aus Text erzeugen. Die Hub-Kategorie Text-to-Audio umfasst neben Musik auch Geräusche und andere Audioerzeugung.',voice:'Vorhandenes Audio bearbeiten: Stimmumwandlung, Audio-Trennung und weitere Audio-to-Audio-Modelle. Eigenständige Studio-Oberflächen gehören unter Weitere Dienste.'};
|
||||
const audioDescriptions={embeddings:'Text in Vektoren umwandeln – für Gedächtnis, Suche und Dokumente. Entdecken, Downloads und Profile sind verfügbar. EmbeddingGemma 300M QAT Q8_0 verwendet die vorhandene llama.cpp-Laufzeit auf CPU. Profil am Endpunkt freigeben und über /v1/embeddings nutzen. Chat bleibt getrennt.',audio:'Geschriebenen Text vorlesen lassen. Die Suche zeigt Text-to-Speech-Modelle.',stt:'Gesprochene Sprache in Text umwandeln. Die Suche zeigt Spracherkennungsmodelle.',music:'Musik und Klänge aus Text erzeugen. Die Hub-Kategorie Text-to-Audio umfasst neben Musik auch Geräusche und andere Audioerzeugung.',voice:'Sprache erzeugen, Stimmen gestalten und mit Referenz-Audio klonen. VoxCPM2 und OmniVoice nutzen Decks GPU-Steuerung. Weboberflächen unter Weitere Dienste.'};
|
||||
function render(page,force=false,modelId=null){
|
||||
if(page==='video'){VideoUI.runtime();return;}
|
||||
if(!force&&document.querySelector('#studio')?.dataset.page===page)return;
|
||||
if(category!==page){category=page;section='discover';}
|
||||
if(modelId)section='profiles';
|
||||
const body=page==='voxcpm-runtime'?VoxCPMUI.html():page==='stt-runtime'?STTUI.html(true):page==='tts-runtime'?TTSUI.html(true):['docker-runtime','services'].includes(page)?DockerUI.html(page==='services'):page==='runtimes'?runtimeOverview():page==='image-runtime'?imageRuntime():page==='runtime'?RuntimeUI.html():`<div class="kicker">ATHENA / MODELLVERWALTUNG</div><h1>${labels[page]}</h1><p>${audioDescriptions[page]||'Modelle entdecken, herunterladen und mit gespeicherten Profilen konfigurieren.'}</p>${page==='voice'?'<p><a class="link" href="#separator-runtime">Audio Separator einrichten →</a> · <a class="link" href="#separation">Audio-Trennung →</a></p><p class="note">Audio-Trennung nutzt die unterstützten Pakete im Audio-Separator-Bereich. Andere Hub-Dateien und Voice-Profile benötigen weiterhin eine geprüfte Anbindung.</p>':''}${audioDescriptions[page]&&!['audio','stt','music','voice','embeddings'].includes(page)?'<p class="note">Entdecken und Downloads sind verfügbar. Für diese Audio-Bereiche ist noch keine ausführbare Laufzeit in Deck angebunden. Gespeicherte Profile sind vorbereitend.</p>':''}<div class="studio-tabs" role="tablist" aria-label="Modellverwaltung">${[['discover','Entdecken'],['library','Bibliothek'],['downloads','Downloads'],['profiles','Profile'],...(['audio','stt'].includes(page)?[['setup','Einrichten']]:[]),...(['image','chat','audio','stt','music','voice'].includes(page)?[['test','Testen'],...(page==='chat'?[['auto','Auto-Test']]:[])]:[])].map(([id,label])=>`<button role="tab" aria-selected="${section===id}" class="${section===id?'chosen':'secondary'}" data-section="${id}">${label}</button>`).join('')}</div><div role="tabpanel">${section==='setup'?(page==='stt'?STTUI.html(true):TTSUI.html(true)):['test','running'].includes(section)&&page==='music'?MusicUI.html():['test','running'].includes(section)&&page==='stt'?STTUI.html():['test','running'].includes(section)&&page==='audio'?TTSUI.html():section==='test'&&page==='voice'?VoiceUI.html():section==='auto'?AutoTestUI.html():section==='test'?(page==='chat'?ChatTestUI.html():ImageTestUI.html()):section==='running'&&page==='image'?ImageTestUI.html(true):section==='profiles'?ProfilesUI.html():section==='running'&&page==='chat'?EndpointUI.runningHTML():section==='running'?'<section class="card"><h2>Keine von Deck gestarteten Modelle</h2><p>Profile werden auf Athena gespeichert. Für diesen Bereich ist noch kein Modellworker angebunden. Fehlende Komponenten stehen beim jeweiligen Profil.</p><a class="link" href="#runtime">llama.cpp-Builds verwalten →</a></section>':CatalogUI.html(section==='library',section==='downloads')}</div>`;
|
||||
const body=page==='omnivoice-runtime'?VoxCPMUI.html().replaceAll('VoxCPM2','OmniVoice').replaceAll('VoxCPM','OmniVoice'):page==='voxcpm-runtime'?VoxCPMUI.html():page==='stt-runtime'?STTUI.html(true):page==='tts-runtime'?TTSUI.html(true):['docker-runtime','services'].includes(page)?DockerUI.html(page==='services'):page==='runtimes'?runtimeOverview():page==='image-runtime'?imageRuntime():page==='runtime'?RuntimeUI.html():`<div class="kicker">ATHENA / MODELLVERWALTUNG</div><h1>${labels[page]}</h1><p>${audioDescriptions[page]||'Modelle entdecken, herunterladen und mit gespeicherten Profilen konfigurieren.'}</p>${page==='voice'?'<p><a class="link" href="#separator-runtime">Audio Separator einrichten →</a> · <a class="link" href="#separation">Audio-Trennung →</a></p><p class="note">Audio-Trennung nutzt die unterstützten Pakete im Audio-Separator-Bereich. Andere Hub-Dateien und Voice-Profile benötigen weiterhin eine geprüfte Anbindung.</p>':''}${audioDescriptions[page]&&!['audio','stt','music','voice','embeddings'].includes(page)?'<p class="note">Entdecken und Downloads sind verfügbar. Für diese Audio-Bereiche ist noch keine ausführbare Laufzeit in Deck angebunden. Gespeicherte Profile sind vorbereitend.</p>':''}<div class="studio-tabs" role="tablist" aria-label="Modellverwaltung">${[['discover','Entdecken'],['library','Bibliothek'],['downloads','Downloads'],['profiles','Profile'],...(['audio','stt'].includes(page)?[['setup','Einrichten']]:[]),...(['image','chat','audio','stt','music','voice'].includes(page)?[['test','Testen'],...(page==='chat'?[['auto','Auto-Test']]:[])]:[])].map(([id,label])=>`<button role="tab" aria-selected="${section===id}" class="${section===id?'chosen':'secondary'}" data-section="${id}">${label}</button>`).join('')}</div><div role="tabpanel">${section==='setup'?(page==='stt'?STTUI.html(true):TTSUI.html(true)):['test','running'].includes(section)&&page==='music'?MusicUI.html():['test','running'].includes(section)&&page==='stt'?STTUI.html():['test','running'].includes(section)&&page==='audio'?TTSUI.html():section==='test'&&page==='voice'?VoiceUI.html():section==='auto'?AutoTestUI.html():section==='test'?(page==='chat'?ChatTestUI.html():ImageTestUI.html()):section==='running'&&page==='image'?ImageTestUI.html(true):section==='profiles'?ProfilesUI.html():section==='running'&&page==='chat'?EndpointUI.runningHTML():section==='running'?'<section class="card"><h2>Keine von Deck gestarteten Modelle</h2><p>Profile werden auf Athena gespeichert. Für diesen Bereich ist noch kein Modellworker angebunden. Fehlende Komponenten stehen beim jeweiligen Profil.</p><a class="link" href="#runtime">llama.cpp-Builds verwalten →</a></section>':CatalogUI.html(section==='library',section==='downloads')}</div>`;
|
||||
document.querySelector('#view').innerHTML=`<div id="studio" data-page="${page}">${body}</div>`;
|
||||
if(['docker-runtime','services'].includes(page)){DockerUI.bind(page==='services');return;}
|
||||
if(page==='stt-runtime'){STTUI.bind(true);return;}
|
||||
if(page==='voice'&§ion==='test'){VoiceUI.bind();return;}
|
||||
if(page==='omnivoice-runtime'){VoxCPMUI.bind('/api/v1/omnivoice-runtime');return;}
|
||||
if(page==='voxcpm-runtime'){VoxCPMUI.bind();return;}
|
||||
if(page==='tts-runtime'){TTSUI.bind(true);return;}
|
||||
if(page==='runtime'){RuntimeUI.bind();return;}
|
||||
@@ -39,6 +40,7 @@ const Studio=(()=>{
|
||||
['LTX Original','Video','ltx-original-runtime','/api/v1/ltx-original-runtime','Originales LTX-Backend für LTX DeskWEB. Modelle und Zusatzdateien bleiben in der Bibliothek.'],
|
||||
['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.'],
|
||||
['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.']
|
||||
];
|
||||
const runtimeEscape=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||||
@@ -59,5 +61,6 @@ const Studio=(()=>{
|
||||
|
||||
function imageRuntime(){return `<div class="kicker">EINSTELLUNGEN / LAUFZEITEN</div><h1>Bildgenerierung</h1><section class="card"><h2>ComfyUI + ComfyUI-GGUF</h2><p>Eigene Bildlaufzeit für Qwen-Image-2.1 GGUF und das unterstützte FLUX.2-Klein-9B-Modell. Die Umgebung kann über den Deck-Installer mitgeliefert oder hier separat installiert werden. Modelle laden erst bei einem Testauftrag.</p><p>Textencoder läuft auf der RTX 3060, Diffusionsmodell und VAE auf der RTX 5080. Bei großen FLUX-Gewichten wird zusätzlich System-RAM genutzt. Beide GPUs müssen frei sein. Pro Test wird ein eigener Prozess gestartet und anschließend beendet.</p><div id="image-runtime-install"><p>Installationsstatus wird geprüft …</p></div><a class="link" href="#image">Bildgenerierung → Testen öffnen</a></section>${ImageTestUI.html(true)}`;}
|
||||
function openProfile(page,modelId){render(page,true,modelId);}
|
||||
return {render,openProfile};
|
||||
function openTest(page){category=page;section='test';render(page,true);}
|
||||
return {render,openProfile,openTest};
|
||||
})();
|
||||
@@ -79,6 +79,16 @@ class RestoreTests(unittest.TestCase):
|
||||
self.assertFalse(summary['blockers'])
|
||||
self.server.backup.start(dict(id=summary['id'],services=[],confirm=True,restore_credentials=False));job=self.wait()
|
||||
self.assertEqual(job['state'],'complete',job);runtime.start.assert_called_once()
|
||||
def test_omnivoice_runtime_roundtrip_and_restore(self):
|
||||
from omnivoice_runtime import VERSION
|
||||
runtime=Mock();runtime.job=None;runtime.status.return_value={'installed':True,'version':VERSION,'job':None}
|
||||
self.server.omnivoice_runtime=runtime;doc=self.server.backup.snapshot();validate(doc)
|
||||
self.assertTrue(doc['runtimes']['omnivoice']);self.assertEqual(doc['runtime_versions']['omnivoice'],VERSION)
|
||||
runtime.status.return_value={'installed':False,'version':VERSION,'job':{'state':'complete'}}
|
||||
summary=self.server.backup.inspect(seal(doc,'backup secure password'),'backup secure password')
|
||||
self.assertFalse(summary['blockers']);self.server.backup.start(dict(id=summary['id'],services=[],confirm=True,restore_credentials=False))
|
||||
self.assertEqual(self.wait()['state'],'complete');runtime.start.assert_called_once()
|
||||
|
||||
def test_separator_restore_installs_runtime_and_redownloads_package(self):
|
||||
from separator_runtime import MODELS
|
||||
doc=self.server.backup.snapshot();name=next(iter(MODELS));doc['runtimes']['separator']={'installed':True,'models':[name]}
|
||||
|
||||
@@ -61,6 +61,19 @@ class EndpointTests(unittest.TestCase):
|
||||
def request(self,path='/v1/models',data=None,token='A'*32):
|
||||
conn=http.client.HTTPConnection('127.0.0.1',self.port,timeout=5);headers={'Content-Type':'application/json','Authorization':'Bearer '+token}
|
||||
conn.request('POST' if data is not None else 'GET',path,body=json.dumps(data) if data is not None else None,headers=headers);r=conn.getresponse();body=r.read();conn.close();return r.status,(body if data and data.get('stream') else json.loads(body))
|
||||
def test_voice_profiles_are_exclusive_and_mode_rejects_other_work(self):
|
||||
for ident in ('vox','omni'):
|
||||
self.rows.append(dict(id=ident,name=ident,kind='voice',revision=1,updated_at=1,runnable=True,blockers=[],parameters={}))
|
||||
self.enable('vox');self.enable('omni')
|
||||
self.assertEqual([p['id'] for p in self.ep.rows() if p['kind']=='voice' and p['enabled']],['omni'])
|
||||
self.ep.scheduler.gpu_mode='voice'
|
||||
code,result=self.request('/v1/audio/speech/models');self.assertEqual(code,200)
|
||||
self.assertEqual([p['id'] for p in result['data']],['omni'])
|
||||
for path in ('/v1/chat/completions','/v1/images/generations','/v1/audio/music'):
|
||||
code,result=self.request(path,{});self.assertEqual(code,503);self.assertEqual(result['error']['code'],'voice_mode_active')
|
||||
release=self.ep.scheduler.image_reservation(kind='voice');release()
|
||||
with self.assertRaises(InferenceError):self.ep.scheduler.image_reservation(kind='image')
|
||||
|
||||
def test_api_identity_and_legacy_name_share_profile(self):
|
||||
self.rows[0].update(name='Qwen Medium',api_id='qwen-medium',api_aliases=['Old Name'])
|
||||
self.enable('alpha')
|
||||
|
||||
@@ -4,6 +4,11 @@ from profiles import QWEN_REPO,FLUX_REPO
|
||||
from tts_runtime import REPO,REVISION
|
||||
class ExecutionSetupTests(unittest.TestCase):
|
||||
def check(self,kind,repo,file,installed=None,**extra):return assess(dict(kind=kind,repo=repo,file=file,**extra),installed or {})
|
||||
def test_omnivoice_uses_own_runtime_and_audio_tokenizer_is_component(self):
|
||||
result=self.check('voice','k2-fsa/OmniVoice','model.safetensors',{'omnivoice':True})
|
||||
self.assertEqual(result['family'],'OmniVoice');self.assertEqual(result['candidates'][0]['id'],'omnivoice')
|
||||
self.assertTrue(result['candidates'][0]['installed'])
|
||||
self.assertEqual(self.check('voice','k2-fsa/OmniVoice','audio_tokenizer/model.safetensors')['state'],'component')
|
||||
def test_unknown_and_asr_not_llama(self):
|
||||
for kind in ['stt','music','voice','video','image','audio']:
|
||||
self.assertEqual(self.check(kind,'other/model','model.gguf')['state'],'unsupported')
|
||||
|
||||
@@ -25,6 +25,18 @@ class VideoComfyTests(unittest.TestCase):
|
||||
def test_ready_reuses_runtime_without_install(self):
|
||||
row=self.video.models()[0];self.assertTrue(row['runnable']);self.assertEqual(len(row['components']),4)
|
||||
self.video.select(self.model['id']);self.assertEqual(self.video.status()['selected'],self.model['id']);self.runtime.install.assert_not_called()
|
||||
def test_voice_switch_requires_ready_profile_and_drains_gpu_work(self):
|
||||
import threading
|
||||
from types import SimpleNamespace
|
||||
with self.assertRaisesRegex(ValueError,'Stimmprofil'):self.video.switch('voice')
|
||||
self.video.scheduler=SimpleNamespace(gpu_mode='llm',cv=threading.Condition(),active=0,tts_active=0,transition=False,key=('chat',))
|
||||
self.video._stop=Mock();self.video._start=Mock();self.video._foreign_services=lambda:[]
|
||||
self.video.voice_profiles=lambda:[dict(id='voice',name='VoxCPM2')]
|
||||
self.video.switch('voice');self.video.thread.join(2)
|
||||
self.assertEqual(self.video.scheduler.gpu_mode,'voice');self.assertEqual(self.video.state,'ready')
|
||||
self.video._start.assert_not_called();self.video.stop_owned.assert_called_once()
|
||||
self.video.switch('llm');self.video.thread.join(2);self.assertEqual(self.video.scheduler.gpu_mode,'llm')
|
||||
|
||||
def test_missing_component_is_not_ready(self):
|
||||
self.entries.pop();row=self.video.models()[0];self.assertFalse(row['runnable']);self.assertIn('Spatial',row['blockers'][0])
|
||||
def test_wrong_revision_is_not_silently_used(self):
|
||||
|
||||
+14
-1
@@ -3,6 +3,19 @@ from pathlib import Path
|
||||
from unittest.mock import Mock,patch
|
||||
from voxcpm_test import VoxCPMTests,validate_reference
|
||||
class VoiceTests(unittest.TestCase):
|
||||
def test_omnivoice_staging_preserves_audio_tokenizer_directory(self):
|
||||
from profiles import omni_recipe
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
root=Path(d);catalog=root/'catalog';catalog.mkdir();work=root/'job';work.mkdir()
|
||||
model=dict(id='main',kind='voice',repo='k2-fsa/OmniVoice',file='model.safetensors')
|
||||
entries={role:dict(id=role,file=info['files'][0]) for role,info in omni_recipe(model).items()}
|
||||
for entry in [model,*entries.values()]:
|
||||
directory=catalog/entry['id'];directory.mkdir();(directory/('model'+Path(entry['file']).suffix)).write_bytes(b'synthetic')
|
||||
profiles=Mock();profiles.catalog.root=catalog;profiles._component.side_effect=lambda model,role,ident:entries[role]
|
||||
t=VoxCPMTests(root,profiles,Mock());t.stage(dict(model=model,components={}),work)
|
||||
self.assertTrue((work/'model/model.safetensors').is_file());self.assertTrue((work/'model/audio_tokenizer/model.safetensors').is_file())
|
||||
self.assertNotEqual((work/'model/model.safetensors').resolve(),(work/'model/audio_tokenizer/model.safetensors').resolve())
|
||||
|
||||
def test_reference_limits(self):
|
||||
for data in (b'',b'not audio',b'x'*(8*1024**2+1)):
|
||||
with self.assertRaises(ValueError):validate_reference(data)
|
||||
@@ -43,7 +56,7 @@ class VoiceTests(unittest.TestCase):
|
||||
with wave.open(str(root/'result.wav'),'wb') as w:w.setnchannels(1);w.setsampwidth(2);w.setframerate(16000);w.writeframes(b'\0\0'*16000)
|
||||
process=Mock();process.poll.return_value=0;return process
|
||||
if outcome=='cancelled':t.cancel.set()
|
||||
with patch('voxcpm_test.subprocess.Popen',side_effect=launch):t._run_voice({},ident,dict(text='synthetic'),b'reference',{'uuid':'test'},release)
|
||||
with patch('voxcpm_test.subprocess.Popen',side_effect=launch):t._run_voice({'model':{'kind':'voice','repo':'openbmb/VoxCPM2','file':'model.safetensors'}},ident,dict(text='synthetic'),b'reference',{'uuid':'test'},release)
|
||||
self.assertEqual(t.job['state'],outcome);release.assert_called_once()
|
||||
self.assertFalse((root/'reference.wav').exists());self.assertFalse((root/'model').exists());self.assertFalse(t.status()['loaded'])
|
||||
self.assertEqual((root/'complete').exists(),outcome=='complete')
|
||||
+6
-4
@@ -55,11 +55,12 @@ class VideoComfy:
|
||||
self.state='failed';self.error='ComfyUI wurde unerwartet beendet. Auf LLM wechseln und Laufzeit erneut starten.'
|
||||
rows=self.models();ident=self.selection.get('model_id');row=next((x for x in rows if x['model']['id']==ident),None)
|
||||
service=dict(id=ident,name=row['model']['file'] if row else 'Kein Videomodell ausgewählt',running=running,ready=running and self.state=='ready',api_url='/ (ComfyUI auf dem gemeinsamen API-Port)',message='5080: Diffusion/VAE · 3060: Textencoder · große BF16-Gewichte nutzen CPU-Auslagerung.') if row else {}
|
||||
return dict(mode=self.scheduler.gpu_mode,state=self.state,error=self.error,target_mode=self.target_mode,switch_phase=self.switch_phase,switch_started_at=self.switch_started_at,service=service,music_profiles=getattr(self,'music_profiles',lambda:[])(),separator=getattr(self,'separator_status',lambda:{})(),services=[dict(id=x['model']['id'],name=x['model']['file'],api_url=x['label'],**{k:x[k] for k in ('blockers','runnable')}) for x in rows],models=rows,selected=ident,memory_policy='Gemeinsame ComfyUI-Installation. Video startet einen eigenen Prozess; Gewichte laden bei Workflow-Anfrage. Der Wechsel auf LLM beendet den Prozess.',runtime=self.runtime.status())
|
||||
return dict(mode=self.scheduler.gpu_mode,state=self.state,error=self.error,target_mode=self.target_mode,switch_phase=self.switch_phase,switch_started_at=self.switch_started_at,service=service,music_profiles=getattr(self,'music_profiles',lambda:[])(),voice_profiles=getattr(self,'voice_profiles',lambda:[])(),separator=getattr(self,'separator_status',lambda:{})(),services=[dict(id=x['model']['id'],name=x['model']['file'],api_url=x['label'],**{k:x[k] for k in ('blockers','runnable')}) for x in rows],models=rows,selected=ident,memory_policy='Gemeinsame ComfyUI-Installation. Video startet einen eigenen Prozess; Gewichte laden bei Workflow-Anfrage. Der Wechsel auf LLM beendet den Prozess.',runtime=self.runtime.status())
|
||||
def switch(self,mode):
|
||||
if mode not in ('llm','video','music','separator'):raise ValueError('Modus muss llm, video, music oder separator sein.')
|
||||
if mode not in ('llm','video','music','separator','voice'):raise ValueError('Modus muss llm, video, music, separator oder voice sein.')
|
||||
with self.lock:
|
||||
if self.state=='switching':raise ValueError('Moduswechsel läuft bereits.')
|
||||
if mode=='voice' and not getattr(self,'voice_profiles',lambda:[])():raise ValueError('Zuerst ein ausführbares Stimmprofil am API-Endpunkt freigeben.')
|
||||
if mode=='music' and not getattr(self,'music_profiles',lambda:[])():raise ValueError('Zuerst ein ausführbares Musikprofil am API-Endpunkt freigeben.')
|
||||
if mode=='separator' and not any(m['installed'] for m in getattr(self,'separator_status',lambda:{'models':[]})().get('models',[])):raise ValueError('Zuerst Audio-Separator-Laufzeit und ein Modellpaket einrichten.')
|
||||
if mode=='video':
|
||||
@@ -78,7 +79,7 @@ class VideoComfy:
|
||||
if time.monotonic()>deadline:raise ValueError('Deck-Aufträge noch aktiv.')
|
||||
self.scheduler.cv.wait(.2)
|
||||
self.scheduler.key=None
|
||||
if mode in ('llm','music','separator'):
|
||||
if mode in ('llm','music','separator','voice'):
|
||||
if any(x.get('running') is not False for x in self._foreign_services()):raise ValueError('Fremder Videodienst blockiert LLM-Modus.')
|
||||
self.foreign_blocked=False
|
||||
else:
|
||||
@@ -93,8 +94,9 @@ class VideoComfy:
|
||||
self.scheduler.key=None
|
||||
self.switch_phase='Freie GPUs prüfen';self._start()
|
||||
with self.scheduler.cv:self.scheduler.gpu_mode=mode;self.scheduler.cv.notify_all()
|
||||
self.state='ready' if mode in ('video','music','separator') else 'idle'
|
||||
self.state='ready' if mode in ('video','music','separator','voice') else 'idle'
|
||||
if mode=='separator':self.switch_phase='Audio-Trennung bereit · Gewichte laden bei Auftrag'
|
||||
if mode=='voice':self.switch_phase='Stimmwerkzeuge bereit · Gewichte laden beim Auftrag'
|
||||
if mode=='music':self.switch_phase='Musik bereit · Gewichte laden bei Anfrage'
|
||||
except Exception as exc:
|
||||
self._stop();self.error=str(exc);self.state='failed'
|
||||
|
||||
+3
-3
@@ -1,10 +1,10 @@
|
||||
window.VoiceUI=(()=>{
|
||||
const e=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||||
function html(){return `<section id="voice-panel" class="card"><h2>Stimme ausprobieren · VoxCPM2</h2><p>Text erzeugt Sprache. Mit optionaler WAV-Referenz übernimmt VoxCPM2 deren Stimme. Nur eingerichtete VoxCPM2-Profile stehen zur Auswahl.</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, PCM-16-WAV, 1–30 Sekunden, bis 8 MiB)<input name="file" type="file" accept="audio/wav,.wav"></label><div class="form-grid"><label>GPU<select name="device"><option value="5080">RTX 5080</option><option value="3060">RTX 3060</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-Modus verfügbar. Deck entlädt sein LLM vor der Stimmgenerierung und lädt es bei der nächsten Chat-Anfrage wieder. VoxCPM2 wird nach dem Auftrag 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 das Referenztranskript.</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, PCM-16-WAV, 1–30 Sekunden, bis 8 MiB)<input name="file" type="file" accept="audio/wav,.wav"></label><label>Transkript der Referenz (für OmniVoice erforderlich)<textarea name="reference_text" maxlength="1000"></textarea></label><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 wird nach dem Auftrag 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||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);}}
|
||||
fetch('/api/v1/profiles').then(async r=>{if(!r.ok)throw Error('Profile konnten nicht geladen werden.');return r.json();}).then(d=>{if(!root.isConnected)return;const rows=d.profiles.filter(p=>p.runnable&&p.model?.repo==='openbmb/VoxCPM2');ready=!!rows.length;el('voice-profile').innerHTML=rows.map(p=>`<option value="${e(p.id)}">${e(p.name)}</option>`).join('')||'<option value="">VoxCPM2-Profil unter Profile → Einrichtung & Komponenten vervollständigen</option>';}).catch(err=>{if(root.isConnected)el('voice-error').textContent=err.message;});
|
||||
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);}}
|
||||
fetch('/api/v1/profiles').then(async r=>{if(!r.ok)throw Error('Profile konnten nicht geladen werden.');return r.json();}).then(d=>{if(!root.isConnected)return;const rows=d.profiles.filter(p=>p.runnable&&['openbmb/VoxCPM2','k2-fsa/OmniVoice'].includes(p.model?.repo));ready=!!rows.length;el('voice-profile').onchange=()=>{const omni=rows.find(p=>p.id===el('voice-profile').value)?.model.repo==='k2-fsa/OmniVoice';root.querySelector('[name=steps]').value=omni?32:10;root.querySelector('[name=steps]').max=omni?64:50;root.querySelector('[name=cfg]').min=omni?0:.5;};el('voice-profile').innerHTML=rows.map(p=>`<option value="${e(p.id)}">${e(p.name)}</option>`).join('')||'<option value="">Stimmprofil unter Profile → Einrichtung & Komponenten vervollständigen</option>';if(rows.length)el('voice-profile').onchange();}).catch(err=>{if(root.isConnected)el('voice-error').textContent=err.message;});
|
||||
el('voice-form').onsubmit=async event=>{event.preventDefault();busy=true;el('voice-start').disabled=true;el('voice-error').textContent='';el('voice-status').textContent='Auftrag wird gestartet …';try{const data=new FormData(event.target);if(!data.get('file')?.size)data.delete('file');await api('/start',data);}catch(err){el('voice-error').textContent=err.message;}finally{busy=false;}};
|
||||
el('voice-cancel').onclick=async()=>{try{await api('/cancel',{});}catch(err){el('voice-error').textContent=err.message;}};refresh();
|
||||
}
|
||||
|
||||
+2
-2
@@ -1,8 +1,8 @@
|
||||
const VoxCPMUI=(()=>{
|
||||
const e=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||||
function html(){return `<div class="kicker">EINSTELLUNGEN / LAUFZEITEN</div><h1>VoxCPM</h1><section class="card" id="voxcpm-panel"><h2>VoxCPM2 einrichten</h2><p>Diese Modellfamilie benötigt die originale VoxCPM-Python-Laufzeit. Eine eigene Umgebung schützt bestehende Laufzeiten; vorhandene CUDA-Pakete werden nach Möglichkeit wiederverwendet.</p><p id="voxcpm-status" role="status">Status wird geprüft …</p><p id="voxcpm-details"></p><progress id="voxcpm-progress" hidden aria-label="Laufzeitinstallation"></progress><div class="card-actions"><button id="voxcpm-install">Passende Laufzeit installieren</button><button id="voxcpm-cancel" class="secondary" disabled>Installation abbrechen</button></div><p class="note">Dieser Schritt installiert die Laufzeit. Er lädt keine Modellgewichte und startet kein Modell. Nach Zuordnung der Modellkomponenten unter Stimmwerkzeuge → Testen Sprache erzeugen oder eine Referenzstimme verwenden.</p><details><summary>Installationsausgabe</summary><button id="voxcpm-log" class="secondary">Ausgabe aktualisieren</button><pre id="voxcpm-output" style="white-space:pre-wrap"></pre></details><p id="voxcpm-error" role="alert"></p><a class="link" href="#voice">Zurück zu Stimmwerkzeugen →</a></section>`;}
|
||||
function bind(){const root=document.querySelector('#voxcpm-panel');if(!root)return;const el=id=>root.querySelector('#'+id);let busy=false;
|
||||
async function api(path='',body){const r=await fetch('/api/v1/voxcpm-runtime'+path,body===undefined?{}:{method:'POST',headers:{'Content-Type':'application/json','X-Athena-Deck':'1'},body:JSON.stringify(body)});const d=await r.json();if(!r.ok)throw Error(d.error||'Einrichtung fehlgeschlagen');return d;}
|
||||
function bind(base="/api/v1/voxcpm-runtime"){const root=document.querySelector('#voxcpm-panel');if(!root)return;const el=id=>root.querySelector('#'+id);let busy=false;
|
||||
async function api(path='',body){const r=await fetch(base+path,body===undefined?{}:{method:'POST',headers:{'Content-Type':'application/json','X-Athena-Deck':'1'},body:JSON.stringify(body)});const d=await r.json();if(!r.ok)throw Error(d.error||'Einrichtung fehlgeschlagen');return d;}
|
||||
async function refresh(){try{const d=await api();if(!root.isConnected)return;el('voxcpm-status').textContent=d.job?.phase||(d.installed?'VoxCPM-Laufzeit installiert.':'Passende VoxCPM-Laufzeit fehlt.');el('voxcpm-details').textContent=`Version ${d.version} · mindestens ${d.required_disk_gib} GiB freier Speicher · ${d.shared_cuda?'CUDA-Pakete können wiederverwendet werden':'CUDA-Pakete werden mitinstalliert'}`;el('voxcpm-progress').hidden=d.job?.state!=='running';el('voxcpm-install').disabled=busy||d.installed||d.job?.state==='running';el('voxcpm-cancel').disabled=busy||d.job?.state!=='running';}catch(err){if(root.isConnected)el('voxcpm-error').textContent=err.message;}finally{if(root.isConnected)setTimeout(refresh,2000);}}
|
||||
async function action(path){busy=true;el('voxcpm-install').disabled=true;el('voxcpm-error').textContent='';try{await api(path,{});}catch(err){el('voxcpm-error').textContent=err.message;}finally{busy=false;}}
|
||||
el('voxcpm-install').onclick=()=>action('/install');el('voxcpm-cancel').onclick=()=>action('/cancel');el('voxcpm-log').onclick=async()=>{try{const d=await api('/log');el('voxcpm-output').textContent=d.text;}catch(err){el('voxcpm-error').textContent=err.message;}};refresh();
|
||||
|
||||
+20
-13
@@ -3,7 +3,7 @@ import io,json,os,shutil,signal,subprocess,threading,time,uuid,wave
|
||||
from pathlib import Path
|
||||
from tts_test import TTSTests
|
||||
from image_test import probe,cgroup_headroom
|
||||
from profiles import voice_recipe
|
||||
from profiles import voice_recipe,omni_recipe
|
||||
WORKER=Path(__file__).with_name('voxcpm_worker.py')
|
||||
|
||||
def validate_reference(audio):
|
||||
@@ -14,10 +14,11 @@ def validate_reference(audio):
|
||||
except (wave.Error,EOFError):raise ValueError('Ungültige WAV-Datei. PCM-16-WAV verwenden.') from None
|
||||
|
||||
class VoxCPMTests(TTSTests):
|
||||
def runtime_for(self,p):return self.omni_runtime if omni_recipe(p['model']) else self.runtime
|
||||
def blockers(self,p):
|
||||
if not voice_recipe(p['model']):return ['Diese Stimm-Modellfamilie wird noch nicht unterstützt.']
|
||||
errors=[]
|
||||
if not self.runtime.status()['installed']:errors.append('VoxCPM-Laufzeit unter Laufzeiten → VoxCPM installieren.')
|
||||
if not self.runtime_for(p).status()['installed']:errors.append(('OmniVoice' if omni_recipe(p['model']) else 'VoxCPM')+'-Laufzeit unter Laufzeiten installieren.')
|
||||
for role,info in voice_recipe(p['model']).items():
|
||||
try:self.profiles._component(p['model'],role,p.get('components',{}).get(role))
|
||||
except ValueError:errors.append(info['label']+' fehlt oder ist noch nicht zugeordnet. Unter Einrichtung & Komponenten ergänzen.')
|
||||
@@ -26,14 +27,20 @@ class VoxCPMTests(TTSTests):
|
||||
model=root/'model';model.mkdir();entries=[p['model']]+[self.profiles._component(p['model'],r,p.get('components',{}).get(r)) for r in voice_recipe(p['model'])]
|
||||
for entry in entries:
|
||||
src=self.profiles.catalog.root/entry['id']/('model'+Path(entry['file']).suffix)
|
||||
(model/Path(entry['file']).name).symlink_to(src.resolve())
|
||||
def start(self,profile_id,text,device='5080',cfg=2.0,steps=10,seed=42,reference=None,wait=False):
|
||||
target=model/entry['file'];target.parent.mkdir(parents=True,exist_ok=True);target.symlink_to(src.resolve())
|
||||
def start(self,profile_id,text,device='5080',cfg=2.0,steps=10,seed=42,reference=None,wait=False,reference_text='',language='',instruct='',speed=1.0,duration=0.0,denoise=True,preprocess_prompt=True,postprocess_output=True):
|
||||
if not isinstance(text,str) or not 1<=len(text.strip())<=1000:raise ValueError('Text mit 1–1000 Zeichen erforderlich.')
|
||||
if device not in ('5080','3060'):raise ValueError('RTX 5080 oder RTX 3060 wählen.')
|
||||
if type(cfg) not in (int,float) or not .5<=cfg<=5 or type(steps)!=int or not 1<=steps<=50 or type(seed)!=int or not 0<=seed<=2147483647:raise ValueError('Ungültige Guidance, Schritte oder Seed.')
|
||||
if type(cfg) not in (int,float) or not 0<=cfg<=5 or type(steps)!=int or not 1<=steps<=64 or type(seed)!=int or not 0<=seed<=2147483647:raise ValueError('Ungültige Guidance, Schritte oder Seed.')
|
||||
if reference is not None:validate_reference(reference)
|
||||
p=next((p for p in self.profiles.status()['profiles'] if p['id']==profile_id),None)
|
||||
if not p or not p['model'] or not voice_recipe(p['model']):raise ValueError('VoxCPM2-Profil nicht gefunden.')
|
||||
if not p or not p['model'] or not voice_recipe(p['model']):raise ValueError('Stimmprofil nicht gefunden.')
|
||||
if not omni_recipe(p['model']) and (cfg<.5 or steps>50):raise ValueError('VoxCPM2: Guidance 0,5–5 und Schritte 1–50 verwenden.')
|
||||
for value in (reference_text,language,instruct):
|
||||
if not isinstance(value,str) or len(value)>1000:raise ValueError('Ungültige Stimmoption.')
|
||||
if type(speed) not in (int,float) or not .5<=speed<=2 or type(duration) not in (int,float) or not 0<=duration<=60:raise ValueError('Ungültige Geschwindigkeit oder Dauer.')
|
||||
if any(type(v) is not bool for v in (denoise,preprocess_prompt,postprocess_output)):raise ValueError('Ungültige Audio-Vorverarbeitung.')
|
||||
if omni_recipe(p['model']) and reference is not None and not reference_text.strip():raise ValueError('OmniVoice: Transkript der Referenzstimme eingeben. ASR wird nicht automatisch heruntergeladen.')
|
||||
errors=self.blockers(p)
|
||||
if errors:raise ValueError(' '.join(errors))
|
||||
# Claim local job before scheduler admission to prevent races between two callers.
|
||||
@@ -48,30 +55,30 @@ class VoxCPMTests(TTSTests):
|
||||
headroom=cgroup_headroom()
|
||||
if headroom is not None and headroom<8*1024**3:raise ValueError('Mindestens 8 GiB freier Deck-Systemspeicher erforderlich.')
|
||||
self.root.mkdir(parents=True,exist_ok=True,mode=0o700)
|
||||
self.job.update(phase='VoxCPM2 wird geladen',gpu=gpu['name']);self.gpu_uuid=gpu['uuid']
|
||||
threading.Thread(target=self._run_voice,args=(p,ident,dict(text=text,cfg=cfg,steps=steps,seed=seed),reference,gpu,release),daemon=True).start();return dict(self.job)
|
||||
self.job.update(phase=('OmniVoice' if omni_recipe(p['model']) else 'VoxCPM2')+' wird geladen',gpu=gpu['name']);self.gpu_uuid=gpu['uuid']
|
||||
threading.Thread(target=self._run_voice,args=(p,ident,dict(text=text,cfg=cfg,steps=steps,seed=seed,**(dict(reference_text=reference_text,language=language,instruct=instruct,speed=speed,duration=duration,denoise=denoise,preprocess_prompt=preprocess_prompt,postprocess_output=postprocess_output) if omni_recipe(p['model']) else {})),reference,gpu,release),daemon=True).start();return dict(self.job)
|
||||
except Exception as exc:
|
||||
if release:release()
|
||||
with self.lock:self.job.update(state='failed',phase=str(exc),finished_at=time.time())
|
||||
raise
|
||||
def _run_voice(self,p,ident,request,reference,gpu,release):
|
||||
root=self.root/ident;state='failed';phase='VoxCPM2-Ausführung fehlgeschlagen'
|
||||
root=self.root/ident;state='failed';phase='Stimm-Ausführung fehlgeschlagen'
|
||||
try:
|
||||
root.mkdir(mode=0o700);self.stage(p,root)
|
||||
if reference is not None:(root/'reference.wav').write_bytes(reference)
|
||||
env={k:v for k,v in os.environ.items() if not k.startswith(('HF_','LLAMA_','DECK_'))};env.update(CUDA_VISIBLE_DEVICES=gpu['uuid'],HF_HUB_OFFLINE='1',TRANSFORMERS_OFFLINE='1',OMP_NUM_THREADS='4',HOME=str(root))
|
||||
with self.lock:
|
||||
if self.cancel.is_set():raise InterruptedError()
|
||||
self.process=subprocess.Popen([str(self.runtime.paths()[0]),str(WORKER),str(root)],stdin=subprocess.PIPE,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,env=env,start_new_session=True,text=True)
|
||||
self.process=subprocess.Popen([str(self.runtime_for(p).paths()[0]),str(Path(__file__).with_name('omnivoice_worker.py') if omni_recipe(p['model']) else WORKER),str(root)],stdin=subprocess.PIPE,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,env=env,start_new_session=True,text=True)
|
||||
process=self.process
|
||||
process.stdin.write(json.dumps(request));process.stdin.close();process.stdin=None;deadline=time.monotonic()+600
|
||||
while process.poll() is None:
|
||||
if self.cancel.wait(.25):raise InterruptedError()
|
||||
if time.monotonic()>deadline:raise ValueError('Zeitlimit für VoxCPM2 erreicht.')
|
||||
if time.monotonic()>deadline:raise ValueError('Zeitlimit für Stimmgenerierung erreicht.')
|
||||
if (root/'phase').exists():
|
||||
with self.lock:self.job['phase']=(root/'phase').read_text()
|
||||
if self.cancel.is_set():raise InterruptedError()
|
||||
if not (root/'result.json').exists():raise ValueError('VoxCPM2-Worker beendet ohne Ergebnis. Speicher oder Laufzeit prüfen.')
|
||||
if not (root/'result.json').exists():raise ValueError('Stimmworker beendet ohne Ergebnis. Speicher oder Laufzeit prüfen.')
|
||||
result=json.loads((root/'result.json').read_text())
|
||||
if not result['ok']:raise ValueError(result['error'])
|
||||
output=root/'result.wav'
|
||||
@@ -82,7 +89,7 @@ class VoxCPMTests(TTSTests):
|
||||
except InterruptedError:state='cancelled';phase='Stimmgenerierung abgebrochen · Modell entladen'
|
||||
except Exception as exc:
|
||||
if self.cancel.is_set():state='cancelled';phase='Stimmgenerierung abgebrochen · Modell entladen'
|
||||
else:phase=str(exc) if isinstance(exc,ValueError) else 'VoxCPM2-Ausführung fehlgeschlagen ('+type(exc).__name__+').'
|
||||
else:phase=str(exc) if isinstance(exc,ValueError) else 'Stimm-Ausführung fehlgeschlagen ('+type(exc).__name__+').'
|
||||
finally:
|
||||
self.unload_idle();shutil.rmtree(root/'model',ignore_errors=True)
|
||||
for name in ('reference.wav','phase'):(root/name).unlink(missing_ok=True)
|
||||
|
||||
Reference in new issue
Block a user