Match voice conversion pitch to reference with optional CPU correction
This commit is contained in:
1 parent
04cd46e3e6
commit
369cb2ffe5
16 files changed
+408
-19
No files matched your search
@@ -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)
|
||||
Reference in new issue
Block a user