Match voice conversion pitch to reference with optional CPU correction

This commit is contained in:
Mikei386 committed 2026-10-19 14:45:44 +02:00
1 parent 04cd46e3e6
commit 369cb2ffe5
16 files changed
+408 -19

No files matched your search

+38
View File
@@ -75,3 +75,41 @@ recipe has not been accepted as a full fresh-Debian-host restore.
CC BY4.0 applies to LAION additions/weights; upstream Chatterbox MIT notices are
retained in the downloaded model's NOTICE. Dependencies keep their own licences.
## Optional reference pitch matching (Deck extension)
Stimmatelier defaults to **Tonhöhe automatisch an Referenz anpassen** and an
additional -12..+12 semitone slider (0.5 steps). The service API is backwards
compatible: omitted options disable correction. Optional multipart fields are
`pitch_auto=true|false` and `pitch_semitones=-12..12` (finite decimal).
Automatic correction compares the voiced median F0 of the reference and the
**converted output**, not gender labels or a fixed female pitch. A constant
semitone shift then changes the output's pitch, preserving its relative contour.
Manual shift is added to the automatic value; the total is clamped to ±12.
Own helper `humaneness_pitch.py` runs CPU-only in the already pinned Humaneness
venv. pYIN (librosa1.0.0,16kHz,60–650Hz,1024/256 samples) uses the RMS-filtered voiced HMM track for the median, with at least12
frames of posterior≥0.1 as a separate confidence gate (to avoid vowel-selection
bias from retaining only high-posterior frames). Unreliable
or silent clips produce a visible warning and skip only the automatic part.
FFmpeg `rubberband=tempo=1:formant=preserved:pitchq=quality` applies the change;
`apad,atrim` and an exact frame-count check preserve the converted WAV length.
No extra GPU, models, container or network service. An isolated Numba cache in
`humaneness-runtime/numba-cache` is reconstructible. The first run can take longer.
Correction is separately cancellable as part of the same job (180s CPU deadline).
Native Debian: install the distribution's `ffmpeg` package with librubberband
support (`ffmpeg -hide_banner -filters | grep rubberband`); the pinned Python
runtime already includes librosa, numba, numpy and soundfile. Missing filter or
worker errors fail the requested corrected job explicitly rather than returning
an uncorrected file as success. No in-place modification of upstream inference
code or weights. Job metadata includes measured F0, requested/applied shift and
warnings; `pitch.json` is included with the existing encrypted job backup.
Update/recovery: rebuild Deck and Stimmatelier from the saved revisions, rebuild
the venv from the lock if needed; old calls without options retain old behavior.
No new private configuration or credentials; raw reference/source cleanup remains.
Pitch matching is DSP, not a guarantee of perceived identity or perfect prosody.
RMS envelopes and word boundaries may change slightly; large shifts can sound
artificial. It preserves duration exactly, not every individual waveform sample
or silence edge. Only recorded acceptance below supports deployed measurements.
+1 -1
View File
@@ -15,7 +15,7 @@ import urllib.request
ROOT = Path(__file__).resolve().parent.parent
LABEL = 'de.casaderoll.athena-deck.standalone'
FILES = ['humaneness.py','humaneness_runtime.py','deploy/humaneness/bootstrap.py','deploy/humaneness/assets.json','deploy/humaneness/upstream-requirements.txt','deploy/humaneness/requirements.lock','deploy/humaneness/component-assets.json','deploy/humaneness/README.md','stimmatelier_proxy.py','qwen_native.py','qwen_native_worker.py','qwen_native_runtime.py','deploy/qwen-native-requirements.lock','deploy/import_qwen_native.py','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','pocket.py','pocket_worker.py','pocket_runtime.py','deploy/pocket-requirements.lock','deploy/import_pocket.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 = ['humaneness_pitch.py','humaneness.py','humaneness_runtime.py','deploy/humaneness/bootstrap.py','deploy/humaneness/assets.json','deploy/humaneness/upstream-requirements.txt','deploy/humaneness/requirements.lock','deploy/humaneness/component-assets.json','deploy/humaneness/README.md','stimmatelier_proxy.py','qwen_native.py','qwen_native_worker.py','qwen_native_runtime.py','deploy/qwen-native-requirements.lock','deploy/import_qwen_native.py','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','pocket.py','pocket_worker.py','pocket_runtime.py','deploy/pocket-requirements.lock','deploy/import_pocket.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']
+13
View File
@@ -149,3 +149,16 @@ WAV successfully. This is one controlled clip, not broad quality acceptance or
proof of identical prosody. Real user microphone acceptance remains pending.
Use **Letzte Umwandlung anzeigen** to recover the latest completed conversion
for the selected profile after reload; source/reference uploads are not restored.
### Automatic reference pitch and manual shift
Humaneness mode has **Tonhöhe automatisch an Referenz anpassen** (on by default)
and an additional ±12-semitone slider in0.5 steps. Deck measures voiced median
pitch in the target reference and converted output, then applies formant-preserving
Rubber Band on CPU. Automatic+manual total is capped at±12. Duration is unchanged;
large changes can cause artifacts and exact subjective voice identity is not
promised. Insufficient voiced speech produces a visible warning and leaves only
the manual adjustment active. The result panel reports the actual applied shift.
These controls use optional `pitch_auto`/`pitch_semitones` multipart API fields.
No new container or model; native dependency/restore details in Deck's runtime
recipe. No settings/recordings stored in browser persistent storage.
+4 -4
View File
@@ -3,7 +3,7 @@ const $=id=>document.getElementById(id);let profiles=[],sttId=null,busy=false,re
async function api(path,body){const opts=body?{method:'POST',headers:{'X-Athena-Deck':'1'},body:body instanceof FormData?body:JSON.stringify(body)}:{};if(body&&!(body instanceof FormData))opts.headers['Content-Type']='application/json';const r=await fetch('/api/v1/'+path,opts);if(r.status===401)throw Error('Bitte zuerst in Athena Deck anmelden und diese Seite neu laden.');const d=await r.json();if(!r.ok)throw Error(typeof d.error==='string'?d.error:d.error?.message||'Anfrage fehlgeschlagen.');return d;}
function error(e){$('error').textContent=e.message||String(e);$('error').hidden=false;}
function selected(){return profiles.find(p=>p.id===$('profile').value);}
function update(){const p=selected(),cpu=p?.kind==='audio',vc=p?.model?.repo==='laion/Humaneness-Voice-Converter';$('model-note').textContent=vc?'Echte Voice Conversion · GPU · Quelle und Zielstimme, ohne Transkription. Sprechweise bleibt möglichst erhalten; keine Garantie für jedes Detail. Quelle und Referenz jeweils 1–30 Sekunden. Strata wird bei Bedarf regulär entladen.':cpu?'0,6B Q8 · CPU · Strata kann geladen bleiben. Eigene Referenzen übernehmen die Stimmfarbe.':'1,7B Base · GPU · Deck entlädt Strata regulär vor der Ausgabe. Mit Referenztranskript kann Qwen auch die Sprechweise besser übernehmen.';$('latest').hidden=!vc;$('latest').disabled=busy||!!recording;if(!source)$('source-name').textContent=vc?'Bis 30 Sekunden':'Bis 120 Sekunden';$('reference-text').disabled=cpu||vc;$('reference-text').hidden=vc;$('reference-text').previousElementSibling.hidden=vc;$('text').hidden=vc;document.querySelector('label[for="text"]').hidden=vc;$('text').nextElementSibling.hidden=vc;$('text-tab').hidden=vc;$('transcribe').hidden=vc;$('generate').innerHTML=vc?'Stimme umwandeln <span>↗</span>':'Sprache erzeugen <span>↗</span>';if(vc){$('source-panel').hidden=false;$('audio-tab').setAttribute('aria-selected','true');$('text-tab').setAttribute('aria-selected','false');}$('source-panel').querySelector('.hint').textContent=vc?'Originalaufnahme hochladen oder einsprechen. Humaneness wandelt sie direkt in die Referenzstimme um; Text und STT werden nicht benötigt. Bis 30 Sekunden.':'WAV hochladen oder aufnehmen. Danach den erkannten Text prüfen. Timing und Betonung der Originalaufnahme werden nicht exakt übernommen.';$('reference-name').textContent=reference?reference.name:cpu?'Gespeicherte Standardstimme aus Deck':vc?'Bitte eine Zielreferenz hinzufügen':'Für 1,7B bitte eine Referenz hinzufügen';$('count').textContent=$('text').value.length+' / 1000';$('generate').disabled=busy||!!recording||!p||(vc?!source:(!$('text').value.trim()||$('text').value.length>1000))||(!cpu&&!reference);$('transcribe').disabled=busy||!!recording||!source||!sttId;$('profile').disabled=busy||!!recording||!profiles.length;}
function update(){const p=selected(),cpu=p?.kind==='audio',vc=p?.model?.repo==='laion/Humaneness-Voice-Converter';$('model-note').textContent=vc?'Echte Voice Conversion · GPU · Quelle und Zielstimme, ohne Transkription. Sprechweise bleibt möglichst erhalten; keine Garantie für jedes Detail. Quelle und Referenz jeweils 1–30 Sekunden. Strata wird bei Bedarf regulär entladen.':cpu?'0,6B Q8 · CPU · Strata kann geladen bleiben. Eigene Referenzen übernehmen die Stimmfarbe.':'1,7B Base · GPU · Deck entlädt Strata regulär vor der Ausgabe. Mit Referenztranskript kann Qwen auch die Sprechweise besser übernehmen.';$('pitch-controls').hidden=!vc;$('pitch-auto').disabled=busy||!!recording;$('pitch-semitones').disabled=busy||!!recording;$('latest').hidden=!vc;$('latest').disabled=busy||!!recording;if(!source)$('source-name').textContent=vc?'Bis 30 Sekunden':'Bis 120 Sekunden';$('reference-text').disabled=cpu||vc;$('reference-text').hidden=vc;$('reference-text').previousElementSibling.hidden=vc;$('text').hidden=vc;document.querySelector('label[for="text"]').hidden=vc;$('text').nextElementSibling.hidden=vc;$('text-tab').hidden=vc;$('transcribe').hidden=vc;$('generate').innerHTML=vc?'Stimme umwandeln <span>↗</span>':'Sprache erzeugen <span>↗</span>';if(vc){$('source-panel').hidden=false;$('audio-tab').setAttribute('aria-selected','true');$('text-tab').setAttribute('aria-selected','false');}$('source-panel').querySelector('.hint').textContent=vc?'Originalaufnahme hochladen oder einsprechen. Humaneness wandelt sie direkt in die Referenzstimme um; Text und STT werden nicht benötigt. Bis 30 Sekunden.':'WAV hochladen oder aufnehmen. Danach den erkannten Text prüfen. Timing und Betonung der Originalaufnahme werden nicht exakt übernommen.';$('reference-name').textContent=reference?reference.name:cpu?'Gespeicherte Standardstimme aus Deck':vc?'Bitte eine Zielreferenz hinzufügen':'Für 1,7B bitte eine Referenz hinzufügen';$('count').textContent=$('text').value.length+' / 1000';$('generate').disabled=busy||!!recording||!p||(vc?!source:(!$('text').value.trim()||$('text').value.length>1000))||(!cpu&&!reference);$('transcribe').disabled=busy||!!recording||!source||!sttId;$('profile').disabled=busy||!!recording||!profiles.length;}
function progress(message){$('error').hidden=true;$('empty').hidden=true;$('result').hidden=true;$('progress').hidden=false;$('status').textContent=message;}
function done(){busy=false;$('progress').hidden=true;if($('result').hidden)$('empty').hidden=false;update();}
async function poll(path,id){const deadline=Date.now()+1200000;while(Date.now()<deadline){await new Promise(r=>setTimeout(r,600));const d=await api(path),j=d.job;if(!j||j.id!==id)throw Error('Dieser Auftrag ist nicht mehr aktuell. Ein anderer Auftrag hat den Status ersetzt.');$('status').textContent=j.phase||'Athena arbeitet …';if(j.state==='complete')return j;if(j.state!=='running')throw Error(j.phase||'Auftrag beendet.');}throw Error('Zeitlimit überschritten. Den Auftrag in Deck prüfen.');}
@@ -12,11 +12,11 @@ async function setAudio(kind,blob){const audio=await normalize(blob,kind==='refe
for(const kind of ['reference','source']){$(kind+'-file').onchange=async e=>{try{if(e.target.files[0])await setAudio(kind,e.target.files[0]);}catch(e){error(e);}};$(kind+'-record').onclick=async()=>{try{if(recording){if(recording.kind===kind)recording.recorder.stop();return;}if(busy)return;if(!window.isSecureContext||!navigator.mediaDevices?.getUserMedia)throw Error('Mikrofon benötigt HTTPS. Bitte das Studio über Athena Deck öffnen.');const stream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:false,noiseSuppression:false,autoGainControl:false}});const type=['audio/webm;codecs=opus','audio/mp4'].find(t=>MediaRecorder.isTypeSupported(t));const recorder=new MediaRecorder(stream,type?{mimeType:type}:{}),chunks=[];recording={kind,recorder};const label=$(kind+'-record').textContent;$(kind+'-record').textContent='■ Aufnahme stoppen';let timer;recorder.ondataavailable=e=>{if(e.data.size)chunks.push(e.data);};recorder.onerror=()=>{stream.getTracks().forEach(t=>t.stop());clearTimeout(timer);recording=null;$(kind+'-record').textContent=label;error(Error('Aufnahme fehlgeschlagen.'));update();};recorder.onstop=async()=>{clearTimeout(timer);stream.getTracks().forEach(t=>t.stop());recording=null;$(kind+'-record').textContent=label;try{await setAudio(kind,new Blob(chunks,{type:recorder.mimeType}));}catch(e){error(e);}update();};recorder.start();timer=setTimeout(()=>{if(recorder.state==='recording')recorder.stop();},(kind==='reference'||selected()?.model?.repo==='laion/Humaneness-Voice-Converter'?29:119)*1000);update();}catch(e){error(e);}};}
$('reference-reset').onclick=()=>{if(busy)return;reference=null;$('reference-file').value='';$('reference-preview').hidden=true;$('reference-reset').hidden=true;update();};
for(const [id,show] of [['text-tab',false],['audio-tab',true]])$(id).onclick=()=>{$('text-tab').setAttribute('aria-selected',String(!show));$('audio-tab').setAttribute('aria-selected',String(show));$('source-panel').hidden=!show;};
$('profile').onchange=update;$('text').oninput=update;
$('pitch-semitones').oninput=()=>{$('pitch-value').textContent=(Number($('pitch-semitones').value)>0?'+':'')+$('pitch-semitones').value;};$('profile').onchange=update;$('text').oninput=update;
$('transcribe').onclick=async()=>{busy=true;update();progress('Aufnahme wird lokal transkribiert …');try{const f=new FormData();f.set('file',source,'aufnahme.wav');f.set('profile_id',sttId);f.set('language','de');const j=await api('stt/start',f),r=await poll('stt',j.id);$('text').value=r.text||'';if($('text').value.length>1000)throw Error('Das Transkript ist länger als 1000 Zeichen. Bitte den Text vor der Ausgabe kürzen.');}catch(e){error(e);}finally{done();}};
async function waveform(blob){const ctx=new AudioContext();try{const b=await ctx.decodeAudioData(await blob.arrayBuffer()),a=b.getChannelData(0),canvas=$('waveform'),c=canvas.getContext('2d');c.clearRect(0,0,600,120);c.strokeStyle='#bd5433';c.lineWidth=2;for(let x=0;x<300;x++){const start=Math.floor(x*a.length/300),end=Math.floor((x+1)*a.length/300);let peak=0;for(let i=start;i<end;i++)peak=Math.max(peak,Math.abs(a[i]));c.beginPath();c.moveTo(x*2,60-peak*52);c.lineTo(x*2,60+peak*52);c.stroke();}}finally{await ctx.close();}}
async function showResult(path,j,p){const url='/api/v1/'+path+'/audio?id='+encodeURIComponent(j.id);const response=await fetch(url);if(!response.ok)throw Error('Die fertige Ausgabe konnte nicht geladen werden.');const blob=await response.blob();if(outputUrl)URL.revokeObjectURL(outputUrl);outputUrl=URL.createObjectURL(blob);$('output').src=outputUrl;$('download').href=url;$('result-meta').textContent=p.name+' · '+(j.source_duration?'Quelle '+Number(j.source_duration).toFixed(2)+'s · Ausgabe ':'')+(j.duration?Number(j.duration).toFixed(j.source_duration?2:1)+' Sekunden · ':'')+'WAV';$('result').hidden=false;await waveform(blob);}
async function showResult(path,j,p){const url='/api/v1/'+path+'/audio?id='+encodeURIComponent(j.id);const response=await fetch(url);if(!response.ok)throw Error('Die fertige Ausgabe konnte nicht geladen werden.');const blob=await response.blob();if(outputUrl)URL.revokeObjectURL(outputUrl);outputUrl=URL.createObjectURL(blob);$('output').src=outputUrl;$('download').href=url;$('result-meta').textContent=p.name+' · '+(j.source_duration?'Quelle '+Number(j.source_duration).toFixed(2)+'s · Ausgabe ':'')+(j.duration?Number(j.duration).toFixed(j.source_duration?2:1)+' Sekunden · ':'')+'WAV'+(j.pitch?' · Tonhöhe '+(j.pitch.applied_semitones>0?'+':'')+j.pitch.applied_semitones+' Halbtöne':'');if(j.pitch?.warnings?.length)error(Error(j.pitch.warnings.join(' ')));$('result').hidden=false;await waveform(blob);}
$('latest').onclick=async()=>{busy=true;update();progress('Letzte Umwandlung wird geladen …');try{const j=(await api('conversion')).job,p=selected();if(!j||j.profile_id!==p.id||j.state!=='complete')throw Error('Keine fertige Umwandlung für dieses Profil verfügbar.');await showResult('conversion',j,p);}catch(e){error(e);}finally{done();}};
$('generate').onclick=async()=>{busy=true;update();progress('Deine Stimme wird vorbereitet …');const p=selected(),cpu=p.kind==='audio',vc=p.model.repo==='laion/Humaneness-Voice-Converter',path=vc?'conversion':cpu?'qwen-native':'voice';try{const f=new FormData();f.set('profile_id',p.id);if(vc){f.set('source',source,'source.wav');f.set('reference',reference,'reference.wav');}else{f.set('text',$('text').value);f.set('language','German');if(reference)f.set('file',reference,'reference.wav');}if(cpu)f.set('speaker','default');else if(!vc){f.set('device','3060');f.set('reference_text',$('reference-text').value);}const j=await api(path+'/start',f),r=await poll(path,j.id);await showResult(path,r,p);}catch(e){error(e);}finally{done();}};
$('generate').onclick=async()=>{busy=true;update();progress('Deine Stimme wird vorbereitet …');const p=selected(),cpu=p.kind==='audio',vc=p.model.repo==='laion/Humaneness-Voice-Converter',path=vc?'conversion':cpu?'qwen-native':'voice';try{const f=new FormData();f.set('profile_id',p.id);if(vc){f.set('pitch_auto',String($('pitch-auto').checked));f.set('pitch_semitones',$('pitch-semitones').value);f.set('source',source,'source.wav');f.set('reference',reference,'reference.wav');}else{f.set('text',$('text').value);f.set('language','German');if(reference)f.set('file',reference,'reference.wav');}if(cpu)f.set('speaker','default');else if(!vc){f.set('device','3060');f.set('reference_text',$('reference-text').value);}const j=await api(path+'/start',f),r=await poll(path,j.id);await showResult(path,r,p);}catch(e){error(e);}finally{done();}};
async function init(){try{const [d,policy]=await Promise.all([api('profiles'),api('audio-policy')]);profiles=d.profiles.filter(p=>p.runnable&&(p.model?.repo==='laion/Humaneness-Voice-Converter'||(p.kind==='audio'&&p.model?.repo==='Serveurperso/Qwen3-TTS-GGUF')||(p.kind==='voice'&&p.model?.repo==='Qwen/Qwen3-TTS-12Hz-1.7B-Base'))).sort((a,b)=>(a.kind==='audio'?-1:1)-(b.kind==='audio'?-1:1));const stts=d.profiles.filter(p=>p.kind==='stt'&&p.runnable);sttId=stts.find(p=>p.id===policy.settings.stt.profile_id)?.id||stts[0]?.id;$('profile').replaceChildren(...profiles.map(p=>new Option(p.name,p.id)));if(!profiles.length)throw Error('Kein ausführbares Qwen-Profil gefunden. Bitte in Deck einrichten.');update();}catch(e){error(e);}}
init();
+1 -1
View File
@@ -2,5 +2,5 @@
<header><a href="/#services" class="back">← Athena Deck</a><span class="tag">QWEN & VOICE CONVERSION</span><span class="privacy">● Lokal auf Athena</span></header>
<main><div class="hero"><div><p class="eyebrow">DEINE WORTE. DEINE ZIELSTIMME.</p><h1>Stimmatelier<span>.</span></h1><p class="intro">Texte sprechen lassen. Deine Aufnahmen mit neuer Stimme hören.</p></div><div class="soundmark" aria-hidden="true"><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i></div></div>
<div class="layout"><section class="inputs"><article class="card"><div class="section-title"><span class="number">01</span><h2>Modell & Zielstimme</h2></div><label for="profile">Stimmprofil</label><select id="profile" disabled><option>Profile werden geladen …</option></select><p id="model-note" class="hint"></p><div class="reference"><div class="row"><h3>Referenzstimme</h3><span class="badge">WAV · 1–30 Sekunden</span></div><p class="hint">Eine klare, ruhige Aufnahme der gewünschten Stimme. Sie bestimmt den Klang, nicht den zu sprechenden Text.</p><label class="upload" for="reference-file">Referenz-WAV auswählen<input id="reference-file" type="file" accept=".wav,audio/wav"></label><div class="mic-row"><button id="reference-record" type="button" class="secondary">● Referenz aufnehmen</button><span id="reference-name" class="hint">Gespeicherte Standardstimme aus Deck</span></div><audio id="reference-preview" controls hidden></audio><button id="reference-reset" class="text-button" type="button" hidden>Referenz entfernen</button><label for="reference-text">Transkript der Referenz <span class="muted">optional · für 1,7B</span></label><textarea id="reference-text" rows="2" placeholder="Was wird in deiner Referenzaufnahme gesagt?"></textarea></div></article>
<article class="card"><div class="section-title"><span class="number">02</span><h2>Was soll gesprochen werden?</h2></div><div class="tabs" role="tablist" aria-label="Quelle"><button role="tab" id="text-tab" aria-selected="true">Text schreiben</button><button role="tab" id="audio-tab" aria-selected="false">Aufnahme verwenden</button></div><div id="source-panel" hidden><p class="hint">WAV hochladen oder aufnehmen. Danach den erkannten Text prüfen. Timing und Betonung der Originalaufnahme werden nicht exakt übernommen.</p><label class="upload" for="source-file">Sprach-WAV auswählen<input id="source-file" type="file" accept=".wav,audio/wav"></label><div class="mic-row"><button id="source-record" type="button" class="secondary">● Sprache aufnehmen</button><span id="source-name" class="hint">Bis 120 Sekunden</span></div><audio id="source-preview" controls hidden></audio><button id="transcribe" type="button" class="secondary" disabled>Aufnahme in Text umwandeln</button></div><label for="text">Text für die Ausgabe</label><textarea id="text" rows="7" maxlength="1000" placeholder="Schreibe hier deinen Text oder übernimm ihn aus einer Aufnahme …"></textarea><div class="row"><span class="hint">Deutsch · Ausgabe als WAV</span><span id="count" class="hint">0 / 1000</span></div><button id="generate" class="primary" disabled>Sprache erzeugen <span>↗</span></button><button id="latest" type="button" class="secondary" hidden>Letzte Umwandlung anzeigen</button><p id="error" role="alert" class="error" hidden></p></article></section>
<article class="card"><div class="section-title"><span class="number">02</span><h2>Was soll gesprochen werden?</h2></div><div class="tabs" role="tablist" aria-label="Quelle"><button role="tab" id="text-tab" aria-selected="true">Text schreiben</button><button role="tab" id="audio-tab" aria-selected="false">Aufnahme verwenden</button></div><div id="source-panel" hidden><p class="hint">WAV hochladen oder aufnehmen. Danach den erkannten Text prüfen. Timing und Betonung der Originalaufnahme werden nicht exakt übernommen.</p><label class="upload" for="source-file">Sprach-WAV auswählen<input id="source-file" type="file" accept=".wav,audio/wav"></label><div class="mic-row"><button id="source-record" type="button" class="secondary">● Sprache aufnehmen</button><span id="source-name" class="hint">Bis 120 Sekunden</span></div><audio id="source-preview" controls hidden></audio><button id="transcribe" type="button" class="secondary" disabled>Aufnahme in Text umwandeln</button></div><label for="text">Text für die Ausgabe</label><textarea id="text" rows="7" maxlength="1000" placeholder="Schreibe hier deinen Text oder übernimm ihn aus einer Aufnahme …"></textarea><div class="row"><span class="hint">Deutsch · Ausgabe als WAV</span><span id="count" class="hint">0 / 1000</span></div><div id="pitch-controls" hidden><label class="pitch-toggle"><input id="pitch-auto" type="checkbox" checked> Tonhöhe automatisch an Referenz anpassen</label><label for="pitch-semitones">Zusätzliche Tonhöhe: <output id="pitch-value">0</output> Halbtöne</label><input id="pitch-semitones" type="range" min="-12" max="12" step="0.5" value="0"><p class="hint">Automatik gleicht die mittlere Tonhöhe an die Zielstimme an. Der Regler verschiebt zusätzlich nach oben oder unten. Dauer und Tempo bleiben gleich; die Gesamtkorrektur ist auf ±12 Halbtöne begrenzt. Große Änderungen können künstlich klingen.</p></div><button id="generate" class="primary" disabled>Sprache erzeugen <span>↗</span></button><button id="latest" type="button" class="secondary" hidden>Letzte Umwandlung anzeigen</button><p id="error" role="alert" class="error" hidden></p></article></section>
<aside><article class="card output"><div class="section-title"><span class="number">03</span><h2>Deine Ausgabe</h2></div><div id="empty"><div class="empty-icon" aria-hidden="true">◉</div><h3>Hier bekommt dein Text eine Stimme.</h3><p>Wähle ein Profil, ergänze deine Zielstimme und starte die Erzeugung.</p></div><div id="progress" hidden><span class="spinner"></span><p id="status" role="status">Wird vorbereitet …</p><small>Du kannst diese Seite geöffnet lassen. Athena verarbeitet den Auftrag lokal.</small></div><div id="result" hidden><span class="success">FERTIG ZUM ANHÖREN</span><canvas id="waveform" width="600" height="120" aria-label="Wellenform der erzeugten Sprache"></canvas><audio id="output" controls></audio><a id="download" class="download" download="stimmatelier.wav">WAV herunterladen ↓</a><p id="result-meta" class="hint"></p></div></article><p class="footnote">Referenzaufnahmen werden nur für den Auftrag an Deck übertragen und anschließend aus dessen Arbeitsdateien entfernt. Ausgaben bleiben in Deck verfügbar. Keine Cloud-Dienste, keine zusätzlichen Modellkopien.</p></aside></div></main><footer>STIMMATELIER <span>Deine Worte. Deine Sprechweise. Deine Zielstimme.</span></footer></body></html>
+2
View File
@@ -1 +1,3 @@
:root{color-scheme:light;--bg:#f4f2ec;--ink:#252b28;--muted:#6f7770;--accent:#bd5433;--line:#dedfd5;--green:#48755c}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);font:15px/1.55 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}header,main,footer{max-width:1240px;margin:auto}header{display:flex;align-items:center;gap:22px;padding:28px 36px;border-bottom:1px solid var(--line)}a{color:inherit;text-decoration:none}.back{font-size:13px;color:var(--muted)}.tag,.eyebrow,.success{font-size:10px;font-weight:750;letter-spacing:2px}.tag{border-left:1px solid var(--line);padding-left:22px}.privacy{margin-left:auto;color:var(--green);font-size:12px}.hero{display:flex;align-items:center;justify-content:space-between;padding:48px 0 38px}.eyebrow{color:var(--accent);margin:0 0 10px}h1{font:clamp(45px,6vw,75px)/1.05 Georgia,serif;letter-spacing:-3px;margin:0 0 18px}h1 span{color:var(--accent)}.intro{color:var(--muted);max-width:500px;margin:0}.soundmark{display:flex;gap:8px;align-items:center;padding:10px 40px}.soundmark i{display:block;width:7px;height:28px;background:#c5cbbd;border-radius:20px}.soundmark i:nth-child(2n){height:62px}.soundmark i:nth-child(3n){height:100px;background:#b9c4b1}.soundmark i:nth-child(5){height:125px;background:var(--accent)}main{padding:0 36px 42px}.layout{display:grid;grid-template-columns:minmax(0,1.35fr) minmax(280px,.85fr);gap:24px}.inputs{display:grid;gap:22px}.card{background:#fdfdf9;border:1px solid var(--line);border-radius:18px;padding:26px;box-shadow:0 4px 18px #222b2104}.section-title{display:flex;gap:12px;align-items:center;margin-bottom:22px}.number{border:1px solid #dedfd5;border-radius:50%;width:30px;height:30px;display:grid;place-items:center;font-size:11px;color:var(--muted)}h2{font-size:17px;font-weight:650;margin:0}h3{font-size:14px;font-weight:600;margin:0}label{display:block;font-size:12px;font-weight:600;margin:15px 0 8px}select,textarea{display:block;width:100%;background:#f7f8f2;border:1px solid #d9ddd2;border-radius:10px;padding:12px;color:var(--ink);font:inherit}textarea{resize:vertical;font-size:14px;line-height:1.6}textarea::placeholder{color:#959c93}select:focus,textarea:focus,button:focus-visible,a:focus-visible{outline:2px solid #bd543380;outline-offset:3px}.hint,.footnote,small{font-size:12px;color:var(--muted)}.reference{border-top:1px solid var(--line);margin-top:22px;padding-top:20px}.row,.mic-row{display:flex;align-items:center;justify-content:space-between;gap:12px}.badge{font-size:10px;color:var(--muted);white-space:nowrap}.muted{color:var(--muted);font-weight:400}.upload{border:1px dashed #bfc8b8;border-radius:10px;padding:14px;text-align:center;background:#f6f8f1;cursor:pointer;font-size:12px}.upload input{display:block;margin:8px auto 0;max-width:100%;font-size:11px;font-weight:400}button{cursor:pointer;border:0;font:inherit}button:disabled{opacity:.45;cursor:not-allowed}.secondary{padding:9px 12px;border:1px solid #d8ddd1;border-radius:8px;background:#f6f8f1;font-size:12px;font-weight:550}.mic-row{justify-content:flex-start;flex-wrap:wrap;margin:12px 0}.text-button{background:none;color:var(--muted);padding:4px 0;font-size:11px;text-decoration:underline}audio{width:100%;height:42px;margin:12px 0}.tabs{display:flex;gap:4px;background:#edf0e7;border-radius:10px;padding:4px;margin-bottom:20px}.tabs button{flex:1;border-radius:7px;background:transparent;padding:10px;font-size:12px}.tabs [aria-selected=true]{background:#fff;box-shadow:0 1px 5px #0001}.primary{display:flex;align-items:center;justify-content:space-between;background:var(--ink);color:#fff;border-radius:10px;padding:16px 18px;width:100%;margin-top:20px;font-weight:600;font-size:13px}.primary span{font-size:20px;color:#e1b093}.error{color:#a13e30;background:#fff0ea;padding:12px;border-radius:8px;font-size:13px}.output{position:sticky;top:22px;min-height:350px}#empty{text-align:center;padding:42px 12px 25px;color:var(--muted)}.empty-icon{font-size:44px;color:#aab99e;margin-bottom:22px}#empty h3{font-family:Georgia,serif;font-size:21px;font-weight:400;color:var(--ink)}#empty p{font-size:13px;max-width:250px;margin:14px auto}.footnote{padding:0 14px;line-height:1.7}.success{color:var(--green)}canvas{width:100%;height:100px;margin-top:25px}.download{display:block;border:1px solid #ccd6c5;background:#edf3e7;border-radius:9px;text-align:center;padding:12px;font-size:12px;font-weight:650}.spinner{display:block;width:30px;height:30px;border:2px solid #e6e8de;border-top-color:var(--accent);border-radius:50%;animation:spin 1s linear infinite;margin:45px auto 20px}#progress{text-align:center}#status{font-size:14px}footer{display:flex;justify-content:space-between;border-top:1px solid var(--line);padding:24px 36px;font-size:10px;letter-spacing:2px;color:var(--muted)}footer span{letter-spacing:0}[hidden]{display:none!important}@keyframes spin{to{transform:rotate(360deg)}}@media(max-width:750px){header{padding:20px}.tag{display:none}main{padding:0 18px 30px}.hero{padding:30Line truncated
#pitch-controls{margin:1.3rem 0;padding:1rem;border:1px solid var(--line,#ddd);border-radius:12px}#pitch-controls .pitch-toggle{display:flex;align-items:center;gap:.6rem}#pitch-auto{width:auto;accent-color:#bd5433}#pitch-semitones{width:100%;accent-color:#bd5433}
+5
View File
@@ -1,5 +1,10 @@
# Neuer Athena-Router: aktueller Dokumentationsstand
Am 19.Oktober2026 ergänzt: **automatischer Tonhöhenabgleich an die Referenz**
und zusätzlicher ±12-Halbtonregler für Humaneness im Stimmatelier. CPU-DSP nach
der Konvertierung, feste Ausgabedauer, Formanterhalt; keine Modelländerung.
API-Felder optional und abwärtskompatibel. [Rezept und Abnahme](maintenance/2026-10-19-humaneness.md#tonhöhenanpassung-am-selben-tag).
Am 19.Oktober2026 zusätzlich **Humaneness Voice Conversion aktiviert**:
Gepinnte Gewichte und Laufzeit geprüft, Profil regulär gespeichert und freigegeben.
Direkte Aufnahme/WAV → andere Stimme ohne STT in Stimmatelier. Reale API- und
@@ -0,0 +1,31 @@
{
"id": "d4e024d1c8524296b7375a01cb144eac",
"state": "complete",
"gpu": "NVIDIA GeForce RTX 3060",
"source_duration": 6.32,
"duration": 6.32,
"pitch": {
"automatic": true,
"manual_semitones": 0.0,
"automatic_semitones": -3.5,
"applied_semitones": -3.5,
"reference": {
"hz": 114.58,
"voiced_frames": 251,
"confident_frames": 124
},
"before": {
"hz": 140.25,
"voiced_frames": 286,
"confident_frames": 146
},
"warnings": [],
"after": {
"hz": 114.58,
"voiced_frames": 289,
"confident_frames": 121
}
},
"started_at": 1792413785.3705032,
"finished_at": 1792413795.9777164
}
@@ -0,0 +1,4 @@
{
"source": "Gerne, hier eine Micro-Story über deinen Arbeitsalltag, genau 50 Wörter.",
"converted": "Gerne. Hier eine Micro-Story über deinen Arbeitsalltag, genau 50 Wörter."
}
@@ -0,0 +1,88 @@
{
"speech": {
"automatic": true,
"manual_semitones": 0,
"automatic_semitones": -3.5,
"applied_semitones": -3.5,
"reference": {
"hz": 114.58,
"voiced_frames": 251,
"confident_frames": 124
},
"before": {
"hz": 140.25,
"voiced_frames": 286,
"confident_frames": 146
},
"warnings": [],
"after": {
"hz": 114.58,
"voiced_frames": 289,
"confident_frames": 121
},
"elapsed_seconds": 1.57,
"frames": 151680,
"sample_rate": 24000
},
"raise": {
"automatic": true,
"manual_semitones": 0,
"automatic_semitones": 6.2,
"applied_semitones": 6.2,
"reference": {
"hz": 200.65,
"voiced_frames": 288,
"confident_frames": 174
},
"before": {
"hz": 140.25,
"voiced_frames": 286,
"confident_frames": 146
},
"warnings": [],
"after": {
"hz": 201.82,
"voiced_frames": 290,
"confident_frames": 173
},
"elapsed_seconds": 0.62,
"frames": 151680,
"sample_rate": 24000
},
"silence": {
"automatic": true,
"manual_semitones": 0,
"automatic_semitones": 0.0,
"applied_semitones": 0.0,
"reference": null,
"before": {
"hz": 140.25,
"voiced_frames": 286,
"confident_frames": 146
},
"warnings": [
"Automatische Anpassung nicht m\u00f6glich: zu wenig sicher erkannte stimmhafte Sprache. Nur manueller Wert angewendet."
],
"after": {
"hz": 140.25,
"voiced_frames": 286,
"confident_frames": 146
},
"elapsed_seconds": 0.31,
"frames": 151680,
"sample_rate": 24000
},
"manual": {
"automatic": false,
"manual_semitones": 2,
"automatic_semitones": 0.0,
"applied_semitones": 2.0,
"reference": null,
"before": null,
"warnings": [],
"after": null,
"elapsed_seconds": 0.16,
"frames": 151680,
"sample_rate": 24000
}
}
+56
View File
@@ -116,3 +116,59 @@ geladen; erfolgreiche Antwort nach42,9s. Deck und Stimmatelier `healthy`,
beide `unless-stopped`, nativer CPU-Qwen-TTS-Worker läuft weiterhin. Auch die
Rohinputs des letzten GUI-Auftrags sind entfernt. Keine API-Keys, privaten
Referenzstimmen oder WAVs in Git; fremde Hermes-Änderungen unberührt.
## Tonhöhenanpassung am selben Tag
Auf Nutzerauftrag ergänzt: automatische mittlere Tonhöhe an Referenz angleichen,
plus zusätzlicher Halbtonregler±12 (0,5Schritte), gemeinsam auf±12 begrenzt.
Stimmatelier-Automatik standardmäßig ein; alte API-Aufrufe ohne Optionen bleiben
unverändert. Keine Geschlechtserkennung, kein fest angenommener Frauenbereich.
Eigener CPU-Helfer nach unverändertem offiziellen Modell; pYIN und FFmpeg/Rubber
Band sind in vorhandener Laufzeit vorhanden, keine neuen Pakete/Gewichte/Dienste.
Installations-/Native-/Restore-Rezept: `deploy/humaneness/README.md`.
Erste Auswertung nur hoher pYIN-Posteriorframes verzerrte den Median zu einzelnen
Vokalen. Vor Aktivierung korrigiert: Median des RMS-gefilterten stimmhaften
HMM-Tracks; getrennte Mindest-Konfidenzprüfung. Messbereich60–650Hz, mindestens12
Frames mit Posterior≥0,1. Stille/ungeeignete Referenz wird mit sichtbarer Warnung
übersprungen (manueller Wert bleibt). Formanten erhalten, Tempo1; exakt gleiche
WAV-Samplezahl geprüft. Keine Garantie für exakte stille Grenzen oder Klangidentität.
Abnahme:77 betroffene Backend-/Auth-/Endpoint-/Proxytests bestanden, danach9
gezielte Tests inklusive zusätzlicher CPU-Worker-Anbindung. JS/Python-Syntax und
Diff-Prüfung bestanden. Vier echte CPU-DSP-Fälle im aktivierten Deck-Build:
- Reale eigene synthetische Sprache:140,25Hz →114,58Hz; Referenz114,58Hz,
Korrektur−3,5Halbtöne. CPU-Schritt1,57s (vorgewärmter Analysecache).
- Kontrolliert erhöhte Sprachreferenz:140,25Hz →201,82Hz; Referenz200,65Hz,
Korrektur+6,2Halbtöne. CPU-Schritt0,62s. Dies ist ein DSP-Test mit künstlich
angehobener Referenz, kein Nachweis einer bestimmten weiblichen Sprecheridentität.
- Stille Referenz:Warnung, automatische Korrektur0, vorhandene Sprache erhalten.
- Manueller Regler+2:Filter erfolgreich ohne erforderliche Referenzanalyse.
- Alle Fälle151.680Frames/24kHz=6,32s, unverändert. Erste JIT-Analyse kann länger
dauern. Messungen: `../experiments/humaneness-2026-10-19/pitch-cpu-check.json`.
Vor Aktivierung reguläre Deck-GUI geprüft:0 laufende/0 wartende Anfragen, Worker
bereits gestoppt/kein Modell geladen. Danach reguläres App-Update mit vorhandener
Laufzeit: **athena-deck-standalone:0a107ae83542e4c5**. Stimmatelier neu gebaut,
identische isolierte Containerkonfiguration; beide healthy/unless-stopped.
Bestehendes UI-Restore-Rezept im Root-Helfer ebenfalls aktualisiert. Keine
Hosttreiber, Zugänge, Modellgewichte oder fremden Hermes-Dateien verändert.
Echter Service-API-Auftrag mit `pitch_auto=true`:RTX3060-Konvertierung und
anschließender CPU-Abgleich erfolgreich,6,32s →6,32s,140,25→114,58Hz bei
Referenz114,58Hz. Gesamte Anfrage11,61s einschließlich Modellstart/Verarbeitung.
Quell-/Referenzrohdateien danach entfernt. Keine neue LLM-Anfrage zur
Wiederherstellung:vor diesem Update war bereits kein LLM geladen.
Subjektiver Hörvergleich und echte tiefe Männeraufnahme gegen Anna benötigen
Nutzerabnahme. Die messbare Tonhöhe allein beweist keine identische Zielstimme.
Kein neuer Fresh-Host-Restore durchgeführt; bestehende verschlüsselte Job-
Sicherung enthält auch die numerischen Pitchmetadaten. Gewichte und private
Audioaufnahmen sind nicht im Git.
CPU-STT-Vergleich auch nach Tonhöhenkorrektur:dieselben Wörter, nur Interpunktion
abweichend (`pitch-content-check.json`). Auftragsdaten:`pitch-api-check.json`.
Die neue GUI-Sichtprüfung wartet auf erneute reguläre Anmeldung nach dem Update;
API und bereitgestellte UI-Assets sind aktualisiert, keine Anmeldung umgangen.
+2 -2
View File
@@ -388,10 +388,10 @@ class APIHandler(BaseHTTPRequestHandler):
if parsed.path=='/v1/audio/voice-conversions' and self.command=='POST':
from humaneness import read_upload
try:
model,source,reference=read_upload(self,field='model');p=ep.find_profile(model,'voice')
model,source,reference,options=read_upload(self,field='model');p=ep.find_profile(model,'voice')
from humaneness_runtime import supported
if not supported(p.get('model')):raise ValueError('Kein Voice-Conversion-Profil.')
job=ep.humaneness.start(p['id'],source,reference,wait=True);deadline=time.monotonic()+610
job=ep.humaneness.start(p['id'],source,reference,wait=True,**options);deadline=time.monotonic()+800
while time.monotonic()<deadline:
status=ep.humaneness.status()['job']
if not status or status['id']!=job['id']:raise ValueError('Auftragsstatus ersetzt.')
+32 -7
View File
@@ -1,5 +1,5 @@
"""Audio-to-audio conversion using the unchanged upstream Humaneness CLI."""
import io,json,os,re,signal,subprocess,threading,time,uuid,wave
import io,json,math,os,re,signal,subprocess,threading,time,uuid,wave
from email.parser import BytesParser
from email.policy import default
from pathlib import Path
@@ -27,12 +27,21 @@ def read_upload(handler,field='profile_id'):
if not message.is_multipart():raise ValueError('Ungültiges Multipart.')
for part in message.iter_parts():
name=part.get_param('name',header='content-disposition');data=part.get_payload(decode=True)
if name not in (field,'source','reference') or name in parts or part.is_multipart() or not isinstance(data,bytes):raise ValueError('Unbekanntes oder doppeltes Feld.')
if name not in (field,'source','reference','pitch_auto','pitch_semitones') or name in parts or part.is_multipart() or not isinstance(data,bytes):raise ValueError('Unbekanntes oder doppeltes Feld.')
parts[name]=data
if set(parts)!={field,'source','reference'} or not 1<=len(parts[field])<=128:raise ValueError('Profil, Quellaufnahme und Referenz erforderlich.')
if not {field,'source','reference'}<=set(parts) or not 1<=len(parts[field])<=128:raise ValueError('Profil, Quellaufnahme und Referenz erforderlich.')
try:name=parts[field].decode('utf-8')
except UnicodeError:raise ValueError('Ungültiger Profilname.') from None
return name,wav_input(parts['source']),wav_input(parts['reference'])
try:
auto=parts.get('pitch_auto',b'false').decode('ascii');manual=parts.get('pitch_semitones',b'0').decode('ascii')
if len(auto)>5 or len(manual)>16 or auto not in ('true','false'):raise ValueError()
options=pitch_options(auto=='true',float(manual))
except (UnicodeError,ValueError):raise ValueError('Tonhöhe: pitch_auto=true/false und pitch_semitones zwischen -12 und12 erforderlich.') from None
return name,wav_input(parts['source']),wav_input(parts['reference']),options
def pitch_options(pitch_auto=False,pitch_semitones=0):
if not isinstance(pitch_auto,bool) or isinstance(pitch_semitones,bool) or not isinstance(pitch_semitones,(int,float)) or not math.isfinite(pitch_semitones) or not -12<=pitch_semitones<=12:raise ValueError('Ungültige Tonhöhenkorrektur.')
return dict(pitch_auto=pitch_auto,pitch_semitones=float(pitch_semitones))
class Humaneness:
def __init__(self,root,runtime,profiles,scheduler):
@@ -40,7 +49,8 @@ class Humaneness:
def blockers(self,p):return [] if self.runtime.status()['installed'] else ['Humaneness-Laufzeit und Gewichte fehlen.']
def status(self):
with self.lock:return dict(runtime=self.runtime.status(),job=dict(self.job) if self.job else None)
def start(self,profile_id,source,reference,wait=False):
def start(self,profile_id,source,reference,wait=False,pitch_auto=False,pitch_semitones=0):
options=pitch_options(pitch_auto,pitch_semitones)
p=next((p for p in self.profiles.status()['profiles'] if p['id']==profile_id and supported(p.get('model'))),None)
if not p or not p['runnable']:raise ValueError('Humaneness-Profil nicht ausführbar.')
source=wav_input(source);reference=wav_input(reference)
@@ -54,7 +64,7 @@ class Humaneness:
if headroom is not None and headroom<6*1024**3:raise ValueError('Mindestens6GiB freier Deck-RAM erforderlich.')
ident=uuid.uuid4().hex;directory=self.root/ident;directory.mkdir(parents=True,mode=0o700);(directory/'source.wav').write_bytes(source);(directory/'reference.wav').write_bytes(reference)
with wave.open(io.BytesIO(source)) as w:source_duration=w.getnframes()/w.getframerate()
with self.lock:self.cancel.clear();self.job=dict(id=ident,profile_id=profile_id,state='running',phase='Humaneness: Stimme wird umgewandelt',started_at=time.time(),gpu=gpu['name'],source_duration=source_duration)
with self.lock:self.cancel.clear();self.job=dict(id=ident,profile_id=profile_id,state='running',phase='Humaneness: Stimme wird umgewandelt',started_at=time.time(),gpu=gpu['name'],source_duration=source_duration,**options)
threading.Thread(target=self._run,args=(ident,gpu,lease),daemon=True).start();return dict(self.job)
except Exception:
if 'directory' in locals():
@@ -74,6 +84,21 @@ class Humaneness:
if time.monotonic()>deadline:raise ValueError('Zeitlimit der Konvertierung erreicht.')
if self.cancel.is_set():raise InterruptedError()
if process.returncode:raise ValueError('Humaneness-Worker beendet, Exitcode '+str(process.returncode)+'.')
if self.job.get('pitch_auto') or self.job.get('pitch_semitones'):
with self.lock:self.job['phase']='Tonhöhe wird an die Referenz angepasst'
args=[str(python),str(Path(__file__).with_name('humaneness_pitch.py')),'--folder',str(folder),'--semitones',str(self.job['pitch_semitones'])]
if self.job['pitch_auto']:args.append('--automatic')
# CPU subprocess with the same controlled cancellation and timeout as inference.
env['CUDA_VISIBLE_DEVICES']='';env['NUMBA_NUM_THREADS']='2';env['NUMBA_CACHE_DIR']=str(self.runtime.root/'numba-cache')
with (folder/'worker.stderr').open('ab') as log:process=subprocess.Popen(args,env=env,stdout=subprocess.DEVNULL,stderr=log,start_new_session=True)
with self.lock:self.process=process
deadline=time.monotonic()+180
while process.poll() is None:
if self.cancel.wait(.2):raise InterruptedError()
if time.monotonic()>deadline:raise ValueError('Zeitlimit der Tonhöhenkorrektur erreicht.')
if self.cancel.is_set():raise InterruptedError()
if process.returncode:raise ValueError('Tonhöhenkorrektur fehlgeschlagen, Exitcode '+str(process.returncode)+'.')
with self.lock:self.job['pitch']=json.loads((folder/'pitch.json').read_text())
with wave.open(str(folder/'result.wav')) as w:duration=w.getnframes()/w.getframerate()
if not 0<duration<=40:raise ValueError('Ungültige Ausgabedauer.')
with self.lock:self.job['duration']=duration
@@ -85,7 +110,7 @@ class Humaneness:
try:os.killpg(process.pid,signal.SIGTERM);process.wait(10)
except subprocess.TimeoutExpired:os.killpg(process.pid,signal.SIGKILL);process.wait()
except ProcessLookupError:pass
for name in ('source.wav','reference.wav'):(folder/name).unlink(missing_ok=True)
for name in ('source.wav','reference.wav','pitch-result.wav'):(folder/name).unlink(missing_ok=True)
if state!='complete':(folder/'result.wav').unlink(missing_ok=True)
with self.lock:self.process=None;self.job.update(state=state,phase=phase,finished_at=time.time());(folder/'job.json').write_text(json.dumps(self.job))
lease.__exit__(None,None,None);self.gate.release()
+90
View File
@@ -0,0 +1,90 @@
"""Optional CPU-only, reference-matched pitch correction after voice conversion.
Uses the existing isolated Humaneness Python environment, not Deck's interpreter.
No model downloads; FFmpeg/librubberband keeps duration and vocal formants.
"""
import argparse
import json
import math
import os
from pathlib import Path
import subprocess
import wave
def estimate(path):
import librosa
import numpy as np
y, sr = librosa.load(path, sr=16000, mono=True)
if not len(y) or float(np.max(np.abs(y))) < .001:
return None
f0, voiced, probability = librosa.pyin(
y, sr=sr, fmin=60, fmax=650, frame_length=1024, hop_length=256)
rms = librosa.feature.rms(y=y, frame_length=1024, hop_length=256)[0]
n = min(len(f0), len(rms))
valid = (voiced[:n] & np.isfinite(f0[:n])
& (rms[:n] > max(.001, float(np.max(rms)) * .03)))
values = f0[:n][valid]
# pYIN's HMM tracks voiced frames across syllables. Selecting only high-
# posterior frames biases the median toward particular vowels/pitch ranges.
# Use the entire voiced track, but require independent confidence evidence.
confident = int(np.sum(valid & (probability[:n] >= .1)))
if len(values) < 12 or confident < 12:
return None
return dict(hz=round(float(np.median(values)), 2), voiced_frames=int(len(values)),
confident_frames=confident)
def correction(reference, converted, automatic, manual):
"""A constant semitone shift preserves the relative melodic contour."""
notes = []
auto = 0.0
if automatic:
if reference and converted:
auto = 12 * math.log2(reference['hz'] / converted['hz'])
else:
notes.append('Automatische Anpassung nicht möglich: zu wenig sicher erkannte stimmhafte Sprache. Nur manueller Wert angewendet.')
shift = max(-12.0, min(12.0, auto + manual))
if abs(shift - (auto + manual)) > .001:
notes.append('Gesamtkorrektur zum Schutz vor starken Artefakten auf ±12 Halbtöne begrenzt.')
return dict(automatic=automatic, manual_semitones=manual,
automatic_semitones=round(auto, 3), applied_semitones=round(shift, 3),
reference=reference, before=converted, warnings=notes)
def process(folder, automatic, manual):
folder = Path(folder)
result = folder / 'result.wav'
metadata = correction(estimate(folder/'reference.wav') if automatic else None,
estimate(result) if automatic else None, automatic, manual)
# Reference and converted median are used deliberately: correcting the source
# before the neural converter would leave its final pitch unconstrained.
shift = metadata['applied_semitones']
if abs(shift) >= .05:
with wave.open(str(result)) as w:
frames, rate = w.getnframes(), w.getframerate()
filtered = folder/'pitch-result.wav'
ratio = 2 ** (shift / 12)
subprocess.run(['ffmpeg', '-nostdin', '-hide_banner', '-loglevel', 'error', '-y',
'-i', str(result), '-af',
f'rubberband=tempo=1:pitch={ratio:.10f}:formant=preserved:pitchq=quality,apad,atrim=end_sample={frames}',
'-ar', str(rate), '-ac', '1', '-c:a', 'pcm_s16le', str(filtered)],
check=True, timeout=90, stdout=subprocess.DEVNULL)
with wave.open(str(filtered)) as w:
if w.getnframes() != frames or w.getframerate() != rate:
raise ValueError('Tonhöhenkorrektur hat die Ausgabedauer verändert.')
os.replace(filtered, result)
metadata['after'] = estimate(result) if automatic else None
(folder/'pitch.json').write_text(json.dumps(metadata, ensure_ascii=False))
return metadata
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--folder', type=Path, required=True)
parser.add_argument('--automatic', action='store_true')
parser.add_argument('--semitones', type=float, default=0)
args = parser.parse_args()
if not math.isfinite(args.semitones) or not -12 <= args.semitones <= 12:
parser.error('semitones must be finite and within -12..12')
process(args.folder, args.automatic, args.semitones)
+2 -2
View File
@@ -907,8 +907,8 @@ class Handler(BaseHTTPRequestHandler):
if self.path == '/api/v1/conversion/start':
try:
from humaneness import read_upload as read_conversion_upload
ident,source,reference=read_conversion_upload(self)
return self.respond(self.server.humaneness.start(ident,source,reference))
ident,source,reference,options=read_conversion_upload(self)
return self.respond(self.server.humaneness.start(ident,source,reference,**options))
except (OSError,ValueError,InferenceError) as exc:return self.respond({'error':str(exc)},400)
if self.path == '/api/v1/conversion/cancel':return self.respond(self.server.humaneness.stop() or {'ok':True})
if self.path in ('/api/v1/qwen-native/install','/api/v1/qwen-native/install-cancel','/api/v1/qwen-native/start','/api/v1/qwen-native/cancel'):
+39 -2
View File
@@ -2,7 +2,7 @@ import contextlib,http.client,io,json,tempfile,unittest,wave
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import Mock,MagicMock,patch
from humaneness import Humaneness,wav_input,read_upload
from humaneness import Humaneness,wav_input,read_upload,pitch_options
from humaneness_runtime import supported,REPO,REVISION
from inference import Scheduler,InferenceError
@@ -44,6 +44,20 @@ class ConversionTests(unittest.TestCase):
self.assertEqual(h.job['state'],'complete');self.assertFalse((folder/'source.wav').exists());self.assertFalse((folder/'reference.wav').exists());self.assertEqual(h.audio(job),audio());lease.__exit__.assert_called_once()
with self.assertRaises(ValueError):h.audio('../bad')
def test_pitch_worker_runs_cpu_and_metadata_is_returned(self):
with tempfile.TemporaryDirectory() as d:
root=Path(d);ident='b'*32;folder=root/ident;folder.mkdir()
for n in ('source.wav','reference.wav','result.wav'):(folder/n).write_bytes(audio())
(folder/'pitch.json').write_text(json.dumps({'applied_semitones':4,'warnings':[]}))
h=Humaneness(root,SimpleNamespace(root=root,paths=lambda:(Path('/python'),root/'model')),None,None)
h.job=dict(id=ident,pitch_auto=True,pitch_semitones=0);h.gate.acquire();lease=MagicMock()
process=Mock();process.poll.return_value=0;process.returncode=0
with patch('humaneness.subprocess.Popen',return_value=process) as start:h._run(ident,{'uuid':'gpu'},lease)
self.assertEqual(h.job['state'],'complete');self.assertEqual(h.job['pitch']['applied_semitones'],4)
self.assertEqual(start.call_count,2);self.assertEqual(start.call_args.kwargs['env']['CUDA_VISIBLE_DEVICES'],'')
self.assertIn('--automatic',start.call_args.args[0]);self.assertFalse((folder/'reference.wav').exists());lease.__exit__.assert_called_once()
import test_endpoint
class ConversionEndpointTests(unittest.TestCase):
setUp=test_endpoint.EndpointTests.setUp
@@ -60,4 +74,27 @@ class ConversionEndpointTests(unittest.TestCase):
for token,expected in [('wrong',401),('A'*32,200)]:
conn=http.client.HTTPConnection('127.0.0.1',self.port,timeout=5);conn.request('POST','/v1/audio/voice-conversions',body,headers={'Authorization':'Bearer '+token,'Content-Type':'multipart/form-data; boundary=test'});r=conn.getresponse();result=r.read();conn.close();self.assertEqual(r.status,expected)
if expected==200:self.assertEqual(result,audio())
backend.start.assert_called_once()
backend.start.assert_called_once_with('hvc',audio(),audio(),wait=True,pitch_auto=False,pitch_semitones=0.0)
class PitchTests(unittest.TestCase):
def test_controls_are_validated_before_gpu_use(self):
for auto,manual in [(True,float('nan')),(False,float('inf')),(True,13),('true',0),(True,True)]:
with self.assertRaises(ValueError):pitch_options(auto,manual)
self.assertEqual(pitch_options(True,-3.5),dict(pitch_auto=True,pitch_semitones=-3.5))
def test_optional_multipart_pitch_controls_and_backwards_default(self):
def parse(fields):
extra=b''.join(b'--test\r\nContent-Disposition: form-data; name="'+k.encode()+b'"\r\n\r\n'+v.encode()+b'\r\n' for k,v in fields)
body=multipart().replace(b'--test--\r\n',extra+b'--test--\r\n')
return read_upload(SimpleNamespace(connection=Mock(),rfile=io.BytesIO(body),headers={'Content-Type':'multipart/form-data; boundary=test','Content-Length':str(len(body))}))
self.assertEqual(parse([])[3],dict(pitch_auto=False,pitch_semitones=0.0))
self.assertEqual(parse([('pitch_auto','true'),('pitch_semitones','2.5')])[3],dict(pitch_auto=True,pitch_semitones=2.5))
for fields in [[('pitch_auto','yes')],[('pitch_semitones','nan')],[('pitch_semitones','-13')],[('pitch_auto','true'),('pitch_auto','false')]]:
with self.assertRaises(ValueError):parse(fields)
def test_reference_matching_manual_offset_and_confidence_fallback(self):
from humaneness_pitch import correction
r=correction({'hz':220},{'hz':110},True,-2)
self.assertEqual(r['applied_semitones'],10)
self.assertTrue(correction({'hz':440},{'hz':110},True,0)['warnings'])
r=correction(None,{'hz':110},True,2)
self.assertEqual(r['applied_semitones'],2);self.assertTrue(r['warnings'])
self.assertEqual(correction(None,None,False,-3)['applied_semitones'],-3)