Anush V commited on
Upload 3 files
Browse files- .gitattributes +1 -0
- app.py +447 -0
- models/openhermes-2.5-mistral-7b-16k.Q4_K_M.gguf +3 -0
- requirements.txt +25 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
models/openhermes-2.5-mistral-7b-16k.Q4_K_M.gguf filter=lfs diff=lfs merge=lfs -text
|
app.py
ADDED
|
@@ -0,0 +1,447 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
import datetime
|
| 3 |
+
import glob
|
| 4 |
+
import json
|
| 5 |
+
import logging
|
| 6 |
+
import os
|
| 7 |
+
import shutil
|
| 8 |
+
import sys
|
| 9 |
+
import uuid
|
| 10 |
+
from json import JSONDecodeError
|
| 11 |
+
from multiprocessing import Pool
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
from time import sleep
|
| 14 |
+
from typing import List, Optional
|
| 15 |
+
|
| 16 |
+
import pandas as pd
|
| 17 |
+
# import qdrant_client
|
| 18 |
+
import streamlit as st
|
| 19 |
+
from dotenv import load_dotenv
|
| 20 |
+
from langchain import LLMChain, PromptTemplate
|
| 21 |
+
from langchain.chains import RetrievalQA, RetrievalQAWithSourcesChain
|
| 22 |
+
from langchain.docstore.document import Document
|
| 23 |
+
from langchain.document_loaders import (
|
| 24 |
+
CSVLoader,
|
| 25 |
+
EverNoteLoader,
|
| 26 |
+
PDFMinerLoader,
|
| 27 |
+
TextLoader,
|
| 28 |
+
UnstructuredEmailLoader,
|
| 29 |
+
UnstructuredEPubLoader,
|
| 30 |
+
UnstructuredHTMLLoader,
|
| 31 |
+
UnstructuredMarkdownLoader,
|
| 32 |
+
UnstructuredODTLoader,
|
| 33 |
+
UnstructuredPowerPointLoader,
|
| 34 |
+
UnstructuredWordDocumentLoader,
|
| 35 |
+
)
|
| 36 |
+
from langchain.llms import CTransformers
|
| 37 |
+
from langchain.embeddings import HuggingFaceEmbeddings, SentenceTransformerEmbeddings
|
| 38 |
+
from langchain.llms import GPT4All, LlamaCpp
|
| 39 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 40 |
+
from langchain.vectorstores import Chroma, Qdrant
|
| 41 |
+
from markdown import markdown
|
| 42 |
+
# from qdrant_client.models import Distance, VectorParams
|
| 43 |
+
from langchain_core.output_parsers import StrOutputParser
|
| 44 |
+
from langchain_core.runnables import RunnablePassthrough
|
| 45 |
+
# from qdrant_client import QdrantClient
|
| 46 |
+
# from qdrant_client.http.models import Distance, VectorParams
|
| 47 |
+
from tqdm import tqdm
|
| 48 |
+
from langchain_core.prompts import PromptTemplate
|
| 49 |
+
# from langchain.callbacks.base import CallbackManager
|
| 50 |
+
# from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
|
| 51 |
+
from tqdm.auto import tqdm
|
| 52 |
+
|
| 53 |
+
from constants import CHROMA_SETTINGS
|
| 54 |
+
|
| 55 |
+
# from constants import CHROMA_SETTINGS
|
| 56 |
+
|
| 57 |
+
load_dotenv()
|
| 58 |
+
######################################## CONSTANTS #########################################
|
| 59 |
+
# index_name = "openai-ada-002-index-1536"
|
| 60 |
+
# reader_model = "gpt-3.5-turbo"
|
| 61 |
+
# embed_model = "text-embedding-ada-002"
|
| 62 |
+
# embedding_dim = 768
|
| 63 |
+
FILE_UPLOAD_PATH = "./data/uploads/"
|
| 64 |
+
qdrant_dir = "./data/qdrant_storage"
|
| 65 |
+
# NAME_SPACE = "qademo"
|
| 66 |
+
os.makedirs(FILE_UPLOAD_PATH, exist_ok=True)
|
| 67 |
+
os.makedirs(qdrant_dir, exist_ok=True)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
#Β Load environment variables
|
| 71 |
+
persist_directory = os.environ.get('PERSIST_DIRECTORY', "vector_db")
|
| 72 |
+
source_directory = os.environ.get('SOURCE_DIRECTORY', 'source_documents')
|
| 73 |
+
embeddings_model_name = os.environ.get('EMBEDDINGS_MODEL_NAME',"all-MiniLM-L6-v2")
|
| 74 |
+
embeddings_dim = os.environ.get('EMBEDDINGS_DIM',384)
|
| 75 |
+
|
| 76 |
+
chunk_size = 100
|
| 77 |
+
chunk_overlap = 20
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
model_type = os.environ.get('MODEL_TYPE',"LlamaCpp")
|
| 81 |
+
model_path = os.environ.get('MODEL_PATH', 'models/openhermes-2.5-mistral-7b-16k.Q4_K_M.gguf')
|
| 82 |
+
model_n_ctx = os.environ.get('MODEL_N_CTX',32000)
|
| 83 |
+
reset_index = os.environ.get("RESET_INDEX",False)
|
| 84 |
+
collection_name = os.environ.get('COLELCTION_NAME', "my_collection")
|
| 85 |
+
|
| 86 |
+
QDRANT_HOST = os.environ.get("QDRANT_HOST", "localhost")
|
| 87 |
+
QDRANT_PORT = os.environ.get("QDRANT_PORT", 6333)
|
| 88 |
+
target_source_chunks = int(os.environ.get('TARGET_SOURCE_CHUNKS',4))
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
print("Current working directory:", os.getcwd())
|
| 92 |
+
try:
|
| 93 |
+
print("Contents of /app/models:", os.listdir('./models'))
|
| 94 |
+
except Exception as e:
|
| 95 |
+
print(f"Exception occurred: {e}")
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
print(f"Working with model_type: {model_type} model_path: {model_path} model_n_ctx: {model_n_ctx} reset_index: {reset_index} collection_name: {collection_name}")
|
| 99 |
+
###########################################################################################
|
| 100 |
+
|
| 101 |
+
# Custom document loaders
|
| 102 |
+
class MyElmLoader(UnstructuredEmailLoader):
|
| 103 |
+
"""Wrapper to fallback to text/plain when default does not work"""
|
| 104 |
+
|
| 105 |
+
def load(self) -> List[Document]:
|
| 106 |
+
"""Wrapper adding fallback for elm without html"""
|
| 107 |
+
try:
|
| 108 |
+
try:
|
| 109 |
+
doc = UnstructuredEmailLoader.load(self)
|
| 110 |
+
except ValueError as e:
|
| 111 |
+
if 'text/html content not found in email' in str(e):
|
| 112 |
+
# Try plain text
|
| 113 |
+
self.unstructured_kwargs["content_source"]="text/plain"
|
| 114 |
+
doc = UnstructuredEmailLoader.load(self)
|
| 115 |
+
else:
|
| 116 |
+
raise
|
| 117 |
+
except Exception as e:
|
| 118 |
+
# Add file_path to exception message
|
| 119 |
+
raise type(e)(f"{self.file_path}: {e}") from e
|
| 120 |
+
|
| 121 |
+
return doc
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
# Map file extensions to document loaders and their arguments
|
| 125 |
+
LOADER_MAPPING = {
|
| 126 |
+
".csv": (CSVLoader, {}),
|
| 127 |
+
# ".docx": (Docx2txtLoader, {}),
|
| 128 |
+
".doc": (UnstructuredWordDocumentLoader, {}),
|
| 129 |
+
".docx": (UnstructuredWordDocumentLoader, {}),
|
| 130 |
+
".enex": (EverNoteLoader, {}),
|
| 131 |
+
".eml": (MyElmLoader, {}),
|
| 132 |
+
".epub": (UnstructuredEPubLoader, {}),
|
| 133 |
+
".html": (UnstructuredHTMLLoader, {}),
|
| 134 |
+
".md": (UnstructuredMarkdownLoader, {}),
|
| 135 |
+
".odt": (UnstructuredODTLoader, {}),
|
| 136 |
+
".pdf": (PDFMinerLoader, {}),
|
| 137 |
+
".ppt": (UnstructuredPowerPointLoader, {}),
|
| 138 |
+
".pptx": (UnstructuredPowerPointLoader, {}),
|
| 139 |
+
".txt": (TextLoader, {"encoding": "utf8"}),
|
| 140 |
+
# Add more mappings for other file extensions and loaders as needed
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def load_single_document(file_path: str) -> Document:
|
| 145 |
+
ext = "." + file_path.rsplit(".", 1)[-1]
|
| 146 |
+
if ext in LOADER_MAPPING:
|
| 147 |
+
loader_class, loader_args = LOADER_MAPPING[ext]
|
| 148 |
+
loader = loader_class(file_path, **loader_args)
|
| 149 |
+
return loader.load()[0]
|
| 150 |
+
|
| 151 |
+
raise ValueError(f"Unsupported file extension '{ext}'")
|
| 152 |
+
|
| 153 |
+
@st.cache_resource
|
| 154 |
+
def get_embedding_model():
|
| 155 |
+
model_kwargs = {'device': 'cpu'}
|
| 156 |
+
embeddings = HuggingFaceEmbeddings(model_name=embeddings_model_name, model_kwargs=model_kwargs)
|
| 157 |
+
return embeddings
|
| 158 |
+
|
| 159 |
+
print("loading the embeddings")
|
| 160 |
+
embeddings = get_embedding_model()
|
| 161 |
+
|
| 162 |
+
@st.cache_resource()
|
| 163 |
+
def get_vector_db():
|
| 164 |
+
# client = qdrant_client.QdrantClient(
|
| 165 |
+
# path=persist_directory, prefer_grpc=True
|
| 166 |
+
# )
|
| 167 |
+
# client = qdrant_client.QdrantClient(host=QDRANT_HOST, port=QDRANT_PORT)
|
| 168 |
+
# available_collections = client.get_collections()
|
| 169 |
+
# print(f"Available collections: {available_collections}")
|
| 170 |
+
# if collection_name not in available_collections:
|
| 171 |
+
# # if reset_index:
|
| 172 |
+
# # print(f"Deleting collection and creating again")
|
| 173 |
+
# # client.delete_collection(collection_name="{collection_name}")
|
| 174 |
+
# print(f"Creating collection: {collection_name}")
|
| 175 |
+
# client.recreate_collection(
|
| 176 |
+
|
| 177 |
+
# collection_name=collection_name,
|
| 178 |
+
# vectors_config=VectorParams(size=embeddings_dim, distance=Distance.COSINE),
|
| 179 |
+
# )
|
| 180 |
+
# vectordb = Qdrant(
|
| 181 |
+
# client=client, collection_name=collection_name,
|
| 182 |
+
# embeddings=embeddings
|
| 183 |
+
# )
|
| 184 |
+
|
| 185 |
+
vectordb = Chroma(persist_directory=persist_directory, embedding_function=embeddings)
|
| 186 |
+
return vectordb
|
| 187 |
+
|
| 188 |
+
print("loading the vector DB")
|
| 189 |
+
vectordb = get_vector_db()
|
| 190 |
+
print("loading the vector as retriever")
|
| 191 |
+
retriever = vectordb.as_retriever(search_type="similarity", search_kwargs={"k": 5})
|
| 192 |
+
|
| 193 |
+
def format_docs(docs):
|
| 194 |
+
return "\n\n".join(doc.page_content for doc in docs)
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
@st.cache_resource
|
| 198 |
+
def get_chain():
|
| 199 |
+
# Callbacks support token-wise streaming
|
| 200 |
+
# callback_manager = CallbackManager([StreamingStdOutCallbackHandler()])
|
| 201 |
+
# Verbose is required to pass to the callback manager
|
| 202 |
+
|
| 203 |
+
# Make sure the model path is correct for your system!
|
| 204 |
+
# model_name = os.getenv("MODEL_PATH", "wizardLM-7B.ggml.q4_2.bin")
|
| 205 |
+
# llm = LlamaCpp(
|
| 206 |
+
# model_path=model_name, n_ctx=1024,verbose=True, n_threads=4, n_batch=512
|
| 207 |
+
# )
|
| 208 |
+
callbacks = []
|
| 209 |
+
|
| 210 |
+
# vectordb = Chroma(persist_directory=persist_directory, embedding_function=embeddings, client_settings=CHROMA_SETTINGS)
|
| 211 |
+
# https://qdrant.tech/documentation/concepts/collections/
|
| 212 |
+
|
| 213 |
+
print("loading the LLM model")
|
| 214 |
+
match model_type:
|
| 215 |
+
case "LlamaCpp":
|
| 216 |
+
llm = LlamaCpp(model_path=model_path,temperature=0.1, n_gpu_layers= 32, n_gqa=8,
|
| 217 |
+
max_new_tokens=512,context_window=2048, n_ctx=model_n_ctx, callbacks=callbacks, verbose=True)
|
| 218 |
+
# llm = CTransformers(model=model_path, config={'max_new_tokens': model_n_ctx, 'temperature': 0.01,'context_length': model_n_ctx})
|
| 219 |
+
case "GPT4All":
|
| 220 |
+
llm = GPT4All(model=model_path, n_ctx=model_n_ctx, backend='gptj', callbacks=callbacks, verbose=False)
|
| 221 |
+
# qa = RetrievalQA.from_chain_type(llm=llm, chain_type="stuff", retriever=retriever, return_source_documents= True)
|
| 222 |
+
print("loading the QA pipeline")
|
| 223 |
+
|
| 224 |
+
qa = RetrievalQAWithSourcesChain.from_chain_type(llm=llm, chain_type="stuff", retriever=retriever, reduce_k_below_max_tokens=True, return_source_documents= True, verbose=True)
|
| 225 |
+
|
| 226 |
+
template = """
|
| 227 |
+
|
| 228 |
+
<s> [INST]Use the following pieces of context to answer the question at the end.
|
| 229 |
+
If you don't know the answer, just say that you don't know, don't try to make up an answer.
|
| 230 |
+
Use three sentences maximum and keep the answer as concise as possible.
|
| 231 |
+
Always say "thanks for asking!" at the end of the answer. [/INST] </s>
|
| 232 |
+
|
| 233 |
+
Context: {context}
|
| 234 |
+
|
| 235 |
+
[INST] Question: {question}
|
| 236 |
+
|
| 237 |
+
Answer: [/INST]"""
|
| 238 |
+
custom_rag_prompt = PromptTemplate.from_template(template)
|
| 239 |
+
|
| 240 |
+
rag_chain = (
|
| 241 |
+
{"context": retriever | format_docs, "question": RunnablePassthrough()}
|
| 242 |
+
| custom_rag_prompt
|
| 243 |
+
| llm
|
| 244 |
+
| StrOutputParser()
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
return qa, vectordb, rag_chain
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
qa, vectordb, rag_chain = get_chain()
|
| 252 |
+
|
| 253 |
+
def query(question, primer, top_k_retriever):
|
| 254 |
+
# Get the answer from the chain
|
| 255 |
+
print("Querying the model")
|
| 256 |
+
# res = qa(question)
|
| 257 |
+
retrieved_docs = retriever.invoke(question)
|
| 258 |
+
if len(retrieved_docs) == 0:
|
| 259 |
+
return {"answer": "No files found", "filenames" : [] }
|
| 260 |
+
|
| 261 |
+
print(f"Retrieved examples: {print(retrieved_docs[0].page_content)}")
|
| 262 |
+
context = "\n\n".join(doc.page_content for doc in retrieved_docs)
|
| 263 |
+
prompt = f"""
|
| 264 |
+
<s> [INST] You are an assistant for question-answering tasks. Use the following pieces of retrieved context to answer the question. If you don't know the answer, just say that you don't know. Use three sentences maximum and keep the answer concise. [/INST] </s>
|
| 265 |
+
[INST] Question: {question}
|
| 266 |
+
Context: {context}
|
| 267 |
+
Answer: [/INST]
|
| 268 |
+
|
| 269 |
+
"""
|
| 270 |
+
print(F"Executing Prompt: {prompt}")
|
| 271 |
+
answer = rag_chain.invoke("What is Task Decomposition?")
|
| 272 |
+
print(f"Result from the model: {answer}")
|
| 273 |
+
# answer, docs = res.get('result', ""), res.get('source_documents', "")
|
| 274 |
+
docs = [doc.metadata["source"] for doc in retrieved_docs]
|
| 275 |
+
res = {"answer": answer, "filenames" : docs }
|
| 276 |
+
return res
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
def set_state_if_absent(key, value):
|
| 280 |
+
if key not in st.session_state:
|
| 281 |
+
st.session_state[key] = value
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
# Adjust to a question that you would like users to see in the search bar when they load the UI:
|
| 285 |
+
DEFAULT_QUESTION_AT_STARTUP = os.getenv("DEFAULT_QUESTION_AT_STARTUP", "What is the state of generative ai in 2022?")
|
| 286 |
+
DEFAULT_ANSWER_AT_STARTUP = os.getenv(
|
| 287 |
+
"DEFAULT_ANSWER_AT_STARTUP",
|
| 288 |
+
"",
|
| 289 |
+
)
|
| 290 |
+
DEFAULT_PRIMER = os.getenv("DEFAULT_PRIMER", f"""You are Q&A bot that answers
|
| 291 |
+
user questions based on the information provided by the user above
|
| 292 |
+
each question. If the information can not be found in the information
|
| 293 |
+
provided by the user you truthfully say "I don't know".
|
| 294 |
+
""")
|
| 295 |
+
|
| 296 |
+
# Sliders
|
| 297 |
+
DEFAULT_DOCS_FROM_RETRIEVER = int(os.getenv("DEFAULT_DOCS_FROM_RETRIEVER", "3"))
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
# st.set_page_config(
|
| 301 |
+
# page_title="Open AI Demo", page_icon="https://haystack.deepset.ai/img/HaystackIcon.png"
|
| 302 |
+
# )
|
| 303 |
+
|
| 304 |
+
# Persistent state
|
| 305 |
+
set_state_if_absent("question", DEFAULT_QUESTION_AT_STARTUP)
|
| 306 |
+
set_state_if_absent("answer", DEFAULT_ANSWER_AT_STARTUP)
|
| 307 |
+
set_state_if_absent("results", None)
|
| 308 |
+
set_state_if_absent("primer", DEFAULT_PRIMER)
|
| 309 |
+
|
| 310 |
+
# Small callback to reset the interface in case the text of the question changes
|
| 311 |
+
def reset_results(*args):
|
| 312 |
+
st.session_state.answer = None
|
| 313 |
+
st.session_state.results = None
|
| 314 |
+
st.session_state.raw_json = None
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
# Title
|
| 318 |
+
st.write("# Open LLM Semantic Search Demo")
|
| 319 |
+
st.markdown(
|
| 320 |
+
"""
|
| 321 |
+
This demo takes its data from PDF, DOCX, and TXT files. \n
|
| 322 |
+
Ask any question on this indexed data and see if OpenAI can find the correct answer to your query! \n
|
| 323 |
+
*Note: do not use keywords, but full-fledged questions.* The demo is not optimized to deal with keyword queries and might misunderstand you.
|
| 324 |
+
""",
|
| 325 |
+
unsafe_allow_html=True,
|
| 326 |
+
)
|
| 327 |
+
|
| 328 |
+
# Sidebar
|
| 329 |
+
st.sidebar.header("Options")
|
| 330 |
+
st.sidebar.write("## File Upload:")
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
with st.sidebar.form("my-form", clear_on_submit=True):
|
| 334 |
+
data_files = st.file_uploader(
|
| 335 |
+
"Upload",
|
| 336 |
+
type=["pdf", "txt", "docx","html"],
|
| 337 |
+
accept_multiple_files=True,
|
| 338 |
+
label_visibility="hidden",
|
| 339 |
+
)
|
| 340 |
+
submitted = st.form_submit_button("UPLOAD!")
|
| 341 |
+
if submitted and data_files is not None:
|
| 342 |
+
st.write("UPLOADED!")
|
| 343 |
+
ALL_FILES = []
|
| 344 |
+
META_DATA = []
|
| 345 |
+
upload_dir = Path(FILE_UPLOAD_PATH) / f"{uuid.uuid4().hex}/"
|
| 346 |
+
os.makedirs(upload_dir, exist_ok=True)
|
| 347 |
+
for data_file in data_files:
|
| 348 |
+
# Upload file
|
| 349 |
+
if data_file:
|
| 350 |
+
file_path = upload_dir / data_file.name
|
| 351 |
+
with open(file_path, "wb") as f:
|
| 352 |
+
f.write(data_file.getbuffer())
|
| 353 |
+
ALL_FILES.append(str(file_path))
|
| 354 |
+
st.sidebar.write(str(data_file.name) + " β
")
|
| 355 |
+
META_DATA.append({"filename": data_file.name})
|
| 356 |
+
|
| 357 |
+
if len(ALL_FILES) > 0:
|
| 358 |
+
|
| 359 |
+
st.sidebar.write("Starting the document indexing ... ")
|
| 360 |
+
with st.spinner(
|
| 361 |
+
"π§ Performing indexing of uploaded documents... \n "
|
| 362 |
+
):
|
| 363 |
+
|
| 364 |
+
with Pool(processes=os.cpu_count()) as pool:
|
| 365 |
+
results = []
|
| 366 |
+
with tqdm(total=len(ALL_FILES), desc='Loading new documents', ncols=80) as pbar:
|
| 367 |
+
for i, doc in enumerate(pool.imap_unordered(load_single_document, ALL_FILES)):
|
| 368 |
+
results.append(doc)
|
| 369 |
+
pbar.update()
|
| 370 |
+
print(f"Loaded {len(results)} new documents from Upload")
|
| 371 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap)
|
| 372 |
+
docs = text_splitter.split_documents(results)
|
| 373 |
+
print(f"Split into {len(docs)} chunks of text (max. {chunk_size} tokens each)")
|
| 374 |
+
vectordb.add_documents(docs)
|
| 375 |
+
vectordb.persist()
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
st.sidebar.write("Document indexing completed β
")
|
| 379 |
+
ALL_FILES = []
|
| 380 |
+
META_DATA = []
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
top_k_retriever = st.sidebar.slider(
|
| 384 |
+
"Max. number of documents from retriever",
|
| 385 |
+
min_value=1,
|
| 386 |
+
max_value=10,
|
| 387 |
+
value=DEFAULT_DOCS_FROM_RETRIEVER,
|
| 388 |
+
step=1,
|
| 389 |
+
on_change=reset_results,
|
| 390 |
+
)
|
| 391 |
+
# primer = st.text_input(
|
| 392 |
+
# value=st.session_state.primer,
|
| 393 |
+
# max_chars=1000,
|
| 394 |
+
# label="primer",
|
| 395 |
+
# )
|
| 396 |
+
primer=""
|
| 397 |
+
question = st.text_input(
|
| 398 |
+
value=st.session_state.question,
|
| 399 |
+
max_chars=200,
|
| 400 |
+
on_change=reset_results,
|
| 401 |
+
label="question",
|
| 402 |
+
label_visibility="hidden",
|
| 403 |
+
)
|
| 404 |
+
col1, col2 = st.columns(2)
|
| 405 |
+
col1.markdown("<style>.stButton button {width:100%;}</style>", unsafe_allow_html=True)
|
| 406 |
+
col2.markdown("<style>.stButton button {width:100%;}</style>", unsafe_allow_html=True)
|
| 407 |
+
|
| 408 |
+
# Run button
|
| 409 |
+
run_pressed = col1.button("Run")
|
| 410 |
+
if run_pressed:
|
| 411 |
+
run_query = run_pressed or question != st.session_state.question
|
| 412 |
+
# Get results for query
|
| 413 |
+
if run_query and question:
|
| 414 |
+
reset_results()
|
| 415 |
+
st.session_state.question = question
|
| 416 |
+
|
| 417 |
+
with st.spinner("π§ Performing neural search on documents... \n "):
|
| 418 |
+
try:
|
| 419 |
+
print(f"Running the query : {question}")
|
| 420 |
+
st.session_state.results = query(question, primer, top_k_retriever=top_k_retriever)
|
| 421 |
+
except JSONDecodeError as je:
|
| 422 |
+
st.error(
|
| 423 |
+
"π An error occurred reading the results. Is the document store working?"
|
| 424 |
+
)
|
| 425 |
+
except Exception as e:
|
| 426 |
+
logging.exception(e)
|
| 427 |
+
if "The server is busy processing requests" in str(e) or "503" in str(e):
|
| 428 |
+
st.error("π§βπΎ All our workers are busy! Try again later.")
|
| 429 |
+
else:
|
| 430 |
+
st.error(f"π An error occurred during the request. {str(e)}")
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
if st.session_state.results:
|
| 434 |
+
st.write("## Results:")
|
| 435 |
+
answer = st.session_state.results["answer"]
|
| 436 |
+
# Hack due to this bug: https://github.com/streamlit/streamlit/issues/3190
|
| 437 |
+
try:
|
| 438 |
+
filenames = st.session_state.results["filenames"]
|
| 439 |
+
st.write(
|
| 440 |
+
markdown(f"**Answer:** \n {answer} \n\n **Using data from files**: {filenames} \n "),
|
| 441 |
+
unsafe_allow_html=True,
|
| 442 |
+
)
|
| 443 |
+
except Exception as e:
|
| 444 |
+
st.write(
|
| 445 |
+
markdown(f"Failed to find answer:"),
|
| 446 |
+
unsafe_allow_html=True,
|
| 447 |
+
)
|
models/openhermes-2.5-mistral-7b-16k.Q4_K_M.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:336011b45dd6813436b00251d880c5240b92c5c244469c30417178cf687e3b58
|
| 3 |
+
size 4368450432
|
requirements.txt
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gpt4all
|
| 2 |
+
pydantic
|
| 3 |
+
ctransformers[cuda]
|
| 4 |
+
urllib3==2.0.2
|
| 5 |
+
pdfminer.six==20221105
|
| 6 |
+
python-dotenv==1.0.0
|
| 7 |
+
unstructured==0.6.6
|
| 8 |
+
extract-msg==0.41.1
|
| 9 |
+
tabulate==0.9.0
|
| 10 |
+
pandoc==2.3
|
| 11 |
+
pypandoc==1.11
|
| 12 |
+
tqdm==4.65.0
|
| 13 |
+
st-annotated-text
|
| 14 |
+
protobuf==3.19.3
|
| 15 |
+
streamlit==1.21.0
|
| 16 |
+
datasets
|
| 17 |
+
bs4
|
| 18 |
+
python-dotenv
|
| 19 |
+
tiktoken
|
| 20 |
+
unstructured[local-inference]
|
| 21 |
+
streamlit-chat
|
| 22 |
+
pymssql
|
| 23 |
+
qdrant-client
|
| 24 |
+
sentence_transformers
|
| 25 |
+
chromadb
|