quivr/loaders/common.py

33 lines
1.3 KiB
Python
Raw Normal View History

2023-05-13 00:22:21 +03:00
import tempfile
2023-05-13 01:39:40 +03:00
import time
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
def process_file(vector_store, file, loader_class, file_suffix):
documents = []
file_sha = ""
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-13 01:39:40 +03:00
dateshort = time.strftime("%Y%m%d")
2023-05-13 00:22:21 +03:00
with tempfile.NamedTemporaryFile(delete=True, suffix=file_suffix) as tmp_file:
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)
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)
return