File size: 8,200 Bytes
e720991
 
00545f5
7c9eeb2
 
34cf2ff
 
 
 
 
 
2c2b51d
522a889
7c9eeb2
 
34cf2ff
 
 
 
 
 
 
 
 
 
 
7c9eeb2
34cf2ff
 
 
 
 
 
 
 
 
 
 
2673451
522a889
34cf2ff
 
 
 
 
 
 
 
 
 
 
2c2b51d
e720991
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
522a889
 
34cf2ff
 
 
 
 
 
 
522a889
7c9eeb2
 
 
 
 
 
 
 
 
 
 
 
522a889
7c9eeb2
 
34cf2ff
7c9eeb2
 
 
 
34cf2ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e720991
522a889
81de6de
7c9eeb2
81de6de
7c9eeb2
 
 
 
 
 
 
81de6de
 
7c9eeb2
81de6de
e720991
7c9eeb2
34cf2ff
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
import gradio as gr
from gtts import gTTS
import tempfile
from transformers import pipeline
import os
import logging
from huggingface_hub import login

# Set up logging for better error tracking
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Configure Hugging Face API Token (Replace with your actual token)
HUGGINGFACE_API_TOKEN = "your_huggingface_api_token"  # Replace with your Hugging Face API token

# Validate API token and log in to Hugging Face Hub
if HUGGINGFACE_API_TOKEN == "your_huggingface_api_token":
    logger.error("Please replace 'your_huggingface_api_token' with a valid Hugging Face API token from https://huggingface.co/settings/tokens")
    raise ValueError("Invalid Hugging Face API token. Please set a valid token.")
try:
    login(token=HUGGINGFACE_API_TOKEN)
    logger.info("Successfully logged in to Hugging Face Hub")
except Exception as e:
    logger.error(f"Failed to log in to Hugging Face Hub: {str(e)}")
    raise

# Initialize Hugging Face Whisper model for speech-to-text (multilingual support)
try:
    whisper_pipeline = pipeline(
        "automatic-speech-recognition",
        model="openai/whisper-tiny",
        token=HUGGINGFACE_API_TOKEN,
        device=-1  # Use CPU if GPU unavailable
    )
    logger.info("Whisper model initialized successfully")
except Exception as e:
    logger.error(f"Failed to initialize Whisper model: {str(e)}")
    raise

# Initialize Hugging Face text generation model for chatbot
try:
    text_generation_pipeline = pipeline(
        "text2text-generation",
        model="google/flan-t5-small",
        token=HUGGINGFACE_API_TOKEN,
        device=-1  # Use CPU if GPU unavailable
    )
    logger.info("Text generation model initialized successfully")
except Exception as e:
    logger.error(f"Failed to initialize text generation model: {str(e)}")
    raise

# Define chatbot knowledge base
base_info = """
You are a highly advanced AI assistant named 'MindCare'.
Your role is to provide support in various aspects of health and well-being, including:
- **Mental health**: Emotional support, mindfulness, stress-relief exercises, anxiety management.
- **Medical guidance**: Basic symptom analysis, possible conditions, and medicine recommendations.
- **Decision-making support**: Helping users with personal, professional, and emotional choices.
- **General health advice**: Lifestyle improvements, nutrition, physical wellness, and mental well-being.
- **Emergency assistance**: If the user is in distress, suggest professional help or helpline numbers.

Your tone is always **empathetic, supportive, and informative**. You ensure users feel heard and cared for.
"""

mental_health = """
If the user is feeling stressed or anxious:
- Suggest mindfulness exercises, deep breathing techniques, or gratitude journaling.
- Encourage taking breaks, engaging in hobbies, and spending time in nature.
- Provide positive affirmations and self-care routines.

If the user is in distress:
- Offer emotional support and let them know they are not alone.
- Encourage them to reach out to a trusted person or professional.
- Provide emergency helpline numbers if needed.
"""

