# Import necessary modules
import gradio as gr
from chatbot import model_inference, EXAMPLES, chatbot
from doctor import respond  # Updated import from doctor.py

# Define Gradio theme with valid color shortcuts and custom fonts
theme = gr.themes.Soft(
    primary_hue="indigo",
    secondary_hue="emerald",
    neutral_hue="gray",
    font=[gr.themes.GoogleFont('Rubik')]
)

# Create Gradio blocks with custom CSS for enhanced UI
with gr.Blocks(
    css="""
        .gradio-container {background-color: #f0f4f8; padding: 20px;}
        h1, h2, h3, h4, h5, h6 {color: #4a5568;}
        .chat-message {background-color: #edf2f7; border-radius: 8px; padding: 10px;}
        .gradio-container .avatar-container {height: 40px; width: 40px; border-radius: 50%; overflow: hidden;}
        #duplicate-button {margin: auto; color: white; background: #2d3748; border-radius: 100vh; padding: 8px 16px;}
        .tab-nav-button {background-color: #e2e8f0; border-radius: 8px;}
        .tab-nav-button.selected {background-color: #cbd5e0;}
    """,
) as chat:
    gr.Markdown("### Please note that only one image can be created at a time. To generate multiple images, consider using an Image Generator tool.")
    gr.ChatInterface(
        fn=model_inference,
        chatbot=chatbot,
        examples=EXAMPLES,
        multimodal=True,
        cache_examples=False,
        autofocus=False,
        concurrency_limit=10,
    )

# Healthcare Chat Interface with imported respond function
with gr.Blocks() as healthcare_chat:
    gr.Markdown("### 🩺 Healthcare Chatbot")
    gr.ChatInterface(
        fn=respond,
        title="Healthcare Chatbot Assistant",
        description=(
            "Enter your symptoms below, and the chatbot will provide health-related advice. "
            "Remember, this tool is not a substitute for professional medical diagnosis. "
            "Always consult a healthcare professional for personalized advice."
        ),
        examples=[
            ["I have a persistent headache and blurred vision."],
            ["I'm experiencing shortness of breath and chest pain."],
            ["I feel fatigued despite getting enough sleep."]
        ],
        theme="compact"
    )

# Voice chat block with placeholder
with gr.Blocks() as voice:
    gr.Markdown("### 🎙️ Speech Generator ")
    gr.HTML("<iframe src='https://wifix199-Multi-language-Text-to-Speech.hf.space' width='100%' height='800px' style='border-radius: 8px;'></iframe>")
    
# Voice chat block with placeholder
with gr.Blocks() as tryon:
    gr.Markdown("### 🖼️Finegrain ")
    gr.HTML("<iframe src='https://finegrain-finegrain-object-cutter.hf.space' width='100%' height='800px' style='border-radius: 8px;'></iframe>")

# Image generation block with iframe
with gr.Blocks() as image:
    gr.Markdown("### 🖼️ Image Generator")
    gr.HTML("<iframe src='https://wifix199-Text-to-image-LuminaIQ.hf.space' width='100%' height='800px' style='border-radius: 8px;'></iframe>")

# Instant video block with iframe
with gr.Blocks() as instant2:
    gr.Markdown("### 🎥  Video Generation")
    gr.HTML("<iframe src='https://kingnish-instant-video.hf.space' width='100%' height='800px' style='border-radius: 8px;'></iframe>")

# Video block with placeholder
with gr.Blocks() as video:
    gr.Markdown("### 📹 Video Engine")
    gr.TabbedInterface([instant2], ['Instant🎥'])     

# Other blocks remain the same...

# Main application block with improved layout and styling
with gr.Blocks(theme=theme, title="RocketGPT") as demo:
    gr.Markdown("# 🚀 RocketGPT - AI-Powered Chatbot")
    gr.TabbedInterface(
        [chat, healthcare_chat, voice, image, video, tryon], 
        ['💬 SuperChat', '🩺 Healthcare Chat', '🗣️ Speech Generator', '🖼️ Image Generator', '🎥 Video Generator', '🖼️Finegrain']
    )

demo.queue(max_size=300)
demo.launch(server_name="10.172.0.233", server_port=7860, share=True)


Add new import modules from sound.py the below is the code 

import sys
import os
import time
import math
import torch
import spaces

