Anne31415 commited on
Commit
a48e7a7
·
1 Parent(s): 93d5398

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +126 -160
app.py CHANGED
@@ -1,121 +1,98 @@
1
  import streamlit as st
2
- from dotenv import load_dotenv
3
  import pickle
 
4
  from huggingface_hub import Repository
5
  from PyPDF2 import PdfReader
6
- from streamlit_extras.add_vertical_space import add_vertical_space
7
  from langchain.text_splitter import RecursiveCharacterTextSplitter
8
  from langchain.embeddings.openai import OpenAIEmbeddings
9
  from langchain.vectorstores import FAISS
10
  from langchain.llms import OpenAI
11
  from langchain.chains.question_answering import load_qa_chain
12
  from langchain.callbacks import get_openai_callback
13
- import os
14
-
15
- st.markdown("""
16
- <style>
17
- .cloud-button {
18
- position: relative;
19
- background: #E0E0E0;
20
- border: none;
21
- padding: 20px 40px;
22
- cursor: pointer;
23
- overflow: hidden;
24
- outline: none;
25
- box-shadow: 2px 2px 12px rgba(0,0,0,0.1);
26
- }
27
-
28
- /* Main cloud shape */
29
- .cloud-button::before {
30
- content: '';
31
- position: absolute;
32
- background: #E0E0E0;
33
- border-radius: 50%;
34
- width: 150px;
35
- height: 150px;
36
- top: -50px;
37
- left: 50%;
38
- transform: translateX(-50%);
39
- }
40
-
41
- /* Additional cloud bubbles */
42
- .cloud-button::after {
43
- content: '';
44
- position: absolute;
45
- background: #E0E0E0;
46
- border-radius: 50%;
47
- width: 120px;
48
- height: 120px;
49
- top: 20px;
50
- left: 15%;
51
- }
52
-
53
- .cloud-button span {
54
- position: relative;
55
- z-index: 1;
56
- }
57
-
58
- /* Hover effect */
59
- .cloud-button:hover {
60
- box-shadow: 2px 2px 18px rgba(0,0,0,0.2);
61
- }
62
-
63
- /* Override some default styles for the button to ensure cloud shape */
64
- .cloud-button, .cloud-button::before, .cloud-button::after {
65
- border: none;
66
- outline: none;
67
- text-decoration: none;
68
- }
69
-
70
- </style>
71
-
72
- """, unsafe_allow_html=True)
73
-
74
- if hasattr(st.session_state, "cloud_button_pressed"):
75
- query = st.session_state.cloud_button_pressed
76
- del st.session_state.cloud_button_pressed # remove the attribute after using it
77
-
78
-
79
 
80
  # Step 1: Clone the Dataset Repository
81
  repo = Repository(
82
  local_dir="Private_Book", # Local directory to clone the repository
83
  repo_type="dataset", # Specify that this is a dataset repository
84
-
85
  clone_from="Anne31415/Private_Book", # Replace with your repository URL
86
-
87
- token=os.environ["HUB_TOKEN"] # Use the secret token to authenticate
88
  )
89
  repo.git_pull() # Pull the latest changes (if any)
90
 
91
  # Step 2: Load the PDF File
92
  pdf_file_path = "Private_Book/KOMBI_all2.pdf" # Replace with your PDF file path
93
 
94
-
95
-
96
- with st.sidebar:
97
- st.title('BinDoc GmbH')
98
- st.markdown("Experience revolutionary interaction with BinDocs Chat App, leveraging state-of-the-art AI technology.")
99
-
100
- add_vertical_space(1) # Adjust as per the desired spacing
101
-
102
- st.markdown("""
103
- Hello! I’m here to assist you with:<br><br>
104
- 📘 **Glossary Inquiries:**<br>
105
- I can clarify terms like "DiGA", "AOP", or "BfArM", providing clear and concise explanations to help you understand our content better.<br><br>
106
- 🆘 **Help Page Navigation:**<br>
107
- Ask me if you forgot your password or want to know more about topics related to the platform.<br><br>
108
- 📰 **Latest Whitepapers Insights:**<br>
109
- Curious about our recent publications? Feel free to ask about our latest whitepapers!<br><br>
110
- """, unsafe_allow_html=True)
111
-
112
- add_vertical_space(1) # Adjust as per the desired spacing
113
-
114
- st.write('Made with ❤️ by BinDoc GmbH')
115
-
116
- api_key = os.getenv("OPENAI_API_KEY")
117
- # Retrieve the API key from st.secrets
118
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
 
