Avoid repeated library scans during voice requests and time TTS preparation
This commit is contained in:
1 parent
a9d65ab7d4
commit
a160562bd6
4 files changed
+50
-11
No files matched your search
+12
-7
@@ -151,11 +151,20 @@ class Catalog:
|
||||
return {'dismissed':True,'model_deleted':False}
|
||||
def entry(self,ident):
|
||||
if not isinstance(ident,str) or not re.fullmatch('[a-f0-9]{64}',ident):raise ValueError('Ungültige Modelldatei-ID.')
|
||||
entry=next((x for x in self.status()['entries'] if x['id']==ident),None)
|
||||
if not entry:raise ValueError('Modelldatei nicht in der Bibliothek.')
|
||||
# A component lookup must not rescan every unrelated model/download.
|
||||
# Read fresh metadata and verify the weight on every lookup: no stale cache.
|
||||
with self.lock:
|
||||
try:entry=self._read_entry(self.root/ident/'entry.json')
|
||||
except (OSError,ValueError):raise ValueError('Modelldatei nicht in der Bibliothek.') from None
|
||||
path=self.root/ident/('model'+PurePosixPath(entry['file']).suffix)
|
||||
if not path.is_file() or path.stat().st_size!=entry['size']:raise ValueError('Modelldatei fehlt oder ist unvollständig.')
|
||||
return entry
|
||||
def _read_entry(self,path):
|
||||
item=json.loads(path.read_text());item['id']=path.parent.name;item.update(file_role(item['file']))
|
||||
if item['repo'].startswith('local/'):
|
||||
from backup import LOCAL_SOURCES
|
||||
item['download_source']=item.get('download_source') or LOCAL_SOURCES.get(item.get('sha256'))
|
||||
return item
|
||||
def delete(self,ident,profiles,active_model_id=None):
|
||||
if not isinstance(ident,str) or not re.fullmatch(r'[a-f0-9]{64}',ident):raise ValueError('Ungültige Modelldatei-ID.')
|
||||
# Profile writes and deletions use the same lock order: profiles, catalog.
|
||||
@@ -231,11 +240,7 @@ class Catalog:
|
||||
if self.root.exists():
|
||||
for p in self.root.glob('*/entry.json'):
|
||||
try:
|
||||
item=json.loads(p.read_text());item['id']=p.parent.name;item.update(file_role(item['file']))
|
||||
if item['repo'].startswith('local/'):
|
||||
from backup import LOCAL_SOURCES
|
||||
item['download_source']=item.get('download_source') or LOCAL_SOURCES.get(item.get('sha256'))
|
||||
entries.append(item)
|
||||
entries.append(self._read_entry(p))
|
||||
except (OSError,ValueError):pass
|
||||
return dict(entries=entries,downloads=[dict(x) for x in reversed(self.history) if not x.get("dismissed")],job=dict(self.job) if self.job else None,free_bytes=shutil.disk_usage(self.root if self.root.exists() else self.root.parent).free)
|
||||
def start(self,repo,filename,revision,kind):
|
||||
|
||||
+3
-1
@@ -351,6 +351,7 @@ 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
|
||||
profile_seconds=time.monotonic()-started
|
||||
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)
|
||||
@@ -359,10 +360,11 @@ class APIHandler(BaseHTTPRequestHandler):
|
||||
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
|
||||
profile_seconds=time.monotonic()-started
|
||||
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 InferenceError as exc:raise APIError(str(exc),503,'tts_resources_unavailable') from None
|
||||
except ValueError as exc:raise APIError(str(exc)) from None
|
||||
logging.getLogger('athena.tts').warning('TTS request admitted job=%s wait_seconds=%.3f',job['id'],time.monotonic()-started)
|
||||
logging.getLogger('athena.tts').warning('TTS request admitted job=%s wait_seconds=%.3f profile_seconds=%.3f',job['id'],time.monotonic()-started,profile_seconds)
|
||||
end=time.monotonic()+620
|
||||
while time.monotonic()<end:
|
||||
current=backend.status()['job']
|
||||
|
||||
@@ -7,6 +7,34 @@ from unittest.mock import patch
|
||||
from catalog import Catalog, safe_url, repo_id, is_derived_model, runtime_metadata
|
||||
|
||||
class CatalogTests(unittest.TestCase):
|
||||
def test_entry_reads_only_requested_model_and_keeps_live_file_validation(self):
|
||||
import json
|
||||
from pathlib import Path
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
c=Catalog(d);ident='a'*64;folder=Path(d)/ident;folder.mkdir()
|
||||
metadata=dict(repo='owner/model',file='model.gguf',kind='chat',size=2)
|
||||
(folder/'entry.json').write_text(json.dumps(metadata));(folder/'model.gguf').write_bytes(b'ab')
|
||||
expected=c.status()['entries'][0]
|
||||
with patch.object(c,'status',side_effect=AssertionError('Unrelated library scan')):
|
||||
self.assertEqual(c.entry(ident),expected)
|
||||
metadata['size']=3;(folder/'entry.json').write_text(json.dumps(metadata))
|
||||
with self.assertRaisesRegex(ValueError,'unvollständig'):c.entry(ident)
|
||||
(folder/'model.gguf').write_bytes(b'abc');self.assertEqual(c.entry(ident)['size'],3)
|
||||
(folder/'model.gguf').unlink()
|
||||
with self.assertRaisesRegex(ValueError,'unvollständig'):c.entry(ident)
|
||||
(folder/'entry.json').unlink()
|
||||
with self.assertRaisesRegex(ValueError,'Bibliothek'):c.entry(ident)
|
||||
def test_direct_local_entry_preserves_role_and_source_metadata(self):
|
||||
import json
|
||||
from pathlib import Path
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
c=Catalog(d);ident='b'*64;folder=Path(d)/ident;folder.mkdir()
|
||||
(folder/'entry.json').write_text(json.dumps(dict(repo='local/import',file='mmproj.gguf',kind='chat',size=1,download_source='original-source')))
|
||||
(folder/'model.gguf').write_bytes(b'x')
|
||||
self.assertEqual(c.entry(ident),c.status()['entries'][0])
|
||||
self.assertEqual(c.entry(ident)['download_source'],'original-source')
|
||||
for invalid in ('../outside','c'*64):
|
||||
with self.assertRaises(ValueError):c.entry(invalid)
|
||||
def test_embeddings_search_has_own_hub_category(self):
|
||||
from urllib.parse import urlsplit,parse_qs
|
||||
from profiles import SCHEMAS
|
||||
|
||||
+7
-3
@@ -1,5 +1,5 @@
|
||||
"""Serial own TTS workers with shared model reservation, WAV results and cancellation."""
|
||||
import json,math,os,signal,subprocess,threading,time,uuid,hashlib,select
|
||||
import json,math,os,signal,subprocess,threading,time,uuid,hashlib,select,logging
|
||||
from pathlib import Path
|
||||
from tts_runtime import REPO,REVISION,SPEAKERS,LANGUAGES
|
||||
from image_test import probe,cgroup_headroom
|
||||
@@ -28,20 +28,24 @@ class TTSTests:
|
||||
if not isinstance(text,str) or not 1<=len(text.strip())<=1000:raise ValueError('Text mit 1–1000 Zeichen erforderlich.')
|
||||
if speaker not in SPEAKERS or language not in LANGUAGES:raise ValueError('Ungültige Stimme oder Sprache.')
|
||||
if speed is not None and (type(speed) not in (int,float) or not .25<=speed<=4):raise ValueError('Geschwindigkeit muss zwischen 0,25 und 4 liegen.')
|
||||
release=self.acquire(wait)
|
||||
queued=time.monotonic();release=self.acquire(wait);queue_seconds=time.monotonic()-queued
|
||||
try:
|
||||
with self.lock:
|
||||
if self.warming:raise ValueError('TTS wird gerade vorgeladen. Gleich erneut versuchen.')
|
||||
if self.job and self.job['state']=='running':raise ValueError('TTS-Auftrag läuft bereits.')
|
||||
checked=time.monotonic()
|
||||
p=next((p for p in self.profiles.status()['profiles'] if p['id']==profile_id and p['kind']=='audio'),None)
|
||||
profile_seconds=time.monotonic()-checked
|
||||
if not p or not p['runnable']:raise ValueError('TTS-Profil noch nicht eingerichtet.')
|
||||
resident=self.process and self.process.poll() is None
|
||||
checked=time.monotonic();resident=self.process and self.process.poll() is None
|
||||
gpu=next((g for g in probe() if g['uuid']==self.gpu_uuid),None) if resident else self._available_gpu()
|
||||
if not gpu:raise ValueError('Für Qwen-TTS ist nicht genug freier VRAM auf der RTX 3060 verfügbar. Andere Prozesse dürfen die Karte gemeinsam nutzen.')
|
||||
headroom=cgroup_headroom()
|
||||
if headroom is not None and headroom<8*1024**3:raise ValueError('Zu wenig freier Deck-RAM für TTS.')
|
||||
preflight_seconds=time.monotonic()-checked
|
||||
self.profile_id=profile_id;self.cancel.clear();ident=uuid.uuid4().hex;self.root.mkdir(parents=True,exist_ok=True,mode=0o700)
|
||||
self.job=dict(id=ident,state='running',phase='Vorhandenes Sprachmodell wird verwendet' if resident else 'Sprachmodell wird geladen',profile_id=profile_id,started_at=time.time())
|
||||
logging.getLogger('athena.tts').warning('TTS preparation job=%s queue_seconds=%.3f profile_seconds=%.3f preflight_seconds=%.3f resident=%s',ident,queue_seconds,profile_seconds,preflight_seconds,bool(resident))
|
||||
threading.Thread(target=self._run,args=(ident,text,speaker,language,speed if speed is not None else p['parameters']['speed'],gpu,release),daemon=True).start();return dict(self.job)
|
||||
except Exception:release();raise
|
||||
def _run(self,ident,text,speaker,language,speed,gpu,release):
|
||||
|
||||
Reference in new issue
Block a user