Spaces:
Paused
Paused
Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950---title: ElevenLabs TTS Proemoji: 🎤colorFrom: bluecolorTo: greensdk: gradiosdk_version: 4.0.0app_file: app.pypinned: false---# 🎤 ElevenLabs TTS ProCông cụ chuyển văn bản thành giọng nói chuyên nghiệp sử dụng API của ElevenLabs.## 🚀 Tính năng- 🤖 Hỗ trợ nhiều API keys của ElevenLabs- 🎭 Tạo giọng nói với nhiều thông số tùy chỉnh- 📝 Hỗ trợ văn bản dài, tự động chia đoạn- 💾 Xuất file audio (MP3, WAV, OGG, FLAC)- 📄 Tạo file phụ đề SRT tự động- 📁 Tải cấu hình từ file (TXT, JSON, ENV)## 🔧 Cách sử dụng1. **Nhập API Keys**: Lấy từ [ElevenLabs](https://elevenlabs.io/) và nhập vào ô API Keys2. **Nhập Voice ID**: Voice ID từ ElevenLabs (VD: `21m00Tcm4TlvDq8ikWAM`)3. **Nhập văn bản**: Văn bản cần chuyển thành giọng nói4. **Tùy chỉnh thông số**: Stability, Similarity, Style, Speed5. **Nhấn "Bắt đầu Tạo Giọng nói"**## 📁 Định dạng file hỗ trợ- **API Keys**: `.txt`, `.json`, `.env`- **Voice IDs**: `.txt`, `.json`- **Văn bản**: `.txt`, `.json`## ⚠️ Lưu ý- Cần có API key hợp lệ từ ElevenLabs- Giới hạn ký tự theo gói subscription của bạn- File tạo ra sẽ được lưu tạm thời và tự động xóa sau phiên làm việc## 🛠️ Công nghệ sử dụng- Gradio: Giao diện web- ElevenLabs API: TTS engine- Pydub: Xử lý audio- Python 3.8+123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662# app.py cho Hugging Face Spaces# -*- coding: utf-8 -*-import os, re, time, random, json, tempfile, shutilfrom pathlib import Pathimport requestsimport gradio as grfrom pydub import AudioSegmentimport natsortimport asynciofrom concurrent.futures import ThreadPoolExecutorimport hashlib# ==================== HÀM GỐC ====================def merge_audio_files(input_folder, format, output_filename, silence_ms=300):audio_files = [f for f in os.listdir(input_folder) if f.lower().endswith(f".{format.lower()}")]if not audio_files:return Noneaudio_files = natsort.natsorted(audio_files)combined = AudioSegment.from_file(os.path.join(input_folder, audio_files[0]), format=format.lower())for audio_file in audio_files[1:]:audio = AudioSegment.from_file(os.path.join(input_folder, audio_file), format=format.lower())combined += AudioSegment.silent(duration=silence_ms)combined += audiooutput_path = f"{output_filename}.{format.lower()}"combined.export(output_path, format=format.lower())return output_pathdef check_api_key(api_key):try:res = requests.get("https://api.elevenlabs.io/v1/user",headers={"xi-api-key": api_key.strip()},timeout=10)if res.status_code == 200:sub = res.json().get("subscription", {})return {"valid": True,"remaining": sub.get("character_limit", 0) - sub.get("character_count", 0),"total": sub.get("character_limit", 0)}return {"valid": False, "message": f"Status code: {res.status_code}"}except Exception as e:return {"valid": False, "message": str(e)}def generate_voice(text, api_key, voice_id, model_id,stability=0.7, similarity=0.8, style=0.0, speed=0.75, speaker_boost=True):time.sleep(random.uniform(0.5, 1.5)) # Giảm delay để nhanh hơnurl = f"https://api.elevenlabs.io/v1/text-to-speech/{voice_id}"headers = {"xi-api-key": api_key.strip(), "Content-Type": "application/json"}payload = {"text": text,"model_id": model_id,"voice_settings": {"stability": stability,"similarity_boost": similarity,"style": style,"speed": speed,"use_speaker_boost": speaker_boost}}try:res = requests.post(url, headers=headers, json=payload, timeout=30)if res.status_code == 200:return res.contentelif res.status_code == 429:time.sleep(2) # Giảm thời gian chờreturn Noneelse:return Noneexcept:return Nonereturn Nonedef parse_text_blocks(raw_text, max_length=200):blocks = []current = ""for s in re.split(r'(?<=[.!?])\s+', raw_text):if len(current) + len(s) <= max_length:if current:current += " " + selse:current = selse:if current:blocks.append(current.strip())current = sif current:blocks.append(current.strip())return blocksdef estimate_credit(text):return len(text) + 50def ms_to_srt_time(ms):h = ms // 3600000m = (ms % 3600000) // 60000s = (ms % 60000) // 1000ms = ms % 1000return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}"def create_srt(voice_dir, texts, silence_ms=300):files_audio = natsort.natsorted([f for f in os.listdir(voice_dir) if f.startswith("voice_")])current_time = 0srt_lines = []for idx, (fname, text) in enumerate(zip(files_audio, texts), start=1):try:audio = AudioSegment.from_file(os.path.join(voice_dir, fname))start = current_timeend = start + len(audio)srt_lines.append(str(idx))srt_lines.append(f"{ms_to_srt_time(start)} --> {ms_to_srt_time(end)}")srt_lines.append(text.strip())srt_lines.append("")current_time = end + silence_msexcept:continueif srt_lines:srt_path = os.path.join(voice_dir, "output_full.srt")with open(srt_path, "w", encoding="utf-8") as f:f.write("\n".join(srt_lines))return srt_pathreturn Nonedef extract_api_keys_from_content(content):"""Trích xuất API keys từ nội dung"""api_keys = []# Tìm tất cả chuỗi bắt đầu bằng sk_pattern = r'sk_[a-zA-Z0-9]{20,}'matches = re.findall(pattern, content)api_keys.extend(matches)# Tìm trong định dạng KEY=sk_...lines = content.splitlines()for line in lines:line = line.strip()if '=' in line:parts = line.split('=', 1)if len(parts) == 2 and parts[1].strip().startswith('sk_'):api_keys.append(parts[1].strip())# Loại bỏ trùng lặpunique_keys = []for key in api_keys:if key and key not in unique_keys:unique_keys.append(key)return unique_keysdef extract_voice_ids_from_content(content):"""Trích xuất Voice IDs từ nội dung"""voice_ids = []# Voice ID thường có độ dài cố địnhpattern = r'[a-zA-Z0-9]{20,}'matches = re.findall(pattern, content)lines = content.splitlines()for line in lines:line = line.strip()if len(line) > 15 and ' ' not in line: # Voice ID thường không có khoảng trắngvoice_ids.append(line)# Loại bỏ trùng lặpunique_voices = []for vid in voice_ids:if vid and vid not in unique_voices:unique_voices.append(vid)return unique_voices[:10] # Giới hạn 10 voice IDsdef get_output_folder():"""Tạo thư mục output tạm thời"""output_dir = os.path.join(tempfile.gettempdir(), "elevenlabs_tts", hashlib.md5(str(time.time()).encode()).hexdigest()[:8])os.makedirs(output_dir, exist_ok=True)return output_dirdef check_all_api_keys(api_keys_text):"""Kiểm tra tất cả API keys"""api_keys = [k.strip() for k in api_keys_text.splitlines() if k.strip()]results = []if not api_keys:return "❌ Vui lòng nhập ít nhất một API key!"for i, key in enumerate(api_keys, 1):result = check_api_key(key)if result.get("valid"):results.append(f"✓ Key {i}: Hợp lệ | Còn lại: {result['remaining']:,}/{result['total']:,} ký tự")else:results.append(f"✗ Key {i}: Không hợp lệ ({result.get('message', 'Unknown error')})")return "\n".join(results)async def process_tts_async(api_keys_text, voice_id, text_input, model_id,format_type, stability, similarity, style, speed,speaker_boost, progress=gr.Progress()):"""Xử lý TTS không đồng bộ"""try:# Chuẩn bị dữ liệuapi_keys = [k.strip() for k in api_keys_text.splitlines() if k.strip()]if not api_keys:raise ValueError("Vui lòng nhập ít nhất một API key!")if not voice_id.strip():raise ValueError("Vui lòng nhập Voice ID!")if not text_input.strip():raise ValueError("Vui lòng nhập văn bản cần chuyển đổi!")# Tạo thư mục outputoutput_dir = get_output_folder()# Phân tích văn bảntexts = parse_text_blocks(text_input.strip())if not texts:raise ValueError("Không thể phân tích văn bản!")progress(0, desc="🔄 Đang khởi tạo...")# Kiểm tra API keysvalid_keys = []progress(0.1, desc="🔍 Đang kiểm tra API keys...")for key in api_keys:info = check_api_key(key)if info.get("valid") and info["remaining"] > 600:valid_keys.append([key, info["remaining"]])if not valid_keys:raise ValueError("Không có API key hợp lệ hoặc đủ hạn ngạch!")# Xử lý từng đoạn văn bảnaudio_files = []current_key_index = 0for i, text in enumerate(texts):progress_percent = 0.1 + (i / len(texts)) * 0.7progress(progress_percent, desc=f"🎤 Đang tạo đoạn {i+1}/{len(texts)}...")success = Falseattempts = 0while attempts < len(valid_keys) and not success:key, remaining = valid_keys[current_key_index]need = estimate_credit(text)if remaining < need:valid_keys.pop(current_key_index)current_key_index %= max(len(valid_keys), 1)attempts += 1continueaudio = generate_voice(text, key, voice_id.strip(), model_id,stability=stability/100,similarity=similarity/100,style=style/100,speed=speed/100,speaker_boost=speaker_boost)if audio:filename = f"voice_{i+1:03d}.{format_type.lower()}"filepath = os.path.join(output_dir, filename)with open(filepath, "wb") as f:f.write(audio)audio_files.append(filepath)valid_keys[current_key_index][1] -= needsuccess = Trueelse:valid_keys.pop(current_key_index)current_key_index %= max(len(valid_keys), 1)attempts += 1if not success:raise ValueError(f"Không thể tạo đoạn {i+1} với tất cả API keys!")# Merge audio filesprogress(0.8, desc="🔗 Đang merge file audio...")merged_file = merge_audio_files(output_dir, format_type, os.path.join(output_dir, "output_full"))# Tạo file SRTprogress(0.9, desc="📝 Đang tạo file phụ đề...")srt_file = create_srt(output_dir, texts)# Đọc file đã tạooutput_files = []if merged_file and os.path.exists(merged_file):output_files.append(merged_file)if srt_file and os.path.exists(srt_file):output_files.append(srt_file)# Thêm các file audio riêng lẻfor audio_file in audio_files[:3]: # Chỉ hiển thị 3 file đầuif os.path.exists(audio_file):output_files.append(audio_file)progress(1.0, desc="✅ Hoàn thành!")return {"message": f"✅ Đã tạo thành công {len(texts)} đoạn audio!","output_dir": output_dir,"files": output_files}except Exception as e:return {"message": f"❌ Lỗi: {str(e)}","output_dir": None,"files": []}# ==================== GRADIO INTERFACE ====================with gr.Blocks(title="🎤 ElevenLabs TTS Pro - Web Edition", theme=gr.themes.Soft()) as demo:gr.Markdown("""# 🎤 ElevenLabs TTS Pro - Web Edition**Công cụ chuyển văn bản thành giọng nói chuyên nghiệp**> Phiên bản Web chạy trên Hugging Face Spaces""")with gr.Tabs():with gr.TabItem("⚙️ Cấu hình chính"):with gr.Row():with gr.Column(scale=2):gr.Markdown("### 🔑 Cấu hình API Keys")api_keys_text = gr.Textbox(label="API Keys (mỗi key một dòng)",placeholder="sk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\nsk_yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy",lines=5,info="Nhập một hoặc nhiều API keys từ ElevenLabs")with gr.Row():check_api_btn = gr.Button("🔍 Kiểm tra API Keys", variant="secondary")clear_api_btn = gr.Button("🗑️ Xóa", variant="secondary")api_check_result = gr.Textbox(label="Kết quả kiểm tra", interactive=False, lines=3)# File upload cho API keysapi_file = gr.File(label="📁 Tải API Keys từ file",file_types=[".txt", ".json", ".env"],type="binary")with gr.Column(scale=1):gr.Markdown("### 🎤 Cài đặt Voice")voice_id = gr.Textbox(label="Voice ID",placeholder="21m00Tcm4TlvDq8ikWAM",info="Voice ID từ ElevenLabs")# File upload cho Voice IDsvoice_file = gr.File(label="📁 Tải Voice IDs từ file",file_types=[".txt", ".json"],type="binary")model_id = gr.Dropdown(label="Model",choices=["eleven_turbo_v2_5", "eleven_flash_v2_5", "eleven_multilingual_v2"],value="eleven_multilingual_v2")format_type = gr.Dropdown(label="Định dạng file",choices=["MP3", "WAV", "OGG", "FLAC"],value="MP3")gr.Markdown("### ⚙️ Thông số Giọng nói")with gr.Row():stability = gr.Slider(minimum=0, maximum=100, value=95, label="Stability")similarity = gr.Slider(minimum=0, maximum=100, value=80, label="Similarity")with gr.Row():style = gr.Slider(minimum=0, maximum=100, value=40, label="Style")speed = gr.Slider(minimum=70, maximum=120, value=80, label="Speed")speaker_boost = gr.Checkbox(label="Speaker Boost", value=True)with gr.TabItem("📝 Văn bản"):text_input = gr.Textbox(label="Văn bản cần chuyển đổi",placeholder="Nhập văn bản cần chuyển đổi thành giọng nói tại đây...",lines=10)with gr.Row():text_file = gr.File(label="📁 Tải văn bản từ file",file_types=[".txt", ".json"],type="binary")clear_text_btn = gr.Button("🗑️ Xóa văn bản", variant="secondary")text_stats = gr.Textbox(label="📊 Thống kê", interactive=False, lines=2)with gr.TabItem("🚀 Xử lý & Kết quả"):with gr.Row():with gr.Column():process_btn = gr.Button("🚀 Bắt đầu Tạo Giọng nói", variant="primary", size="lg")status_text = gr.Textbox(label="Trạng thái", interactive=False, lines=3)gr.Markdown("### 📁 Kết quả")output_files = gr.File(label="File đã tạo",file_count="multiple",interactive=False)output_message = gr.Markdown("")with gr.Column():gr.Markdown("### 📊 Logs xử lý")progress_bar = gr.ProgressBar()logs_text = gr.Textbox(label="Logs",interactive=False,lines=15,max_lines=50)# ==================== CALLBACK FUNCTIONS ====================def update_text_stats(text):"""Cập nhật thống kê văn bản"""char_count = len(text)if text.strip():blocks = parse_text_blocks(text)block_count = len(blocks)estimated_credits = char_count + (block_count * 50)return f"📊 {char_count:,} ký tự | {block_count} đoạn | Ước tính: {estimated_credits:,} credits"return "📊 0 ký tự | 0 đoạn | Ước tính: 0 credits"def clear_api_keys():"""Xóa API keys"""return "", "✅ Đã xóa API keys"def clear_text():"""Xóa văn bản"""return "", update_text_stats("")def process_api_file(file):"""Xử lý file API keys"""if file is None:return "", "⚠ Chưa chọn file"try:content = file.read().decode('utf-8', errors='ignore')api_keys = extract_api_keys_from_content(content)if api_keys:return "\n".join(api_keys), f"✅ Đã tải {len(api_keys)} API keys từ file"else:return "", "⚠ Không tìm thấy API keys trong file"except Exception as e:return "", f"❌ Lỗi: {str(e)}"def process_voice_file(file):"""Xử lý file Voice IDs"""if file is None:return "", "⚠ Chưa chọn file"try:content = file.read().decode('utf-8', errors='ignore')voice_ids = extract_voice_ids_from_content(content)if voice_ids:return voice_ids[0], f"✅ Đã tải {len(voice_ids)} Voice IDs (sử dụng đầu tiên)"else:return "", "��� Không tìm thấy Voice IDs trong file"except Exception as e:return "", f"❌ Lỗi: {str(e)}"def process_text_file(file):"""Xử lý file văn bản"""if file is None:return "", "⚠ Chưa chọn file"try:content = file.read().decode('utf-8', errors='ignore')# Thử phân tích JSONtry:data = json.loads(content)if isinstance(data, dict) and 'text' in data:content = data['text']elif isinstance(data, dict) and 'content' in data:content = data['content']elif isinstance(data, list):content = '\n'.join(str(item) for item in data)except:pass # Không phải JSON, giữ nguyênreturn content, f"✅ Đã tải văn bản ({len(content):,} ký tự)"except Exception as e:return "", f"❌ Lỗi: {str(e)}"def process_tts(api_keys_text, voice_id, text_input, model_id, format_type,stability, similarity, style, speed, speaker_boost, progress=gr.Progress()):"""Xử lý TTS chính"""logs = []def log_message(msg):logs.append(f"[{time.strftime('%H:%M:%S')}] {msg}")return "\n".join(logs[-20:]) # Giữ 20 dòng cuốitry:# Kiểm tra đầu vàoif not api_keys_text.strip():return {status_text: "❌ Vui lòng nhập API keys!",logs_text: log_message("❌ Lỗi: Chưa nhập API keys"),output_files: None,output_message: "### ❌ Lỗi: Vui lòng nhập API keys"}if not voice_id.strip():return {status_text: "❌ Vui lòng nhập Voice ID!",logs_text: log_message("❌ Lỗi: Chưa nhập Voice ID"),output_files: None,output_message: "### ❌ Lỗi: Vui lòng nhập Voice ID"}if not text_input.strip():return {status_text: "❌ Vui lòng nhập văn bản!",logs_text: log_message("❌ Lỗi: Chưa nhập văn bản"),output_files: None,output_message: "### ❌ Lỗi: Vui lòng nhập văn bản"}logs_text_value = log_message("🚀 Bắt đầu xử lý TTS...")status_text_value = "🔄 Đang khởi tạo..."progress(0, desc="Đang khởi tạo...")# Xử lý không đồng bộloop = asyncio.new_event_loop()asyncio.set_event_loop(loop)result = loop.run_until_complete(process_tts_async(api_keys_text, voice_id, text_input, model_id, format_type,stability, similarity, style, speed, speaker_boost, progress))loop.close()logs_text_value = log_message(result["message"])if result["files"]:status_text_value = "✅ Hoàn thành!"message = f"### ✅ Hoàn thành!\n\nĐã tạo {len([f for f in result['files'] if 'voice_' in str(f)])} file audio\n[📥 Tải xuống file đã tạo](#)"return {status_text: status_text_value,logs_text: logs_text_value,output_files: result["files"],output_message: message}else:status_text_value = "❌ Thất bại"message = f"### ❌ Thất bại\n\n{result['message']}"return {status_text: status_text_value,logs_text: logs_text_value,output_files: None,output_message: message}except Exception as e:error_msg = f"❌ Lỗi hệ thống: {str(e)}"return {status_text: "❌ Lỗi hệ thống",logs_text: log_message(error_msg),output_files: None,output_message: f"### ❌ Lỗi hệ thống\n\n{str(e)}"}# ==================== EVENT HANDLERS ====================# Text stats updatetext_input.change(fn=update_text_stats,inputs=[text_input],outputs=[text_stats])# API keys checkcheck_api_btn.click(fn=check_all_api_keys,inputs=[api_keys_text],outputs=[api_check_result])# Clear buttonsclear_api_btn.click(fn=clear_api_keys,inputs=[],outputs=[api_keys_text, api_check_result])clear_text_btn.click(fn=clear_text,inputs=[],outputs=[text_input, text_stats])# File upload handlersapi_file.upload(fn=process_api_file,inputs=[api_file],outputs=[api_keys_text, api_check_result]).then(fn=check_all_api_keys,inputs=[api_keys_text],outputs=[api_check_result])voice_file.upload(fn=process_voice_file,inputs=[voice_file],outputs=[voice_id, status_text])text_file.upload(fn=process_text_file,inputs=[text_file],outputs=[text_input, status_text]).then(fn=update_text_stats,inputs=[text_input],outputs=[text_stats])# Main TTS processprocess_btn.click(fn=process_tts,inputs=[api_keys_text, voice_id, text_input, model_id, format_type,stability, similarity, style, speed, speaker_boost],outputs=[status_text, logs_text, output_files, output_message])# ==================== LAUNCH APP ====================if __name__ == "__main__":demo.queue() # Enable queuing for async operationsdemo.launch(server_name="0.0.0.0",server_port=7860,share=False,debug=False)
app.py+650-38