Update app.py
Browse files
app.py
CHANGED
@@ -1,15 +1,14 @@
|
|
1 |
import os
|
2 |
import gradio as gr
|
3 |
-
|
4 |
-
from typing import List, Tuple
|
5 |
import fitz # PyMuPDF
|
6 |
from sentence_transformers import SentenceTransformer
|
7 |
import numpy as np
|
8 |
import faiss
|
9 |
|
10 |
-
#
|
11 |
GOOGLE_API_KEY = os.environ.get("GOOGLE_API_KEY")
|
12 |
-
|
13 |
|
14 |
# Placeholder for the app's state
|
15 |
class MyApp:
|
@@ -31,55 +30,105 @@ class MyApp:
|
|
31 |
print("PDF processed successfully!")
|
32 |
|
33 |
def build_vector_db(self) -> None:
|
34 |
-
"""Builds a vector database using
|
35 |
-
model = SentenceTransformer(
|
36 |
-
embeddings = model.encode([doc["content"] for doc in self.documents])
|
37 |
-
self.embeddings = np.array(embeddings, dtype="float32")
|
38 |
self.index = faiss.IndexFlatL2(self.embeddings.shape[1])
|
39 |
-
self.index.add(self.embeddings)
|
40 |
print("Vector database built successfully!")
|
41 |
|
42 |
-
def
|
43 |
-
"""Searches for
|
44 |
-
|
45 |
-
|
46 |
-
|
|
|
|
|
47 |
|
48 |
-
|
49 |
-
"""Generates a response using the Gemini model based on the query."""
|
50 |
-
if not GOOGLE_API_KEY:
|
51 |
-
raise ValueError("GOOGLE_API_KEY is not set. Please set it up.")
|
52 |
|
53 |
-
|
54 |
-
|
55 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
56 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
57 |
|
58 |
-
|
59 |
-
|
60 |
-
response = model.generate_content([query], generation_config=generation_config)
|
61 |
-
|
62 |
-
return response[0].text if response else "No response generated."
|
63 |
-
|
64 |
-
# Gradio UI setup for interaction
|
65 |
-
def main():
|
66 |
-
app = MyApp()
|
67 |
-
|
68 |
-
def handle_query(query):
|
69 |
-
search_results = app.search(query)
|
70 |
-
response = app.generate_response(query)
|
71 |
-
return {"Search Results": search_results, "Response": response}
|
72 |
-
|
73 |
-
gr.Interface(
|
74 |
-
fn=handle_query,
|
75 |
-
inputs=gr.Textbox(placeholder="Enter your query here"),
|
76 |
-
outputs=[
|
77 |
-
gr.JSON(label="Search Results"),
|
78 |
-
gr.Textbox(label="Generated Response")
|
79 |
-
],
|
80 |
-
title="Dialectical Behavioral Exercise with Gemini",
|
81 |
-
description="This app uses Google Gemini to generate responses based on document content."
|
82 |
-
).launch()
|
83 |
|
84 |
if __name__ == "__main__":
|
85 |
-
|
|
|
1 |
import os
|
2 |
import gradio as gr
|
3 |
+
from google.generativeai import GenerativeModel, configure, types
|
|
|
4 |
import fitz # PyMuPDF
|
5 |
from sentence_transformers import SentenceTransformer
|
6 |
import numpy as np
|
7 |
import faiss
|
8 |
|
9 |
+
# Set up the Google API for the Gemini model
|
10 |
GOOGLE_API_KEY = os.environ.get("GOOGLE_API_KEY")
|
11 |
+
configure(api_key=GOOGLE_API_KEY)
|
12 |
|
13 |
# Placeholder for the app's state
|
14 |
class MyApp:
|
|
|
30 |
print("PDF processed successfully!")
|
31 |
|
32 |
def build_vector_db(self) -> None:
|
33 |
+
"""Builds a vector database using the content of the PDF."""
|
34 |
+
model = SentenceTransformer('all-MiniLM-L6-v2')
|
35 |
+
self.embeddings = model.encode([doc["content"] for doc in self.documents], show_progress_bar=True)
|
|
|
36 |
self.index = faiss.IndexFlatL2(self.embeddings.shape[1])
|
37 |
+
self.index.add(np.array(self.embeddings))
|
38 |
print("Vector database built successfully!")
|
39 |
|
40 |
+
def search_documents(self, query: str, k: int = 3) -> List[str]:
|
41 |
+
"""Searches for relevant documents using vector similarity."""
|
42 |
+
model = SentenceTransformer('all-MiniLM-L6-v2')
|
43 |
+
query_embedding = model.encode([query], show_progress_bar=False)
|
44 |
+
D, I = self.index.search(np.array(query_embedding), k)
|
45 |
+
results = [self.documents[i]["content"] for i in I[0]]
|
46 |
+
return results if results else ["No relevant documents found."]
|
47 |
|
48 |
+
app = MyApp()
|
|
|
|
|
|
|
49 |
|
50 |
+
def respond(message: str, history: List[Tuple[str, str]]):
|
51 |
+
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."
|
52 |
+
messages = [{"role": "system", "content": system_message}]
|
53 |
+
|
54 |
+
for val in history:
|
55 |
+
if val[0]:
|
56 |
+
messages.append({"role": "user", "content": val[0]})
|
57 |
+
if val[1]:
|
58 |
+
messages.append({"role": "assistant", "content": val[1]})
|
59 |
+
|
60 |
+
messages.append({"role": "user", "content": message})
|
61 |
+
|
62 |
+
# RAG - Retrieve relevant documents if the query suggests exercises or specific information
|
63 |
+
if any(keyword in message.lower() for keyword in ["exercise", "technique", "information", "guide", "help", "how to"]):
|
64 |
+
retrieved_docs = app.search_documents(message)
|
65 |
+
context = "\n".join(retrieved_docs)
|
66 |
+
if context.strip():
|
67 |
+
messages.append({"role": "system", "content": "Relevant documents: " + context})
|
68 |
+
|
69 |
+
model = GenerativeModel("gemini-1.5-pro-latest")
|
70 |
+
generation_config = types.GenerationConfig(
|
71 |
+
temperature=0.7,
|
72 |
+
max_output_tokens=1024
|
73 |
+
)
|
74 |
+
response = model.generate_content([message], generation_config=generation_config)
|
75 |
+
|
76 |
+
response_content = response[0].text if response else "No response generated."
|
77 |
+
history.append((message, response_content))
|
78 |
+
return history, ""
|
79 |
+
|
80 |
+
with gr.Blocks() as demo:
|
81 |
+
gr.Markdown("# 🧘♀️ **Dialectical Behaviour Therapy**")
|
82 |
+
gr.Markdown(
|
83 |
+
"‼️Disclaimer: This chatbot is based on a DBT exercise book that is publicly available. "
|
84 |
+
"We are not medical practitioners, and the use of this chatbot is at your own responsibility."
|
85 |
+
)
|
86 |
+
|
87 |
+
chatbot = gr.Chatbot()
|
88 |
+
|
89 |
+
with gr.Row():
|
90 |
+
txt_input = gr.Textbox(
|
91 |
+
show_label=False,
|
92 |
+
placeholder="Type your message here...",
|
93 |
+
lines=1
|
94 |
)
|
95 |
+
submit_btn = gr.Button("Submit", scale=1)
|
96 |
+
refresh_btn = gr.Button("Refresh Chat", scale=1, variant="secondary")
|
97 |
+
|
98 |
+
example_questions = [
|
99 |
+
["What are some techniques to handle distressing situations?"],
|
100 |
+
["How does DBT help with emotional regulation?"],
|
101 |
+
["Can you give me an example of an interpersonal effectiveness skill?"],
|
102 |
+
["I want to practice mindfulness. Can you help me?"],
|
103 |
+
["I want to practice distraction techniques. What can I do?"],
|
104 |
+
["How do I plan self-accommodation?"],
|
105 |
+
["What are some distress tolerance skills?"],
|
106 |
+
["Can you help me with emotional regulation techniques?"],
|
107 |
+
["How can I improve my interpersonal effectiveness?"],
|
108 |
+
["What are some ways to cope with stress using DBT?"],
|
109 |
+
["Can you guide me through a grounding exercise?"],
|
110 |
+
["How do I use DBT skills to handle intense emotions?"],
|
111 |
+
["What are some self-soothing techniques I can practice?"],
|
112 |
+
["How can I create a sensory-friendly safe space?"],
|
113 |
+
["Can you help me create a personal crisis plan?"],
|
114 |
+
["What are some affirmations for neurodivergent individuals?"],
|
115 |
+
["How can I manage rejection sensitive dysphoria?"],
|
116 |
+
["Can you guide me through observing with my senses?"],
|
117 |
+
["What are some accessible mindfulness exercises?"],
|
118 |
+
["How do I engage my wise mind?"],
|
119 |
+
["What are some values that I can identify with?"],
|
120 |
+
["How can I practice mindful appreciation?"],
|
121 |
+
["What is the STOP skill in distress tolerance?"],
|
122 |
+
["How can I use the TIPP skill to manage distress?"],
|
123 |
+
["What are some tips for managing meltdowns?"],
|
124 |
+
["Can you provide a list of stims that I can use?"],
|
125 |
+
["How do I improve my environment to reduce distress?"]
|
126 |
+
]
|
127 |
+
|
128 |
+
gr.Examples(examples=example_questions, inputs=[txt_input])
|
129 |
|
130 |
+
submit_btn.click(fn=respond, inputs=[txt_input, chatbot], outputs=[chatbot, txt_input])
|
131 |
+
refresh_btn.click(lambda: [], None, chatbot)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
132 |
|
133 |
if __name__ == "__main__":
|
134 |
+
demo.launch()
|