Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,178 +1,17 @@
|
|
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 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
clone_from="Anne31415/Private_Book", # Replace with your repository URL
|
21 |
-
|
22 |
-
token=os.environ["HUB_TOKEN"] # Use the secret token to authenticate
|
23 |
-
)
|
24 |
-
repo.git_pull() # Pull the latest changes (if any)
|
25 |
-
|
26 |
-
# Step 2: Load the PDF File
|
27 |
-
pdf_file_path = "Private_Book/KOMBI_all2.pdf" # Replace with your PDF file path
|
28 |
-
|
29 |
-
|
30 |
-
def cloud_button(label, query, key=None, color=None, overlap=30):
|
31 |
-
button_id = f"cloud-button-{key or label}".replace(" ", "-")
|
32 |
-
color_class = f"color-{color}" if color else ""
|
33 |
-
num_circles = max(3, min(35, len(label) // 4))
|
34 |
-
circle_size = 60
|
35 |
-
|
36 |
-
circles_html = ''.join([
|
37 |
-
f'<div class="circle {color_class}" style="margin-right: -{overlap}px;"></div>'
|
38 |
-
for _ in range(num_circles)
|
39 |
-
])
|
40 |
-
circles_html += f'<div class="circle-text">{label}</div>'
|
41 |
-
|
42 |
-
cloud_button_html = f"""
|
43 |
-
<div class="cloud" id="{button_id}" style="margin-bottom: 20px; cursor: pointer;">
|
44 |
-
<div class="wrapper {color_class}">
|
45 |
-
{circles_html}
|
46 |
-
</div>
|
47 |
</div>
|
48 |
-
<script>
|
49 |
-
document.getElementById("{button_id}").onclick = function() {{
|
50 |
-
const query = "{query}";
|
51 |
-
const label = "{label}";
|
52 |
-
const button_id = "{button_id}";
|
53 |
-
window.parent.postMessage({{
|
54 |
-
'isStreamlitMessage': true,
|
55 |
-
'type': 'streamlit:setComponentValue',
|
56 |
-
'value': {{'label': label, 'query': query, 'button_id': button_id}},
|
57 |
-
'key': 'button_clicked'
|
58 |
-
}}, '*');
|
59 |
-
}};
|
60 |
-
</script>
|
61 |
"""
|
62 |
-
st.markdown(
|
63 |
-
|
64 |
-
|
65 |
-
def display_chat_history(chat_history):
|
66 |
-
for sender, msg, _ in chat_history:
|
67 |
-
background_color = "#FFA07A" if sender == "User" else "#caf"
|
68 |
-
st.markdown(f"<div style='background-color: {background_color}; padding: 10px; border-radius: 10px; margin: 10px;'>{sender}: {msg}</div>", unsafe_allow_html=True)
|
69 |
-
|
70 |
-
|
71 |
-
def load_pdf(file_path):
|
72 |
-
pdf_reader = PdfReader(file_path)
|
73 |
-
text = ""
|
74 |
-
for page in pdf_reader.pages:
|
75 |
-
text += page.extract_text()
|
76 |
-
|
77 |
-
text_splitter = RecursiveCharacterTextSplitter(
|
78 |
-
chunk_size=1000,
|
79 |
-
chunk_overlap=200,
|
80 |
-
length_function=len
|
81 |
-
)
|
82 |
-
chunks = text_splitter.split_text(text=text)
|
83 |
-
|
84 |
-
store_name, _ = os.path.splitext(os.path.basename(file_path))
|
85 |
-
|
86 |
-
if os.path.exists(f"{store_name}.pkl"):
|
87 |
-
with open(f"{store_name}.pkl", "rb") as f:
|
88 |
-
VectorStore = pickle.load(f)
|
89 |
-
else:
|
90 |
-
embeddings = OpenAIEmbeddings()
|
91 |
-
VectorStore = FAISS.from_texts(chunks, embedding=embeddings)
|
92 |
-
with open(f"{store_name}.pkl", "wb") as f:
|
93 |
-
pickle.dump(VectorStore, f)
|
94 |
-
|
95 |
-
return VectorStore
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
def load_chatbot():
|
100 |
-
return load_qa_chain(llm=OpenAI(), chain_type="stuff")
|
101 |
-
|
102 |
-
|
103 |
-
def main():
|
104 |
-
hide_streamlit_style = """
|
105 |
-
<style>
|
106 |
-
#MainMenu {visibility: hidden;}
|
107 |
-
footer {visibility: hidden;}
|
108 |
-
</style>
|
109 |
-
"""
|
110 |
-
st.markdown(hide_streamlit_style, unsafe_allow_html=True)
|
111 |
-
|
112 |
-
st.title("Welcome to BinDocs ChatBot! 🤖")
|
113 |
-
|
114 |
-
pdf_path = pdf_file_path
|
115 |
-
if not os.path.exists(pdf_path):
|
116 |
-
st.error("File not found. Please check the file path.")
|
117 |
-
return
|
118 |
-
|
119 |
-
if "chat_history" not in st.session_state:
|
120 |
-
st.session_state['chat_history'] = []
|
121 |
-
|
122 |
-
display_chat_history(st.session_state['chat_history'])
|
123 |
-
|
124 |
-
st.write("<!-- Start Spacer -->", unsafe_allow_html=True)
|
125 |
-
st.write("<div style='flex: 1;'></div>", unsafe_allow_html=True)
|
126 |
-
st.write("<!-- End Spacer -->", unsafe_allow_html=True)
|
127 |
-
|
128 |
-
if pdf_path is not None:
|
129 |
-
query = st.text_input("Ask questions about your PDF file (in any preferred language):", key="user_query")
|
130 |
-
|
131 |
-
cloud_buttons = [
|
132 |
-
("Was genau ist ein Belegarzt?", "Was genau ist ein Belegarzt?", "1"),
|
133 |
-
("Wofür wird die Alpha-ID verwendet?", "Wofür wird die Alpha-ID verwendet?", "2"),
|
134 |
-
# Add more buttons as needed
|
135 |
-
]
|
136 |
-
|
137 |
-
for label, query, color in cloud_buttons:
|
138 |
-
cloud_button(label, query, color=color)
|
139 |
-
|
140 |
-
user_input = st.empty()
|
141 |
-
|
142 |
-
if "button_clicked" in st.session_state:
|
143 |
-
button_info = st.session_state["button_clicked"]
|
144 |
-
if button_info:
|
145 |
-
st.write(f"You clicked: {button_info['label']}")
|
146 |
-
st.write(f"Query: {button_info['query']}")
|
147 |
-
# Handle the button click as needed
|
148 |
-
# For example, you can call a function to process the query
|
149 |
-
# process_query(button_info['query'])
|
150 |
-
st.session_state["button_clicked"] = None # Reset after handling
|
151 |
-
|
152 |
-
|
153 |
-
if st.button("Ask"):
|
154 |
-
user_input = st.session_state.user_query
|
155 |
-
handle_query(user_input, pdf_path)
|
156 |
-
|
157 |
-
def handle_query(query, pdf_path):
|
158 |
-
if not query:
|
159 |
-
st.warning("Please enter a query.")
|
160 |
-
return
|
161 |
-
|
162 |
-
st.session_state['chat_history'].append(("User", query, "new"))
|
163 |
-
loading_message = st.empty()
|
164 |
-
loading_message.text('Bot is thinking...')
|
165 |
-
|
166 |
-
VectorStore = load_pdf(pdf_path)
|
167 |
-
chain = load_chatbot()
|
168 |
-
docs = VectorStore.similarity_search(query=query, k=3)
|
169 |
-
with get_openai_callback() as cb:
|
170 |
-
response = chain.run(input_documents=docs, question=query)
|
171 |
|
172 |
-
|
173 |
-
|
174 |
-
loading_message.empty()
|
175 |
-
st.session_state['chat_history'] = [(sender, msg, "old") for sender, msg, _ in st.session_state['chat_history']]
|
176 |
|
177 |
-
if
|
178 |
-
|
|
|
1 |
import streamlit as st
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
|
3 |
+
def cloud_button(label, key):
|
4 |
+
button_html = f"""
|
5 |
+
<div style="text-align: center;">
|
6 |
+
<div style="display: inline-block; background-color: #FF6347; border-radius: 50%; width: 100px; height: 100px;"></div>
|
7 |
+
<div style="margin-top: -100px;">{label}</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
"""
|
10 |
+
st.markdown(button_html, unsafe_allow_html=True)
|
11 |
+
return st.button("", key=key, use_container_width=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
|
13 |
+
if cloud_button("Click Me!", "button1"):
|
14 |
+
st.success("Button 1 clicked!")
|
|
|
|
|
15 |
|
16 |
+
if cloud_button("Another Button", "button2"):
|
17 |
+
st.success("Button 2 clicked!")
|