Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
import time
|
3 |
+
import io
|
4 |
+
from io import StringIO
|
5 |
+
from typing import Any, Dict, List
|
6 |
+
#Modules to Import
|
7 |
+
import openai
|
8 |
+
import streamlit as st
|
9 |
+
from langchain import LLMChain, OpenAI
|
10 |
+
from langchain.agents import AgentExecutor, Tool, ZeroShotAgent
|
11 |
+
from langchain.chains import RetrievalQA
|
12 |
+
from langchain.chains.question_answering import load_qa_chain
|
13 |
+
from langchain.docstore.document import Document
|
14 |
+
from langchain.document_loaders import PyPDFLoader
|
15 |
+
from langchain.embeddings.openai import OpenAIEmbeddings
|
16 |
+
from langchain.llms import OpenAI
|
17 |
+
from langchain.memory import ConversationBufferMemory
|
18 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
19 |
+
from langchain.vectorstores import VectorStore
|
20 |
+
from langchain.vectorstores.faiss import FAISS
|
21 |
+
from pypdf import PdfReader
|
22 |
+
|
23 |
+
@st.cache_data
|
24 |
+
def parse_pdf (file: io.BytesIO)-> List[str]:
|
25 |
+
pdf = PdfReader(file)
|
26 |
+
output = []
|
27 |
+
for page in pdf.pages:
|
28 |
+
|
29 |
+
text = page.extract_text()
|
30 |
+
#Merge hyphenated words
|
31 |
+
text = re.sub(r"(\w+)-\n(\w+)", "\1\2", text)
|
32 |
+
# Fix newlines in the middle of sentences
|
33 |
+
text = re.sub(r"(?<!\n\s)\n(?!\s\n)", " ", text.strip())
|
34 |
+
#Remove multiple newlines
|
35 |
+
text = re.sub(r"\n\s*\n", "\n\n", text)
|
36 |
+
|
37 |
+
output.append(text)
|
38 |
+
return output
|
39 |
+
|
40 |
+
@st.cache_data
|
41 |
+
def text_to_docs(text: str) -> List [Document]:
|
42 |
+
|
43 |
+
"""Converts a string or list of strings to a list of Documents with metadata,"""
|
44 |
+
|
45 |
+
if isinstance(text, str):
|
46 |
+
#Take a single string as one page
|
47 |
+
text = [text]
|
48 |
+
page_docs = [Document (page_content=page) for page in text]
|
49 |
+
# Add page numbers as metadata
|
50 |
+
for i, doc in enumerate(page_docs):
|
51 |
+
|
52 |
+
doc.metadata["page"] = 1 + 1
|
53 |
+
# Split pages into chunks
|
54 |
+
doc_chunks = []
|
55 |
+
for doc in page_docs:
|
56 |
+
text_splitter = RecursiveCharacterTextSplitter(
|
57 |
+
chunk_size=4000,
|
58 |
+
separators=["\n\n", "\n", ".", "!", "?", ",", " ", ""],
|
59 |
+
chunk_overlap=0,
|
60 |
+
)
|
61 |
+
chunks = text_splitter.split_text(doc.page_content)
|
62 |
+
for i, chunk in enumerate(chunks):
|
63 |
+
doc = Document(
|
64 |
+
page_content=chunk, metadata={"page": doc.metadata["page"], "chunk": 1}
|
65 |
+
)
|
66 |
+
# Add sources a metadata
|
67 |
+
doc.metadata["source"] = f"{doc.metadata['page']}-{doc.metadata['chunk']}"
|
68 |
+
doc_chunks.append(doc)
|
69 |
+
return doc_chunks
|
70 |
+
|
71 |
+
|
72 |
+
|
73 |
+
uploaded_file = st.sidebar.file_uploader(":blue[Upload]", type=["pdf"])
|
74 |
+
if uploaded_file:
|
75 |
+
|
76 |
+
doc = parse_pdf(uploaded_file)
|
77 |
+
|
78 |
+
pages = text_to_docs(doc)
|
79 |
+
# pages
|
80 |
+
if pages:
|
81 |
+
with st.expander('Show page contents', expanded=False):
|
82 |
+
page_sel =st.number_input(
|
83 |
+
label="selected page", min_value=1, max_value=len(pages), step=1
|
84 |
+
)
|
85 |
+
st.write(pages[page_sel-1])
|
86 |
+
api = st.sidebar.text_input(
|
87 |
+
"Open api key",
|
88 |
+
type="password",
|
89 |
+
placeholder="sk-",
|
90 |
+
help="https://platform.openai.com/account/api-keys",
|
91 |
+
)
|
92 |
+
if api:
|
93 |
+
embeddings = OpenAIEmbeddings(openai_api_key = api)
|
94 |
+
# Indexing
|
95 |
+
# Save in a Vector DB_
|
96 |
+
with st.spinner("It's indexing. .."):
|
97 |
+
|
98 |
+
index = FAISS.from_documents(pages, embeddings)
|
99 |
+
|
100 |
+
qa = RetrievalQA.from_chain_type(
|
101 |
+
llm = OpenAI(openai_api_key = api),
|
102 |
+
chain_type = "stuff",
|
103 |
+
retriever = index.as_retriever()
|
104 |
+
)
|
105 |
+
|
106 |
+
# our tool
|
107 |
+
tools = [
|
108 |
+
Tool(
|
109 |
+
name="State of Union QA System",
|
110 |
+
func=qa.run,
|
111 |
+
description="Useful for when you need to answer questions about the aspects asked. Input may be a partial or fully formed question."
|
112 |
+
)
|
113 |
+
]
|
114 |
+
prefix=""""Have a conversation with a human, answering the following questions as best you can based on the context and memory available.
|
115 |
+
You have access to a single tool:"""
|
116 |
+
suffix="""Begin!"
|
117 |
+
{chat_history}
|
118 |
+
Question: {input}
|
119 |
+
{agent_scratchpad}"""
|
120 |
+
prompt = ZeroShotAgent.create_prompt(
|
121 |
+
tools,
|
122 |
+
prefix=prefix,
|
123 |
+
suffix=suffix,
|
124 |
+
input_variables=["input", "chat_history", "agent_scratchpad"],
|
125 |
+
)
|
126 |
+
|
127 |
+
if "memory" not in st.session_state:
|
128 |
+
st.session_state.memory = ConversationBufferMemory(memory_key ="chat_history")
|
129 |
+
|
130 |
+
#Chain
|
131 |
+
# ZeroShotAgent
|
132 |
+
|
133 |
+
llm_chain = LLMChain(
|
134 |
+
llm=OpenAI(
|
135 |
+
temperature=0, openai_api_key=api, model_name="gpt-3.5-turbo"
|
136 |
+
),
|
137 |
+
prompt=prompt,
|
138 |
+
)
|
139 |
+
agent = ZeroShotAgent (llm_chain=llm_chain, tools=tools, verbose=True)
|
140 |
+
agent_chain = AgentExecutor.from_agent_and_tools(
|
141 |
+
agent=agent, tools=tools, verbose=True, memory=st.session_state.memory
|
142 |
+
)
|
143 |
+
container = st.container()
|
144 |
+
with container:
|
145 |
+
st.title("🤖 AI ChatBot")
|
146 |
+
|
147 |
+
# Initialize chat history
|
148 |
+
if "messages" not in st.session_state:
|
149 |
+
st.session_state.messages = []
|
150 |
+
# Display chat messages from history on app rerun
|
151 |
+
for message in st.session_state.messages:
|
152 |
+
with st.chat_message(message["role"]):
|
153 |
+
st.markdown(message["content"])
|
154 |
+
|
155 |
+
if query := st.chat_input("Hey yo !!! Wazzups!"):
|
156 |
+
|
157 |
+
|
158 |
+
st.chat_message("user").markdown(query)
|
159 |
+
# Add user message to chat history
|
160 |
+
st.session_state.messages.append({"role": "user", "content": query})
|
161 |
+
|
162 |
+
# response=llm_chain.memory.chat_memory.add_user_message(prompt)
|
163 |
+
with st.spinner("It's indexing. .."):
|
164 |
+
response = agent_chain.run(query)
|
165 |
+
# st.write(response)
|
166 |
+
# #f"Echo: {prompt}" get_completion(template_string) #
|
167 |
+
# Display assistant response in chat message container
|
168 |
+
with st.chat_message("assistant"):
|
169 |
+
st.markdown(response)
|
170 |
+
# Add assistant response to chat history
|
171 |
+
st.session_state.messages.append({"role": "assistant", "content": response})
|
172 |
+
# with st.expander("History/Memory"):
|
173 |
+
# st.write(st.session_state.memory)
|
174 |
+
|