import gradio as gr
import tempfile
import os
from gtts import gTTS
from io import BytesIO
import base64
def text_to_speech(text, language="ko", slow=False):
"""
텍스트를 음성으로 변환하는 함수
Args:
text (str): 변환할 텍스트
language (str): 언어 코드 (기본값: 한국어 'ko')
slow (bool): 느린 속도로 읽기 여부
Returns:
str: 생성된 오디오 파일 경로
"""
if not text.strip():
return None
try:
# gTTS 객체 생성
tts = gTTS(text=text, lang=language, slow=slow)
# 임시 파일 생성
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:
tts.save(tmp_file.name)
return tmp_file.name
except Exception as e:
print(f"TTS 변환 중 오류 발생: {e}")
return None
def create_tts_interface():
"""Gradio 인터페이스 생성"""
# 지원 언어 목록
languages = {
"한국어": "ko",
"English": "en",
"日本語": "ja",
"中文": "zh",
"Español": "es",
"Français": "fr",
"Deutsch": "de",
"Italiano": "it",
"Русский": "ru"
}
with gr.Blocks(title="Text-to-Speech 변환기", theme=gr.themes.Soft()) as demo:
gr.Markdown("# 🎤 Text-to-Speech 변환기")
gr.Markdown("텍스트를 입력하면 음성으로 변환해드립니다!")
with gr.Row():
with gr.Column(scale=2):
# 텍스트 입력
text_input = gr.Textbox(
label="변환할 텍스트",
placeholder="여기에 텍스트를 입력하세요...",
lines=3,
max_lines=10
)
with gr.Row():
# 언어 선택
language_dropdown = gr.Dropdown(
choices=list(languages.keys()),
value="한국어",
label="언어 선택"
)
# 속도 선택
speed_checkbox = gr.Checkbox(
label="느린 속도로 읽기",
value=False
)
# 변환 버튼
convert_btn = gr.Button("🎵 음성 변환", variant="primary")
with gr.Column(scale=1):
# 오디오 출력
audio_output = gr.Audio(
label="생성된 음성",
type="filepath"
)
# 예제 텍스트
gr.Examples(
examples=[
["안녕하세요! 오늘 날씨가 정말 좋네요.", "한국어", False],
["Hello, how are you today?", "English", False],
["こんにちは、元気ですか?", "日本語", False],
["Bonjour, comment allez-vous?", "Français", False],
["Hola, ¿cómo estás?", "Español", False]
],
inputs=[text_input, language_dropdown, speed_checkbox]
)
def convert_text_to_speech(text, selected_language, slow_speed):
"""텍스트를 음성으로 변환하는 이벤트 핸들러"""
if not text.strip():
gr.Warning("텍스트를 입력해주세요!")
return None
# 선택된 언어의 코드 가져오기
lang_code = languages.get(selected_language, "ko")
# TTS 변환 실행
audio_file = text_to_speech(text, lang_code, slow_speed)
if audio_file:
gr.Info("음성 변환이 완료되었습니다!")
return audio_file
else:
gr.Error("음성 변환 중 오류가 발생했습니다.")
return None
# 이벤트 바인딩
convert_btn.click(
fn=convert_text_to_speech,
inputs=[text_input, language_dropdown, speed_checkbox],
outputs=audio_output
)
# Enter 키로도 변환 가능
text_input.submit(
fn=convert_text_to_speech,
inputs=[text_input, language_dropdown, speed_checkbox],
outputs=audio_output
)
return demo
# 고급 TTS 인터페이스 (추가 기능 포함)
def create_advanced_tts_interface():
"""고급 기능이 포함된 TTS 인터페이스"""
def batch_tts(text_list, language="ko"):
"""여러 텍스트를 한번에 변환"""
audio_files = []
for text in text_list.split('\n'):
if text.strip():
audio_file = text_to_speech(text.strip(), language)
if audio_file:
audio_files.append(audio_file)
return audio_files if audio_files else None
with gr.Blocks(title="고급 TTS 변환기", theme=gr.themes.Glass()) as demo:
gr.Markdown("# 🎙️ 고급 Text-to-Speech 변환기")
with gr.Tabs():
# 기본 TTS 탭
with gr.TabItem("기본 변환"):
with gr.Row():
text_input = gr.Textbox(
label="텍스트 입력",
placeholder="변환할 텍스트를 입력하세요...",
lines=4
)
with gr.Row():
lang_choice = gr.Radio(
choices=["ko", "en", "ja", "zh", "es", "fr"],
value="ko",
label="언어"
)
slow_speech = gr.Checkbox(label="느린 속도", value=False)
convert_basic_btn = gr.Button("변환", variant="primary")
audio_basic_output = gr.Audio(label="음성 결과")
# 배치 변환 탭
with gr.TabItem("배치 변환"):
gr.Markdown("여러 줄의 텍스트를 한번에 변환합니다. (각 줄마다 별도의 음성 파일 생성)")
batch_text_input = gr.Textbox(
label="텍스트 목록 (한 줄씩 입력)",
placeholder="첫 번째 문장\n두 번째 문장\n세 번째 문장",
lines=6
)
batch_lang = gr.Dropdown(
choices=["ko", "en", "ja", "zh", "es", "fr"],
value="ko",
label="언어"
)
batch_convert_btn = gr.Button("배치 변환", variant="secondary")
batch_audio_output = gr.File(label="변환된 음성 파일들", file_count="multiple")
# 이벤트 핸들러들
def basic_convert(text, lang, slow):
return text_to_speech(text, lang, slow)
def batch_convert(texts, lang):
if not texts.strip():
return None
files = []
for i, text in enumerate(texts.split('\n')):
if text.strip():
audio_file = text_to_speech(text.strip(), lang)
if audio_file:
# 파일명을 더 명확하게 변경
new_name = f"tts_output_{i+1}.mp3"
new_path = os.path.join(os.path.dirname(audio_file), new_name)
os.rename(audio_file, new_path)
files.append(new_path)
return files if files else None
# 이벤트 바인딩
convert_basic_btn.click(
fn=basic_convert,
inputs=[text_input, lang_choice, slow_speech],
outputs=audio_basic_output
)
batch_convert_btn.click(
fn=batch_convert,
inputs=[batch_text_input, batch_lang],
outputs=batch_audio_output
)
return demo
# 실행 코드
if __name__ == "__main__":
print("TTS Gradio 인터페이스를 시작합니다...")
# 기본 인터페이스 실행
print("\n=== 기본 TTS 인터페이스 ===")
basic_demo = create_tts_interface()
basic_demo.launch(
share=True, # 공개 링크 생성
debug=True # 디버그 모드 활성화
)
# 주석을 해제하면 고급 인터페이스도 실행 가능
# print("\n=== 고급 TTS 인터페이스 ===")
# advanced_demo = create_advanced_tts_interface()
# advanced_demo.launch(share=True, debug=True)
# 사용법 안내
print("""
🎯 사용법:
1. 위의 코드를 Colab 셀에서 실행하세요
2. 생성된 공개 링크를 클릭하거나 인라인 인터페이스를 사용하세요
3. 텍스트를 입력하고 언어를 선택한 후 변환 버튼을 클릭하세요
4. 생성된 음성을 재생하거나 다운로드할 수 있습니다
🌟 주요 기능:
- 9개 언어 지원 (한국어, 영어, 일본어, 중국어, 스페인어, 프랑스어, 독일어, 이탈리아어, 러시아어)
- 느린 속도 읽기 옵션
- 예제 텍스트 제공
- 배치 변환 기능 (고급 버전)
- 실시간 오디오 재생
💡 팁:
- 긴 텍스트는 문장 단위로 나누어 입력하는 것이 좋습니다
- 특수문자나 이모지는 제거하고 입력하세요
- 인터넷 연결이 필요합니다 (gTTS는 Google의 온라인 서비스를 사용)
""")