|
import numpy as np |
|
import io |
|
import os |
|
import logging |
|
import collections |
|
import tempfile |
|
from langchain.document_loaders import UnstructuredFileLoader |
|
from langchain.text_splitter import CharacterTextSplitter |
|
from langchain.vectorstores import FAISS |
|
from langchain.embeddings import HuggingFaceEmbeddings |
|
|
|
from langchain.document_loaders import PDFMinerPDFasHTMLLoader |
|
from bs4 import BeautifulSoup |
|
import re |
|
from langchain.docstore.document import Document |
|
|
|
import unstructured |
|
from unstructured.partition.docx import partition_docx |
|
from unstructured.partition.auto import partition |
|
|
|
from transformers import AutoTokenizer |
|
|
|
import pandas as pd |
|
|
|
|
|
MODEL = "thenlper/gte-base" |
|
CHUNK_SIZE = 1000 |
|
CHUNK_OVERLAP = 200 |
|
|
|
embeddings = HuggingFaceEmbeddings( |
|
model_name=MODEL, |
|
cache_folder=os.getenv("SENTENCE_TRANSFORMERS_HOME") |
|
) |
|
|
|
model_id = "mistralai/Mistral-7B-Instruct-v0.1" |
|
|
|
tokenizer = AutoTokenizer.from_pretrained( |
|
model_id, |
|
padding_side="left" |
|
) |
|
|
|
text_splitter = CharacterTextSplitter( |
|
separator = "\n", |
|
chunk_size = CHUNK_SIZE, |
|
chunk_overlap = CHUNK_OVERLAP, |
|
length_function = len, |
|
) |
|
|
|
|
|
|
|
def group_text_by_font_size(content): |
|
cur_fs = [] |
|
cur_text = '' |
|
cur_page = -1 |
|
cur_c = content[0] |
|
multi_fs = False |
|
snippets = [] |
|
for c in content: |
|
|
|
if c.find('a') != None and c.find('a').get('name'): |
|
cur_page = int(c.find('a').get('name')) |
|
sp_list = c.find_all('span') |
|
if not sp_list: |
|
continue |
|
for sp in sp_list: |
|
|
|
if not sp: |
|
continue |
|
st = sp.get('style') |
|
if not st: |
|
continue |
|
fs = re.findall('font-size:(\d+)px',st) |
|
|
|
if not fs: |
|
continue |
|
fs = [int(fs[0])] |
|
if len(cur_fs)==0: |
|
cur_fs = fs |
|
if fs == cur_fs: |
|
cur_text += sp.text |
|
elif not sp.find('br') and cur_c==c: |
|
cur_text += sp.text |
|
cur_fs.extend(fs) |
|
multi_fs = True |
|
elif sp.find('br') and multi_fs == True: |
|
cur_fs.extend(fs) |
|
snippets.append((cur_text+sp.text,max(cur_fs), cur_page)) |
|
cur_fs = [] |
|
cur_text = '' |
|
cur_c = c |
|
multi_fs = False |
|
else: |
|
snippets.append((cur_text,max(cur_fs), cur_page)) |
|
cur_fs = fs |
|
cur_text = sp.text |
|
cur_c = c |
|
multi_fs = False |
|
snippets.append((cur_text,max(cur_fs), cur_page)) |
|
return snippets |
|
|
|
def get_titles_fs(fs_list): |
|
filtered_fs_list = [item[0] for item in fs_list if item[0] > fs_list[0][0]] |
|
return sorted(filtered_fs_list, reverse=True) |
|
|
|
def calculate_total_characters(snippets): |
|
font_sizes = {} |
|
|
|
for text, font_size, _ in snippets: |
|
|
|
cleaned_text = text.replace('\n', '') |
|
|
|
total_characters = len(cleaned_text) |
|
|
|
|
|
if font_size in font_sizes: |
|
font_sizes[font_size] += total_characters |
|
else: |
|
font_sizes[font_size] = total_characters |
|
|
|
size_charac_list = sorted(font_sizes.items(), key=lambda x: x[1], reverse=True) |
|
|
|
return size_charac_list |
|
|
|
def create_documents(source, snippets, font_sizes): |
|
docs = [] |
|
|
|
titles_fs = get_titles_fs(font_sizes) |
|
|
|
for snippet in snippets: |
|
cur_fs = snippet[1] |
|
if cur_fs>font_sizes[0][0] and len(snippet[0])>2: |
|
content = min((titles_fs.index(cur_fs)+1), 3)*"#" + " " + snippet[0].replace(" ", " ") |
|
category = "Title" |
|
else: |
|
content = snippet[0].replace(" ", " ") |
|
category = "Paragraph" |
|
metadata={"source":source, "filename":source.split("/")[-1], "file_directory": "/".join(source.split("/")[:-1]), "file_category":"", "file_sub-cat":"", "file_sub2-cat":"", "category":category, "filetype":source.split(".")[-1], "page_number":snippet[2]} |
|
categories = source.split("/") |
|
cat_update="" |
|
if len(categories)>4: |
|
cat_update = {"file_category":categories[1], "file_sub-cat":categories[2], "file_sub2-cat":categories[3]} |
|
elif len(categories)>3: |
|
cat_update = {"file_category":categories[1], "file_sub-cat":categories[2]} |
|
elif len(categories)>2: |
|
cat_update = {"file_category":categories[1]} |
|
metadata.update(cat_update) |
|
docs.append(Document(page_content=content, metadata=metadata)) |
|
return docs |
|
|
|
|
|
|
|
|
|
def group_chunks_by_section(chunks, min_chunk_size=512): |
|
filtered_chunks = [chunk for chunk in chunks if chunk.metadata['category'] != 'PageBreak'] |
|
|
|
new_chunks = [] |
|
seen_paragraph = False |
|
new_title = True |
|
for i, chunk in enumerate(filtered_chunks): |
|
|
|
if new_title: |
|
|
|
new_chunk = chunk |
|
new_title = False |
|
add_content = False |
|
new_chunk.metadata['titles'] = "" |
|
|
|
|
|
if chunk.metadata['category'].lower() =='title': |
|
new_chunk.metadata['titles'] += f"{chunk.page_content} ~~ " |
|
else: |
|
|
|
seen_paragraph = True |
|
|
|
|
|
if add_content: |
|
new_chunk.page_content += f"\n{chunk.page_content}" |
|
|
|
try: |
|
new_chunk.metadata['end_page'] = chunk.metadata['page_number'] |
|
except: |
|
print("", end="") |
|
|
|
|
|
add_content = True |
|
|
|
|
|
try: |
|
|
|
if filtered_chunks[i+1].metadata['category'].lower() =="title" and seen_paragraph and len(new_chunk.page_content)>min_chunk_size: |
|
if 'category' in new_chunk.metadata: |
|
new_chunk.metadata.pop('category') |
|
new_chunks.append(new_chunk) |
|
new_title = True |
|
seen_paragraph = False |
|
|
|
except: |
|
new_chunks.append(new_chunk) |
|
|
|
break |
|
return new_chunks |
|
|
|
|
|
|
|
|
|
def split_pdf(file_path, folder): |
|
loader = PDFMinerPDFasHTMLLoader(file_path) |
|
|
|
data = loader.load()[0] |
|
soup = BeautifulSoup(data.page_content,'html.parser') |
|
content = soup.find_all('div') |
|
try: |
|
snippets = group_text_by_font_size(content) |
|
except Exception as e: |
|
print("ERROR WHILE GROUPING BY FONT SIZE", e) |
|
snippets = [("ERROR WHILE GROUPING BY FONT SIZE", 0, -1)] |
|
font_sizes = calculate_total_characters(snippets) |
|
chunks = create_documents(file_path, snippets, font_sizes) |
|
return chunks |
|
|
|
|
|
def split_docx(file_path, folder): |
|
chunks_elms = partition_docx(filename=file_path) |
|
chunks = [] |
|
file_categories = file_path.split("/") |
|
for chunk_elm in chunks_elms: |
|
category = chunk_elm.category |
|
if category == "Title": |
|
chunk = Document(page_content= min(chunk_elm.metadata.to_dict()['category_depth']+1, 3)*"#" + ' ' + chunk_elm.text, metadata=chunk_elm.metadata.to_dict()) |
|
else: |
|
chunk = Document(page_content=chunk_elm.text, metadata=chunk_elm.metadata.to_dict()) |
|
metadata={"source":file_path, "filename":file_path.split("/")[-1], "file_category":"", "file_sub-cat":"", "file_sub2-cat":"", "category":category, "filetype":file_path.split(".")[-1]} |
|
cat_update="" |
|
if len(file_categories)>4: |
|
cat_update = {"file_category":file_categories[1], "file_sub-cat":file_categories[2], "file_sub2-cat":file_categories[3]} |
|
elif len(file_categories)>3: |
|
cat_update = {"file_category":file_categories[1], "file_sub-cat":file_categories[2]} |
|
elif len(file_categories)>2: |
|
cat_update = {"file_category":file_categories[1]} |
|
metadata.update(cat_update) |
|
chunk.metadata.update(metadata) |
|
chunks.append(chunk) |
|
return chunks |
|
|
|
|
|
|
|
def rebuild_index(input_folder, output_folder): |
|
paths_time = [] |
|
to_keep = set() |
|
print(f'number of files {len(paths_time)}') |
|
if len(output_folder.list_paths_in_partition()) > 0: |
|
with tempfile.TemporaryDirectory() as temp_dir: |
|
for f in output_folder.list_paths_in_partition(): |
|
with output_folder.get_download_stream(f) as stream: |
|
with open(os.path.join(temp_dir, os.path.basename(f)), "wb") as f2: |
|
f2.write(stream.read()) |
|
index = FAISS.load_local(temp_dir, embeddings) |
|
to_remove = [] |
|
logging.info(f"{len(index.docstore._dict)} vectors loaded") |
|
for idx, doc in index.docstore._dict.items(): |
|
source = (doc.metadata["source"], doc.metadata["last_modified"]) |
|
if source in paths_time: |
|
|
|
to_keep.add(source) |
|
else: |
|
|
|
to_remove.append(idx) |
|
|
|
docstore_id_to_index = {v: k for k, v in index.index_to_docstore_id.items()} |
|
|
|
|
|
vectors_to_remove = [] |
|
for idx in to_remove: |
|
del index.docstore._dict[idx] |
|
ind = docstore_id_to_index[idx] |
|
del index.index_to_docstore_id[ind] |
|
vectors_to_remove.append(ind) |
|
index.index.remove_ids(np.array(vectors_to_remove, dtype=np.int64)) |
|
|
|
index.index_to_docstore_id = { |
|
i: ind |
|
for i, ind in enumerate(index.index_to_docstore_id.values()) |
|
} |
|
logging.info(f"{len(to_remove)} vectors removed") |
|
else: |
|
index = None |
|
to_add = [path[0] for path in paths_time if path not in to_keep] |
|
print(f'to_keep: {to_keep}') |
|
print(f'to_add: {to_add}') |
|
return index, to_add |
|
|
|
|
|
def split_chunks_by_tokens(documents, max_length=170, overlap=10): |
|
|
|
resized = [] |
|
|
|
|
|
for doc in documents: |
|
encoded = tokenizer.encode(doc.page_content) |
|
if len(encoded) > max_length: |
|
remaining_encoded = tokenizer.encode(doc.page_content) |
|
while len(remaining_encoded) > 0: |
|
split_doc = Document(page_content=tokenizer.decode(remaining_encoded[:max(10, max_length)]), metadata=doc.metadata.copy()) |
|
resized.append(split_doc) |
|
remaining_encoded = remaining_encoded[max(10, max_length - overlap):] |
|
|
|
else: |
|
resized.append(doc) |
|
print(f"Number of chunks before resplitting: {len(documents)} \nAfter splitting: {len(resized)}") |
|
return resized |
|
|
|
|
|
def split_chunks_by_tokens_period(documents, max_length=170, overlap=10, min_chunk_size=20): |
|
|
|
resized = [] |
|
previous_file="" |
|
|
|
for doc in documents: |
|
current_file = doc.metadata['source'] |
|
if current_file != previous_file: |
|
previous_file = current_file |
|
chunk_counter = 0 |
|
is_first_chunk = True |
|
encoded = tokenizer.encode(doc.page_content) |
|
if len(encoded) > max_length: |
|
remaining_encoded = encoded |
|
is_last_chunk = False |
|
while len(remaining_encoded) > 1 and not is_last_chunk: |
|
|
|
overlap_text = tokenizer.decode(remaining_encoded[:overlap]) |
|
period_index_b = overlap_text.find('.') |
|
if len(remaining_encoded)>max_length + min_chunk_size: |
|
current_encoded = remaining_encoded[:max(10, max_length)] |
|
else: |
|
current_encoded = remaining_encoded[:max(10, max_length + min_chunk_size)] |
|
is_last_chunk = True |
|
period_index_e = len(doc.page_content) |
|
if len(remaining_encoded)>max_length+min_chunk_size: |
|
overlap_text_last = tokenizer.decode(current_encoded[-overlap:]) |
|
period_index_last = overlap_text_last.find('.') |
|
if period_index_last != -1 and period_index_last < len(overlap_text_last) - 1: |
|
|
|
period_index_e = period_index_last - len(overlap_text_last) + 1 |
|
|
|
|
|
if not is_first_chunk: |
|
if period_index_b == -1: |
|
|
|
split_doc = Document(page_content=tokenizer.decode(current_encoded)[:period_index_e], metadata=doc.metadata.copy()) |
|
else: |
|
if is_last_chunk : |
|
split_doc = Document(page_content=tokenizer.decode(current_encoded)[period_index_b+1:], metadata=doc.metadata.copy()) |
|
|
|
else: |
|
split_doc = Document(page_content=tokenizer.decode(current_encoded)[period_index_b+1:period_index_e], metadata=doc.metadata.copy()) |
|
else: |
|
split_doc = Document(page_content=tokenizer.decode(current_encoded)[:period_index_e], metadata=doc.metadata.copy()) |
|
if 'titles' in split_doc.metadata: |
|
chunk_counter += 1 |
|
split_doc.metadata['chunk_id'] = chunk_counter |
|
|
|
split_doc.metadata['token_length'] = len(tokenizer.encode(split_doc.page_content)) |
|
resized.append(split_doc) |
|
remaining_encoded = remaining_encoded[max(10, max_length - overlap):] |
|
is_first_chunk = False |
|
|
|
elif len(encoded)>min_chunk_size: |
|
|
|
if 'titles' in doc.metadata: |
|
chunk_counter += 1 |
|
doc.metadata['chunk_id'] = chunk_counter |
|
doc.metadata['token_length'] = len(encoded) |
|
resized.append(doc) |
|
print(f"Number of chunks before resplitting: {len(documents)} \nAfter splitting: {len(resized)}") |
|
return resized |
|
|
|
|
|
|
|
def split_doc_in_chunks(input_folder): |
|
docs = [] |
|
for i, filename in enumerate(input_folder): |
|
path = filename |
|
print(f"Treating file {i}/{len(input_folder)}") |
|
|
|
chunks=[] |
|
if path.endswith(".pdf"): |
|
try: |
|
print("Treatment of pdf file", path) |
|
raw_chuncks = split_pdf(path, input_folder) |
|
chunks = group_chunks_by_section(raw_chuncks) |
|
print(f"Document splitted in {len(chunks)} chunks") |
|
|
|
|
|
except Exception as e: |
|
print("Error while splitting the pdf file: ", e) |
|
elif path.endswith(".docx"): |
|
try: |
|
print ("Treatment of docx file", path) |
|
raw_chuncks = split_docx(path, input_folder) |
|
|
|
chunks = group_chunks_by_section(raw_chuncks) |
|
print(f"Document splitted in {len(chunks)} chunks") |
|
|
|
|
|
|
|
except Exception as e: |
|
print("Error while splitting the docx file: ", e) |
|
elif path.endswith(".doc"): |
|
try: |
|
loader = UnstructuredFileLoader(path) |
|
|
|
chunks = loader.load_and_split(text_splitter=text_splitter) |
|
counter, counter2 = collections.Counter(), collections.Counter() |
|
filename = os.path.basename(path) |
|
|
|
for chunk in chunks: |
|
chunk.metadata["filename"] = filename.split("/")[-1] |
|
chunk.metadata["file_directory"] = filename.split("/")[:-1] |
|
chunk.metadata["filetype"] = filename.split(".")[-1] |
|
if "page" in chunk.metadata: |
|
counter[chunk.metadata['page']] += 1 |
|
for i in range(len(chunks)): |
|
counter2[chunks[i].metadata['page']] += 1 |
|
chunks[i].metadata['source'] = filename |
|
else: |
|
if len(chunks) == 1: |
|
chunks[0].metadata['source'] = filename |
|
|
|
except Exception as e: |
|
print(f"An error occurred: {e}") |
|
try: |
|
if len(chunks)>0: |
|
docs += chunks |
|
except NameError as e: |
|
print(f"An error has occured: {e}") |
|
return docs |
|
|
|
|
|
def resplit_by_end_of_sentence(docs): |
|
print("❌❌\nResplitting docs by end of sentence\n❌❌") |
|
resized_docs = split_chunks_by_tokens_period(docs, max_length=200, overlap=40, min_chunk_size=20) |
|
try: |
|
|
|
cur_source = "" |
|
cpt_chunk = 1 |
|
for resized_doc in resized_docs: |
|
try: |
|
title = resized_doc.metadata['titles'].split(' ~~ ')[-2] |
|
if title not in resized_doc.page_content: |
|
resized_doc.page_content = title + "\n" + resized_doc.page_content |
|
if cur_source == resized_doc.metadata["source"]: |
|
resized_doc.metadata['chunk_number'] = cpt_chunk |
|
else: |
|
cpt_chunk = 1 |
|
cur_source = resized_doc.metadata["source"] |
|
resized_doc.metadata['chunk_number'] = cpt_chunk |
|
except Exception as e: |
|
print("An error occured: ", e) |
|
|
|
cpt_chunk += 1 |
|
except Exception as e: |
|
print('AN ERROR OCCURRED: ', e) |
|
return resized_docs |
|
|
|
|
|
def build_index(docs, index, output_folder): |
|
if len(docs) > 0: |
|
if index is not None: |
|
|
|
new_index = FAISS.from_documents(docs, embeddings) |
|
index.merge_from(new_index) |
|
else: |
|
index = FAISS.from_documents(docs, embeddings) |
|
with tempfile.TemporaryDirectory() as temp_dir: |
|
index.save_local(temp_dir) |
|
for f in os.listdir(temp_dir): |
|
output_folder.upload_file(f, os.path.join(temp_dir, f)) |
|
|
|
|
|
def split_in_df(files): |
|
documents = split_doc_in_chunks(files) |
|
df = pd.DataFrame() |
|
for document in documents: |
|
filename = document.metadata['filename'] |
|
content = document.page_content |
|
|
|
|
|
|
|
|
|
|
|
doc_data = {'Filename': filename, 'Content': content} |
|
|
|
|
|
|
|
|
|
df = pd.concat([df, pd.DataFrame([doc_data])], ignore_index=True) |
|
|
|
df.to_excel("dataframe.xlsx", index=False) |
|
|
|
return "dataframe.xlsx" |