2023-05-13 00:22:21 +03:00
|
|
|
import tempfile
|
2023-05-13 01:39:40 +03:00
|
|
|
import time
|
2023-05-17 21:32:09 +03:00
|
|
|
import os
|
2023-05-13 00:22:21 +03:00
|
|
|
from utils import compute_sha1_from_file
|
|
|
|
from langchain.schema import Document
|
2023-05-13 00:58:19 +03:00
|
|
|
import streamlit as st
|
2023-05-13 00:22:21 +03:00
|
|
|
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
2023-05-17 13:12:52 +03:00
|
|
|
from stats import add_usage
|
2023-05-13 00:22:21 +03:00
|
|
|
|
2023-05-17 13:12:52 +03:00
|
|
|
def process_file(vector_store, file, loader_class, file_suffix, stats_db=None):
|
2023-05-13 00:22:21 +03:00
|
|
|
documents = []
|
2023-05-13 01:39:40 +03:00
|
|
|
file_name = file.name
|
2023-05-13 02:12:51 +03:00
|
|
|
file_size = file.size
|
2023-05-17 13:12:52 +03:00
|
|
|
if st.secrets.self_hosted == "false":
|
|
|
|
if file_size > 1000000:
|
|
|
|
st.error("File size is too large. Please upload a file smaller than 1MB or self host.")
|
|
|
|
return
|
2023-05-20 00:13:46 +03:00
|
|
|
|
2023-05-13 01:39:40 +03:00
|
|
|
dateshort = time.strftime("%Y%m%d")
|
2023-05-17 21:32:09 +03:00
|
|
|
with tempfile.NamedTemporaryFile(delete=False, suffix=file_suffix) as tmp_file:
|
2023-05-13 00:22:21 +03:00
|
|
|
tmp_file.write(file.getvalue())
|
|
|
|
tmp_file.flush()
|
|
|
|
|
|
|
|
loader = loader_class(tmp_file.name)
|
|
|
|
documents = loader.load()
|
|
|
|
file_sha1 = compute_sha1_from_file(tmp_file.name)
|
2023-05-20 00:13:46 +03:00
|
|
|
|
2023-05-17 21:32:09 +03:00
|
|
|
os.remove(tmp_file.name)
|
2023-05-13 00:22:21 +03:00
|
|
|
|
|
|
|
chunk_size = st.session_state['chunk_size']
|
|
|
|
chunk_overlap = st.session_state['chunk_overlap']
|
|
|
|
|
|
|
|
text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(chunk_size=chunk_size, chunk_overlap=chunk_overlap)
|
|
|
|
|
|
|
|
documents = text_splitter.split_documents(documents)
|
|
|
|
|
|
|
|
# Add the document sha1 as metadata to each document
|
2023-05-13 02:12:51 +03:00
|
|
|
docs_with_metadata = [Document(page_content=doc.page_content, metadata={"file_sha1": file_sha1,"file_size":file_size ,"file_name": file_name, "chunk_size": chunk_size, "chunk_overlap": chunk_overlap, "date": dateshort}) for doc in documents]
|
2023-05-13 00:22:21 +03:00
|
|
|
|
|
|
|
vector_store.add_documents(docs_with_metadata)
|
2023-05-17 13:12:52 +03:00
|
|
|
if stats_db:
|
|
|
|
add_usage(stats_db, "embedding", "file", metadata={"file_name": file_name,"file_type": file_suffix, "chunk_size": chunk_size, "chunk_overlap": chunk_overlap})
|