medical_assistance = """
If the user provides symptoms:
- Analyze symptoms and suggest possible conditions.
- Provide general advice but **never** replace a doctor’s consultation.
- Suggest lifestyle changes or basic home remedies if applicable.
- If symptoms are severe, advise them to visit a healthcare professional.

If the user asks about medicines:
- Suggest **common antibiotics** based on infection type (e.g., Amoxicillin for bacterial infections).
- Recommend **painkillers** like Paracetamol, Ibuprofen, or Diclofenac for pain relief.
- Mention precautions and possible side effects.
- Clearly **state that a doctor’s consultation is necessary before taking any medicine**.
"""

medicine_recommendation = """
If the user asks for a prescription, provide general guidance on **commonly used medicines**:
- **Antibiotics** (for bacterial infections): Amoxicillin, Azithromycin, Ciprofloxacin.
- **Painkillers**: Paracetamol (mild pain/fever), Ibuprofen (anti-inflammatory), Diclofenac (muscle pain).
- **Cold & Flu**: Antihistamines like Cetirizine, Cough syrups like Dextromethorphan.
- **Stomach Issues**: Antacids like Ranitidine, PPI like Omeprazole.

Always remind the user that **only a licensed doctor can prescribe medicines, and misuse can be harmful**.
"""

decision_guidance = """
If the user is struggling with a decision:
- Help them weigh pros and cons logically.
- Suggest considering their values, long-term goals, and emotions.
- Provide structured approaches like decision matrices or intuitive checks.
- Encourage seeking advice from trusted people if needed.
"""

emergency_help = """
If the user mentions severe mental distress:
- Respond with immediate emotional support.
- Provide crisis helpline numbers (if applicable to the region).
- Encourage talking to a trusted friend, family member, or professional.
- Remind them that they are not alone and help is available.
"""

# Combine all knowledge into one structured context
context = [base_info, mental_health, medical_assistance, medicine_recommendation, decision_guidance, emergency_help]

# Function to get AI response using text generation model
def get_llm_response(message):
    try:
        full_context = "\n".join(context) + f"\nUser: {message}\nMindCare:"
        response = text_generation_pipeline(full_context, max_length=500, num_return_sequences=1)[0]['generated_text']
        return response
    except Exception as e:
        logger.error(f"Error generating response: {str(e)}")
        return f"Error generating response: {str(e)}"

# Function to process voice input and convert to text
def process_voice_input(audio_file, language="en"):
    # Map language codes for Whisper model
    language_map = {
        "en": "english",
        "es": "spanish",
        "hi": "hindi",
        "zh": "chinese"
    }
    try:
        # Transcribe audio using Hugging Face Whisper model
        transcription = whisper_pipeline(audio_file, 
                                        generate_kwargs={"language": language_map.get(language, "english")})
        return transcription["text"]
    except Exception as e:
        logger.error(f"Error processing audio: {str(e)}")
        return f"Error processing audio: {str(e)}"

# Define chatbot response function with voice and text input
def bot(message=None, audio_file=None, language="en", history=None):
    try:
        if audio_file:
            # Process voice input if provided
            message = process_voice_input(audio_file, language)
        
        if not message:
            return "No input provided. Please type a message or upload an audio file.", None
        
        # Get response from text generation model
        response = get_llm_response(message)
        
        # Convert the response to speech using gTTS
        tts = gTTS(text=response, lang=language, slow=False)
        
        # Save the audio file in a temporary directory
        with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as temp_audio:
            audio_path = temp_audio.name
            tts.save(audio_path)
        
        return response, audio_path
    except Exception as e:
        logger.error(f"Error in bot function: {str(e)}")
        return f"Error: {str(e)}", None

# Create Gradio interface with voice and text input
demo = gr.Interface(
    fn=bot,
    inputs=[
        gr.Textbox(label="Enter your message (optional)"),
        gr.Audio(label="Record your voice", type="filepath"),
        gr.Dropdown(label="Select Language", choices=["en", "es", "hi", "zh"], value="en")
    ],
    outputs=[
        gr.Textbox(label="Response"),
        gr.Audio(label="Response Audio")
    ],
    title="MindCare - Your Personal Health & Wellness Assistant",
    description="Type a message or record your voice in English, Spanish, Hindi, or Mandarin."
)

# Launch the Gradio app
if __name__ == "__main__":
    try:
        demo.launch(debug=True, share=True)
    except Exception as e:
        logger.error(f"Failed to launch Gradio app: {str(e)}")
        raise