Shad0ws commited on
Commit
39e845d
1 Parent(s): dc4e166

Upload 9 files

Browse files
__init__.py ADDED
File without changes
__pycache__/embeddings.cpython-310.pyc ADDED
Binary file (4.42 kB). View file
 
__pycache__/prompts.cpython-310.pyc ADDED
Binary file (2.19 kB). View file
 
__pycache__/utils.cpython-310.pyc ADDED
Binary file (5.33 kB). View file
 
app.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from streamlit_chat import message
3
+ import os
4
+ from utils import (
5
+ parse_docx,
6
+ parse_pdf,
7
+ parse_txt,
8
+ parse_csv,
9
+ parse_pptx,
10
+ search_docs,
11
+ embed_docs,
12
+ text_to_docs,
13
+ get_answer,
14
+ get_sources,
15
+ wrap_text_in_html,
16
+ )
17
+ from openai.error import OpenAIError
18
+
19
+ def clear_submit():
20
+ st.session_state["submit"] = False
21
+
22
+ def set_openai_api_key(api_key: str):
23
+ st.session_state["OPENAI_API_KEY"] = api_key
24
+
25
+ st.markdown('<h1>File GPT </h1>', unsafe_allow_html=True)
26
+
27
+ # Sidebar
28
+ index = None
29
+ doc = None
30
+ with st.sidebar:
31
+ user_secret = st.text_input(
32
+ "OpenAI API Key",
33
+ type="password",
34
+ placeholder="Paste your OpenAI API key here (sk-...)",
35
+ help="You can get your API key from https://platform.openai.com/account/api-keys.",
36
+ value=st.session_state.get("OPENAI_API_KEY", ""),
37
+ )
38
+ if user_secret:
39
+ set_openai_api_key(user_secret)
40
+
41
+ uploaded_file = st.file_uploader(
42
+ "Upload a pdf, docx, or txt file",
43
+ type=["pdf", "docx", "txt", "csv", "pptx"],
44
+ help="Scanned documents are not supported yet!",
45
+ on_change=clear_submit,
46
+ )
47
+
48
+ if uploaded_file is not None:
49
+ if uploaded_file.name.endswith(".pdf"):
50
+ doc = parse_pdf(uploaded_file)
51
+ elif uploaded_file.name.endswith(".docx"):
52
+ doc = parse_docx(uploaded_file)
53
+ elif uploaded_file.name.endswith(".csv"):
54
+ doc = parse_csv(uploaded_file)
55
+ elif uploaded_file.name.endswith(".txt"):
56
+ doc = parse_txt(uploaded_file)
57
+ elif uploaded_file.name.endswith(".pptx"):
58
+ doc = parse_pptx(uploaded_file)
59
+ else:
60
+ st.error("File type not supported")
61
+ doc = None
62
+ text = text_to_docs(doc)
63
+ st.write(text)
64
+ try:
65
+ with st.spinner("Indexing document... This may take a while⏳"):
66
+ index = embed_docs(text)
67
+ st.session_state["api_key_configured"] = True
68
+ except OpenAIError as e:
69
+ st.error(e._message)
70
+
71
+ tab1 = st.tabs(["Chat with the File"])
72
+
73
+ with tab1:
74
+ st.write('To obtain an API Key you must create an OpenAI account at the following link: https://openai.com/api/')
75
+ if 'generated' not in st.session_state:
76
+ st.session_state['generated'] = []
77
+
78
+ if 'past' not in st.session_state:
79
+ st.session_state['past'] = []
80
+
81
+ def get_text():
82
+ if user_secret:
83
+ st.header("Ask me something about the document:")
84
+ input_text = st.text_area("You:", on_change=clear_submit)
85
+ return input_text
86
+ user_input = get_text()
87
+
88
+ button = st.button("Submit")
89
+ if button or st.session_state.get("submit"):
90
+ if not user_input:
91
+ st.error("Please enter a question!")
92
+ else:
93
+ st.session_state["submit"] = True
94
+ sources = search_docs(index, user_input)
95
+ try:
96
+ answer = get_answer(sources, user_input)
97
+ st.session_state.past.append(user_input)
98
+ st.session_state.generated.append(answer["output_text"].split("SOURCES: ")[0])
99
+ except OpenAIError as e:
100
+ st.error(e._message)
101
+ if st.session_state['generated']:
102
+ for i in range(len(st.session_state['generated'])-1, -1, -1):
103
+ message(st.session_state["generated"][i], key=str(i))
104
+ message(st.session_state['past'][i], is_user=True, key=str(i) + '_user')
embeddings.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Wrapper around OpenAI embedding models."""
2
+ from typing import Any, Dict, List, Optional
3
+
4
+ from pydantic import BaseModel, Extra, root_validator
5
+
6
+ from langchain.embeddings.base import Embeddings
7
+ from langchain.utils import get_from_dict_or_env
8
+
9
+ from tenacity import (
10
+ retry,
11
+ retry_if_exception_type,
12
+ stop_after_attempt,
13
+ wait_exponential,
14
+ )
15
+ from openai.error import Timeout, APIError, APIConnectionError, RateLimitError
16
+
17
+
18
+ class OpenAIEmbeddings(BaseModel, Embeddings):
19
+ """Wrapper around OpenAI embedding models.
20
+ To use, you should have the ``openai`` python package installed, and the
21
+ environment variable ``OPENAI_API_KEY`` set with your API key or pass it
22
+ as a named parameter to the constructor.
23
+ Example:
24
+ .. code-block:: python
25
+ from langchain.embeddings import OpenAIEmbeddings
26
+ openai = OpenAIEmbeddings(openai_api_key="my-api-key")
27
+ """
28
+
29
+ client: Any #: :meta private:
30
+ document_model_name: str = "text-embedding-ada-002"
31
+ query_model_name: str = "text-embedding-ada-002"
32
+ openai_api_key: Optional[str] = None
33
+
34
+ class Config:
35
+ """Configuration for this pydantic object."""
36
+
37
+ extra = Extra.forbid
38
+
39
+ # TODO: deprecate this
40
+ @root_validator(pre=True, allow_reuse=True)
41
+ def get_model_names(cls, values: Dict) -> Dict:
42
+ """Get model names from just old model name."""
43
+ if "model_name" in values:
44
+ if "document_model_name" in values:
45
+ raise ValueError(
46
+ "Both `model_name` and `document_model_name` were provided, "
47
+ "but only one should be."
48
+ )
49
+ if "query_model_name" in values:
50
+ raise ValueError(
51
+ "Both `model_name` and `query_model_name` were provided, "
52
+ "but only one should be."
53
+ )
54
+ model_name = values.pop("model_name")
55
+ values["document_model_name"] = f"text-search-{model_name}-doc-001"
56
+ values["query_model_name"] = f"text-search-{model_name}-query-001"
57
+ return values
58
+
59
+ @root_validator(allow_reuse=True)
60
+ def validate_environment(cls, values: Dict) -> Dict:
61
+ """Validate that api key and python package exists in environment."""
62
+ openai_api_key = get_from_dict_or_env(
63
+ values, "openai_api_key", "OPENAI_API_KEY"
64
+ )
65
+ try:
66
+ import openai
67
+
68
+ openai.api_key = openai_api_key
69
+ values["client"] = openai.Embedding
70
+ except ImportError:
71
+ raise ValueError(
72
+ "Could not import openai python package. "
73
+ "Please it install it with `pip install openai`."
74
+ )
75
+ return values
76
+
77
+ @retry(
78
+ reraise=True,
79
+ stop=stop_after_attempt(100),
80
+ wait=wait_exponential(multiplier=1, min=10, max=60),
81
+ retry=(
82
+ retry_if_exception_type(Timeout)
83
+ | retry_if_exception_type(APIError)
84
+ | retry_if_exception_type(APIConnectionError)
85
+ | retry_if_exception_type(RateLimitError)
86
+ ),
87
+ )
88
+ def _embedding_func(self, text: str, *, engine: str) -> List[float]:
89
+ """Call out to OpenAI's embedding endpoint with exponential backoff."""
90
+ # replace newlines, which can negatively affect performance.
91
+ text = text.replace("\n", " ")
92
+ return self.client.create(input=[text], engine=engine)["data"][0]["embedding"]
93
+
94
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
95
+ """Call out to OpenAI's embedding endpoint for embedding search docs.
96
+ Args:
97
+ texts: The list of texts to embed.
98
+ Returns:
99
+ List of embeddings, one for each text.
100
+ """
101
+ responses = [
102
+ self._embedding_func(text, engine=self.document_model_name)
103
+ for text in texts
104
+ ]
105
+ return responses
106
+
107
+ def embed_query(self, text: str) -> List[float]:
108
+ """Call out to OpenAI's embedding endpoint for embedding query text.
109
+ Args:
110
+ text: The text to embed.
111
+ Returns:
112
+ Embeddings for the text.
113
+ """
114
+ embedding = self._embedding_func(text, engine=self.query_model_name)
115
+ return embedding
prompts.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain.prompts import PromptTemplate
2
+
3
+ ## Use a shorter template to reduce the number of tokens in the prompt
4
+ template = """Create a final answer to the given questions using the provided document excerpts(in no particular order) as references. ALWAYS include a "SOURCES" section in your answer including only the minimal set of sources needed to answer the question. If you are unable to answer the question, simply state that you do not know. Do not attempt to fabricate an answer and leave the SOURCES section empty.
5
+ ---------
6
+ QUESTION: What is the purpose of ARPA-H?
7
+ =========
8
+ Content: More support for patients and families. \n\nTo get there, I call on Congress to fund ARPA-H, the Advanced Research Projects Agency for Health. \n\nIt’s based on DARPA—the Defense Department project that led to the Internet, GPS, and so much more. \n\nARPA-H will have a singular purpose—to drive breakthroughs in cancer, Alzheimer’s, diabetes, and more.
9
+ Source: 1-32
10
+ Content: While we’re at it, let’s make sure every American can get the health care they need. \n\nWe’ve already made historic investments in health care. \n\nWe’ve made it easier for Americans to get the care they need, when they need it. \n\nWe’ve made it easier for Americans to get the treatments they need, when they need them. \n\nWe’ve made it easier for Americans to get the medications they need, when they need them.
11
+ Source: 1-33
12
+ Content: The V.A. is pioneering new ways of linking toxic exposures to disease, already helping veterans get the care they deserve. \n\nWe need to extend that same care to all Americans. \n\nThat’s why I’m calling on Congress to pass legislation that would establish a national registry of toxic exposures, and provide health care and financial assistance to those affected.
13
+ Source: 1-30
14
+ =========
15
+ FINAL ANSWER: The purpose of ARPA-H is to drive breakthroughs in cancer, Alzheimer’s, diabetes, and more.
16
+ SOURCES: 1-32
17
+ ---------
18
+ QUESTION: {question}
19
+ =========
20
+ {summaries}
21
+ =========
22
+ FINAL ANSWER:"""
23
+
24
+ STUFF_PROMPT = PromptTemplate(
25
+ template=template, input_variables=["summaries", "question"]
26
+ )
requirements.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ openai
2
+ pypdf
3
+ scikit-learn
4
+ numpy
5
+ tiktoken
6
+ docx2txt
7
+ langchain
8
+ pydantic
9
+ typing
10
+ faiss-cpu
11
+ streamlit_chat
12
+ python-pptx
utils.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
2
+ from langchain.vectorstores.faiss import FAISS
3
+ from langchain import OpenAI, Cohere
4
+ from langchain.chains.qa_with_sources import load_qa_with_sources_chain
5
+ from embeddings import OpenAIEmbeddings
6
+ from langchain.llms import OpenAI
7
+ from langchain.docstore.document import Document
8
+ from langchain.vectorstores import FAISS, VectorStore
9
+ import docx2txt
10
+ from typing import List, Dict, Any
11
+ import re
12
+ import numpy as np
13
+ from io import StringIO
14
+ from io import BytesIO
15
+ import streamlit as st
16
+ from prompts import STUFF_PROMPT
17
+ from pypdf import PdfReader
18
+ from openai.error import AuthenticationError
19
+ import pptx
20
+
21
+ @st.experimental_memo()
22
+ def parse_docx(file: BytesIO) -> str:
23
+ text = docx2txt.process(file)
24
+ # Remove multiple newlines
25
+ text = re.sub(r"\n\s*\n", "\n\n", text)
26
+ return text
27
+
28
+
29
+ @st.experimental_memo()
30
+ def parse_pdf(file: BytesIO) -> List[str]:
31
+ pdf = PdfReader(file)
32
+ output = []
33
+ for page in pdf.pages:
34
+ text = page.extract_text()
35
+ # Merge hyphenated words
36
+ text = re.sub(r"(\w+)-\n(\w+)", r"\1\2", text)
37
+ # Fix newlines in the middle of sentences
38
+ text = re.sub(r"(?<!\n\s)\n(?!\s\n)", " ", text.strip())
39
+ # Remove multiple newlines
40
+ text = re.sub(r"\n\s*\n", "\n\n", text)
41
+
42
+ output.append(text)
43
+
44
+ return output
45
+
46
+
47
+ @st.experimental_memo()
48
+ def parse_txt(file: BytesIO) -> str:
49
+ text = file.read().decode("utf-8")
50
+ # Remove multiple newlines
51
+ text = re.sub(r"\n\s*\n", "\n\n", text)
52
+ return text
53
+
54
+ @st.experimental_memo()
55
+ def parse_pptx(file: BytesIO) -> str:
56
+
57
+ ppt_file = pptx.Presentation(file)
58
+
59
+ string_data = ""
60
+
61
+ for slide in ppt_file.slides:
62
+ for shape in slide.shapes:
63
+ if shape.has_text_frame:
64
+ string_data += shape.text_frame.text + '\n'
65
+ return string_data
66
+
67
+ @st.experimental_memo()
68
+ def parse_csv(uploaded_file):
69
+ # To read file as bytes:
70
+ #bytes_data = uploaded_file.getvalue()
71
+ #st.write(bytes_data)
72
+
73
+ # To convert to a string based IO:
74
+ stringio = StringIO(uploaded_file.getvalue().decode("utf-8"))
75
+ #st.write(stringio)
76
+
77
+ # To read file as string:
78
+ string_data = stringio.read()
79
+ #st.write(string_data)
80
+
81
+ # Can be used wherever a "file-like" object is accepted:
82
+ # dataframe = pd.read_csv(uploaded_file)
83
+ return string_data
84
+
85
+
86
+ @st.cache(allow_output_mutation=True)
87
+ def text_to_docs(text: str) -> List[Document]:
88
+ """Converts a string or list of strings to a list of Documents
89
+ with metadata."""
90
+ if isinstance(text, str):
91
+ # Take a single string as one page
92
+ text = [text]
93
+ page_docs = [Document(page_content=page) for page in text]
94
+
95
+ # Add page numbers as metadata
96
+ for i, doc in enumerate(page_docs):
97
+ doc.metadata["page"] = i + 1
98
+
99
+ # Split pages into chunks
100
+ doc_chunks = []
101
+
102
+ for doc in page_docs:
103
+ text_splitter = RecursiveCharacterTextSplitter(
104
+ chunk_size=800,
105
+ separators=["\n\n", "\n", ".", "!", "?", ",", " ", ""],
106
+ chunk_overlap=0,
107
+ )
108
+ chunks = text_splitter.split_text(doc.page_content)
109
+ for i, chunk in enumerate(chunks):
110
+ doc = Document(
111
+ page_content=chunk, metadata={"page": doc.metadata["page"], "chunk": i}
112
+ )
113
+ # Add sources a metadata
114
+ doc.metadata["source"] = f"{doc.metadata['page']}-{doc.metadata['chunk']}"
115
+ doc_chunks.append(doc)
116
+ return doc_chunks
117
+
118
+
119
+ @st.cache(allow_output_mutation=True, show_spinner=False)
120
+ def embed_docs(docs: List[Document]) -> VectorStore:
121
+ """Embeds a list of Documents and returns a FAISS index"""
122
+
123
+ if not st.session_state.get("OPENAI_API_KEY"):
124
+ raise AuthenticationError(
125
+ "Enter your OpenAI API key in the sidebar. You can get a key at https://platform.openai.com/account/api-keys."
126
+ )
127
+ else:
128
+ # Embed the chunks
129
+ embeddings = OpenAIEmbeddings(openai_api_key=st.session_state.get("OPENAI_API_KEY")) # type: ignore
130
+ index = FAISS.from_documents(docs, embeddings)
131
+
132
+ return index
133
+
134
+
135
+ @st.cache(allow_output_mutation=True)
136
+ def search_docs(index: VectorStore, query: str) -> List[Document]:
137
+ """Searches a FAISS index for similar chunks to the query
138
+ and returns a list of Documents."""
139
+
140
+ # Search for similar chunks
141
+ docs = index.similarity_search(query, k=5)
142
+ return docs
143
+
144
+
145
+ @st.cache(allow_output_mutation=True)
146
+ def get_answer(docs: List[Document], query: str) -> Dict[str, Any]:
147
+ """Gets an answer to a question from a list of Documents."""
148
+
149
+ # Get the answer
150
+ chain = load_qa_with_sources_chain(OpenAI(temperature=0, openai_api_key=st.session_state.get("OPENAI_API_KEY")), chain_type="stuff", prompt=STUFF_PROMPT) # type: ignore
151
+
152
+ answer = chain(
153
+ {"input_documents": docs, "question": query}, return_only_outputs=True
154
+ )
155
+ return answer
156
+
157
+
158
+ @st.cache(allow_output_mutation=True)
159
+ def get_sources(answer: Dict[str, Any], docs: List[Document]) -> List[Document]:
160
+ """Gets the source documents for an answer."""
161
+
162
+ # Get sources for the answer
163
+ source_keys = [s for s in answer["output_text"].split("SOURCES: ")[-1].split(", ")]
164
+
165
+ source_docs = []
166
+ for doc in docs:
167
+ if doc.metadata["source"] in source_keys:
168
+ source_docs.append(doc)
169
+
170
+ return source_docs
171
+
172
+
173
+ def wrap_text_in_html(text: str) -> str:
174
+ """Wraps each text block separated by newlines in <p> tags"""
175
+ if isinstance(text, list):
176
+ # Add horizontal rules between pages
177
+ text = "\n<hr/>\n".join(text)
178
+ return "".join([f"<p>{line}</p>" for line in text.split("\n")])