dhruvilhere commited on
Commit
25e2ea6
Β·
verified Β·
1 Parent(s): 0e66202

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +118 -1
app.py CHANGED
@@ -1 +1,118 @@
1
- {"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"},"kaggle":{"accelerator":"none","dataSources":[],"isInternetEnabled":true,"language":"python","sourceType":"script","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# πŸ§ πŸ’¬ Advanced Mental Health Companion AI Chatbot with Gradio UI\n# Developed using Gemini 1.5 Pro API with RAG, JSON mode, embeddings, and vector search\n\n# --- πŸ“Œ Install Required Libraries ---\nimport os\nimport json\nimport gradio as gr\nimport google.generativeai as genai\nfrom langchain.vectorstores import FAISS\nfrom langchain.embeddings import OpenAIEmbeddings\nfrom langchain.docstore.document import Document\nfrom langchain.text_splitter import CharacterTextSplitter\n\n# --- πŸ“Œ Load Gemini API Key ---\ngemini_key = os.getenv(\"GEMINI_API_KEY\")\ngenai.configure(api_key=gemini_key)\n\n# --- πŸ“Œ Initialize Gemini Model ---\nmodel = genai.GenerativeModel(model_name=\"gemini-1.5-pro\")\nchat = model.start_chat(history=[])\n\n# --- πŸ“Œ Define Core Functionalities ---\ndef detect_emotion(user_input):\n prompt = f\"\"\"\n Analyze the message and return a JSON with:\n {{\n \"emotion\": \"<Emotion>\",\n \"tone\": \"<Suggested_Tone>\",\n \"affirmation\": \"<One_Line_Affirmation>\",\n \"response\": \"<Comforting response>\"\n }}\n\n Message: \"{user_input}\"\n \"\"\"\n response = model.generate_content(prompt, generation_config={\"response_mime_type\": \"application/json\"})\n return json.loads(response.text)\n\ndef get_affirmation():\n prompt = \"Provide a unique calming affirmation for someone feeling overwhelmed.\"\n return model.generate_content(prompt).text\n\ndef get_journaling_prompt():\n prompt = \"Give me a mental health journaling prompt.\"\n return model.generate_content(prompt).text\n\ndef get_calming_technique():\n prompt = \"Suggest a calming breathing or grounding technique.\"\n return model.generate_content(prompt).text\n\n# --- πŸ“Œ Memory & Vector Store (RAG Setup) ---\ndocuments = [\n Document(page_content=\"Take a deep breath. You are doing your best.\"),\n Document(page_content=\"It's okay to not be okay. Give yourself grace.\"),\n Document(page_content=\"You are not alone. Many have walked this path and found light again.\"),\n Document(page_content=\"Small steps lead to big changes. Just begin.\")\n]\n\nsplitter = CharacterTextSplitter(chunk_size=100, chunk_overlap=0)\nsplit_docs = splitter.split_documents(documents)\nembedding = OpenAIEmbeddings(openai_api_key=gemini_key)\nvector_db = FAISS.from_documents(split_docs, embedding)\n\ndef retrieve_supportive_text(user_input):\n docs = vector_db.similarity_search(user_input, k=2)\n return \"\\n\".join([d.page_content for d in docs])\n\n# --- πŸ“Œ Smart Response Generator ---\ndef generate_companion_response(name, issue):\n emotion_data = detect_emotion(issue)\n rag_support = retrieve_supportive_text(issue)\n\n system_prompt = f\"\"\"\n You're MindMate, a kind mental health assistant.\n Respond personally to {name}.\n\n Emotion: {emotion_data['emotion']}\n Tone: {emotion_data['tone']}\n Affirmation: {emotion_data['affirmation']}\n\n Based on the above, and the following supportive texts:\n {rag_support}\n\n Compose a comforting and warm message to the user:\n Message: {issue}\n \"\"\"\n response = chat.send_message(system_prompt)\n return response.text, emotion_data['emotion'], emotion_data['affirmation']\n\n# --- πŸ“Œ Gradio UI ---\ndef chatbot_interface(name, issue):\n response, emotion, affirmation = generate_companion_response(name, issue)\n journaling = get_journaling_prompt()\n technique = get_calming_technique()\n\n return {\n \"Emotion\": emotion,\n \"Affirmation\": affirmation,\n \"Companion Response\": response,\n \"Journaling Prompt\": journaling,\n \"Calming Tip\": technique\n }\n\ninputs = [\n gr.Textbox(label=\"Your Name\"),\n gr.Textbox(label=\"What's troubling you today?\", lines=4)\n]\n\noutputs = gr.JSON(label=\"MindMate's Support\")\n\ndemo = gr.Interface(\n fn=chatbot_interface,\n inputs=inputs,\n outputs=outputs,\n title=\"🧠 MindMate: Your Mental Health Companion\",\n description=\"Talk to MindMate by sharing your name and what's on your mind. Get emotional insights, affirmations, and comfort.\"\n)\n\ndemo.launch()\n\n# --- πŸ“Œ Notes for Deployment ---\n# Save this file as app.py\n# Create requirements.txt with:\n# gradio\n# google-generativeai\n# langchain\n# faiss-cpu\n# openai\n# tiktoken\n# Push both to Hugging Face Spaces (Gradio app type)\n# Add your GEMINI_API_KEY under Settings > Secrets\n","metadata":{"_uuid":"bdce8786-d7ca-4786-97c2-1b7a55ba21fb","_cell_guid":"162a3627-87ff-431e-96e1-3fd5cfefce13","trusted":true,"collapsed":false,"jupyter":{"outputs_hidden":false}},"outputs":[],"execution_count":null}]}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # πŸ§ πŸ’¬ Advanced Mental Health Companion AI Chatbot with Gradio UI
2
+ # Developed using Gemini 1.5 Pro API with RAG, JSON mode, embeddings, and vector search
3
+
4
+ # --- πŸ“Œ Install Required Libraries ---
5
+ import os
6
+ import json
7
+ import gradio as gr
8
+ import google.generativeai as genai
9
+ from langchain.vectorstores import FAISS
10
+ from langchain.embeddings import OpenAIEmbeddings
11
+ from langchain.docstore.document import Document
12
+ from langchain.text_splitter import CharacterTextSplitter
13
+
14
+ # --- πŸ“Œ Load Gemini API Key ---
15
+ gemini_key = os.getenv("GEMINI_API_KEY")
16
+ genai.configure(api_key=gemini_key)
17
+
18
+ # --- πŸ“Œ Initialize Gemini Model ---
19
+ model = genai.GenerativeModel(model_name="gemini-1.5-pro")
20
+ chat = model.start_chat(history=[])
21
+
22
+ # --- πŸ“Œ Define Core Functionalities ---
23
+ def detect_emotion(user_input):
24
+ prompt = f"""
25
+ Analyze the message and return a JSON with:
26
+ {{
27
+ "emotion": "<Emotion>",
28
+ "tone": "<Suggested_Tone>",
29
+ "affirmation": "<One_Line_Affirmation>",
30
+ "response": "<Comforting response>"
31
+ }}
32
+
33
+ Message: "{user_input}"
34
+ """
35
+ response = model.generate_content(prompt, generation_config={"response_mime_type": "application/json"})
36
+ return json.loads(response.text)
37
+
38
+ def get_affirmation():
39
+ prompt = "Provide a unique calming affirmation for someone feeling overwhelmed."
40
+ return model.generate_content(prompt).text
41
+
42
+ def get_journaling_prompt():
43
+ prompt = "Give me a mental health journaling prompt."
44
+ return model.generate_content(prompt).text
45
+
46
+ def get_calming_technique():
47
+ prompt = "Suggest a calming breathing or grounding technique."
48
+ return model.generate_content(prompt).text
49
+
50
+ # --- πŸ“Œ Memory & Vector Store (RAG Setup) ---
51
+ documents = [
52
+ Document(page_content="Take a deep breath. You are doing your best."),
53
+ Document(page_content="It's okay to not be okay. Give yourself grace."),
54
+ Document(page_content="You are not alone. Many have walked this path and found light again."),
55
+ Document(page_content="Small steps lead to big changes. Just begin.")
56
+ ]
57
+
58
+ splitter = CharacterTextSplitter(chunk_size=100, chunk_overlap=0)
59
+ split_docs = splitter.split_documents(documents)
60
+ embedding = OpenAIEmbeddings(openai_api_key=gemini_key)
61
+ vector_db = FAISS.from_documents(split_docs, embedding)
62
+
63
+ def retrieve_supportive_text(user_input):
64
+ docs = vector_db.similarity_search(user_input, k=2)
65
+ return "\n".join([d.page_content for d in docs])
66
+
67
+ # --- πŸ“Œ Smart Response Generator ---
68
+ def generate_companion_response(name, issue):
69
+ emotion_data = detect_emotion(issue)
70
+ rag_support = retrieve_supportive_text(issue)
71
+
72
+ system_prompt = f"""
73
+ You're MindMate, a kind mental health assistant.
74
+ Respond personally to {name}.
75
+
76
+ Emotion: {emotion_data['emotion']}
77
+ Tone: {emotion_data['tone']}
78
+ Affirmation: {emotion_data['affirmation']}
79
+
80
+ Based on the above, and the following supportive texts:
81
+ {rag_support}
82
+
83
+ Compose a comforting and warm message to the user:
84
+ Message: {issue}
85
+ """
86
+ response = chat.send_message(system_prompt)
87
+ return response.text, emotion_data['emotion'], emotion_data['affirmation']
88
+
89
+ # --- πŸ“Œ Gradio UI ---
90
+ def chatbot_interface(name, issue):
91
+ response, emotion, affirmation = generate_companion_response(name, issue)
92
+ journaling = get_journaling_prompt()
93
+ technique = get_calming_technique()
94
+
95
+ return {
96
+ "Emotion": emotion,
97
+ "Affirmation": affirmation,
98
+ "Companion Response": response,
99
+ "Journaling Prompt": journaling,
100
+ "Calming Tip": technique
101
+ }
102
+
103
+ inputs = [
104
+ gr.Textbox(label="Your Name"),
105
+ gr.Textbox(label="What's troubling you today?", lines=4)
106
+ ]
107
+
108
+ outputs = gr.JSON(label="MindMate's Support")
109
+
110
+ demo = gr.Interface(
111
+ fn=chatbot_interface,
112
+ inputs=inputs,
113
+ outputs=outputs,
114
+ title="🧠 MindMate: Your Mental Health Companion",
115
+ description="Talk to MindMate by sharing your name and what's on your mind. Get emotional insights, affirmations, and comfort."
116
+ )
117
+
118
+ demo.launch()