dhruvilhere commited on
Commit
40660a1
·
verified ·
1 Parent(s): d52f03e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -93
app.py CHANGED
@@ -1,113 +1,76 @@
1
- import json
2
- import gradio as gr
3
- from openai import OpenAI
4
  from langchain_community.vectorstores import FAISS
5
  from langchain_community.embeddings import FakeEmbeddings
6
- from langchain.docstore.document import Document
7
  from langchain.text_splitter import CharacterTextSplitter
 
 
 
 
 
 
 
 
 
 
8
 
9
- # --- DeepSeek R1 API Setup via OpenRouter ---
 
 
 
 
 
 
 
10
  client = OpenAI(
11
  base_url="https://openrouter.ai/api/v1",
12
  api_key="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",
13
  )
14
 
15
- # --- Dummy Embeddings and RAG Docs ---
16
- documents = [
17
- Document(page_content="Take a deep breath. You are doing your best."),
18
- Document(page_content="It's okay to not be okay. Give yourself grace."),
19
- Document(page_content="You are not alone. Many have walked this path and found light again."),
20
- Document(page_content="Small steps lead to big changes. Just begin.")
21
- ]
22
- splitter = CharacterTextSplitter(chunk_size=100, chunk_overlap=0)
23
- split_docs = splitter.split_documents(documents)
24
- vector_db = FAISS.from_documents(split_docs, FakeEmbeddings())
25
-
26
- # --- Emotion Detection using DeepSeek R1 ---
27
- def detect_emotion(user_input):
28
- prompt = f"""
29
- Analyze the message and return a JSON with:
30
- {{
31
- "emotion": "<Emotion>",
32
- "tone": "<Suggested_Tone>",
33
- "affirmation": "<One_Line_Affirmation>",
34
- "response": "<Comforting response>"
35
- }}
36
- Message: "{user_input}"
37
- """
38
 
39
- completion = client.chat.completions.create(
40
- model="deepseek/deepseek-r1:free",
41
- messages=[{"role": "user", "content": prompt}]
42
- )
43
- return json.loads(completion.choices[0].message.content)
44
 
45
- # --- Extra Tools ---
46
- def get_affirmation():
47
- completion = client.chat.completions.create(
48
- model="deepseek/deepseek-r1:free",
49
- messages=[{"role": "user", "content": "Give a one-line calming affirmation."}]
50
- )
51
- return completion.choices[0].message.content
52
 
53
- def get_journaling_prompt():
54
- completion = client.chat.completions.create(
55
- model="deepseek/deepseek-r1:free",
56
- messages=[{"role": "user", "content": "Give a journaling prompt for mental clarity."}]
57
- )
58
- return completion.choices[0].message.content
59
 
60
- def get_calming_technique():
61
  completion = client.chat.completions.create(
62
  model="deepseek/deepseek-r1:free",
63
- messages=[{"role": "user", "content": "Suggest a calming breathing or grounding technique."}]
 
 
 
 
64
  )
 
65
  return completion.choices[0].message.content
66
 
67
- # --- Chatbot Main Logic ---
68
- def chatbot_interface(name, issue):
69
- emotion_data = detect_emotion(issue)
70
- rag_support = "\n".join([d.page_content for d in vector_db.similarity_search(issue, k=2)])
71
-
72
- system_prompt = f"""
73
- You're MindMate, a kind mental health assistant.
74
- Talk directly to {name}.
75
- Emotion: {emotion_data['emotion']}
76
- Tone: {emotion_data['tone']}
77
- Affirmation: {emotion_data['affirmation']}
78
- Message: {issue}
79
- Based on this and the below RAG support:
80
- {rag_support}
81
- Write a warm, comforting response.
82
- """
83
-
84
- final_response = client.chat.completions.create(
85
- model="deepseek/deepseek-r1:free",
86
- messages=[{"role": "user", "content": system_prompt}]
87
- )
88
 