120
  def load_pdf(file_path):
121
  pdf_reader = PdfReader(file_path)
@@ -143,20 +120,34 @@ def load_pdf(file_path):
143
 
144
  return VectorStore
145
 
146
- # Load the PDF file when the app starts
147
- if "pdf_data" not in st.session_state:
148
- st.session_state.pdf_data = load_pdf(pdf_file_path)
149
-
150
-
151
-
152
  def load_chatbot():
153
  return load_qa_chain(llm=OpenAI(), chain_type="stuff")
154
 
155
- # Load the chatbot when the app starts
156
- if "chatbot_instance" not in st.session_state:
157
- st.session_state.chatbot_instance = load_chatbot()
 
158
 
159
  def main():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
160
 
161
  hide_streamlit_style = """
162
  <style>
@@ -166,11 +157,8 @@ def main():
166
  """
167
  st.markdown(hide_streamlit_style, unsafe_allow_html=True)
168
 
169
-
170
  # Main content
171
  st.title("Welcome to BinDocs ChatBot! 🤖")
172
-
173
- # Directly specifying the path to the PDF file
174
  pdf_path = pdf_file_path
175
  if not os.path.exists(pdf_path):
176
  st.error("File not found. Please check the file path.")
@@ -190,58 +178,36 @@ def main():
190
  if pdf_path is not None:
191
  query = st.text_input("Ask questions about your PDF file (in any preferred language):")
192
 
193
- st.markdown("""
194
- <button class="cloud-button" onclick="document.dispatchEvent(new CustomEvent('cloud_button_event', {detail: 'Was genau ist ein Belegarzt?'}));">
195
- <span>Was genau ist ein Belegarzt?</span>
196
- </button>
197
- <script>
198
- document.addEventListener('cloud_button_event', function(e) {
199
- window.streamlitSetComponentValue(e.detail);
200
- });
201
- </script>
202
- """, unsafe_allow_html=True)
203
-
204
-
205
- if st.button("Wofür wird die Alpha-ID verwendet?"):
206
- query = "Wofür wird die Alpha-ID verwendet?"
207
-
208
- if st.button("Ask") or hasattr(st.session_state, "cloud_button_pressed") or (not st.session_state['chat_history'] and query) or (st.session_state['chat_history'] and query != st.session_state['chat_history'][-1][1]):
209
-
210
- if hasattr(st.session_state, "cloud_button_pressed"):
211
- query = is_cloud_button_pressed
212
-
213
- loading_message = st.empty()
214
- loading_message.text('Bot is thinking...')
215
- docs = st.session_state.pdf_data.similarity_search(query=query, k=3)
216
- with get_openai_callback() as cb:
217
- response = st.session_state.chatbot_instance.run(input_documents=docs, question=query)
218
-
219
- st.session_state['chat_history'].append(("Bot", response, "new"))
220
-
221
- # Display new messages at the bottom
222
- new_messages = st.session_state['chat_history'][-2:]
223
- for chat in new_messages:
224
- background_color = "#FFA07A" if chat[2] == "new" else "#acf" if chat[0] == "User" else "#caf"
225
- new_messages_placeholder.markdown(f"<div style='background-color: {background_color}; padding: 10px; border-radius: 10px; margin: 10px;'>{chat[0]}: {chat[1]}</div>", unsafe_allow_html=True)
226
-
227
- # Scroll to the latest response using JavaScript
228
- st.write("<script>document.getElementById('response').scrollIntoView();</script>", unsafe_allow_html=True)
229
-
230
- loading_message.empty()
231
-
232
- # Clear the input field by setting the query variable to an empty string
233
- query = ""
234
-
235
- # Mark all messages as old after displaying
236
- st.session_state['chat_history'] = [(sender, msg, "old") for sender, msg, _ in st.session_state['chat_history']]
237
-
238
-
239
-
240
-
241
- def display_chat_history(chat_history):
242
- for chat in chat_history:
243
- background_color = "#FFA07A" if chat[2] == "new" else "#acf" if chat[0] == "User" else "#caf"
244
- st.markdown(f"<div style='background-color: {background_color}; padding: 10px; border-radius: 10px; margin: 10px;'>{chat[0]}: {chat[1]}</div>", unsafe_allow_html=True)
245
 
