File size: 19,787 Bytes
1056960
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
import os
import re
import logging
import tempfile
import numpy as np
import soundfile as sf
from pathlib import Path
from typing import Dict, List, Optional, Tuple, Union
from dataclasses import dataclass
from straycat import Resampler

# ๋กœ๊น… ์„ค์ •
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

@dataclass
class OtoEntry:
    """UTAU oto.ini ์—”ํŠธ๋ฆฌ ํด๋ž˜์Šค"""
    filename: str          # WAV ํŒŒ์ผ๋ช…
    alias: str            # ๋ณ„๋ช… (๋ฐœ์Œ)
    offset: float         # ์˜คํ”„์…‹ (ms)
    consonant: float      # ์ž์Œ ๊ธธ์ด (ms)  
    cutoff: float         # ์ปท์˜คํ”„ (ms)
    preutterance: float   # ํ”„๋ฆฌ์œ ํ„ฐ๋Ÿฐ์Šค (ms)
    overlap: float        # ์˜ค๋ฒ„๋žฉ (ms)
    
    @property
    def is_breath(self) -> bool:
        """์ˆจ์†Œ๋ฆฌ/๋ฌด์Œ ๊ตฌ๊ฐ„์ธ์ง€ ํ™•์ธ"""
        return self.alias.startswith('-') or self.alias.startswith('*')
    
    @property
    def clean_alias(self) -> str:
        """์ ‘๋‘์‚ฌ ์ œ๊ฑฐ๋œ ์ˆœ์ˆ˜ ๋ณ„๋ช…"""
        alias = self.alias
        if alias.startswith('- '):
            return alias[2:]
        elif alias.startswith('* '):
            return alias[2:]
        elif alias.startswith('-'):
            return alias[1:]
        elif alias.startswith('*'):
            return alias[1:]
        return alias