# By using XTTS you agree to CPML license https://coqui.ai/cpml
os.environ["COQUI_TOS_AGREED"] = "1"

import gradio as gr
from TTS.api import TTS
from TTS.utils.manage import ModelManager

model_names = TTS().list_models()
print(model_names)
print(dir(model_names))  # Shows the available methods and attributes of the list
model_name = "tts_models/multilingual/multi-dataset/xtts_v2"
m = model_name

# Automatic device detection
if torch.cuda.is_available():
    device_type = "cuda"
    device_selection = "cuda:0"
    data_type = torch.float16
else:
    device_type = "cpu"
    device_selection = "cpu"
    data_type = torch.float32

tts = TTS(model_name, gpu=torch.cuda.is_available())
tts.to(device_type)

def predict(prompt, language, gender, audio_file_pth, mic_file_path, use_mic):
    start = time.time()
    if len(prompt) < 2:
        gr.Warning("Please give a longer prompt text")
        return None, None, None
    if len(prompt) > 50000:
        gr.Warning("Text length limited to 50,000 characters for this demo, please try shorter text")
        return None, None, None

    if use_mic:
        if mic_file_path is None:
            gr.Warning("Please record your voice with Microphone, or uncheck Use Microphone to use reference audios")
            return None, None, None
        else:
            speaker_wav = mic_file_path
    else:
        speaker_wav = audio_file_pth

    if speaker_wav is None:
        speaker_wav = "./examples/male.mp3" if gender == "male" else "./examples/female.wav"
    
    try:
        if language == "fr" and "your" in m:
            language = "fr-fr"
        if "/fr/" in m:
            language = None
        predict_on_gpu(prompt, speaker_wav, language)
    except RuntimeError as e:
        if "device-assert" in str(e):
            gr.Warning("Unhandled Exception encountered, please retry in a minute")
            print("Cuda device-assert Runtime encountered need restart")
            sys.exit("Exit due to cuda device-assert")
        else:
            raise e
    
    end = time.time()
    time_taken = end - start
    minutes, seconds = divmod(int(time_taken), 60)
    hours, minutes = divmod(minutes, 60)
    time_info = f"The sound has been generated in {hours} h, {minutes} min, {seconds} sec." if hours else \
                f"The sound has been generated in {minutes} min, {seconds} sec." if minutes else \
                f"The sound has been generated in {seconds} sec."

    return "output.wav", "output.wav", time_info

@spaces.GPU(duration=60)
def predict_on_gpu(prompt, speaker_wav, language):
    tts.tts_to_file(
        text=prompt,
        file_path="output.wav",
        speaker_wav=speaker_wav,
        language=language
    )

with gr.Blocks() as interface:
    gr.HTML("Multi-language Text-to-Speech")
    gr.HTML(
        """
        <a href="https://huggingface.co/coqui/XTTS-v1">XTTS</a> is a Voice generation model that lets you clone voices into different languages by using just a quick 3-second audio clip.
        """
    )
    with gr.Column():
        prompt = gr.Textbox(
            label="Text Prompt",
            value="Hello, World! Here is an example of light voice cloning. Try to upload your best audio samples quality",
        )
        language = gr.Dropdown(
            label="Language",
            choices=["ar", "pt", "zh-cn", "cs", "nl", "en", "fr", "de", "it", "pl", "ru", "es", "tr"],
            value="en",
        )
        gender = gr.Radio(["female", "male"], label="Gender")
        audio_file_pth = gr.Audio(label="Reference Audio", type="filepath", value=None)
        mic_file_path = gr.Audio(sources=["microphone"], type="filepath", label="Use Microphone for Reference")
        use_mic = gr.Checkbox(label="Check to use Microphone as Reference", value=False)
        submit = gr.Button("🚀 Speak", variant="primary")

        waveform_visual = gr.Video(label="Waveform Visual", autoplay=True)
        synthesised_audio = gr.Audio(label="Synthesised Audio", autoplay=False)
        information = gr.HTML()

    submit.click(
        predict, 
        inputs=[prompt, language, gender, audio_file_pth, mic_file_path, use_mic],
        outputs=[waveform_visual, synthesised_audio, information],
        scroll_to_output=True
    )

interface.queue().launch(server_name="10.172.0.233", server_port=7860, debug=True)