UTAU-WebUI / compressed_utau_engine.py
crlotwhite's picture
Add UTAU WebUI project with LFS support for voice files
1056960
import tempfile
import numpy as np
import soundfile as sf
from pathlib import Path
from typing import Dict, List, Optional, Tuple, Union
import logging
from straycat import Resampler
from voice_data_converter import CompressedVoicebankManager, OtoEntry
logger = logging.getLogger(__name__)
class CompressedUTAUEngine:
"""์••์ถ•๋œ HDF5 ๋ณด์ด์Šค๋ฑ…ํฌ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” UTAU ํ˜ธํ™˜ ์Œ์„ฑ ํ•ฉ์„ฑ ์—”์ง„"""
def __init__(self, compressed_voicebank_path: Union[str, Path]):
self.voicebank = CompressedVoicebankManager(compressed_voicebank_path)
self.default_phoneme = "ใ‚" # ๊ธฐ๋ณธ ์Œ์†Œ
logger.info(f"์••์ถ•๋œ UTAU ์—”์ง„ ์ดˆ๊ธฐํ™” ์™„๋ฃŒ")
def synthesize_sequence(self,
notes: List[Dict],
lyrics: List[str],
tempo: int = 120,
volume: int = 100) -> Tuple[Optional[str], str]:
"""๋…ธํŠธ ์‹œํ€€์Šค์™€ ๊ฐ€์‚ฌ๋กœ ์Œ์„ฑ ํ•ฉ์„ฑ"""
if len(notes) != len(lyrics):
return None, "๋…ธํŠธ์™€ ๊ฐ€์‚ฌ์˜ ๊ฐœ์ˆ˜๊ฐ€ ์ผ์น˜ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค."
if not notes:
return None, "ํ•ฉ์„ฑํ•  ๋…ธํŠธ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค."
try:
# ์ „์ฒด ์‹œํ€€์Šค ๊ธธ์ด ๊ณ„์‚ฐ
max_end_time = max(note.get('endSeconds',
note.get('startSeconds', 0) + note.get('durationSeconds', 0.5))
for note in notes)
sample_rate = 44100
total_samples = int(max_end_time * sample_rate) + sample_rate
final_audio = np.zeros(total_samples)
# ๊ฐ ๋…ธํŠธ ํ•ฉ์„ฑ
for i, (note, lyric) in enumerate(zip(notes, lyrics)):
try:
# ์Œ์†Œ ๋ณ€ํ™˜
phoneme = self._lyric_to_phoneme(lyric)
# oto ์—”ํŠธ๋ฆฌ ์ฐพ๊ธฐ
oto_entry = self.voicebank.get_sample_for_phoneme(phoneme)
if not oto_entry:
logger.warning(f"์Œ์†Œ '{phoneme}'์— ํ•ด๋‹นํ•˜๋Š” ์ƒ˜ํ”Œ์„ ์ฐพ์„ ์ˆ˜ ์—†์Œ")
continue
# ์˜ค๋””์˜ค ๋ฐ์ดํ„ฐ ๋กœ๋“œ (์••์ถ•๋œ ๋ฐ์ดํ„ฐ์—์„œ)
audio_result = self.voicebank.get_audio_data(oto_entry.filename)
if not audio_result:
logger.warning(f"์˜ค๋””์˜ค ํŒŒ์ผ ๋กœ๋“œ ์‹คํŒจ: {oto_entry.filename}")
continue
source_audio, source_sample_rate = audio_result
# ๋…ธํŠธ ํ•ฉ์„ฑ
synth_audio = self._synthesize_note(
note, oto_entry, source_audio, source_sample_rate, tempo, volume
)
if synth_audio is not None:
# ์‹œ๊ฐ„ ์œ„์น˜ ๊ณ„์‚ฐ ๋ฐ ์˜ค๋””์˜ค ๋ฐฐ์น˜
start_sample = int(note.get('startSeconds', 0) * sample_rate)
end_sample = start_sample + len(synth_audio)
if end_sample <= len(final_audio):
final_audio[start_sample:end_sample] += synth_audio * (note.get('velocity', 100) / 100)
else:
# ๋ฒ„ํผ ํ™•์žฅ
new_size = end_sample + sample_rate
new_final_audio = np.zeros(new_size)
new_final_audio[:len(final_audio)] = final_audio
new_final_audio[start_sample:end_sample] += synth_audio * (note.get('velocity', 100) / 100)
final_audio = new_final_audio
logger.info(f"๋…ธํŠธ {i+1} ํ•ฉ์„ฑ ์™„๋ฃŒ: {phoneme}")
except Exception as e:
logger.error(f"๋…ธํŠธ {i+1} ํ•ฉ์„ฑ ์‹คํŒจ: {e}")
continue
# ์ตœ์ข… ์˜ค๋””์˜ค ์ •๊ทœํ™”
if np.max(np.abs(final_audio)) > 0:
final_audio = final_audio / np.max(np.abs(final_audio)) * 0.85
# ์ž„์‹œ ํŒŒ์ผ ์ €์žฅ
output_file = tempfile.NamedTemporaryFile(suffix='.wav', delete=False)
sf.write(output_file.name, final_audio, sample_rate)
output_file.close()
duration_sec = len(final_audio) / sample_rate
return output_file.name, f"โœ… ์••์ถ•๋œ ๋ณด์ด์Šค๋ฑ…ํฌ๋กœ ํ•ฉ์„ฑ ์™„๋ฃŒ: {len(notes)}๊ฐœ ๋…ธํŠธ, {duration_sec:.1f}์ดˆ"
except Exception as e:
logger.error(f"์‹œํ€€์Šค ํ•ฉ์„ฑ ์‹คํŒจ: {e}")
return None, f"โŒ ํ•ฉ์„ฑ ์‹คํŒจ: {str(e)}"
def _lyric_to_phoneme(self, lyric: str) -> str:
"""๊ฐ€์‚ฌ๋ฅผ ์Œ์†Œ๋กœ ๋ณ€ํ™˜ (๊ธฐ์กด ๋กœ์ง๊ณผ ๋™์ผ)"""
lyric = lyric.strip()
if not lyric:
return self.default_phoneme
# ํ•œ๊ธ€ โ†’ ์ผ๋ณธ์–ด ์Œ์†Œ ๋ณ€ํ™˜ (๊ฐ„๋‹จํ•œ ๋งคํ•‘)
hangul_to_japanese = {
'๊ฐ€': 'ka', '๋‚˜': 'na', '๋‹ค': 'da', '๋ผ': 'ra', '๋งˆ': 'ma',
'๋ฐ”': 'ba', '์‚ฌ': 'sa', '์•„': 'a', '์ž': 'za', '์ฐจ': 'cha',
'์นด': 'ka', 'ํƒ€': 'ta', 'ํŒŒ': 'pa', 'ํ•˜': 'ha',
'๊ฑฐ': 'ke', '๋„ˆ': 'ne', '๋”': 'de', '๋Ÿฌ': 're', '๋จธ': 'me',
'๋ฒ„': 'be', '์„œ': 'se', '์–ด': 'e', '์ €': 'ze', '์ฒ˜': 'che',
'์ปค': 'ke', 'ํ„ฐ': 'te', 'ํผ': 'pe', 'ํ—ˆ': 'he',
'๊ณ ': 'ko', '๋…ธ': 'no', '๋„': 'do', '๋กœ': 'ro', '๋ชจ': 'mo',
'๋ณด': 'bo', '์†Œ': 'so', '์˜ค': 'o', '์กฐ': 'zo', '์ดˆ': 'cho',
'์ฝ”': 'ko', 'ํ† ': 'to', 'ํฌ': 'po', 'ํ˜ธ': 'ho',
'๊ตฌ': 'ku', '๋ˆ„': 'nu', '๋‘': 'du', '๋ฃจ': 'ru', '๋ฌด': 'mu',
'๋ถ€': 'bu', '์ˆ˜': 'su', '์šฐ': 'u', '์ฃผ': 'zu', '์ถ”': 'chu',
'์ฟ ': 'ku', 'ํˆฌ': 'tu', 'ํ‘ธ': 'pu', 'ํ›„': 'hu',
'๊ธฐ': 'ki', '๋‹ˆ': 'ni', '๋””': 'di', '๋ฆฌ': 'ri', '๋ฏธ': 'mi',
'๋น„': 'bi', '์‹œ': 'si', '์ด': 'i', '์ง€': 'zi', '์น˜': 'chi',
'ํ‚ค': 'ki', 'ํ‹ฐ': 'ti', 'ํ”ผ': 'pi', 'ํžˆ': 'hi',
'๋„': 'do', '๋ ˆ': 're', '๋ฏธ': 'mi', 'ํŒŒ': 'pa', '์†”': 'so', '๋ผ': 'ra', '์‹œ': 'si'
}
if lyric in hangul_to_japanese:
return hangul_to_japanese[lyric]
return lyric if lyric in self.voicebank.oto_entries else self.default_phoneme
def _synthesize_note(self,
note: Dict,
oto_entry: OtoEntry,
source_audio: np.ndarray,
source_sample_rate: int,
tempo: int,
volume: int) -> Optional[np.ndarray]:
"""๊ฐœ๋ณ„ ๋…ธํŠธ ํ•ฉ์„ฑ (์••์ถ•๋œ ์˜ค๋””์˜ค ๋ฐ์ดํ„ฐ ์‚ฌ์šฉ)"""
try:
# ์ž„์‹œ ํŒŒ์ผ์— ์›๋ณธ ์˜ค๋””์˜ค ์ €์žฅ
temp_input = tempfile.NamedTemporaryFile(suffix='.wav', delete=False)
sf.write(temp_input.name, source_audio, source_sample_rate)
temp_input.close()
# ์ถœ๋ ฅ ํŒŒ์ผ
temp_output = tempfile.NamedTemporaryFile(suffix='.wav', delete=False)
temp_output.close()
# ๋…ธํŠธ ์ •๋ณด ์ถ”์ถœ
pitch = note['pitch']
duration_ms = note.get('durationSeconds', 0.5) * 1000
velocity = note.get('velocity', 100)
# MIDI ๋…ธํŠธ๋ฅผ ์Œ๊ณ„๋ช…์œผ๋กœ ๋ณ€ํ™˜
note_name = self._midi_to_note_name(pitch)
# straycat Resampler๋กœ ํ•ฉ์„ฑ
resampler = Resampler(
in_file=temp_input.name,
out_file=temp_output.name,
pitch=note_name,
velocity=velocity,
length=max(duration_ms, 200), # ์ตœ์†Œ 200ms
volume=volume,
offset=oto_entry.offset,
consonant=oto_entry.consonant,
cutoff=oto_entry.cutoff,
modulation=10,
tempo=f'!{tempo}'
)
# ํ•ฉ์„ฑ๋œ ์˜ค๋””์˜ค ๋กœ๋“œ
if Path(temp_output.name).exists():
synth_audio, _ = sf.read(temp_output.name)
# ์ •๋ฆฌ
Path(temp_input.name).unlink(missing_ok=True)
Path(temp_output.name).unlink(missing_ok=True)
return synth_audio
else:
logger.error(f"ํ•ฉ์„ฑ๋œ ํŒŒ์ผ์ด ์ƒ์„ฑ๋˜์ง€ ์•Š์Œ: {temp_output.name}")
return None
except Exception as e:
logger.error(f"๋…ธํŠธ ํ•ฉ์„ฑ ์‹คํŒจ: {e}")
return None
def _midi_to_note_name(self, midi_note: int) -> str:
"""MIDI ๋…ธํŠธ ๋ฒˆํ˜ธ๋ฅผ ์Œ๊ณ„๋ช…์œผ๋กœ ๋ณ€ํ™˜"""
notes = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
octave = (midi_note // 12) - 1
note = notes[midi_note % 12]
return f"{note}{octave}"
def get_available_phonemes(self) -> List[str]:
"""์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ ์Œ์†Œ ๋ชฉ๋ก ๋ฐ˜ํ™˜"""
return self.voicebank.list_available_phonemes()
def get_compression_info(self) -> Dict[str, any]:
"""์••์ถ• ์ •๋ณด ๋ฐ˜ํ™˜"""
return self.voicebank.get_compression_info()