Rahatara commited on
Commit
b0b36a2
·
verified ·
1 Parent(s): 3689a53

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -14
app.py CHANGED
@@ -2,6 +2,9 @@ import gradio as gr
2
  from huggingface_hub import InferenceClient
3
  from typing import List, Tuple
4
  import fitz # PyMuPDF
 
 
 
5
 
6
  client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
7
 
@@ -9,7 +12,10 @@ client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
9
  class MyApp:
10
  def __init__(self) -> None:
11
  self.documents = []
 
 
12
  self.load_pdf("THEDIA1.pdf")
 
13
 
14
  def load_pdf(self, file_path: str) -> None:
15
  """Extracts text from a PDF file and stores it in the app's documents."""
@@ -21,10 +27,21 @@ class MyApp:
21
  self.documents.append({"page": page_num + 1, "content": text})
22
  print("PDF processed successfully!")
23
 
 
 
 
 
 
 
 
 
24
  def search_documents(self, query: str, k: int = 3) -> List[str]:
25
- """Searches for relevant documents containing the query string."""
26
- results = [doc["content"] for doc in self.documents if query.lower() in doc["content"].lower()]
27
- return results[:k] if results else ["No relevant documents found."]
 
 
 
28
 
29
  app = MyApp()
30
 
@@ -36,7 +53,7 @@ def respond(
36
  temperature: float,
37
  top_p: float,
38
  ):
39
- system_message = "You are a knowledgeable DBT coach. Use relevant documents to guide users through DBT exercises and provide helpful information."
40
  messages = [{"role": "system", "content": system_message}]
41
 
42
  for val in history:
@@ -69,27 +86,23 @@ demo = gr.Blocks()
69
  with demo:
70
  gr.Markdown("🧘‍♀️ **Dialectical Behaviour Therapy**")
71
  gr.Markdown(
72
- "Disclaimer: This chatbot is just for testing. It is based on a DBT exercise book that is publicly available. "
73
- "This is just a prototype of DBT excercise assistant, and the use of this chatbot is at your own responsibility."
74
  )
75
 
76
  chatbot = gr.ChatInterface(
77
  respond,
78
- additional_inputs=[
79
- gr.Textbox(value="You are a knowledgeable DBT coach. Use relevant documents to guide users through DBT exercises and provide helpful information.", label="System message"),
80
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
81
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
82
- gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)"),
83
- ],
84
  examples=[
85
  ["I feel overwhelmed with work."],
86
  ["Can you guide me through a quick meditation?"],
87
  ["How do I stop worrying about things I can't control?"],
88
  ["What are some DBT skills for managing anxiety?"],
89
  ["Can you explain mindfulness in DBT?"],
90
- ["What is radical acceptance?"]
 
 
91
  ],
92
- title='DBT Coach 🧘‍♀️'
93
  )
94
 
95
  if __name__ == "__main__":
 
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
 
 
12
  class MyApp:
13
  def __init__(self) -> None:
14
  self.documents = []
15
+ self.embeddings = None
16
+ self.index = None
17
  self.load_pdf("THEDIA1.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."""
 
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
 
 
53
  temperature: float,
54
  top_p: float,
55
  ):
56
+ system_message = "You are a knowledgeable DBT coach. You always talk about one options at at a time. you add greetings and you ask questions like real counsellor. Remember you are helpful and a good listener. You are concise and never ask multiple questions, or give long response. You response like a human counsellor accurately and correctly. consider the users as your client. and practice verbal cues only where needed. Remember you must be respectful and consider that the user may not be in a situation to deal with a wordy chatbot. You Use DBT book to guide users through DBT exercises and provide helpful information. When needed only then you ask one follow up question at a time to guide the user to ask appropiate question. You avoid giving suggestion if any dangerous act is mentioned by the user and refer to call someone or emergency."
57
  messages = [{"role": "system", "content": system_message}]
58
 
59
  for val in history:
 
86
  with demo:
87
  gr.Markdown("🧘‍♀️ **Dialectical Behaviour Therapy**")
88
  gr.Markdown(
89
+ "‼️Disclaimer: This chatbot is based on a DBT exercise book that is publicly available. "
90
+ "We are not medical practitioners, and the use of this chatbot is at your own responsibility.‼️"
91
  )
92
 
93
  chatbot = gr.ChatInterface(
94
  respond,
 
 
 
 
 
 
95
  examples=[
96
  ["I feel overwhelmed with work."],
97
  ["Can you guide me through a quick meditation?"],
98
  ["How do I stop worrying about things I can't control?"],
99
  ["What are some DBT skills for managing anxiety?"],
100
  ["Can you explain mindfulness in DBT?"],
101
+ ["I am interested in DBT excercises"],
102
+ ["I feel restless. Please help me."],
103
+ ["I have destructive thoughts coming to my mind repetatively."]
104
  ],
105
+ title='Dialectical Behaviour Therapy Assitant👩‍⚕️'
106
  )
107
 
108
  if __name__ == "__main__":