import gradio as gr import time import uuid import re from util import ( create_task_v3, get_task_result, ) IP_Dict = {} # 支持的语言列表 SUPPORTED_LANGUAGES = [ {"flag": "🇺🇸", "name": "English", "code": "en"}, {"flag": "🇨🇳", "name": "中文", "code": "zh"}, {"flag": "🇪🇸", "name": "Español", "code": "es"}, {"flag": "🇫🇷", "name": "Français", "code": "fr"}, {"flag": "🇩🇪", "name": "Deutsch", "code": "de"}, {"flag": "🇮🇹", "name": "Italiano", "code": "it"}, {"flag": "🇯🇵", "name": "日本語", "code": "ja"}, {"flag": "🇰🇷", "name": "한국어", "code": "ko"}, {"flag": "🇷🇺", "name": "Русский", "code": "ru"} ] def detect_language(text): """ 语言检测函数 - 只检测容易区分的语言 """ if len(text) < 5: return None # 语言特征字符 language_features = { "zh": re.compile(r'[\u4e00-\u9fff\u3400-\u4dbf\uff00-\uffef\u3000-\u303f]'), "ja": re.compile(r'[\u3040-\u309f\u30a0-\u30ff]'), "ko": re.compile(r'[\uac00-\ud7af]'), "ru": re.compile(r'[\u0400-\u04ff]') } scores = {lang: 0 for lang in language_features.keys()} # 字符特征检测 - 只检测明显的非拉丁字符 for char in text: for lang, pattern in language_features.items(): if pattern.search(char): scores[lang] += 1 # 找到得分最高的语言 max_score = 0 detected_lang = None for lang, score in scores.items(): if score > max_score and score > 0: max_score = score detected_lang = lang # 检查是否满足阈值 - 如果有明显的非拉丁字符就切换 if detected_lang and max_score >= 2: return detected_lang # 没有检测到其他语言,默认保持英语 return None def get_language_display_text(language_code): """获取语言的显示文本(国旗 + 名称)""" for lang in SUPPORTED_LANGUAGES: if lang["code"] == language_code: return f"{lang['flag']} {lang['name']}" return "🇺🇸 English" def get_language_code_from_display(display_text): """从显示文本中提取语言代码""" for lang in SUPPORTED_LANGUAGES: if f"{lang['flag']} {lang['name']}" == display_text: return lang['code'] return "en" def auto_detect_language(text, current_language_display): """ 自动检测语言并返回更新后的语言选择 """ if not text or len(text.strip()) < 5: return current_language_display current_code = get_language_code_from_display(current_language_display) detected_lang = detect_language(text) if detected_lang and detected_lang != current_code: print(f"Language auto-detected: {current_code} -> {detected_lang}") return get_language_display_text(detected_lang) return current_language_display def generate_obama_voice_with_realtime_updates(text, language_display, request: gr.Request): """ Obama AI voice generation function with real-time status updates """ # 从显示文本中提取语言代码 language = get_language_code_from_display(language_display) client_ip = request.client.host x_forwarded_for = dict(request.headers).get('x-forwarded-for') if x_forwarded_for: client_ip = x_forwarded_for if client_ip not in IP_Dict: IP_Dict[client_ip] = 0 IP_Dict[client_ip] += 1 print(f"client_ip: {client_ip}, count: {IP_Dict[client_ip]}") if IP_Dict[client_ip] >= 6: msg = "You have reached the maximum number of requests" # Create "Get More Tries" button HTML get_more_tries_html = f"""
🚀 Get More Tries for Free
""" yield msg, None, gr.update(value=get_more_tries_html, visible=True), "" return msg, None, gr.update(value=get_more_tries_html, visible=True), "" if not text or len(text.strip()) < 3: return "Text too short, please enter at least 3 characters", None, gr.update(visible=False), "" if len(text.strip()) >= 1800: msg = "⚠️ This space has a maximum limit of 2000 characters. Please visit our official website to generate longer content for free." # Create "Go to Official Website" button HTML go_to_website_html = f"""
🌐 Go to Official Website for Free
""" yield msg, None, gr.update(value=go_to_website_html, visible=True), "" return msg, None, gr.update(value=go_to_website_html, visible=True), "" try: task_type = "voice" word_num = len(text.strip().split()) # 自动计算单词数 # Create task task_result = create_task_v3(task_type, text.strip(), word_num, is_rewrite=False, language=language) if not task_result: return "Failed to create task", None, gr.update(visible=False), "" else: yield "Task created successfully", None, gr.update(visible=False), "" max_polls = 300 poll_interval = 1 task_url = f"https://trumpaivoice.net/task/{task_result['uuid']}" for i in range(max_polls): time.sleep(poll_interval) task = get_task_result(task_result['uuid']) # print(task, i, "get_task_result") if task.get('data', {}): status = task.get('data').get('status', '') text_final = task.get('data').get('text_final', '') if status in ['completed',]: voice_url = task.get('data').get('voice_url', '') print(voice_url, "===>voice_url") # 下载音频文件到本地以避免SSRF保护问题 local_audio_path = voice_url # Create action buttons HTML action_buttons_html = f"""
🎬 Generate 4K Video 👀 Check Generate Details
""" yield f"✅ success!!!", local_audio_path, gr.update(value=action_buttons_html, visible=True), task_url return "✅ Generation successful!", local_audio_path, gr.update(value=action_buttons_html, visible=True), task_url elif status in ['failed', 'voice_error', 'no_credits']: yield "❌ Generation failed!", None, gr.update(visible=False), "" return "❌ Generation failed!", None, gr.update(visible=False), "" else: yield f"query {i} times, on processing, go to task page {task_url} to check status", None, gr.update(visible=False), task_url return "❌ Generation failed!", None, gr.update(visible=False), "" except Exception as e: error_msg = f"Generation failed: {str(e)}" yield error_msg, None, gr.update(visible=False), "" return error_msg, None, gr.update(visible=False), "" # Create Gradio Interface with gr.Blocks(title="Barack Obama AI Voice", theme=gr.themes.Soft()) as demo: # Main title - at the top gr.HTML("""

