Rahatara commited on
Commit
2e21200
1 Parent(s): 1bd8073

Delete app.py

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