class VoicebankManager:
    """UTAU ๋ณด์ด์Šค๋ฑ…ํฌ ๊ด€๋ฆฌ ํด๋ž˜์Šค"""
    
    def __init__(self, voicebank_path: Union[str, Path]):
        self.voicebank_path = Path(voicebank_path)
        self.oto_entries: Dict[str, OtoEntry] = {}
        self.wav_files: Dict[str, Path] = {}
        self.load_voicebank()
    
    def load_voicebank(self):
        """๋ณด์ด์Šค๋ฑ…ํฌ ๋กœ๋“œ"""
        if not self.voicebank_path.exists():
            raise FileNotFoundError(f"๋ณด์ด์Šค๋ฑ…ํฌ ๊ฒฝ๋กœ๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค: {self.voicebank_path}")
        
        # oto.ini ํŒŒ์ผ ์ฐพ๊ธฐ
        oto_file = self.voicebank_path / "oto.ini"
        if not oto_file.exists():
            raise FileNotFoundError(f"oto.ini ํŒŒ์ผ์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค: {oto_file}")
        
        # WAV ํŒŒ์ผ๋“ค ์ธ๋ฑ์‹ฑ
        self._index_wav_files()
        
        # oto.ini ํŒŒ์‹ฑ
        self._parse_oto_ini(oto_file)
        
        logger.info(f"๋ณด์ด์Šค๋ฑ…ํฌ ๋กœ๋“œ ์™„๋ฃŒ: {len(self.oto_entries)}๊ฐœ ์—”ํŠธ๋ฆฌ, {len(self.wav_files)}๊ฐœ WAV ํŒŒ์ผ")
    
    def _index_wav_files(self):
        """WAV ํŒŒ์ผ๋“ค ์ธ๋ฑ์‹ฑ"""
        for wav_file in self.voicebank_path.glob("*.wav"):
            self.wav_files[wav_file.name] = wav_file
        
        # ํ•˜์œ„ ํด๋”๋„ ๊ฒ€์ƒ‰
        for subfolder in self.voicebank_path.iterdir():
            if subfolder.is_dir():
                for wav_file in subfolder.glob("*.wav"):
                    self.wav_files[wav_file.name] = wav_file
    
    def _parse_oto_ini(self, oto_file: Path):
        """oto.ini ํŒŒ์ผ ํŒŒ์‹ฑ"""
        try:
            # ๋‹ค์–‘ํ•œ ์ธ์ฝ”๋”ฉ์œผ๋กœ ์‹œ๋„
            encodings = ['shift_jis', 'utf-8', 'cp932', 'euc-jp']
            content = None
            
            for encoding in encodings:
                try:
                    with open(oto_file, 'r', encoding=encoding) as f:
                        content = f.read()
                    logger.info(f"oto.ini๋ฅผ {encoding} ์ธ์ฝ”๋”ฉ์œผ๋กœ ์ฝ์—ˆ์Šต๋‹ˆ๋‹ค.")
                    break
                except UnicodeDecodeError:
                    continue
            
            if content is None:
                raise Exception("oto.ini ํŒŒ์ผ์„ ์ฝ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ์ธ์ฝ”๋”ฉ ๋ฌธ์ œ๊ฐ€ ์žˆ์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.")
            
            # ๊ฐ ๋ผ์ธ ํŒŒ์‹ฑ
            for line_num, line in enumerate(content.strip().split('\n'), 1):
                line = line.strip()
                if not line or line.startswith('#'):
                    continue
                
                try:
                    self._parse_oto_line(line)
                except Exception as e:
                    logger.warning(f"oto.ini {line_num}๋ฒˆ์งธ ์ค„ ํŒŒ์‹ฑ ์‹คํŒจ: {e}")
                    continue
                    
        except Exception as e:
            logger.error(f"oto.ini ํŒŒ์‹ฑ ์‹คํŒจ: {e}")
            raise
    
    def _parse_oto_line(self, line: str):
        """oto.ini ํ•œ ์ค„ ํŒŒ์‹ฑ"""
        # ํ˜•์‹: filename=alias,offset,consonant,cutoff,preutterance,overlap
        if '=' not in line:
            return
            
        filename, params = line.split('=', 1)
        parts = params.split(',')
        
        if len(parts) != 6:
            logger.warning(f"์ž˜๋ชป๋œ oto.ini ํ˜•์‹: {line}")
            return
        
        try:
            alias = parts[0]
            offset = float(parts[1])
            consonant = float(parts[2]) 
            cutoff = float(parts[3])
            preutterance = float(parts[4])
            overlap = float(parts[5])
            
            entry = OtoEntry(
                filename=filename,
                alias=alias,
                offset=offset,
                consonant=consonant,
                cutoff=cutoff,
                preutterance=preutterance,
                overlap=overlap
            )
            
            self.oto_entries[alias] = entry
            
        except ValueError as e:
            logger.warning(f"oto.ini ํŒŒ๋ผ๋ฏธํ„ฐ ํŒŒ์‹ฑ ์‹คํŒจ: {line} - {e}")
    
    def get_sample_for_phoneme(self, phoneme: str) -> Optional[OtoEntry]:
        """์Œ์†Œ์— ํ•ด๋‹นํ•˜๋Š” ์ƒ˜ํ”Œ ์ฐพ๊ธฐ"""
        # ์ •ํ™•ํ•œ ๋งค์น˜ ๋จผ์ € ์‹œ๋„
        if phoneme in self.oto_entries:
            return self.oto_entries[phoneme]
        
        # ์œ ์‚ฌํ•œ ๋ฐœ์Œ ์ฐพ๊ธฐ
        candidates = []
        for alias in self.oto_entries:
            entry = self.oto_entries[alias]
            if entry.clean_alias == phoneme:
                candidates.append(entry)
        
        if candidates:
            # ์ˆจ์†Œ๋ฆฌ๊ฐ€ ์•„๋‹Œ ๊ฒƒ์„ ์šฐ์„ 
            non_breath = [c for c in candidates if not c.is_breath]
            return non_breath[0] if non_breath else candidates[0]
        
        return None
    
    def get_wav_path(self, filename: str) -> Optional[Path]:
        """WAV ํŒŒ์ผ ๊ฒฝ๋กœ ๊ฐ€์ ธ์˜ค๊ธฐ"""
        return self.wav_files.get(filename)
    
    def list_available_phonemes(self) -> List[str]:
        """์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ ์Œ์†Œ ๋ชฉ๋ก"""
        return list(set(entry.clean_alias for entry in self.oto_entries.values()))

