Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from huggingface_hub import InferenceClient
|
3 |
+
from typing import List, Tuple
|
4 |
+
import fitz # PyMuPDF
|
5 |
+
from sentence_transformers import SentenceTransformer, util
|
6 |
+
import numpy as np
|
7 |
+
import faiss
|
8 |
+
|
9 |
+
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
10 |
+
|
11 |
+
# Placeholder for the app's state
|
12 |
+
class MyApp:
|
13 |
+
def __init__(self) -> None:
|
14 |
+
self.documents = []
|
15 |
+
self.embeddings = None
|
16 |
+
self.index = None
|
17 |
+
self.load_pdf("/mnt/data/DBT+Neurodivergent+Friendly.pdf")
|
18 |
+
self.build_vector_db()
|
19 |
+
|
20 |
+
def load_pdf(self, file_path: str) -> None:
|
21 |
+
"""Extracts text from a PDF file and stores it in the app's documents."""
|
22 |
+
doc = fitz.open(file_path)
|
23 |
+
self.documents = []
|
24 |
+
for page_num in range(len(doc)):
|
25 |
+
page = doc[page_num]
|
26 |
+
text = page.get_text()
|
27 |
+
self.documents.append({"page": page_num + 1, "content": text})
|
28 |
+
print("PDF processed successfully!")
|
29 |
+
|
30 |
+
def build_vector_db(self) -> None:
|
31 |
+
"""Builds a vector database using the content of the PDF."""
|
32 |
+
model = SentenceTransformer('all-MiniLM-L6-v2')
|
33 |
+
self.embeddings = model.encode([doc["content"] for doc in self.documents])
|
34 |
+
self.index = faiss.IndexFlatL2(self.embeddings.shape[1])
|
35 |
+
self.index.add(np.array(self.embeddings))
|
36 |
+
print("Vector database built successfully!")
|
37 |
+
|
38 |
+
def search_documents(self, query: str, k: int = 3) -> List[str]:
|
39 |
+
"""Searches for relevant documents using vector similarity."""
|
40 |
+
model = SentenceTransformer('all-MiniLM-L6-v2')
|
41 |
+
query_embedding = model.encode([query])
|
42 |
+
D, I = self.index.search(np.array(query_embedding), k)
|
43 |
+
results = [self.documents[i]["content"] for i in I[0]]
|
44 |
+
return results if results else ["No relevant documents found."]
|
45 |
+
|
46 |
+
app = MyApp()
|
47 |
+
|
48 |
+
def preprocess_input(user_input: str) -> str:
|
49 |
+
"""Preprocesses user input to enhance it for better context."""
|
50 |
+
if "therapy" in user_input.lower() or "exercise" in user_input.lower():
|
51 |
+
return "I am looking for guidance on therapy. Can you help me with some exercises or techniques to manage my stress and emotions?"
|
52 |
+
return user_input
|
53 |
+
|
54 |
+
def preprocess_response(response: str) -> str:
|
55 |
+
"""Preprocesses the response to make it more polished."""
|
56 |
+
response = response.strip()
|
57 |
+
response = response.replace("\n\n", "\n")
|
58 |
+
response = response.replace(" ,", ",")
|
59 |
+
response = response.replace(" .", ".")
|
60 |
+
response = " ".join(response.split())
|
61 |
+
return response
|
62 |
+
|
63 |
+
def shorten_response(response: str) -> str:
|
64 |
+
"""Uses the Zephyr model to shorten and refine the response."""
|
65 |
+
messages = [{"role": "system", "content": "Shorten and refine this response in bullet list."}, {"role": "user", "content": response}]
|
66 |
+
result = client.chat_completion(messages, max_tokens=512, temperature=0.5, top_p=0.9)
|
67 |
+
return result.choices[0].message['content'].strip()
|
68 |
+
|
69 |
+
def respond(message: str, history: List[Tuple[str, str]]):
|
70 |
+
system_message = "You are a concisely speaking empathetic Dialectical Behaviour Therapist assistant. You politely guide users through DBT exercises based on the given DBT book. You must say one thing at a time and ask follow-up questions to continue the chat."
|
71 |
+
messages = [{"role": "system", "content": system_message}]
|
72 |
+
|
73 |
+
for val in history:
|
74 |
+
if val[0]:
|
75 |
+
messages.append({"role": "user", "content": val[0]})
|
76 |
+
if val[1]:
|
77 |
+
messages.append({"role": "assistant", "content": val[1]})
|
78 |
+
|
79 |
+
# Preprocess user input
|
80 |
+
preprocessed_message = preprocess_input(message)
|
81 |
+
messages.append({"role": "user", "content": preprocessed_message})
|
82 |
+
|
83 |
+
# RAG - Retrieve relevant documents
|
84 |
+
retrieved_docs = app.search_documents(preprocessed_message)
|
85 |
+
context = "\n".join(retrieved_docs)
|
86 |
+
if context.strip():
|
87 |
+
messages.append({"role": "system", "content": "Relevant documents: " + context})
|
88 |
+
|
89 |
+
response = client.chat_completion(messages, max_tokens=1024, temperature=0.7, top_p=0.9)
|
90 |
+
response_content = "".join([choice.message['content'] for choice in response.choices if 'content' in choice.message])
|
91 |
+
|
92 |
+
polished_response = preprocess_response(response_content)
|
93 |
+
shortened_response = shorten_response(polished_response)
|
94 |
+
|
95 |
+
history.append((message, shortened_response))
|
96 |
+
return history, ""
|
97 |
+
|
98 |
+
with gr.Blocks() as demo:
|
99 |
+
gr.Markdown("# 🧘♀️ **Dialectical Behaviour Therapy**")
|
100 |
+
gr.Markdown(
|
101 |
+
"‼️Disclaimer: This chatbot is based on a DBT exercise book that is publicly available. "
|
102 |
+
"We are not medical practitioners, and the use of this chatbot is at your own responsibility."
|
103 |
+
)
|
104 |
+
|
105 |
+
chatbot = gr.Chatbot()
|
106 |
+
|
107 |
+
with gr.Row():
|
108 |
+
txt_input = gr.Textbox(
|
109 |
+
show_label=False,
|
110 |
+
placeholder="Type your message here...",
|
111 |
+
lines=1
|
112 |
+
)
|
113 |
+
submit_btn = gr.Button("Submit", scale=1)
|
114 |
+
refresh_btn = gr.Button("Refresh Chat", scale=1, variant="secondary")
|
115 |
+
|
116 |
+
example_questions = [
|
117 |
+
["What are some techniques to handle distressing situations?"],
|
118 |
+
["How does DBT help with emotional regulation?"],
|
119 |
+
["Can you give me an example of an interpersonal effectiveness skill?"],
|
120 |
+
["I want to practice mindfulness. Can you help me?"],
|
121 |
+
["I want to practice distraction techniques. What can I do?"],
|
122 |
+
["How do I plan self-accommodation?"],
|
123 |
+
["What are some distress tolerance skills?"],
|
124 |
+
["Can you help me with emotional regulation techniques?"],
|
125 |
+
["How can I improve my interpersonal effectiveness?"],
|
126 |
+
["What are some ways to cope with stress using DBT?"],
|
127 |
+
["Can you guide me through a grounding exercise?"],
|
128 |
+
["How do I use DBT skills to handle intense emotions?"],
|
129 |
+
["What are some self-soothing techniques I can practice?"],
|
130 |
+
["How can I create a sensory-friendly safe space?"],
|
131 |
+
["Can you help me create a personal crisis plan?"],
|
132 |
+
["What are some affirmations for neurodivergent individuals?"],
|
133 |
+
["How can I manage rejection sensitive dysphoria?"],
|
134 |
+
["Can you guide me through observing with my senses?"],
|
135 |
+
["What are some accessible mindfulness exercises?"],
|
136 |
+
["How do I engage my wise mind?"],
|
137 |
+
["What are some values that I can identify with?"],
|
138 |
+
["How can I practice mindful appreciation?"],
|
139 |
+
["What is the STOP skill in distress tolerance?"],
|
140 |
+
["How can I use the TIPP skill to manage distress?"],
|
141 |
+
["What are some tips for managing meltdowns?"],
|
142 |
+
["Can you provide a list of stims that I can use?"],
|
143 |
+
["How do I improve my environment to reduce distress?"]
|
144 |
+
]
|
145 |
+
|
146 |
+
gr.Examples(examples=example_questions, inputs=[txt_input])
|
147 |
+
|
148 |
+
submit_btn.click(respond, [txt_input, chatbot], [chatbot, txt_input])
|
149 |
+
refresh_btn.click(lambda: [], None, chatbot)
|
150 |
+
|
151 |
+
if __name__ == "__main__":
|
152 |
+
demo.launch()
|