246
  if __name__ == "__main__":
247
  main()
 
1
  import streamlit as st
2
+ import os
3
  import pickle
4
+ from streamlit_extras.add_vertical_space import add_vertical_space
5
  from huggingface_hub import Repository
6
  from PyPDF2 import PdfReader
 
7
  from langchain.text_splitter import RecursiveCharacterTextSplitter
8
  from langchain.embeddings.openai import OpenAIEmbeddings
9
  from langchain.vectorstores import FAISS
10
  from langchain.llms import OpenAI
11
  from langchain.chains.question_answering import load_qa_chain
12
  from langchain.callbacks import get_openai_callback
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
  # Step 1: Clone the Dataset Repository
15
  repo = Repository(
16
  local_dir="Private_Book", # Local directory to clone the repository
17
  repo_type="dataset", # Specify that this is a dataset repository
 
18
  clone_from="Anne31415/Private_Book", # Replace with your repository URL
19
+ token=os.getenv("HUB_TOKEN") # Use the secret token to authenticate
 
20
  )
21
  repo.git_pull() # Pull the latest changes (if any)
22
 
23
  # Step 2: Load the PDF File
24
  pdf_file_path = "Private_Book/KOMBI_all2.pdf" # Replace with your PDF file path
25
 
26
+ def cloud_button(label, key=None):
27
+ button_id = f"cloud-button-{key or label}"
28
+ cloud_button_html = f"""
29
+ <div class="cloud" id="{button_id}">
30
+ <div class="circle small"></div>
31
+ <div class="circle medium"></div>
32
+ <div class="circle large"></div>
33
+ <div class="rectangle">{label}</div>
34
+ <div class="circle medium"></div>
35
+ <div class="circle small"></div>
36
+ </div>
37
+ <style>
38
+ .cloud {{
39
+ position: relative;
40
+ display: inline-block;
41
+ cursor: pointer;
42
+ user-select: none;
43
+ }}
44
+ .rectangle {{
45
+ width: 120px;
46
+ height: 60px;
47
+ background-color: white;
48
+ border-radius: 30px;
49
+ position: absolute;
50
+ top: 20px;
51
+ left: 10px;
52
+ display: flex;
53
+ align-items: center;
54
+ justify-content: center;
55
+ font-size: 16px;
56
+ font-weight: bold;
57
+ transition: background-color 0.4s;
58
+ }}
59
+ .circle {{
60
+ position: absolute;
61
+ background-color: white;
62
+ }}
63
+ .circle.small {{
64
+ width: 40px;
65
+ height: 40px;
66
+ border-radius: 20px;
67
+ top: 10px;
68
+ left: 50px;
69
+ }}
70
+ .circle.medium {{
71
+ width: 60px;
72
+ height: 60px;
73
+ border-radius: 30px;
74
+ }}
75
+ .circle.large {{
76
+ width: 80px;
77
+ height: 80px;
78
+ border-radius: 40px;
79
+ top: -10px;
80
+ left: 40px;
81
+ }}
82
+ .cloud:hover .rectangle {{
83
+ background-color: #008CBA;
84
+ color: white;
85
+ }}
86
+ </style>
87
+ <script>
88
+ document.getElementById("{button_id}").onclick = function() {{
89
+ google.script.run.withSuccessHandler(function(e) {{
90
+ document.getElementById("{button_id}").innerText = e;
91
+ }}).getCloudButtonValue("{label}");
92
+ }};
93
+ </script>
94
+ """
95
+ st.markdown(cloud_button_html, unsafe_allow_html=True)
96
 
97
  def load_pdf(file_path):
98
  pdf_reader = PdfReader(file_path)
 
120
 
121
  return VectorStore
122
 
 
 
 
 
 
 
123
  def load_chatbot():
124
  return load_qa_chain(llm=OpenAI(), chain_type="stuff")
125
 
126
+ def display_chat_history(chat_history):
127
+ for chat in chat_history:
128
+ background_color = "#FFA07A" if chat[2] == "new" else "#acf" if chat[0] == "User" else "#caf"
129
+ st.markdown(f"<div style='background-color: {background_color}; padding: 10px; border-radius: 10px; margin: 10px;'>{chat[0]}: {chat[1]}</div>", unsafe_allow_html=True)
130
 
