Spaces:
Build error
Build error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
| 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], show_progress_bar=True)
|
| 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], show_progress_bar=False)
|
| 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_response(response: str) -> str:
|
| 49 |
+
"""Preprocesses the response to make it more polished and empathetic."""
|
| 50 |
+
response = response.strip()
|
| 51 |
+
response = response.replace("\n\n", "\n")
|
| 52 |
+
response = response.replace(" ,", ",")
|
| 53 |
+
response = response.replace(" .", ".")
|
| 54 |
+
response = " ".join(response.split())
|
| 55 |
+
if not any(word in response.lower() for word in ["sorry", "apologize", "empathy"]):
|
| 56 |
+
response = "I'm here to help. " + response
|
| 57 |
+
return response
|
| 58 |
+
|
| 59 |
+
def shorten_response(response: str) -> str:
|
| 60 |
+
"""Uses the Zephyr model to shorten and refine the response."""
|
| 61 |
+
messages = [{"role": "system", "content": "Shorten and refine this response in a supportive and empathetic manner."}, {"role": "user", "content": response}]
|
| 62 |
+
result = client.chat_completion(messages, max_tokens=512, temperature=0.5, top_p=0.9)
|
| 63 |
+
return result.choices[0].message['content'].strip()
|
| 64 |
+
|
| 65 |
+
def respond(message: str, history: List[Tuple[str, str]]):
|
| 66 |
+
system_message = "You are a supportive and 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."
|
| 67 |
+
messages = [{"role": "system", "content": system_message}]
|
| 68 |
+
|
| 69 |
+
for val in history:
|
| 70 |
+
if val[0]:
|
| 71 |
+
messages.append({"role": "user", "content": val[0]})
|
| 72 |
+
if val[1]:
|
| 73 |
+
messages.append({"role": "assistant", "content": val[1]})
|
| 74 |
+
|
| 75 |
+
messages.append({"role": "user", "content": message})
|
| 76 |
+
|
| 77 |
+
# RAG - Retrieve relevant documents if the query suggests exercises or specific information
|
| 78 |
+
if any(keyword in message.lower() for keyword in ["exercise", "technique", "information", "guide", "help", "how to"]):
|
| 79 |
+
retrieved_docs = app.search_documents(message)
|
| 80 |
+
context = "\n".join(retrieved_docs)
|
| 81 |
+
if context.strip():
|
| 82 |
+
messages.append({"role": "system", "content": "Relevant documents: " + context})
|
| 83 |
+
|
| 84 |
+
response = client.chat_completion(messages, max_tokens=1024, temperature=0.7, top_p=0.9)
|
| 85 |
+
response_content = "".join([choice.message['content'] for choice in response.choices if 'content' in choice.message])
|
| 86 |
+
|
| 87 |
+
polished_response = preprocess_response(response_content)
|
| 88 |
+
shortened_response = shorten_response(polished_response)
|
| 89 |
+
|
| 90 |
+
history.append((message, shortened_response))
|
| 91 |
+
return history, ""
|
| 92 |
+
|
| 93 |
+
with gr.Blocks() as demo:
|
| 94 |
+
gr.Markdown("# 🧘♀️ **Dialectical Behaviour Therapy**")
|
| 95 |
+
gr.Markdown(
|
| 96 |
+
"‼️Disclaimer: This chatbot is based on a DBT exercise book that is publicly available. "
|
| 97 |
+
"We are not medical practitioners, and the use of this chatbot is at your own responsibility."
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
chatbot = gr.Chatbot()
|
| 101 |
+
|
| 102 |
+
with gr.Row():
|
| 103 |
+
txt_input = gr.Textbox(
|
| 104 |
+
show_label=False,
|
| 105 |
+
placeholder="Type your message here...",
|
| 106 |
+
lines=1
|
| 107 |
+
)
|
| 108 |
+
submit_btn = gr.Button("Submit", scale=1)
|
| 109 |
+
refresh_btn = gr.Button("Refresh Chat", scale=1, variant="secondary")
|
| 110 |
+
|
| 111 |
+
example_questions = [
|
| 112 |
+
["What are some techniques to handle distressing situations?"],
|
| 113 |
+
["How does DBT help with emotional regulation?"],
|
| 114 |
+
["Can you give me an example of an interpersonal effectiveness skill?"],
|
| 115 |
+
["I want to practice mindfulness. Can you help me?"],
|
| 116 |
+
["I want to practice distraction techniques. What can I do?"],
|
| 117 |
+
["How do I plan self-accommodation?"],
|
| 118 |
+
["What are some distress tolerance skills?"],
|
| 119 |
+
["Can you help me with emotional regulation techniques?"],
|
| 120 |
+
["How can I improve my interpersonal effectiveness?"],
|
| 121 |
+
["What are some ways to cope with stress using DBT?"],
|
| 122 |
+
["Can you guide me through a grounding exercise?"],
|
| 123 |
+
["How do I use DBT skills to handle intense emotions?"],
|
| 124 |
+
["What are some self-soothing techniques I can practice?"],
|
| 125 |
+
["How can I create a sensory-friendly safe space?"],
|
| 126 |
+
["Can you help me create a personal crisis plan?"],
|
| 127 |
+
["What are some affirmations for neurodivergent individuals?"],
|
| 128 |
+
["How can I manage rejection sensitive dysphoria?"],
|
| 129 |
+
["Can you guide me through observing with my senses?"],
|
| 130 |
+
["What are some accessible mindfulness exercises?"],
|
| 131 |
+
["How do I engage my wise mind?"],
|
| 132 |
+
["What are some values that I can identify with?"],
|
| 133 |
+
["How can I practice mindful appreciation?"],
|
| 134 |
+
["What is the STOP skill in distress tolerance?"],
|
| 135 |
+
["How can I use the TIPP skill to manage distress?"],
|
| 136 |
+
["What are some tips for managing meltdowns?"],
|
| 137 |
+
["Can you provide a list of stims that I can use?"],
|
| 138 |
+
["How do I improve my environment to reduce distress?"]
|
| 139 |
+
]
|
| 140 |
+
|
| 141 |
+
gr.Examples(examples=example_questions, inputs=[txt_input])
|
| 142 |
+
|
| 143 |
+
submit_btn.click(fn=respond, inputs=[txt_input, chatbot], outputs=[chatbot, txt_input])
|
| 144 |
+
refresh_btn.click(lambda: [], None, chatbot)
|
| 145 |
+
|
| 146 |
+
if __name__ == "__main__":
|
| 147 |
+
demo.launch()
|