89
- return {
90
- "Emotion": emotion_data['emotion'],
91
- "Affirmation": emotion_data['affirmation'],
92
- "Companion Response": final_response.choices[0].message.content,
93
- "Journaling Prompt": get_journaling_prompt(),
94
- "Calming Tip": get_calming_technique()
95
- }
96
-
97
- # --- Gradio UI ---
98
- inputs = [
99
- gr.Textbox(label="Your Name", placeholder="e.g. Dhruvil"),
100
- gr.Textbox(label="What's troubling you today?", lines=4)
101
- ]
102
-
103
- outputs = gr.JSON(label="🧠 MindMate's Support")
104
-
105
- demo = gr.Interface(
106
- fn=chatbot_interface,
107
- inputs=inputs,
108
- outputs=outputs,
109
- title="🧠 MindMate: Your Mental Health Companion",
110
- description="Just share your name and how you're feeling. MindMate will support you emotionally with warmth, care, and science. Powered by DeepSeek R1 via OpenRouter 💖"
111
- )
112
 
113
- demo.launch()
 
 
 
 
1
  from langchain_community.vectorstores import FAISS
2
  from langchain_community.embeddings import FakeEmbeddings
 
3
  from langchain.text_splitter import CharacterTextSplitter
4
+ from langchain_community.document_loaders import TextLoader
5
+ from openai import OpenAI
6
+
7
+ import os
8
+ import gradio as gr
9
+ import json
10
+
11
+ # ========== Load Documents and Create Vector DB ==========
12
+ loader = TextLoader("mindmate.txt")
13
+ documents = loader.load()
14
 
15
+ text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
16
+ split_docs = text_splitter.split_documents(documents)
17
+
18
+ # Fix for FakeEmbeddings requiring size
19
+ embedding = FakeEmbeddings(size=1536)
20
+ vector_db = FAISS.from_documents(split_docs, embedding)
21
+
22
+ # ========== OpenRouter DeepSeek R1 Setup ==========
23
  client = OpenAI(
24
  base_url="https://openrouter.ai/api/v1",
25
  api_key="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",
26
  )
27
 
28
+ # ========== Gradio App ==========
29
+ def mindmate(name, feeling):
30
+ if not name or not feeling:
31
+ return "Please enter your name and what's troubling you."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
+ context_docs = vector_db.similarity_search(feeling, k=2)
34
+ context_text = "\n".join([doc.page_content for doc in context_docs])
 
 
 
35
 
36
+ prompt = f"""You are a compassionate and empathetic mental health support assistant named MindMate.
37
+ The user's name is {name}. They said: "{feeling}"
 
 
 
 
 
38
 
39
+ Based on the context and user's input, respond with a warm, personalized, emotionally intelligent response.
40
+ Use the following context to help, but DO NOT mention it's from a document:
41
+
42
+ Context:
43
+ {context_text}
44
+ """
45
 
 
46
  completion = client.chat.completions.create(
47
  model="deepseek/deepseek-r1:free",
48
+ messages=[{"role": "user", "content": prompt}],
49
+ extra_headers={
50
+ "HTTP-Referer": "https://huggingface.co/spaces/dhruvilhere/mindmate-chatbot",
51
+ "X-Title": "MindMate Chatbot",
52
+ },
53
  )
54
+
55
  return completion.choices[0].message.content
56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
+ # ========== Gradio UI ==========
59
+ with gr.Blocks(theme=gr.themes.Soft(), ssr=True) as demo:
60
+ gr.Markdown("🧠 **MindMate: Your Mental Health Companion**")
61
+ gr.Markdown("Just share your name and how you're feeling. MindMate will support you emotionally with warmth, care, and science. No key needed ❤️")
62
+
63
+ with gr.Row():
64
+ with gr.Column():
65
+ name = gr.Textbox(label="Your Name")
66
+ feeling = gr.Textbox(label="What's troubling you today?", lines=4)
67
+ submit_btn = gr.Button("Submit", scale=1)
68
+ clear_btn = gr.Button("Clear")
69
+
70
+ with gr.Column():
71
+ output = gr.JSON(label="🧘 MindMate's Support")
72
+
73
+ submit_btn.click(fn=mindmate, inputs=[name, feeling], outputs=output)
74
+ clear_btn.click(fn=lambda: ("", "", {}), inputs=[], outputs=[name, feeling, output])
 
 
 
 
 
 
75
 
76
+ demo.launch()