131
  def main():
132
+ with st.sidebar:
133
+ st.title('BinDoc GmbH')
134
+ st.markdown("Experience revolutionary interaction with BinDocs Chat App, leveraging state-of-the-art AI technology.")
135
+
136
+ add_vertical_space(1) # Adjust as per the desired spacing
137
+
138
+ st.markdown("""
139
+ Hello! I’m here to assist you with:<br><br>
140
+ 📘 **Glossary Inquiries:**<br>
141
+ I can clarify terms like "DiGA", "AOP", or "BfArM", providing clear and concise explanations to help you understand our content better.<br><br>
142
+ 🆘 **Help Page Navigation:**<br>
143
+ Ask me if you forgot your password or want to know more about topics related to the platform.<br><br>
144
+ 📰 **Latest Whitepapers Insights:**<br>
145
+ Curious about our recent publications? Feel free to ask about our latest whitepapers!<br><br>
146
+ """, unsafe_allow_html=True)
147
+
148
+ add_vertical_space(1) # Adjust as per the desired spacing
149
+ st.write('Made with ❤️ by BinDoc GmbH')
150
+ api_key = os.getenv("OPENAI_API_KEY")
151
 
152
  hide_streamlit_style = """
153
  <style>
 
157
  """
158
  st.markdown(hide_streamlit_style, unsafe_allow_html=True)
159
 
 
160
  # Main content
161
  st.title("Welcome to BinDocs ChatBot! 🤖")
 
 
162
  pdf_path = pdf_file_path
163
  if not os.path.exists(pdf_path):
164
  st.error("File not found. Please check the file path.")
 
178
  if pdf_path is not None:
179
  query = st.text_input("Ask questions about your PDF file (in any preferred language):")
180
 
181
+ if cloud_button("Was genau ist ein Belegarzt?"):
182
+ query = "Was genau ist ein Belegarzt?"
183
+ if cloud_button("Wofür wird die Alpha-ID verwendet?"):
184
+ query = "Wofür wird die Alpha-ID verwendet?"
185
+ if cloud_button("Was sind die Vorteile des ambulanten operierens?"):
186
+ query = "Was sind die Vorteile des ambulanten operierens?"
187
+ if cloud_button("Was kann ich mit dem Prognose-Analyse Toll machen?"):
188
+ query = "Was kann ich mit dem Prognose-Analyse Toll machen?"
189
+ if cloud_button("Was sagt mir die Farbe der Balken der Bevölkerungsentwicklung?"):
190
+ query = "Was sagt mir die Farbe der Balken der Bevölkerungsentwicklung?"
191
+ if cloud_button("Ich habe mein Meta Password vergessen, wie kann ich es zurücksetzen?"):
192
+ query = "Ich habe mein Meta Password vergessen, wie kann ich es zurücksetzen?"
193
+
194
+ if st.button("Ask") or (not st.session_state['chat_history'] and query) or (st.session_state['chat_history'] and query != st.session_state['chat_history'][-1][1]):
195
+ st.session_state['chat_history'].append(("User", query, "new"))
196
+ loading_message = st.empty()
197
+ loading_message.text('Bot is thinking...')
198
+ VectorStore = load_pdf(pdf_path)
199
+ chain = load_chatbot()
200
+ docs = VectorStore.similarity_search(query=query, k=3)
201
+ response = chain.run(input_documents=docs, question=query)
202
+ st.session_state['chat_history'].append(("Bot", response, "new"))
203
+ new_messages = st.session_state['chat_history'][-2:]
204
+ for chat in new_messages:
205
+ background_color = "#FFA07A" if chat[2] == "new" else "#acf" if chat[0] == "User" else "#caf"
206
+ new_messages_placeholder.markdown(f"<div style='background-color: {background_color}; padding: 10px; border-radius: 10px; margin: 10px;'>{chat[0]}: {chat[1]}</div>", unsafe_allow_html=True)
207
+ st.write("<script>document.getElementById('response').scrollIntoView();</script>", unsafe_allow_html=True)
208
+ loading_message.empty()
209
+ query = ""
210
+ st.session_state['chat_history'] = [(sender, msg, "old") for sender, msg, _ in st.session_state['chat_history']]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
211
 
212
  if __name__ == "__main__":
213
  main()