class UTAUEngine:
    """UTAU ํ˜ธํ™˜ ์Œ์„ฑ ํ•ฉ์„ฑ ์—”์ง„"""
    
    def __init__(self, voicebank_path: Union[str, Path]):
        self.voicebank = VoicebankManager(voicebank_path)
        self.default_phoneme = "ใ‚"  # ๊ธฐ๋ณธ ์Œ์†Œ
    
    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_seconds = max(note.get('endSeconds', note.get('startSeconds', 0) + note.get('durationSeconds', 0.5)) for note in notes)
            max_end_time = max_end_time_seconds * 1000  # ๋ฐ€๋ฆฌ์ดˆ๋กœ ๋ณ€ํ™˜
            sample_rate = 44100
            total_samples = int(max_end_time * sample_rate / 1000) + sample_rate
            final_audio = np.zeros(total_samples)
            
            synthesized_count = 0
            
            for i, (note, lyric) in enumerate(zip(notes, lyrics)):
                try:
                    # ์Œ์†Œ๋กœ ๋ณ€ํ™˜ (๊ฐ„๋‹จํ•œ ์ผ๋ณธ์–ด ์Œ์†Œ ๋งคํ•‘)
                    phoneme = self._lyric_to_phoneme(lyric)
                    
                    # ๋ณด์ด์Šค๋ฑ…ํฌ์—์„œ ์ƒ˜ํ”Œ ์ฐพ๊ธฐ
                    oto_entry = self.voicebank.get_sample_for_phoneme(phoneme)
                    if not oto_entry:
                        logger.warning(f"์Œ์†Œ '{phoneme}' (๊ฐ€์‚ฌ: '{lyric}')์— ํ•ด๋‹นํ•˜๋Š” ์ƒ˜ํ”Œ์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.")
                        continue
                    
                    # WAV ํŒŒ์ผ ๊ฒฝ๋กœ
                    wav_path = self.voicebank.get_wav_path(oto_entry.filename)
                    if not wav_path or not wav_path.exists():
                        logger.warning(f"WAV ํŒŒ์ผ์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค: {oto_entry.filename}")
                        continue
                    
                    # ์Œ์„ฑ ํ•ฉ์„ฑ
                    synth_audio = self._synthesize_note(note, oto_entry, wav_path, 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
                        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
                            final_audio = new_final_audio
                        
                        synthesized_count += 1
                        logger.info(f"๋…ธํŠธ {i+1} ํ•ฉ์„ฑ ์™„๋ฃŒ: {lyric} -> {phoneme}")
                
                except Exception as e:
                    logger.error(f"๋…ธํŠธ {i+1} ํ•ฉ์„ฑ ์‹คํŒจ: {e}")
                    continue
            
            if synthesized_count == 0:
                return None, "ํ•ฉ์„ฑ๋œ ๋…ธํŠธ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค."
            
            # ์ตœ์ข… ์˜ค๋””์˜ค ์ •๊ทœํ™”
            if np.max(np.abs(final_audio)) > 0:
                final_audio = final_audio / np.max(np.abs(final_audio)) * 0.8
            
            # ํŒŒ์ผ ์ €์žฅ
            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"โœ… UTAU ํ•ฉ์„ฑ ์™„๋ฃŒ: {synthesized_count}/{len(notes)}๊ฐœ ๋…ธํŠธ, {duration_sec:.1f}์ดˆ"
            
        except Exception as e:
            error_msg = f"โŒ UTAU ํ•ฉ์„ฑ ์ค‘ ์˜ค๋ฅ˜: {str(e)}"
            logger.error(error_msg)
            return None, error_msg
    
    def _lyric_to_phoneme(self, lyric: str) -> str:
        """๊ฐ€์‚ฌ๋ฅผ ์Œ์†Œ๋กœ ๋ณ€ํ™˜ (ํ•œ๊ตญ์–ด + ์ผ๋ณธ์–ด ๋งคํ•‘)"""
        # ๊ณต๋ฐฑ ์ œ๊ฑฐ
        lyric = lyric.strip()
        
        # ๋นˆ ๊ฐ€์‚ฌ๋ฉด ๊ธฐ๋ณธ๊ฐ’ ๋ฐ˜ํ™˜
        if not lyric:
            return self.default_phoneme
        
        # ํ•œ๊ตญ์–ด ์Œ์†Œ ๋งคํ•‘ (hanseol CVC์šฉ)
        korean_map = {
            # ๊ธฐ๋ณธ ๋ชจ์Œ
            '์•„': 'a', '์ด': 'i', '์šฐ': 'u', '์—': 'e', '์˜ค': 'o', '์œผ': 'eu', '์–ด': 'eo',
            # ๊ธฐ๋ณธ ์ž์Œ+๋ชจ์Œ
            '๋ฐ”': 'ba', '๋น„': 'bi', '๋ถ€': 'bu', '๋ฒ ': 'be', '๋ณด': 'bo', '๋ธŒ': 'beu', '๋ฒ„': 'beo',
            '๋‹ค': 'da', '๋””': 'di', '๋‘': 'du', '๋ฐ': 'de', '๋„': 'do', '๋“œ': 'deu', '๋”': 'deo',
            '๊ฐ€': 'ga', '๊ธฐ': 'gi', '๊ตฌ': 'gu', '๊ฒŒ': 'ge', '๊ณ ': 'go', '๊ทธ': 'geu', '๊ฑฐ': 'geo',
            'ํ•˜': 'ha', 'ํžˆ': 'hi', 'ํ›„': 'hu', 'ํ—ค': 'he', 'ํ˜ธ': 'ho', 'ํ': 'heu', 'ํ—ˆ': 'heo',
            '์ž': 'ja', '์ง€': 'ji', '์ฃผ': 'ju', '์ œ': 'je', '์กฐ': 'jo', '์ฆˆ': 'jeu', '์ €': 'jeo',
            '์นด': 'ka', 'ํ‚ค': 'ki', '์ฟ ': 'ku', '์ผ€': 'ke', '์ฝ”': 'ko', 'ํฌ': 'keu', '์ปค': 'keo',
            '๋ผ': 'la', '๋ฆฌ': 'li', '๋ฃจ': 'lu', '๋ ˆ': 'le', '๋กœ': 'lo', '๋ฅด': 'leu', '๋Ÿฌ': 'leo',
            '๋งˆ': 'ma', '๋ฏธ': 'mi', '๋ฌด': 'mu', '๋ฉ”': 'me', '๋ชจ': 'mo', '๋ฏ€': 'meu', '๋จธ': 'meo',
            '๋‚˜': 'na', '๋‹ˆ': 'ni', '๋ˆ„': 'nu', '๋„ค': 'ne', '๋…ธ': 'no', '๋А': 'neu', '๋„ˆ': 'neo',
            'ํŒŒ': 'pa', 'ํ”ผ': 'pi', 'ํ‘ธ': 'pu', 'ํŽ˜': 'pe', 'ํฌ': 'po', 'ํ”„': 'peu', 'ํผ': 'peo',
            '๋ผ': 'ra', '๋ฆฌ': 'ri', '๋ฃจ': 'ru', '๋ ˆ': 're', '๋กœ': 'ro', '๋ฅด': 'reu', '๋Ÿฌ': 'reo',
            '์‚ฌ': 'sa', '์‹œ': 'si', '์ˆ˜': 'su', '์„ธ': 'se', '์†Œ': 'so', '์Šค': 'seu', '์„œ': 'seo',
            'ํƒ€': 'ta', 'ํ‹ฐ': 'ti', 'ํˆฌ': 'tu', 'ํ…Œ': 'te', 'ํ† ': 'to', 'ํŠธ': 'teu', 'ํ„ฐ': 'teo',
            # ๋ณตํ•ฉ๋ชจ์Œ
            '์•ผ': 'ya', '์˜ˆ': 'ye', '์—ฌ': 'yeo', '์š”': 'yo', '์œ ': 'yu', '์˜': 'eui',
            '์™€': 'wa', '์›จ': 'we', '์œ„': 'wi', '์›Œ': 'weo',
            # ๊ธฐํƒ€ ํ•œ๊ตญ์–ด ๋„๋ ˆ๋ฏธ
            '๋„': 'do', '๋ ˆ': 're', '๋ฏธ': 'mi', 'ํŒŒ': 'fa', '์†”': 'so', '๋ผ': 'la', '์‹œ': 'si'
        }
        
        # ํ•œ๊ตญ์–ด ๋งคํ•‘ ์‹œ๋„
        if lyric in korean_map:
            return korean_map[lyric]
        
        # ๋กœ๋งˆ์ž -> ํžˆ๋ผ๊ฐ€๋‚˜ ๋ณ€ํ™˜ (์ผ๋ณธ์–ด)
        romaji_map = {
            'a': 'ใ‚', 'i': 'ใ„', 'u': 'ใ†', 'e': 'ใˆ', 'o': 'ใŠ',
            'ka': 'ใ‹', 'ki': 'ใ', 'ku': 'ใ', 'ke': 'ใ‘', 'ko': 'ใ“',
            'sa': 'ใ•', 'shi': 'ใ—', 'su': 'ใ™', 'se': 'ใ›', 'so': 'ใ',
            'ta': 'ใŸ', 'chi': 'ใก', 'tsu': 'ใค', 'te': 'ใฆ', 'to': 'ใจ',
            'na': 'ใช', 'ni': 'ใซ', 'nu': 'ใฌ', 'ne': 'ใญ', 'no': 'ใฎ',
            'ha': 'ใฏ', 'hi': 'ใฒ', 'fu': 'ใต', 'he': 'ใธ', 'ho': 'ใป',
            'ma': 'ใพ', 'mi': 'ใฟ', 'mu': 'ใ‚€', 'me': 'ใ‚', 'mo': 'ใ‚‚',
            'ya': 'ใ‚„', 'yu': 'ใ‚†', 'yo': 'ใ‚ˆ',
            'ra': 'ใ‚‰', 'ri': 'ใ‚Š', 'ru': 'ใ‚‹', 're': 'ใ‚Œ', 'ro': 'ใ‚',
            'wa': 'ใ‚', 'wo': 'ใ‚’', 'n': 'ใ‚“'
        }
        
        # ๋กœ๋งˆ์ž ๋ณ€ํ™˜ ์‹œ๋„
        lyric_lower = lyric.lower()
        if lyric_lower in romaji_map:
            return romaji_map[lyric_lower]
        
        # ์ด๋ฏธ ์Œ์†Œ์ธ ๊ฒฝ์šฐ (hanseol CVC ์ง์ ‘ ์ž…๋ ฅ)
        available_phonemes = self.voicebank.list_available_phonemes()
        if lyric in available_phonemes:
            return lyric
        
        # ๊ธฐ๋ณธ๊ฐ’ ๋ฐ˜ํ™˜
        logger.warning(f"์•Œ ์ˆ˜ ์—†๋Š” ๊ฐ€์‚ฌ: '{lyric}', ๊ธฐ๋ณธ ์Œ์†Œ '{self.default_phoneme}' ์‚ฌ์šฉ")
        return self.default_phoneme
    
    def _synthesize_note(self, 
                        note: Dict, 
                        oto_entry: OtoEntry, 
                        wav_path: Path,
                        tempo: int,
                        volume: int) -> Optional[np.ndarray]:
        """๊ฐœ๋ณ„ ๋…ธํŠธ ํ•ฉ์„ฑ"""
        try:
            # MIDI ๋…ธํŠธ๋ฅผ ๋…ธํŠธ ์ด๋ฆ„์œผ๋กœ ๋ณ€ํ™˜
            note_name = self._midi_to_note_name(note['pitch'])
            
            # ๋…ธํŠธ ๊ธธ์ด ๊ฒ€์ฆ ๋ฐ ์กฐ์ •
            min_duration = 200  # ์ตœ์†Œ 200ms
            duration = max(note.get('durationSeconds', 0.5) * 1000, min_duration)  # ์ดˆ๋ฅผ ๋ฐ€๋ฆฌ์ดˆ๋กœ ๋ณ€ํ™˜
            
            # ์ž„์‹œ ์ถœ๋ ฅ ํŒŒ์ผ
            with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as temp_file:
                temp_output = temp_file.name
            
            try:
                # UTAU ํŒŒ๋ผ๋ฏธํ„ฐ ๊ฒ€์ฆ ๋ฐ ์กฐ์ •
                offset = max(oto_entry.offset, 0)  # ์Œ์ˆ˜ ์˜คํ”„์…‹ ๋ฐฉ์ง€
                consonant = max(oto_entry.consonant if oto_entry.consonant > 0 else 50, 10)  # ์ตœ์†Œ 10ms
                cutoff = max(oto_entry.cutoff if oto_entry.cutoff > 0 else 0, 0)
                
                # WAV ํŒŒ์ผ ๊ธธ์ด ํ™•์ธ
                try:
                    info = sf.info(wav_path)
                    wav_duration_ms = (info.frames / info.samplerate) * 1000
                    
                    # ์˜คํ”„์…‹์ด WAV ํŒŒ์ผ๋ณด๋‹ค ๊ธด ๊ฒฝ์šฐ ์กฐ์ •
                    if offset >= wav_duration_ms - 100:  # 100ms ์—ฌ์œ 
                        offset = max(0, wav_duration_ms - 200)
                        logger.warning(f"์˜คํ”„์…‹์ด ๋„ˆ๋ฌด ํฝ๋‹ˆ๋‹ค. {offset}ms๋กœ ์กฐ์ •ํ–ˆ์Šต๋‹ˆ๋‹ค.")
                    
                    # ์ž์Œ ๊ธธ์ด๊ฐ€ ๋„ˆ๋ฌด ๊ธด ๊ฒฝ์šฐ ์กฐ์ •
                    max_consonant = min(duration / 2, wav_duration_ms - offset - 50)
                    consonant = min(consonant, max_consonant)
                    
                except Exception as e:
                    logger.warning(f"WAV ํŒŒ์ผ ์ •๋ณด ํ™•์ธ ์‹คํŒจ: {e}")
                
                # ์ตœ์†Œ ๊ธธ์ด ๋ณด์žฅ
                if consonant < 10:
                    consonant = 10
                if duration < consonant + 50:
                    duration = consonant + 50
                
                logger.info(f"ํ•ฉ์„ฑ ํŒŒ๋ผ๋ฏธํ„ฐ: offset={offset:.1f}ms, consonant={consonant:.1f}ms, duration={duration:.1f}ms")
                
                # straycat์œผ๋กœ ํ•ฉ์„ฑ
                resampler = Resampler(
                    in_file=str(wav_path),
                    out_file=temp_output,
                    pitch=note_name,
                    velocity=note.get('velocity', 100),
                    length=duration,
                    volume=volume,
                    flags='',
                    offset=offset,
                    consonant=consonant,
                    cutoff=cutoff,
                    modulation=0,
                    tempo=f'!{tempo}'
                )
                
                # ํ•ฉ์„ฑ๋œ ์˜ค๋””์˜ค ๋กœ๋“œ
                if os.path.exists(temp_output):
                    synth_audio, _ = sf.read(temp_output)
                    
                    # ๊ฒฐ๊ณผ ๊ฒ€์ฆ
                    if len(synth_audio) == 0:
                        logger.warning("ํ•ฉ์„ฑ๋œ ์˜ค๋””์˜ค๊ฐ€ ๋น„์–ด์žˆ์Šต๋‹ˆ๋‹ค.")
                        return None
                    
                    return synth_audio
                else:
                    logger.warning("ํ•ฉ์„ฑ ๊ฒฐ๊ณผ ํŒŒ์ผ์ด ์ƒ์„ฑ๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค.")
                    return None
                
            except Exception as e:
                logger.error(f"straycat ํ•ฉ์„ฑ ์‹คํŒจ: {e}")
                return None
            
            finally:
                # ์ž„์‹œ ํŒŒ์ผ ์ •๋ฆฌ
                if os.path.exists(temp_output):
                    try:
                        os.unlink(temp_output)
                    except:
                        pass
                    
        except Exception as e:
            logger.error(f"๋…ธํŠธ ํ•ฉ์„ฑ ์‹คํŒจ: {e}")
            return None
        
        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 test_utau_engine():
    """UTAU ์—”์ง„ ํ…Œ์ŠคํŠธ"""
    try:
        voicebank_path = "voice/hanseol CVC"
        engine = UTAUEngine(voicebank_path)
        
        print(f"hanseol CVC ๋ณด์ด์Šค๋ฑ…ํฌ ๋กœ๋“œ ์™„๋ฃŒ!")
        print(f"์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ ์Œ์†Œ: {len(engine.get_available_phonemes())}๊ฐœ")
        print(f"์ฒซ 10๊ฐœ ์Œ์†Œ: {engine.get_available_phonemes()[:10]}")
        
        return engine
        
    except Exception as e:
        print(f"UTAU ์—”์ง„ ํ…Œ์ŠคํŠธ ์‹คํŒจ: {e}")
        return None

if __name__ == "__main__":
    test_utau_engine()