quivr/backend/parsers/common.py

66 lines
2.3 KiB
Python
Raw Normal View History

2023-05-18 02:22:13 +03:00
# from stats import add_usage
import asyncio
import os
import tempfile
import time
from typing import Optional
from fastapi import UploadFile
from langchain.schema import Document
from langchain.text_splitter import RecursiveCharacterTextSplitter
from utils import (compute_sha1_from_content, compute_sha1_from_file,
create_summary, create_vector, documents_vector_store)
2023-05-18 02:22:13 +03:00
2023-05-22 09:39:55 +03:00
async def process_file(file: UploadFile, loader_class, file_suffix, enable_summarization, user):
2023-05-18 02:22:13 +03:00
documents = []
file_name = file.filename
file_size = file.file._file.tell() # Getting the size of the file
dateshort = time.strftime("%Y%m%d")
2023-05-22 09:39:55 +03:00
2023-05-18 02:22:13 +03:00
# Here, we're writing the uploaded file to a temporary file, so we can use it with your existing code.
with tempfile.NamedTemporaryFile(delete=False, suffix=file.filename) as tmp_file:
await file.seek(0)
content = await file.read()
tmp_file.write(content)
tmp_file.flush()
2023-05-22 09:39:55 +03:00
2023-05-18 02:22:13 +03:00
loader = loader_class(tmp_file.name)
documents = loader.load()
2023-05-22 09:39:55 +03:00
# Ensure this function works with FastAPI
file_sha1 = compute_sha1_from_file(tmp_file.name)
2023-05-18 02:22:13 +03:00
os.remove(tmp_file.name)
chunk_size = 500
chunk_overlap = 0
2023-05-22 09:39:55 +03:00
text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(
chunk_size=chunk_size, chunk_overlap=chunk_overlap)
2023-05-18 02:22:13 +03:00
2023-05-22 09:39:55 +03:00
documents = text_splitter.split_documents(documents)
for doc in documents:
metadata = {
"file_sha1": file_sha1,
"file_size": file_size,
"file_name": file_name,
"chunk_size": chunk_size,
"chunk_overlap": chunk_overlap,
"date": dateshort,
"summarization": "true" if enable_summarization else "false"
}
doc_with_metadata = Document(
page_content=doc.page_content, metadata=metadata)
create_vector(user.email, doc_with_metadata)
2023-05-22 09:39:55 +03:00
if enable_summarization and ids and len(ids) > 0:
create_summary(ids[0], doc.page_content, metadata)
2023-05-18 02:22:13 +03:00
return
2023-05-22 09:39:55 +03:00
async def file_already_exists(supabase, file, user):
2023-05-18 02:22:13 +03:00
file_content = await file.read()
file_sha1 = compute_sha1_from_content(file_content)
response = supabase.table("vectors").select("id").filter("metadata->>file_sha1", "eq", file_sha1) \
.filter("user_id", "eq", user.email).execute()
2023-05-18 02:22:13 +03:00
return len(response.data) > 0