import gradio as gr import os import tempfile import re from pydub import AudioSegment # Thư viện để kết hợp các file âm thanh from openai import OpenAI # API key và endpoint mặc định DEFAULT_API_KEY = "sk-GINVEtfNbrXNcGQhf3rEUIgzoicNGIApovqZxe0AYJF5PkTV" DEFAULT_BASE_URL = "https://open.keyai.shop" # Giới hạn ký tự tối đa mỗi yêu cầu API MAX_CHAR_LIMIT = 140964096 def clean_text(text): # Loại bỏ khoảng trắng thừa và xuống dòng cleaned_text = re.sub(r'\s+', ' ', text.strip()) return cleaned_text def split_text(text, limit=MAX_CHAR_LIMIT): # Tách văn bản thành các đoạn không vượt quá giới hạn ký tự words = text.split(' ') chunks = [] current_chunk = "" for word in words: if len(current_chunk) + len(word) + 1 <= limit: current_chunk += word + " " else: chunks.append(current_chunk.strip()) current_chunk = word + " " if current_chunk: chunks.append(current_chunk.strip()) return chunks def tts(text, model, voice, speed): cleaned_text = clean_text(text) chunks = split_text(cleaned_text) audio_segments = [] try: client = OpenAI(api_key=DEFAULT_API_KEY, base_url=DEFAULT_BASE_URL + '/v1') for chunk in chunks: response = client.audio.speech.create( model=model, # Các lựa chọn: "tts-1", "tts-1-hd" voice=voice, # Các lựa chọn: 'alloy', 'echo', 'fable', 'onyx', 'nova', 'shimmer' input=chunk, speed=speed ) with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as temp_file: temp_file.write(response.content) temp_file_path = temp_file.name audio_segments.append(AudioSegment.from_mp3(temp_file_path)) except Exception as error: raise gr.Error("Đã xảy ra lỗi khi tạo giọng nói. Vui lòng kiểm tra API key hoặc thử lại sau.") # Nối các đoạn âm thanh lại thành một file duy nhất final_audio = sum(audio_segments) with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as final_temp_file: final_audio.export(final_temp_file.name, format="mp3") final_audio_path = final_temp_file.name return final_audio_path # CSS tùy chỉnh với giao diện tối và tích hợp FontAwesome cho icon custom_css = """ @import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css'); body { background-color: #1e1e2f; color: #e0e0e0; font-family: 'Arial', sans-serif; } .title { font-size: 2.5rem; font-weight: bold; text-align: center; margin-bottom: 30px; color: #f1f1f1; } .container { margin: auto; width: 90%; padding: 20px; } .card { background: #2e2e42; padding: 20px; border-radius: 8px; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.5); margin-bottom: 20px; } .gradio-container { background: #1e1e2f; } button { background-color: #4CAF50; color: white; border: none; border-radius: 8px; padding: 10px 20px; font-size: 1rem; cursor: pointer; } button:hover { background-color: #45a049; } input, textarea, select { background: #3a3a50; border: 1px solid #555; color: #e0e0e0; padding: 8px; border-radius: 4px; } select { padding: 8px 10px; } label { font-weight: bold; margin-bottom: 5px; } """ with gr.Blocks(css=custom_css) as demo: # Tiêu đề với icon Microphone gr.Markdown("