Prepare CPU Parakeet Redux and interchangeable STT endpoint
This commit is contained in:
1 parent
d28dce4476
commit
81cc316ebe
15 files changed
+349
-14
No files matched your search
+4
-1
@@ -65,10 +65,13 @@ class AudioPolicy:
|
||||
else:self.errors.pop(kind,None)
|
||||
continue
|
||||
ident=rows[0]['id']
|
||||
if kind=='stt' and item['mode']=='warm':
|
||||
rows=[p for p in self.endpoint.rows() if p['kind']=='stt' and p['enabled'] and p['runnable']]
|
||||
if len(rows)==1:ident=rows[0]['id']
|
||||
with worker.lock:
|
||||
if worker.warming or worker.job and worker.job.get('state')=='running':continue
|
||||
loaded=bool(worker.process and worker.process.poll() is None)
|
||||
if loaded and (not automatic or getattr(worker,'profile_id',None)==ident):continue
|
||||
if loaded and ((not automatic and kind!='stt') or getattr(worker,'profile_id',ident)==ident):continue
|
||||
if loaded:worker.unload_idle()
|
||||
with self.lock:
|
||||
retry_key=(kind,ident)
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@ import urllib.request
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
LABEL = 'de.casaderoll.athena-deck.standalone'
|
||||
FILES = ['deploy/install_strata_vision.py','assets/tts-presets/bundle.safetensors','assets/tts-presets/bundle.json','deploy/applio-requirements.lock','deploy/activate_applio.py','deploy/import_applio.py','deploy/backup_applio_data.py','applio.py','applio_runtime.py','applio_worker.py','applio-ui.js','deploy/activate_acestep.py','acestep_models.py','deploy/import_acestep.py','deploy/acestep-web/Dockerfile','deploy/acestep-web/app.py','deploy/acestep-web/index.html','acestep.py','acestep_worker.py','acestep_runtime.py','acestep-ui.js','deploy/acestep-requirements.lock','deploy/omnivoice-requirements.lock','omnivoice_runtime.py','omnivoice_worker.py','deploy/voice-web/Dockerfile','deploy/voice-web/base.Dockerfile','deploy/voice-web/bridge.py','deploy/patch_yue2_residency.py','embeddings.py','voxcpm_test.py','voxcpm_worker.py','qwen_clone_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/hosts.py','network/policy.py','network/rpc.py','deploy/Dockerfile','deploy/image-requirements.lock']
|
||||
FILES = ['deploy/install_strata_vision.py','assets/tts-presets/bundle.safetensors','assets/tts-presets/bundle.json','deploy/applio-requirements.lock','deploy/activate_applio.py','deploy/import_applio.py','deploy/backup_applio_data.py','applio.py','applio_runtime.py','applio_worker.py','applio-ui.js','deploy/activate_acestep.py','acestep_models.py','deploy/import_acestep.py','deploy/acestep-web/Dockerfile','deploy/acestep-web/app.py','deploy/acestep-web/index.html','acestep.py','acestep_worker.py','acestep_runtime.py','acestep-ui.js','deploy/acestep-requirements.lock','deploy/omnivoice-requirements.lock','omnivoice_runtime.py','omnivoice_worker.py','deploy/voice-web/Dockerfile','deploy/voice-web/base.Dockerfile','deploy/voice-web/bridge.py','deploy/patch_yue2_residency.py','embeddings.py','voxcpm_test.py','voxcpm_worker.py','qwen_clone_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','parakeet_runtime.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/hosts.py','network/policy.py','network/rpc.py','deploy/Dockerfile','deploy/image-requirements.lock']
|
||||
|
||||
|
||||
FILES += ['soulx_singer.py','soulx_singer_runtime.py','soulx-singer-ui.js','deploy/prepare_soulx_singer.py']
|
||||
|
||||
+11
-2
@@ -95,6 +95,9 @@ class Endpoint:
|
||||
row=next((p for p in rows if p['id']==data['id']),None)
|
||||
if not row:raise ValueError('Profil nicht gefunden.')
|
||||
if data['enabled'] and not row['runnable']:raise ValueError('Profil nicht ausführbar: '+' '.join(row['blockers']))
|
||||
if row['kind']=='stt' and self.stt:
|
||||
job=self.stt.status().get('job') or {}
|
||||
if job.get('state')=='running':raise ValueError('STT-Auftrag läuft. Erst abschließen oder abbrechen, dann Profil wechseln.')
|
||||
if row['kind']=='voice' and getattr(self,'applio',None):self.applio.unload_idle()
|
||||
if row['kind']=='voice' and getattr(self,'xvc',None):self.xvc.unload_idle()
|
||||
if row['kind']=='voice' and getattr(self,'soulx_singer',None):self.soulx_singer.unload_idle()
|
||||
@@ -104,7 +107,7 @@ class Endpoint:
|
||||
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'] in ('image','voice'):enabled.difference_update(p['id'] for p in rows if p['kind']==row['kind'])
|
||||
if row['kind'] in ('image','voice','stt'):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()
|
||||
@@ -165,7 +168,13 @@ class Endpoint:
|
||||
return bool(record and record.get('api_token_hash') and secrets.compare_digest(hashlib.sha256(header[7:].encode()).hexdigest(),record['api_token_hash']))
|
||||
def find_profile(self,name,kind):
|
||||
if not isinstance(name,str):raise APIError('model muss den API-Namen eines aktivierten Profils enthalten.')
|
||||
row=next((p for p in self.rows() if (name in [p.get('api_id',p['name']),p['name'],*p.get('api_aliases',[])] or (kind=='image' and name=='athena-image')) and p['kind']==kind and p['enabled']),None)
|
||||
rows=self.rows()
|
||||
row=next((p for p in rows if (name in [p.get('api_id',p['name']),p['name'],*p.get('api_aliases',[])] or (kind=='image' and name=='athena-image')) and p['kind']==kind and p['enabled']),None)
|
||||
if kind=='stt' and row is None:
|
||||
known=name in ('athena-stt','deck-stt','whisper-1') or any(name in [p.get('api_id',p['name']),p['name'],*p.get('api_aliases',[])] for p in rows if p['kind']=='stt')
|
||||
active=[p for p in rows if p['kind']=='stt' and p['enabled']]
|
||||
if known and len(active)==1:row=active[0]
|
||||
elif known and len(active)>1:raise APIError('Mehrere STT-Profile aktiv. Genau eines in Deck bereitstellen.',409,'ambiguous_stt_profile')
|
||||
if not row:raise APIError('Modellprofil nicht aktiviert oder unbekannt.',404,'model_not_found')
|
||||
if not row['runnable']:raise APIError('Profil derzeit nicht ausführbar: '+' '.join(row['blockers']),503,'model_unavailable')
|
||||
return row
|
||||
|
||||
@@ -3,6 +3,7 @@ from catalog import file_role
|
||||
from stt import supported as stt_supported
|
||||
from profiles import image_recipe, image_adapter, video_recipe, voice_recipe, omni_recipe, acestep_recipe, qwen_clone_model
|
||||
from tts_runtime import REPO, REVISION
|
||||
from parakeet_runtime import supported as redux_supported
|
||||
|
||||
def _assess(model, installed, profile=None):
|
||||
kind=model.get('kind'); filename=model.get('file',''); repo=model.get('repo','')
|
||||
@@ -29,6 +30,10 @@ def _assess(model, installed, profile=None):
|
||||
result.update(family='Qwen1.7B Base Stimmklonen',evidence='Vorhandenes Base-Modell mit Speaker-Encoder',runtime='Qwen-TTS · gemeinsame native TTS-Laufzeit',route='#voice',installed=bool(installed.get('audio')),state='ready' if installed.get('audio') else 'setup',label='Qwen-Stimmklonen',message='Referenzaufnahme und Zieltext unter Stimmwerkzeuge → Testen. Bestehende 1.7B-Base-Gewichte und Sprach-Tokenizer werden wiederverwendet; kein zusätzlicher Modelldownload.')
|
||||
if profile:result.update(state='ready' if profile.get('runnable') else 'profile_incomplete',blockers=profile.get('blockers',[]))
|
||||
return result
|
||||
if kind=='stt' and redux_supported(model):
|
||||
result.update(family='Parakeet Redux',runtime='parakeet.cpp · CPU/AVX2',route='#stt-runtime',installed=bool(installed.get('parakeet')),state='ready' if installed.get('parakeet') else 'setup',label='Parakeet Redux CPU',components=[],message='Gepacktes ternäres Redux-GGUF. Kein Audio-Projektor. Derselbe STT-Endpunkt; Profil in Deck freigeben. Vorbereitung startet keine Transkription.')
|
||||
if profile:result.update(state='ready' if profile.get('runnable') else 'profile_incomplete',blockers=profile.get('blockers',[]))
|
||||
return result
|
||||
if kind=='embeddings':
|
||||
from embeddings import supported
|
||||
if supported(model):
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
# Parakeet Redux — preparation on Athena, 2026-10-13
|
||||
|
||||
**Prepared only. No transcription test, app activation/restart, endpoint publication,
|
||||
service launch or change to running Qwen/Strata/audio policies.**
|
||||
|
||||
## Files and runtime
|
||||
|
||||
Public model: `mudler/parakeet-cpp-gguf/redux-packed.gguf`, revision
|
||||
`741158ae71e64ef5c89385862c18f777d07a97a1`,213319296 bytes,SHA256
|
||||
`574614b9a4d9f72ab202877a7ad6a1f4bf819dd1d27b9d42dfe8cd429fcebdd5`.
|
||||
This is the packed ternary Redux conversion, NOT the expanded f16 or q8 model.
|
||||
Original model credit: Moondream and NVIDIA, CC-BY-4.0.
|
||||
|
||||
Runtime: official CPU-x64 parakeet.cpp v0.6.1 (commit
|
||||
`5c9b0fbbd8e611d88e47d7e1ebae9bca9b447e8f`), archive SHA256
|
||||
`cce60d122ab72e1068cd0d164e54a21655a0b83f1b9c21befc20124f5a972c10`.
|
||||
Native binaries; no extra container, compiler, Python ML packages or CUDA runtime.
|
||||
`prepare.py` pins URLs and verifies both digests, rejects unsafe archive paths/links,
|
||||
extracts only into the dedicated runtime root. CLI/server help executed successfully
|
||||
on Athena (help returns2 by design); no model loaded or inference performed.
|
||||
|
||||
Paths:
|
||||
- `/opt/athena-deck-dev/runtime/state/parakeet-runtime/v0.6.1`: CPU binaries/model/manifest.
|
||||
- `/opt/athena-deck-dev/parakeet-prepared-20261013`: staged Deck source/build/activation script.
|
||||
- `/opt/athena-deck-dev/runtime/state/parakeet-comparison-prepared`: Go-guarded test script,
|
||||
two explicitly listed previously generated synthetic WAVs and expected text.
|
||||
- Prepared image `athena-deck-standalone:parakeet-prepared-20261013`; not running.
|
||||
|
||||
The runtime and weights are inside the existing managed state mount. Only the new
|
||||
parakeet-runtime root is writable by Deck UID65534, so future catalogue registration
|
||||
can store its marker; pinned version files are readable/executable. Other paths unchanged.
|
||||
|
||||
## Go test, independently of the app update
|
||||
|
||||
Run only after the user asks to start the test:
|
||||
|
||||
```sh
|
||||
docker exec athena-deck-dev python3 \
|
||||
/var/lib/deck/parakeet-comparison-prepared/compare.py --go \
|
||||
--cases /var/lib/deck/parakeet-comparison-prepared/cases/cases.json \
|
||||
--output /var/lib/deck/parakeet-comparison-prepared/results
|
||||
```
|
||||
|
||||
Uses existing installed Qwen3-ASR0.6B-Q8 model/projector/active llama-server,
|
||||
and the prepared packed Redux model. Each backend launches temporarily on a random
|
||||
loopback port with2CPU threads; GPU visibility disabled. Backends run sequentially,
|
||||
then their own process groups are stopped. Production workers/config remain untouched.
|
||||
Checks startup and transcribes each identical synthetic file twice. Records startup,
|
||||
processing/audio duration,RTF and simple case/punctuation-normalized WER, plus the
|
||||
synthetic transcripts in its own results file. No private inputs/logs or library scans.
|
||||
A live user's voice/noisy recordings are not part of this initial test; synthetic
|
||||
samples cannot establish real German accuracy or superiority. Testing temporarily
|
||||
uses additional CPU/RAM and can compete with production CPU work, even without restarts.
|
||||
|
||||
## Stable Deck endpoint, prepared implementation
|
||||
|
||||
After a separate activation in an idle maintenance window:
|
||||
|
||||
```sh
|
||||
python3 /opt/athena-deck-dev/parakeet-prepared-20261013/activate-prepared.py --activate
|
||||
```
|
||||
|
||||
Uses existing manifest/installer and preserves mounts, credentials, API ports,
|
||||
profiles and audio policy. It does restart the Deck app, so do not execute while
|
||||
user work runs. First startup registers a symlinked STT catalogue entry and the
|
||||
**Parakeet Redux CPU** profile once, without publishing it. Existing Qwen stays selected.
|
||||
|
||||
Later: publish exactly one STT profile in Deck. Enabling a different STT profile
|
||||
unchecks the former one; active STT jobs block switching. `/v1/audio/transcriptions`,
|
||||
API base URL and token stay identical. `athena-stt`, `deck-stt`, `whisper-1`, plus
|
||||
names/API IDs belonging to existing disabled STT profiles route to the sole published
|
||||
STT profile, retaining current client configuration. Unknown names still fail; no
|
||||
published profile fails; ambiguous older configs fail explicitly. Chat/other model
|
||||
routing is unchanged. Native Parakeet requests are serialized and loopback-only
|
||||
behind Deck authentication; Qwen and Redux use distinct model/backend residency keys.
|
||||
Warm STT follows the currently published profile instead of silently reloading the
|
||||
old Qwen policy target. Running jobs are never evicted by warm reconciliation.
|
||||
|
||||
No silent inference fallback from Redux to Qwen: report the real backend error.
|
||||
Parakeet server accepts WAV and returns JSON text, which matches Deck's existing
|
||||
normalization and response. Its verbose_json language is an `en` placeholder and
|
||||
its language hint is not a forced language selector; Deck exposes only the existing
|
||||
text result. Word timestamps/live previews are NOT part of this initial adapter.
|
||||
The same existing120-second upload and4-GiB admission limits are retained initially;
|
||||
preparation does not claim a measured RAM minimum or change unrelated limits.
|
||||
|
||||
## Verification / restore
|
||||
|
||||
35 targeted tests passed. They cover fixed revision, no false installed state, old client-name routing,
|
||||
unknown/ambiguous/disabled routes, and warm profile switching without active-job eviction.
|
||||
Existing STT/audio-policy/execution mapping tests run too. A broad historical endpoint
|
||||
suite has pre-existing chat-forwarding failures (one reproduced against unchanged HEAD);
|
||||
those are not ASR/model test results. No measured performance/accuracy claims yet.
|
||||
|
||||
Native restore: from Git run `prepare.py --root <state>/parakeet-runtime/v0.6.1`,
|
||||
ensure the server's native account can write `<state>/parakeet-runtime` and its catalogue,
|
||||
then use the packaged server/modules. `deploy/install.py` includes parakeet_runtime.py.
|
||||
Existing profile/catalogue/endpoint/audio-policy state is part of encrypted restore.
|
||||
Public weights/runtime are reproducible from pinned URLs/digests; no secrets, weights
|
||||
or private audio committed. Fresh-host restore has not been tested.
|
||||
|
||||
Official sources:
|
||||
- https://github.com/mudler/parakeet.cpp/releases/tag/v0.6.1
|
||||
- https://github.com/mudler/parakeet.cpp/blob/v0.6.1/examples/server/README.md
|
||||
- https://github.com/mudler/parakeet.cpp/blob/v0.6.1/docs/ultra-redux.md
|
||||
- https://huggingface.co/moondream/parakeet-redux
|
||||
@@ -0,0 +1,12 @@
|
||||
"""Activate only after an explicit separate --activate request in an idle window."""
|
||||
import argparse,importlib.util,json,pathlib,subprocess,urllib.request
|
||||
p=argparse.ArgumentParser();p.add_argument('--activate',action='store_true');a=p.parse_args()
|
||||
if not a.activate:raise SystemExit('Prepared only. No services changed.')
|
||||
root=pathlib.Path('/opt/athena-deck-dev/parakeet-prepared-20261013')
|
||||
item=json.loads(subprocess.check_output(['docker','inspect','athena-voxcpm2-web']))[0]
|
||||
f=next(pathlib.Path(m['Source']) for m in item['Mounts'] if m['Destination']=='/data');key=json.loads((f/'deck-connection.json').read_text())['token']
|
||||
d=json.load(urllib.request.urlopen(urllib.request.Request('http://127.0.0.1:8108/api/v1/status',headers={'Authorization':'Bearer '+key})))
|
||||
if d['endpoint']['active_requests']:raise SystemExit('Deck request active: no activation.')
|
||||
spec=importlib.util.spec_from_file_location('installer',root/'app/deploy/install.py');m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m)
|
||||
m.build=lambda runtime_image=None:'athena-deck-standalone:parakeet-prepared-20261013'
|
||||
m.update(pathlib.Path('/opt/athena-deck-dev/runtime'),reuse_runtime=True,keep_snapshots=True)
|
||||
@@ -0,0 +1,56 @@
|
||||
"""Isolated CPU-only ASR comparison. Requires explicit --go. Never reads private chats."""
|
||||
import argparse,contextlib,io,json,os,pathlib,re,signal,socket,subprocess,time,urllib.request,wave
|
||||
p=argparse.ArgumentParser();p.add_argument('--go',action='store_true');p.add_argument('--state-root',default='/var/lib/deck');p.add_argument('--cases',required=True);p.add_argument('--output',required=True);a=p.parse_args()
|
||||
if not a.go:raise SystemExit('Prepared only. Add --go after user authorization.')
|
||||
root=pathlib.Path(a.state_root);out=pathlib.Path(a.output);out.mkdir(parents=True,exist_ok=True)
|
||||
cases=json.loads(pathlib.Path(a.cases).read_text());version='v0.6.1';pr=root/'parakeet-runtime'/version
|
||||
runtime=json.loads((root/'runtime/state.json').read_text());llama=root/'runtime'/runtime['active']/'build/bin/llama-server'
|
||||
entries=[]
|
||||
for path in (root/'models').glob('*/entry.json'):
|
||||
d=json.loads(path.read_text())
|
||||
if d.get('repo')=='ggml-org/Qwen3-ASR-0.6B-GGUF':entries.append((d['file'],path.parent/'model.gguf'))
|
||||
qmodel=next(path for name,path in entries if name=='Qwen3-ASR-0.6B-Q8_0.gguf');proj=next(path for name,path in entries if name=='mmproj-Qwen3-ASR-0.6B-Q8_0.gguf')
|
||||
def wer(reference,hypothesis):
|
||||
def words(s):return re.findall(r'\w+',s.casefold())
|
||||
r,h=words(reference),words(hypothesis);row=list(range(len(h)+1))
|
||||
for i,x in enumerate(r,1):
|
||||
nxt=[i]
|
||||
for j,y in enumerate(h,1):nxt.append(min(nxt[-1]+1,row[j]+1,row[j-1]+(x!=y)))
|
||||
row=nxt
|
||||
return row[-1]/max(1,len(r))
|
||||
def request(url,audio):
|
||||
boundary='athena-synthetic-comparison'
|
||||
body=(f'--{boundary}\r\nContent-Disposition: form-data; name="model"\r\n\r\ndeck-stt\r\n--{boundary}\r\nContent-Disposition: form-data; name="language"\r\n\r\nde\r\n--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="synthetic.wav"\r\nContent-Type: audio/wav\r\n\r\n').encode()+audio+f'\r\n--{boundary}--\r\n'.encode()
|
||||
with urllib.request.urlopen(urllib.request.Request(url+'/v1/audio/transcriptions',data=body,headers={'Content-Type':'multipart/form-data; boundary='+boundary}),timeout=280) as resp:return json.load(resp)['text'].split('<asr_text>')[-1].replace('<|endoftext|>','').strip()
|
||||
results=[]
|
||||
for engine in ('qwen','redux'):
|
||||
with socket.socket() as s:s.bind(('127.0.0.1',0));port=s.getsockname()[1]
|
||||
args=([str(llama),'--model',str(qmodel),'--mmproj',str(proj),'--no-mmproj-offload','--n-gpu-layers','0','--ctx-size','4096','--threads','2','--parallel','1','--host','127.0.0.1','--port',str(port),'--no-ui','--fit','off','--alias','deck-stt'] if engine=='qwen' else [str(pr/'runtime'/('parakeet-'+version+'-bin-linux-cpu-x64')/'parakeet-server'),'--model',str(pr/'redux-packed.gguf'),'--host','127.0.0.1','--port',str(port),'--threads','2','--concurrency','1'])
|
||||
start=time.monotonic();proc=subprocess.Popen(args,env=dict(os.environ,CUDA_VISIBLE_DEVICES='',OMP_NUM_THREADS='2'),stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,start_new_session=True)
|
||||
try:
|
||||
url=f'http://127.0.0.1:{port}'
|
||||
while True:
|
||||
if proc.poll() is not None:raise RuntimeError(engine+' startup failed')
|
||||
if time.monotonic()-start>120:raise RuntimeError(engine+' startup timeout')
|
||||
try:
|
||||
with urllib.request.urlopen(url+'/health',timeout=1) as resp:
|
||||
if resp.status==200:break
|
||||
except OSError:time.sleep(.2)
|
||||
load=time.monotonic()-start
|
||||
for case in cases:
|
||||
source=pathlib.Path(a.cases).parent/case['file']
|
||||
# Converts only the explicitly listed synthetic files; no library scans.
|
||||
pcm=subprocess.check_output(['ffmpeg','-nostdin','-v','error','-i',str(source),'-ac','1','-ar','16000','-f','s16le','pipe:1'],stderr=subprocess.DEVNULL)
|
||||
buffer=io.BytesIO()
|
||||
with wave.open(buffer,'wb') as w:w.setnchannels(1);w.setsampwidth(2);w.setframerate(16000);w.writeframes(pcm)
|
||||
audio=buffer.getvalue();duration=len(pcm)/32000
|
||||
for repetition in (1,2):
|
||||
t=time.monotonic();text=request(url,audio);elapsed=time.monotonic()-t
|
||||
row=dict(engine=engine,case=case['name'],repetition=repetition,startup_seconds=round(load,3),seconds=round(elapsed,3),audio_seconds=round(duration,3),rtf=round(elapsed/duration,4),wer=round(wer(case['expected'],text),4),text=text)
|
||||
results.append(row);(out/'results.json').write_text(json.dumps(results,indent=2));print(json.dumps({k:v for k,v in row.items() if k!='text'}),flush=True)
|
||||
finally:
|
||||
if proc.poll() is None:
|
||||
os.killpg(proc.pid,signal.SIGTERM)
|
||||
try:proc.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:os.killpg(proc.pid,signal.SIGKILL);proc.wait()
|
||||
(out/'complete').write_text('Synthetic comparison complete\n')
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"version": "v0.6.1",
|
||||
"model_repo": "mudler/parakeet-cpp-gguf",
|
||||
"model_revision": "741158ae71e64ef5c89385862c18f777d07a97a1",
|
||||
"files": [
|
||||
{
|
||||
"path": "runtime.tar.gz",
|
||||
"url": "https://github.com/mudler/parakeet.cpp/releases/download/v0.6.1/parakeet-v0.6.1-bin-linux-cpu-x64.tar.gz",
|
||||
"sha256": "cce60d122ab72e1068cd0d164e54a21655a0b83f1b9c21befc20124f5a972c10"
|
||||
},
|
||||
{
|
||||
"path": "redux-packed.gguf",
|
||||
"url": "https://huggingface.co/mudler/parakeet-cpp-gguf/resolve/741158ae71e64ef5c89385862c18f777d07a97a1/redux-packed.gguf",
|
||||
"sha256": "574614b9a4d9f72ab202877a7ad6a1f4bf819dd1d27b9d42dfe8cd429fcebdd5"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
"""Download pinned CPU runtime/model only. Never start an inference service."""
|
||||
import argparse,hashlib,json,os,pathlib,tarfile,urllib.request
|
||||
p=argparse.ArgumentParser();p.add_argument('--root',required=True);args=p.parse_args()
|
||||
root=pathlib.Path(args.root);root.mkdir(parents=True,exist_ok=True)
|
||||
files=[dict(path='runtime.tar.gz',url='https://github.com/mudler/parakeet.cpp/releases/download/v0.6.1/parakeet-v0.6.1-bin-linux-cpu-x64.tar.gz',sha256='cce60d122ab72e1068cd0d164e54a21655a0b83f1b9c21befc20124f5a972c10'),dict(path='redux-packed.gguf',url='https://huggingface.co/mudler/parakeet-cpp-gguf/resolve/741158ae71e64ef5c89385862c18f777d07a97a1/redux-packed.gguf',sha256='574614b9a4d9f72ab202877a7ad6a1f4bf819dd1d27b9d42dfe8cd429fcebdd5')]
|
||||
def digest(path):
|
||||
h=hashlib.sha256()
|
||||
with path.open('rb') as f:
|
||||
for block in iter(lambda:f.read(8*1024*1024),b''):h.update(block)
|
||||
return h.hexdigest()
|
||||
for row in files:
|
||||
target=root/row['path']
|
||||
if not target.exists():
|
||||
part=target.with_suffix(target.suffix+'.part')
|
||||
with urllib.request.urlopen(row['url'],timeout=120) as r,part.open('wb') as f:
|
||||
while True:
|
||||
block=r.read(8*1024*1024)
|
||||
if not block:break
|
||||
f.write(block)
|
||||
if digest(part)!=row['sha256']:raise RuntimeError('Download checksum mismatch')
|
||||
part.replace(target)
|
||||
if digest(target)!=row['sha256']:raise RuntimeError('Existing artifact checksum mismatch')
|
||||
print(json.dumps({'verified':row['path'],'bytes':target.stat().st_size}),flush=True)
|
||||
with tarfile.open(root/'runtime.tar.gz') as t:
|
||||
# Reject traversal, links and devices rather than trusting an archive layout.
|
||||
for member in t.getmembers():
|
||||
path=pathlib.PurePosixPath(member.name)
|
||||
if path.is_absolute() or '..' in path.parts or member.issym() or member.islnk() or member.isdev():raise RuntimeError('Unsafe archive member')
|
||||
t.extractall(root/'runtime',filter='data')
|
||||
for binary in (root/'runtime').rglob('parakeet-*'):
|
||||
if binary.is_file() and binary.name in ('parakeet-cli','parakeet-server'):binary.chmod(0o755)
|
||||
(root/'manifest.json').write_text(json.dumps({'version':'v0.6.1','model_repo':'mudler/parakeet-cpp-gguf','model_revision':'741158ae71e64ef5c89385862c18f777d07a97a1','files':files},indent=2))
|
||||
print(json.dumps({'prepared':True,'inference_started':False}))
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Pinned, native CPU-only Redux runtime; no implicit download or inference."""
|
||||
import hashlib,json,os,time
|
||||
from pathlib import Path
|
||||
REPO='mudler/parakeet-cpp-gguf'
|
||||
REVISION='741158ae71e64ef5c89385862c18f777d07a97a1'
|
||||
MODEL='redux-packed.gguf'
|
||||
SHA256='574614b9a4d9f72ab202877a7ad6a1f4bf819dd1d27b9d42dfe8cd429fcebdd5'
|
||||
VERSION='v0.6.1'
|
||||
def supported(model):return bool(model and model.get('repo')==REPO and model.get('revision')==REVISION and model.get('file')==MODEL)
|
||||
class ParakeetRuntime:
|
||||
def __init__(self,root):self.root=Path(root)
|
||||
def paths(self):
|
||||
root=self.root/VERSION
|
||||
binary=root/'runtime'/('parakeet-'+VERSION+'-bin-linux-cpu-x64')/'parakeet-server'
|
||||
return binary,root/MODEL
|
||||
def status(self):
|
||||
binary,model=self.paths();manifest=self.root/VERSION/'manifest.json'
|
||||
try:
|
||||
data=json.loads(manifest.read_text());verified=data['version']==VERSION and data['model_revision']==REVISION and any(r['path']==MODEL and r['sha256']==SHA256 for r in data['files'])
|
||||
except (OSError,ValueError,KeyError,TypeError):verified=False
|
||||
return dict(installed=bool(verified and binary.is_file() and os.access(binary,os.X_OK) and model.is_file()),version=VERSION,repo=REPO,revision=REVISION,device='cpu')
|
||||
def binary(self):
|
||||
if not self.status()['installed']:raise ValueError('Parakeet-CPU-Laufzeit fehlt. Gepinntes Vorbereitungsrezept ausführen.')
|
||||
return self.paths()[0]
|
||||
def register(self,catalog):
|
||||
if not self.status()['installed']:raise ValueError('Parakeet-Dateien fehlen.')
|
||||
_,model=self.paths();ident=hashlib.sha256((REPO+REVISION+MODEL).encode()).hexdigest();target=catalog.root/ident
|
||||
target.mkdir(parents=True,exist_ok=True,mode=0o700)
|
||||
dest=target/'model.gguf'
|
||||
if not dest.exists():dest.symlink_to(model.resolve())
|
||||
entry=dict(repo=REPO,revision=REVISION,file=MODEL,kind='stt',size=model.stat().st_size,sha256=SHA256,upstream_hash_verified=True,downloaded_at=time.time(),state='downloaded',runtime_ready=True)
|
||||
temp=target/'entry.tmp';temp.write_text(json.dumps(entry));temp.replace(target/'entry.json');return ident
|
||||
@@ -386,6 +386,8 @@ class Profiles:
|
||||
return item
|
||||
def components(self,model_id,extra_repo=None):
|
||||
model=self.catalog.entry(model_id)
|
||||
from parakeet_runtime import supported as redux_supported
|
||||
if redux_supported(model):return dict(supported=True,requirements=[],no_components=True,worker_available=True,source='https://github.com/mudler/parakeet.cpp',license='CC-BY-4.0',runtime='parakeet.cpp · CPU/AVX2',message='Gepacktes Redux-GGUF, kein separater Projektor. Gepinnte CPU-Laufzeit aus dem Vorbereitungsrezept verwenden.')
|
||||
from soulx_singer import soulx_singer_model
|
||||
if soulx_singer_model(model):return dict(supported=True,requirements=[],source='https://huggingface.co/Plachta/SoulX-Singer',license='apache-2.0',runtime='SoulX-Singer · Python/PyTorch',runtime_route='#soulx-singer-runtime',runtime_installed=not bool(getattr(self,'soulx_singer_blockers',lambda p:['Laufzeit fehlt'])({'model':model})),worker_available=True,no_components=True,message='Gesangsdatei und Referenzstimme ohne Training umwandeln. Originales 24-kHz-Gesangsmodell; alle Zusatzgewichte gehören zum geprüften Laufzeitpaket. ')
|
||||
from xvc import xvc_model
|
||||
|
||||
@@ -147,6 +147,16 @@ class Server(ThreadingHTTPServer):
|
||||
self.tts_tests.acquire=self.scheduler.tts_reservation
|
||||
self.scheduler.evict_tts=self.tts_tests.unload_idle
|
||||
self.stt=STT(self.profiles,self.catalog,self.runtime)
|
||||
self.profiles.stt_blockers=self.stt.blockers
|
||||
if self.stt.parakeet.status()['installed']:
|
||||
marker=self.stt.parakeet.root/'profile-created'
|
||||
if not marker.exists():
|
||||
from parakeet_runtime import supported as redux_supported
|
||||
from profiles import SCHEMAS
|
||||
model_id=self.stt.parakeet.register(self.catalog)
|
||||
if not any(p['kind']=='stt' and redux_supported(p.get('model')) for p in self.profiles.status()['profiles']):
|
||||
self.profiles.save(dict(id=None,revision=0,name='Parakeet Redux CPU',kind='stt',model_id=model_id,parameters={k:v[2] for k,v in SCHEMAS['stt'].items()}))
|
||||
marker.write_text('Redux STT profile registered\n')
|
||||
self.voxcpm_tests.reference_transcriber=self.stt.transcribe_reference
|
||||
self.profiles.stt_blockers=self.stt.blockers
|
||||
self.endpoint=Endpoint(self.catalog.root.parent,self.profiles,self.worker,self.scheduler,self.image_tests,self.credentials,self.server_port)
|
||||
@@ -426,7 +436,7 @@ class Handler(BaseHTTPRequestHandler):
|
||||
else self.server.video.runtime)
|
||||
return {'embeddings':chat,'stt':chat,'chat':chat,
|
||||
'image':self.server.image_runtime.status().get('installed',False),
|
||||
'audio':self.server.tts_runtime.status().get('installed',False),
|
||||
'audio':self.server.tts_runtime.status().get('installed',False),'parakeet':self.server.stt.parakeet.status()['installed'],
|
||||
'video':video_runtime.status().get('installed',False),
|
||||
'acestep':self.server.acestep_runtime.status()['installed'],
|
||||
'audio_cpp':self.server.audio_cpp_runtime.status()['installed'],
|
||||
|
||||
@@ -4,7 +4,7 @@ window.STTUI=(()=>{
|
||||
function html(setup=false){return `<section class="card" id="stt-panel"><h2>${setup?'Spracherkennung einrichten':'Audio in Text umwandeln'}</h2><p id="stt-status" role="status"></p><p id="stt-error" role="alert"></p>${setup?'<p>Qwen3-ASR 0.6B Q8_0 nutzt die vorhandene llama.cpp-Laufzeit auf der CPU. Installiert werden die geprüfte Modellvariante von ggml-org (rund 805 MB) und der Audio-Projektor (214 MB). Andere GGUF-Konvertierungen können inkompatibel sein. Bestehende Dienste werden nicht verwendet oder verändert.</p><a class="link" href="#runtime">llama.cpp installieren / Build auswählen →</a><p><button id="stt-setup">Modell und Audio-Projektor einrichten</button></p><p>Der Download erscheint unter STT → Downloads. Nach Abschluss ein neues Profil aus der Bibliothek anlegen oder ein bestehendes Profil unten ausdrücklich umstellen. Alte Dateien bleiben erhalten.</p><h3>Vorhandenes Profil umstellen</h3><p>Ersetzt die Modellzuordnung durch die geprüfte ggml-org-Variante. Profilname bleibt erhalten.</p><select id="stt-profile"></select><button id="stt-assign">Kompatibles Modell diesem Profil zuordnen</button><h3>Speicherverhalten</h3><p>Automatisch hält das Modell nach der ersten Anfrage geladen. Immer bereit lädt das gewählte Profil im LLM-Betrieb vor, soweit Ressourcen frei sind. Nach jeder Anfrage entladen gibt Speicher sofort frei.</p><label>Verhalten<select id="stt-policy"><option value="auto">Automatisch</option><option value="warm">Immer bereit</option><option value="per_request">Nach jeder Anfrage entladen</option></select></label><label>Profil für „Immer bereit“<select id="stt-warm-profile"></select></label><button id="stt-policy-save">Speicherverhalten speichern</button><p id="stt-policy-state" role="status"></p>':'<form id="stt-form"><label>Profil<select id="stt-profile" required></select></label><label>Audiodatei (maximal 120 Sekunden, 20 MiB)<input type="file" id="stt-file" accept="audio/*" required></label><label>Sprache<select id="stt-language"><option value="de">Deutsch</option><option value="en">Englisch</option><option value="auto">Automatisch</option></select></label><button id="stt-start">Transkribieren</button><button type="button" class="secondary" id="stt-cancel">Abbrechen</button></form><h3>Transkript</h3><pre id="stt-result" style="white-space:pre-wrap"></pre><p>Die Audiodatei wird im Browser in Mono-WAV mit 16 kHz umgewandelt. Unterstützte Eingabeformate hängen vom Browser ab. Audio und Transkript werden nicht dauerhaft gespeichert; das letzte Ergebnis bleibt bis zum nächsten Auftrag im Arbeitsspeicher.</p>'}</section>`;}
|
||||
async function wav(file){if(file.size>20*1024**2)throw Error('Datei ist größer als 20 MiB.');const context=new AudioContext();let decoded;try{decoded=await context.decodeAudioData(await file.arrayBuffer());}finally{await context.close();}if(!decoded.duration||decoded.duration>120)throw Error('Maximal 120 Sekunden Audio erlaubt.');const offline=new OfflineAudioContext(1,Math.ceil(decoded.duration*16000),16000),source=offline.createBufferSource();source.buffer=decoded;source.connect(offline.destination);source.start();const samples=(await offline.startRendering()).getChannelData(0),buffer=new ArrayBuffer(44+samples.length*2),v=new DataView(buffer);const str=(at,s)=>{for(let i=0;i<s.length;i++)v.setUint8(at+i,s.charCodeAt(i));};str(0,'RIFF');v.setUint32(4,36+samples.length*2,true);str(8,'WAVEfmt ');v.setUint32(16,16,true);v.setUint16(20,1,true);v.setUint16(22,1,true);v.setUint32(24,16000,true);v.setUint32(28,32000,true);v.setUint16(32,2,true);v.setUint16(34,16,true);str(36,'data');v.setUint32(40,samples.length*2,true);samples.forEach((s,i)=>v.setInt16(44+i*2,Math.max(-1,Math.min(1,s))*(s<0?32768:32767),true));return new Blob([buffer],{type:'audio/wav'});}
|
||||
function bind(setup=false){const root=document.querySelector('#stt-panel');if(!root)return;const el=id=>root.querySelector('#'+id);let busy=false,profiles=[];
|
||||
async function refresh(){try{const s=await api('stt');if(!root.isConnected)return;el('stt-status').textContent=setup?`llama.cpp: ${s.installed?'vorhanden':'fehlt'} · Modell: ${s.model?'vorhanden':'fehlt'} · Audio-Projektor: ${s.projector?'vorhanden':'fehlt'}`:(s.job?.phase||'Profil und Audiodatei auswählen.')+` · CPU-Modell ${s.loaded?'geladen':'nicht geladen'}`;if(setup){el('stt-setup').disabled=busy||(s.projector&&s.model);el('stt-assign').disabled=busy||!s.model||!profiles.length;}else{el('stt-start').disabled=busy||s.job?.state==='running'||!profiles.length;el('stt-cancel').disabled=s.job?.state!=='running';el('stt-result').textContent=s.job?.text||'';}}catch(err){if(root.isConnected)el('stt-error').textContent=err.message;}finally{if(root.isConnected)setTimeout(refresh,2000);}}
|
||||
async function refresh(){try{const s=await api('stt');if(!root.isConnected)return;el('stt-status').textContent=setup?`llama.cpp: ${s.installed?'vorhanden':'fehlt'} · Modell: ${s.model?'vorhanden':'fehlt'} · Parakeet: ${s.parakeet?.installed?'vorbereitet':'fehlt'} · Qwen-Audio-Projektor: ${s.projector?'vorhanden':'fehlt'}`:(s.job?.phase||'Profil und Audiodatei auswählen.')+` · CPU-Modell ${s.loaded?'geladen':'nicht geladen'}`;if(setup){el('stt-setup').disabled=busy||(s.projector&&s.model);el('stt-assign').disabled=busy||!s.model||!profiles.length;}else{el('stt-start').disabled=busy||s.job?.state==='running'||!profiles.length;el('stt-cancel').disabled=s.job?.state!=='running';el('stt-result').textContent=s.job?.text||'';}}catch(err){if(root.isConnected)el('stt-error').textContent=err.message;}finally{if(root.isConnected)setTimeout(refresh,2000);}}
|
||||
if(setup){api('profiles').then(p=>{if(!root.isConnected)return;profiles=p.profiles.filter(p=>p.kind==='stt');el('stt-profile').innerHTML=profiles.map(p=>`<option value="${e(p.id)}">${e(p.name)}</option>`).join('');}).catch(err=>{if(root.isConnected)el('stt-error').textContent=err.message;});el('stt-assign').onclick=async()=>{const p=profiles.find(p=>p.id===el('stt-profile').value);if(!p)return;busy=true;try{await api('stt/assign',{id:p.id,revision:p.revision});el('stt-error').textContent='Profil umgestellt. Jetzt STT → Testen öffnen.';p.revision++;}catch(err){el('stt-error').textContent=err.message;}finally{busy=false;}};el('stt-setup').onclick=async()=>{busy=true;try{await api('stt/setup',{});el('stt-error').textContent='Download ist eingeplant. Fortschritt unter Downloads.';}catch(err){el('stt-error').textContent=err.message;}finally{busy=false;}};}
|
||||
else{api('profiles').then(p=>{if(!root.isConnected)return;profiles=p.profiles.filter(p=>p.kind==='stt'&&p.runnable);el('stt-profile').innerHTML=profiles.map(p=>`<option value="${e(p.id)}">${e(p.name)}</option>`).join('')||'<option value="">Zuerst STT einrichten und ein Profil anlegen</option>';}).catch(err=>{if(root.isConnected)el('stt-error').textContent=err.message;});el('stt-form').onsubmit=async ev=>{ev.preventDefault();busy=true;el('stt-start').disabled=true;el('stt-error').textContent='';try{const body=new FormData();body.set('file',await wav(el('stt-file').files[0]),'audio.wav');body.set('profile_id',el('stt-profile').value);body.set('language',el('stt-language').value);if(root.isConnected)await api('stt/start',body);}catch(err){if(root.isConnected)el('stt-error').textContent=err.message;}finally{busy=false;}};el('stt-cancel').onclick=()=>api('stt/cancel',{}).catch(err=>{if(root.isConnected)el('stt-error').textContent=err.message;});} if(setup){
|
||||
const policy=el('stt-policy'),warm=el('stt-warm-profile'),save=el('stt-policy-save'),status=el('stt-policy-state');
|
||||
|
||||
@@ -4,6 +4,7 @@ from email import policy
|
||||
from email.parser import BytesParser
|
||||
from pathlib import Path
|
||||
from image_test import cgroup_headroom
|
||||
from parakeet_runtime import ParakeetRuntime,supported as redux_supported
|
||||
REPO='ggml-org/Qwen3-ASR-0.6B-GGUF'
|
||||
REVISION='928ab958557df9aa2ef1c93e0e83c7ad0933fae2'
|
||||
MODEL='Qwen3-ASR-0.6B-Q8_0.gguf'
|
||||
@@ -82,7 +83,8 @@ def read_upload(handler,validate=True,max_audio=MAX_AUDIO,allowed_fields=None,ma
|
||||
|
||||
class STT:
|
||||
def __init__(self,profiles,catalog,runtime):
|
||||
self.profiles=profiles;self.catalog=catalog;self.runtime=runtime;self.lock=threading.RLock();self.job=None;self.process=None;self.port=None;self.key=None;self.binary_path=None;self.cancel=threading.Event();self.policy='auto';self.warming=False
|
||||
self.profiles=profiles;self.catalog=catalog;self.runtime=runtime;self.lock=threading.RLock();self.job=None;self.process=None;self.port=None;self.key=None;self.binary_path=None;self.cancel=threading.Event();self.policy='auto';self.warming=False;self.profile_id=None;self.session_model=None
|
||||
self.parakeet=ParakeetRuntime(self.catalog.root.parent/'parakeet-runtime') if self.catalog is not None else None
|
||||
def build(self):
|
||||
state=self.runtime.status();ident=state.get('active')
|
||||
if not isinstance(ident,str) or len(ident)!=32 or any(c not in '0123456789abcdef' for c in ident):raise ValueError('Zuerst unter Laufzeiten → llama.cpp einen Build erstellen und aktivieren.')
|
||||
@@ -94,6 +96,7 @@ class STT:
|
||||
if x['repo']==PROJECTOR_REPO and x['revision']==PROJECTOR_REVISION and x['file']==PROJECTOR:return self.catalog.entry(x['id'])
|
||||
raise ValueError('Audio-Projektor fehlt. Unter STT → Einrichten herunterladen.')
|
||||
def blockers(self,p):
|
||||
if redux_supported(p['model']):return [] if self.parakeet and self.parakeet.status()['installed'] else ['Parakeet-CPU-Laufzeit fehlt. Vorbereitungsrezept ausführen.']
|
||||
if not supported(p['model']):return ['Diese STT-Variante ist noch nicht angebunden. Unterstützt wird Qwen3-ASR 0.6B Q8_0 aus dem geprüften Repository.']
|
||||
errors=[]
|
||||
for f in [self.build,self.projector]:
|
||||
@@ -107,7 +110,7 @@ class STT:
|
||||
except ValueError:projector=False
|
||||
try:self.model_entry();model=True
|
||||
except ValueError:model=False
|
||||
with self.lock:return dict(model=model,job=dict(self.job) if self.job else None,installed=installed,projector=projector,repo=REPO,revision=REVISION,loaded=bool(self.process and self.process.poll() is None),policy=self.policy,warming=self.warming)
|
||||
with self.lock:return dict(model=model,job=dict(self.job) if self.job else None,installed=installed,projector=projector,repo=REPO,revision=REVISION,loaded=bool(self.process and self.process.poll() is None),policy=self.policy,warming=self.warming,profile_id=self.profile_id,parakeet=self.parakeet.status() if self.parakeet else {'installed':False})
|
||||
def model_entry(self):
|
||||
for x in self.catalog.status()['entries']:
|
||||
if supported(x):return self.catalog.entry(x['id'])
|
||||
@@ -138,9 +141,15 @@ class STT:
|
||||
if not self.process or self.process.poll() is not None:
|
||||
headroom=cgroup_headroom()
|
||||
if headroom is not None and headroom<4*1024**3:raise ValueError('Mindestens 4 GiB freier Deck-RAM werden benötigt.')
|
||||
binary=self.build();model=self.catalog.root/p['model_id']/'model.gguf';projector=self.catalog.root/self.projector()['id']/'model.gguf'
|
||||
binary,model,projector=self.selected_paths(p)
|
||||
self.profile_id=profile_id
|
||||
self.cancel.clear();ident=uuid.uuid4().hex;self.job=dict(id=ident,state='running',phase='Vorhandene Spracherkennung wird verwendet' if self.process and self.process.poll() is None else 'Spracherkennung lädt auf der CPU',profile_id=profile_id)
|
||||
threading.Thread(target=self._run,args=(binary,model,projector,audio,language),daemon=True).start();return dict(self.job)
|
||||
def selected_paths(self,p):
|
||||
model=self.catalog.root/p['model_id']/'model.gguf'
|
||||
if redux_supported(p['model']):return self.parakeet.binary(),model,None
|
||||
return self.build(),model,self.catalog.root/self.projector()['id']/'model.gguf'
|
||||
|
||||
def transcribe_reference(self,audio,cancel):
|
||||
# Normalize in memory for the existing CPU ASR; never fetch another model.
|
||||
p=next((p for p in self.profiles.status()['profiles'] if p['kind']=='stt' and p['runnable']),None)
|
||||
@@ -179,6 +188,7 @@ class STT:
|
||||
process=None;result=dict(state='failed',phase='Spracherkennung fehlgeschlagen. Laufzeit und Speicher prüfen.')
|
||||
try:
|
||||
port,key=self._ensure(binary,model,projector)
|
||||
with self.lock:self.profile_id=self.job['profile_id']
|
||||
base=f'http://127.0.0.1:{port}';headers={'Authorization':'Bearer '+key};deadline=time.monotonic()+90
|
||||
with self.lock:self.job['phase']='Audio wird auf der CPU transkribiert'
|
||||
boundary='deck-'+uuid.uuid4().hex
|
||||
@@ -203,16 +213,17 @@ class STT:
|
||||
try:
|
||||
with self.lock:
|
||||
if self.cancel.is_set():raise InterruptedError()
|
||||
process=self.process if self.process and self.process.poll() is None and self.binary_path==str(binary) else None
|
||||
process=self.process if self.process and self.process.poll() is None and self.binary_path==str(binary) and self.session_model==(str(model),str(projector)) else None
|
||||
if process is None:
|
||||
self.unload_idle()
|
||||
key=secrets.token_hex(24)
|
||||
with socket.socket() as s:s.bind(('127.0.0.1',0));port=s.getsockname()[1]
|
||||
env=dict(os.environ,CUDA_VISIBLE_DEVICES='',OMP_NUM_THREADS='2')
|
||||
args=[str(binary),'--model',str(model),'--mmproj',str(projector),'--no-mmproj-offload','--n-gpu-layers','0','--ctx-size','4096','--threads','2','--parallel','1','--host','127.0.0.1','--port',str(port),'--no-ui','--fit','off','--alias','deck-stt','--api-key',key]
|
||||
if projector is None:args=[str(binary),'--model',str(model),'--host','127.0.0.1','--port',str(port),'--threads','2','--concurrency','1']
|
||||
with self.lock:
|
||||
if self.cancel.is_set():raise InterruptedError()
|
||||
process=subprocess.Popen(args,env=env,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,start_new_session=True);self.process=process;self.port=port;self.key=key;self.binary_path=str(binary)
|
||||
process=subprocess.Popen(args,env=env,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,start_new_session=True);self.process=process;self.port=port;self.key=key;self.binary_path=str(binary);self.session_model=(str(model),str(projector))
|
||||
deadline=time.monotonic()+90
|
||||
while True:
|
||||
if self.cancel.wait(.3):raise InterruptedError()
|
||||
@@ -230,7 +241,7 @@ class STT:
|
||||
def warm(self,profile_id):
|
||||
with self.lock:
|
||||
if self.job and self.job.get('state')=='running':return False
|
||||
if self.process and self.process.poll() is None:return True
|
||||
if self.process and self.process.poll() is None and self.profile_id==profile_id:return True
|
||||
if self.warming:return False
|
||||
p=next((p for p in self.profiles.status()['profiles'] if p['id']==profile_id and p['kind']=='stt' and p['runnable']),None)
|
||||
if not p:raise ValueError('Das ausgewählte STT-Profil ist nicht ausführbar.')
|
||||
@@ -238,12 +249,12 @@ class STT:
|
||||
try:
|
||||
headroom=cgroup_headroom()
|
||||
if headroom is not None and headroom<4*1024**3:raise ValueError('Mindestens 4 GiB freier Deck-RAM werden benötigt.')
|
||||
self._ensure(self.build(),self.catalog.root/p['model_id']/'model.gguf',self.catalog.root/self.projector()['id']/'model.gguf');return True
|
||||
self._ensure(*self.selected_paths(p));self.profile_id=profile_id;return True
|
||||
finally:
|
||||
with self.lock:self.warming=False
|
||||
def unload_idle(self):
|
||||
with self.lock:
|
||||
process=self.process;self.process=None;self.port=None;self.key=None;self.binary_path=None
|
||||
process=self.process;self.process=None;self.port=None;self.key=None;self.binary_path=None;self.session_model=None;self.profile_id=None
|
||||
if process and process.poll() is None:
|
||||
try:
|
||||
os.killpg(process.pid,signal.SIGTERM)
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import tempfile,unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import Mock
|
||||
from parakeet_runtime import supported,REPO,REVISION,MODEL,ParakeetRuntime
|
||||
from endpoint import Endpoint,APIError
|
||||
class ReduxSTTTests(unittest.TestCase):
|
||||
def test_packed_exact_revision_required(self):
|
||||
m=dict(repo=REPO,revision=REVISION,file=MODEL)
|
||||
self.assertTrue(supported(m));self.assertFalse(supported(dict(m,file='redux-f16.gguf')));self.assertFalse(supported(dict(m,revision='other')))
|
||||
def test_uninstalled_runtime_never_claims_ready(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
rt=ParakeetRuntime(d);self.assertFalse(rt.status()['installed'])
|
||||
with self.assertRaises(ValueError):rt.binary()
|
||||
def rows(self):return [dict(id='old',name='Qwen-ASR',api_id='qwen-asr',kind='stt',enabled=False,runnable=True,blockers=[]),dict(id='new',name='Parakeet Redux CPU',api_id='parakeet-redux-cpu',kind='stt',enabled=True,runnable=True,blockers=[])]
|
||||
def test_existing_client_names_route_to_newly_published_backend(self):
|
||||
ep=Endpoint.__new__(Endpoint);ep.rows=lambda:self.rows()
|
||||
for name in ('Qwen-ASR','qwen-asr','whisper-1','athena-stt','parakeet-redux-cpu'):self.assertEqual(ep.find_profile(name,'stt')['id'],'new')
|
||||
with self.assertRaises(APIError):ep.find_profile('invented-name','stt')
|
||||
def test_disabled_or_ambiguous_backend_is_not_silently_chosen(self):
|
||||
ep=Endpoint.__new__(Endpoint);rows=self.rows();ep.rows=lambda:rows
|
||||
rows[1]['enabled']=False
|
||||
with self.assertRaises(APIError):ep.find_profile('athena-stt','stt')
|
||||
rows[0]['enabled']=rows[1]['enabled']=True
|
||||
with self.assertRaises(APIError):ep.find_profile('athena-stt','stt')
|
||||
def test_backend_model_and_projector_are_part_of_residency(self):
|
||||
# Actual switches cannot reuse a Qwen process for Redux just because it exists.
|
||||
from stt import STT
|
||||
s=STT(None,None,Mock());self.assertIsNone(s.session_model);self.assertIsNone(s.profile_id)
|
||||
if __name__=='__main__':unittest.main()
|
||||
|
||||
class WarmSwitchTests(unittest.TestCase):
|
||||
def test_published_stt_overrides_old_warm_profile_without_interrupting_job(self):
|
||||
import threading
|
||||
from audio_policy import AudioPolicy
|
||||
worker=Mock();worker.lock=threading.RLock();worker.warming=False;worker.job=None;worker.profile_id='old';worker.process=Mock();worker.process.poll.return_value=None
|
||||
manager=AudioPolicy.__new__(AudioPolicy);manager.lock=threading.RLock();manager.settings={'stt':{'mode':'warm','profile_id':'old'},'tts':{'mode':'per_request','profile_id':None}};manager.errors={};manager.retry_after={};manager.stt=worker;manager.tts=Mock();manager.scheduler=Mock();manager.scheduler.gpu_mode='llm';manager.endpoint=Mock();manager.endpoint.state='running';manager.endpoint.rows.return_value=[dict(id='new',kind='stt',enabled=True,runnable=True)]
|
||||
manager.reconcile();worker.unload_idle.assert_called_once();worker.warm.assert_called_once_with('new')
|
||||
worker.reset_mock();worker.job={'state':'running'}
|
||||
manager.reconcile();worker.unload_idle.assert_not_called();worker.warm.assert_not_called()
|
||||
Reference in new issue
Block a user