🎤 Obama AI Voice

""", padding=False) # # Showcase link banner - second # gr.HTML(""" #
#
#

# 🎬 Check out Obama AI videos created by others → #

#
#
# """, padding=False) # Powered by link - small text gr.HTML("""

powered by trumpaivoice.net

""", padding=False) # Simple description text - third # gr.HTML(""" #
#

# 🔥 Try the most advanced Obama AI Voice and Video generator for FREE at # donaldtrumpaivoice.com! #

#
# """) with gr.Row(): with gr.Column(scale=2): text_input = gr.Textbox( label="📝 Input Text", lines=4, max_length=2000, placeholder="Enter what you want Obama to say...", value="Hello everyone, this is a demonstration of the Obama AI Voice system with real-time status monitoring." ) with gr.Column(scale=1): # 创建语言选择器的选项 language_choices = [f"{lang['flag']} {lang['name']}" for lang in SUPPORTED_LANGUAGES] language_values = [lang['code'] for lang in SUPPORTED_LANGUAGES] language_dropdown = gr.Dropdown( choices=language_choices, value="🇺🇸 English", # 默认值 label="🌍 Language", interactive=True ) submit_btn = gr.Button( "🚀 Generate Obama AI Voice", variant="primary", size="lg" ) with gr.Row(): status_output = gr.Textbox( label="📊 Status", interactive=False, placeholder="Waiting for generation..." ) # Action buttons that will show after task completion with gr.Row(): action_links = gr.HTML(visible=False) with gr.Row(): audio_output = gr.Audio( label="🎵 Obama AI Voice", interactive=False ) # Video Showcase Section gr.HTML("""

🎬 Video Showcase

Watch amazing AI-generated Obama videos with realistic animations and perfect lip-sync!

🌺 White House Garden

🏛️ Oval Office Address

🎬 Generate 4K Obama Video

Create high-quality Obama AI videos and original songs with custom text and scenarios!

""", padding=False) # Comprehensive introduction section gr.HTML("""

🇺🇸 Experience the Power of AI-Generated Obama Voice

Transform any text into authentic Barack Obama speech with our cutting-edge AI voice synthesis technology. Whether you're creating content for entertainment, education, or social media, our advanced neural network captures Obama's distinctive speaking style, intonation, and rhetorical patterns with remarkable accuracy.

🎯 Ultra-Realistic Voice

Our AI model is trained on thousands of hours of Obama speeches, capturing his unique vocal characteristics, pronunciation patterns, and speaking rhythm to deliver incredibly lifelike results.

⚡ Lightning Fast Generation

Generate high-quality Obama AI voice clips in seconds, not minutes. Our optimized infrastructure ensures rapid processing while maintaining exceptional audio quality.

🎨 Creative Content Creation

Perfect for memes, podcasts, educational content, entertainment videos, or any creative project that needs an authentic Obama voice performance.

🎭 Try More Celebrity AI Voices

Explore our premium collection of celebrity AI voices! Our high-quality service delivers lightning-fast results with exceptional audio quality. Experience the best AI voice generation with our reliable and responsive platform.

🌟 Explore Celebrity Voices 🎭 View Showcase

💡 Pro Tips for Best Results

📖 Clear Text: Use proper punctuation and avoid special characters for optimal results.
⏱️ Length Matters: Shorter texts (20-60 words) typically produce the most natural-sounding results.
🎯 Obama Style: Text written in Obama's speaking style will sound more authentic and natural.
""", padding=False) # Powered by link - small text gr.HTML("""

Click obama ai voices showcase to see more videos

""", padding=False) # Hidden state to store task_url task_url_state = gr.State("") # 自动语言检测事件 text_input.change( auto_detect_language, inputs=[text_input, language_dropdown], outputs=[language_dropdown] ) # Bind event submit_btn.click( generate_obama_voice_with_realtime_updates, inputs=[text_input, language_dropdown], outputs=[status_output, audio_output, action_links, task_url_state] ) if __name__ == "__main__": demo.launch()