Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Adapted from https://docs.streamlit.io/knowledge-base/tutorials/build-conversational-apps#build-a-simple-chatbot-gui-with-streaming
|
2 |
+
import os
|
3 |
+
|
4 |
+
import base64
|
5 |
+
import gc
|
6 |
+
import random
|
7 |
+
import tempfile
|
8 |
+
import time
|
9 |
+
import uuid
|
10 |
+
|
11 |
+
from IPython.display import Markdown, display
|
12 |
+
|
13 |
+
from llama_index.core import Settings
|
14 |
+
from llama_index.llms.ollama import Ollama
|
15 |
+
from llama_index.core import PromptTemplate
|
16 |
+
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
|
17 |
+
from llama_index.core import VectorStoreIndex, ServiceContext, SimpleDirectoryReader
|
18 |
+
|
19 |
+
import streamlit as st
|
20 |
+
|
21 |
+
|
22 |
+
if "id" not in st.session_state:
|
23 |
+
st.session_state.id = uuid.uuid4()
|
24 |
+
st.session_state.file_cache = {}
|
25 |
+
|
26 |
+
session_id = st.session_state.id
|
27 |
+
client = None
|
28 |
+
|
29 |
+
def reset_chat():
|
30 |
+
st.session_state.messages = []
|
31 |
+
st.session_state.context = None
|
32 |
+
gc.collect()
|
33 |
+
|
34 |
+
|
35 |
+
def display_pdf(file):
|
36 |
+
# Opening file from file path
|
37 |
+
|
38 |
+
st.markdown("### PDF Preview")
|
39 |
+
base64_pdf = base64.b64encode(file.read()).decode("utf-8")
|
40 |
+
|
41 |
+
# Embedding PDF in HTML
|
42 |
+
pdf_display = f"""<iframe src="data:application/pdf;base64,{base64_pdf}" width="400" height="100%" type="application/pdf"
|
43 |
+
style="height:100vh; width:100%"
|
44 |
+
>
|
45 |
+
</iframe>"""
|
46 |
+
|
47 |
+
# Displaying File
|
48 |
+
st.markdown(pdf_display, unsafe_allow_html=True)
|
49 |
+
|
50 |
+
|
51 |
+
with st.sidebar:
|
52 |
+
st.header(f"Add your documents!")
|
53 |
+
|
54 |
+
uploaded_file = st.file_uploader("Choose your `.pdf` file", type="pdf")
|
55 |
+
|
56 |
+
if uploaded_file:
|
57 |
+
try:
|
58 |
+
with tempfile.TemporaryDirectory() as temp_dir:
|
59 |
+
file_path = os.path.join(temp_dir, uploaded_file.name)
|
60 |
+
|
61 |
+
with open(file_path, "wb") as f:
|
62 |
+
f.write(uploaded_file.getvalue())
|
63 |
+
|
64 |
+
file_key = f"{session_id}-{uploaded_file.name}"
|
65 |
+
st.write("Indexing your document...")
|
66 |
+
|
67 |
+
if file_key not in st.session_state.get('file_cache', {}):
|
68 |
+
|
69 |
+
if os.path.exists(temp_dir):
|
70 |
+
loader = SimpleDirectoryReader(
|
71 |
+
input_dir = temp_dir,
|
72 |
+
required_exts=[".pdf"],
|
73 |
+
recursive=True
|
74 |
+
)
|
75 |
+
else:
|
76 |
+
st.error('Could not find the file you uploaded, please check again...')
|
77 |
+
st.stop()
|
78 |
+
|
79 |
+
docs = loader.load_data()
|
80 |
+
|
81 |
+
# setup llm & embedding model
|
82 |
+
llm=Ollama(model="llama3", request_timeout=120.0)
|
83 |
+
embed_model = HuggingFaceEmbedding( model_name="BAAI/bge-large-en-v1.5", trust_remote_code=True)
|
84 |
+
# Creating an index over loaded data
|
85 |
+
Settings.embed_model = embed_model
|
86 |
+
index = VectorStoreIndex.from_documents(docs, show_progress=True)
|
87 |
+
|
88 |
+
# Create the query engine, where we use a cohere reranker on the fetched nodes
|
89 |
+
Settings.llm = llm
|
90 |
+
query_engine = index.as_query_engine(streaming=True)
|
91 |
+
|
92 |
+
# ====== Customise prompt template ======
|
93 |
+
qa_prompt_tmpl_str = (
|
94 |
+
"Context information is below.\n"
|
95 |
+
"---------------------\n"
|
96 |
+
"{context_str}\n"
|
97 |
+
"---------------------\n"
|
98 |
+
"Given the context information above I want you to think step by step to answer the query in a crisp manner, incase case you don't know the answer say 'I don't know!'.\n"
|
99 |
+
"Query: {query_str}\n"
|
100 |
+
"Answer: "
|
101 |
+
)
|
102 |
+
qa_prompt_tmpl = PromptTemplate(qa_prompt_tmpl_str)
|
103 |
+
|
104 |
+
query_engine.update_prompts(
|
105 |
+
{"response_synthesizer:text_qa_template": qa_prompt_tmpl}
|
106 |
+
)
|
107 |
+
|
108 |
+
st.session_state.file_cache[file_key] = query_engine
|
109 |
+
else:
|
110 |
+
query_engine = st.session_state.file_cache[file_key]
|
111 |
+
|
112 |
+
# Inform the user that the file is processed and Display the PDF uploaded
|
113 |
+
st.success("Ready to Chat!")
|
114 |
+
display_pdf(uploaded_file)
|
115 |
+
except Exception as e:
|
116 |
+
st.error(f"An error occurred: {e}")
|
117 |
+
st.stop()
|
118 |
+
|
119 |
+
col1, col2 = st.columns([6, 1])
|
120 |
+
|
121 |
+
with col1:
|
122 |
+
st.header(f"Chat with Docs using Llama-3")
|
123 |
+
|
124 |
+
with col2:
|
125 |
+
st.button("Clear ↺", on_click=reset_chat)
|
126 |
+
|
127 |
+
# Initialize chat history
|
128 |
+
if "messages" not in st.session_state:
|
129 |
+
reset_chat()
|
130 |
+
|
131 |
+
|
132 |
+
# Display chat messages from history on app rerun
|
133 |
+
for message in st.session_state.messages:
|
134 |
+
with st.chat_message(message["role"]):
|
135 |
+
st.markdown(message["content"])
|
136 |
+
|
137 |
+
|
138 |
+
# Accept user input
|
139 |
+
if prompt := st.chat_input("What's up?"):
|
140 |
+
# Add user message to chat history
|
141 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
142 |
+
# Display user message in chat message container
|
143 |
+
with st.chat_message("user"):
|
144 |
+
st.markdown(prompt)
|
145 |
+
|
146 |
+
# Display assistant response in chat message container
|
147 |
+
with st.chat_message("assistant"):
|
148 |
+
message_placeholder = st.empty()
|
149 |
+
full_response = ""
|
150 |
+
|
151 |
+
# Simulate stream of response with milliseconds delay
|
152 |
+
streaming_response = query_engine.query(prompt)
|
153 |
+
|
154 |
+
for chunk in streaming_response.response_gen:
|
155 |
+
full_response += chunk
|
156 |
+
message_placeholder.markdown(full_response + "▌")
|
157 |
+
|
158 |
+
# full_response = query_engine.query(prompt)
|
159 |
+
|
160 |
+
message_placeholder.markdown(full_response)
|
161 |
+
# st.session_state.context = ctx
|
162 |
+
|
163 |
+
# Add assistant response to chat history
|
164 |
+
st.session_state.messages.append({"role": "assistant", "content": full_response})
|