import gradio as gr
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
import speech_recognition as sr
from gtts import gTTS
import os
from playsound import playsound
import pandas as pd

# Load healthcare data from GitHub raw CSV link
github_raw_url = 'https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/latest/owid-covid-latest.csv'
healthcare_data = pd.read_csv(github_raw_url)

# Assuming columns "Condition" and "Advice" exist in your chosen data
def get_healthcare_advice(condition):
    # Search for matching entries in the 'location' column
    matching_entries = healthcare_data[healthcare_data['location'].str.contains(condition, case=False, na=False)]
    if not matching_entries.empty:
        total_cases = matching_entries['total_cases'].values[0]
        return f"The total reported cases in {condition} are {total_cases}."
    else:
        return None

# Initialize models and tools
model_name = "microsoft/DialoGPT-medium"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name)

recognizer = sr.Recognizer()

chat_history_ids = None

def generate_response(user_input, chat_history_ids=None):
    # Check if healthcare data has relevant information
    healthcare_advice = get_healthcare_advice(user_input)
    
    if healthcare_advice:
        response = f"Based on healthcare data, here's some advice: {healthcare_advice}"
    else:
        new_input_ids = tokenizer.encode(user_input + tokenizer.eos_token, return_tensors='pt')
        if chat_history_ids is not None:
            bot_input_ids = torch.cat([chat_history_ids, new_input_ids], dim=-1)
        else:
            bot_input_ids = new_input_ids

        chat_history_ids = model.generate(
            bot_input_ids,
            max_length=1000,
            pad_token_id=tokenizer.eos_token_id,
            no_repeat_ngram_size=3,
            do_sample=True,
            top_k=50,
            top_p=0.95
        )
        response = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
    
    return response, chat_history_ids


def chat_function(user_input):
    global chat_history_ids
    response, chat_history_ids = generate_response(user_input, chat_history_ids)
    return response

def speech_to_text(audio_path):
    with sr.AudioFile(audio_path) as source:
        audio = recognizer.record(source)
    try:
        text = recognizer.recognize_google(audio)
        return text
    except sr.UnknownValueError:
        return "I did not understand that."
    except sr.RequestError:
        return "Network error."

def text_to_speech(text):
    tts = gTTS(text=text, lang='en')
    tts.save("response.mp3")
    playsound("response.mp3")
    os.remove("response.mp3")

def chat_voice(audio):
    user_text = speech_to_text(audio)
    response = chat_function(user_text)
    text_to_speech(response)
    return response

# Gradio Interfaces
iface_text = gr.Interface(
    fn=chat_function,
    inputs=gr.Textbox(lines=2, placeholder="Enter your question here..."),
    outputs="text",
    title="Healthcare AI Chatbot",
    description="Type your medical-related questions. **Disclaimer:** This AI is not a substitute for professional medical advice."
)

iface_voice = gr.Interface(
    fn=chat_voice,
    inputs=gr.Audio(type="filepath"),
    outputs="text",
    title="Healthcare AI Chatbot with Voice",
    description="Upload an audio file, and the AI will respond verbally. **Disclaimer:** This AI is not a substitute for professional medical advice."
)

# Launch both interfaces in tabs
tabbed_interface = gr.TabbedInterface(
    [iface_text, iface_voice],
    ["Text Chat", "Voice Chat"]
)

tabbed_interface.launch()


Can you change the healthcare dataset more advanced