Rahatara commited on
Commit
93223a4
·
verified ·
1 Parent(s): 338f642

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -146
app.py DELETED
@@ -1,146 +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, 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("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."""
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():
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
- # Add more rules as needed
53
- return user_input
54
-
55
- def preprocess_response(response: str) -> str:
56
- """Preprocesses the response to make it more polished."""
57
- response = response.strip()
58
- response = response.replace("\n\n", "\n")
59
- response = response.replace(" ,", ",")
60
- response = response.replace(" .", ".")
61
- response = " ".join(response.split())
62
- return response
63
-
64
- def shorten_response(response: str) -> str:
65
- """Uses the Zephyr model to shorten and refine the response."""
66
- messages = [{"role": "system", "content": "Shorten and refine this response."}, {"role": "user", "content": response}]
67
- response = client.chat_completion(messages, max_tokens=256, temperature=0.5, top_p=0.9)
68
- return response.choices[0].message['content'].strip()
69
-
70
- def respond(
71
- message: str,
72
- history: List[Tuple[str, str]],
73
- ):
74
- 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."
75
- messages = [{"role": "system", "content": system_message}]
76
-
77
- for val in history:
78
- if val[0]:
79
- messages.append({"role": "user", "content": val[0]})
80
- if val[1]:
81
- messages.append({"role": "assistant", "content": val[1]})
82
-
83
- # Preprocess user input
84
- preprocessed_message = preprocess_input(message)
85
- messages.append({"role": "user", "content": preprocessed_message})
86
-
87
- # RAG - Retrieve relevant documents
88
- retrieved_docs = app.search_documents(preprocessed_message)
89
- context = "\n".join(retrieved_docs)
90
- if context.strip():
91
- messages.append({"role": "system", "content": "Relevant documents: " + context})
92
-
93
- response = ""
94
- for message in client.chat_completion(
95
- messages,
96
- max_tokens=1024,
97
- stream=True,
98
- temperature=0.7,
99
- top_p=0.9,
100
- ):
101
- token = message.choices[0].delta.content
102
- response += token
103
-
104
- polished_response = preprocess_response(response)
105
- shortened_response = shorten_response(polished_response)
106
- return history + [(message, shortened_response)], shortened_response
107
-
108
- with gr.Blocks() as demo:
109
- gr.Markdown("# 🧘‍♀️ **Dialectical Behaviour Therapy**")
110
- gr.Markdown(
111
- "‼️Disclaimer: This chatbot is based on a DBT exercise book that is publicly available. "
112
- "We are not medical practitioners, and the use of this chatbot is at your own responsibility."
113
- )
114
-
115
- chatbot = gr.Chatbot()
116
-
117
- with gr.Row():
118
- txt_input = gr.Textbox(
119
- show_label=False,
120
- placeholder="Type your message here...",
121
- lines=1
122
- )
123
- submit_btn = gr.Button("Submit", scale=1)
124
- refresh_btn = gr.Button("Refresh Chat", scale=1, variant="secondary")
125
-
126
- example_questions = [
127
- ["I feel overwhelmed with work."],
128
- ["Can you guide me through a quick meditation?"],
129
- ["How do I stop worrying about things I can't control?"],
130
- ["What are some DBT skills for managing anxiety?"],
131
- ["Can you explain mindfulness in DBT?"],
132
- ["What is radical acceptance?"],
133
- ["How can I practice distress tolerance?"],
134
- ["What are some techniques to handle distressing situations?"],
135
- ["How does DBT help with emotional regulation?"],
136
- ["Can you give me an example of an interpersonal effectiveness skill?"]
137
- ]
138
-
139
- for example in example_questions:
140
- gr.Examples(example, inputs=[txt_input])
141
-
142
- submit_btn.click(respond, [txt_input, chatbot], [chatbot, txt_input])
143
- refresh_btn.click(lambda: [], None, chatbot)
144
-
145
- if __name__ == "__main__":
146
- demo.launch()