File size: 2,060 Bytes
8f4d57a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import tiktoken
from langchain_text_splitters import CharacterTextSplitter
from langchain_chroma import Chroma
from langchain_community.embeddings import HuggingFaceBgeEmbeddings
from langchain.document_loaders import PyMuPDFLoader,Docx2txtLoader
from transformers import pipeline
from app_config import VECTOR_MAX_TOKENS, VECTORS_TOKEN_OVERLAP_SIZE
from langchain.docstore.document import Document
from dotenv import load_dotenv
from pathlib import Path
import os
env_path = Path('.') / '.env'
load_dotenv(dotenv_path=env_path)

tokenizer = tiktoken.get_encoding('cl100k_base')

# create the length function
def tiktoken_len(text):
    tokens = tokenizer.encode(
        text,
        disallowed_special=()
    )
    return len(tokens)


def get_vectorstore_with_doc_from_pdf(pdf_path):
    model_name = "BAAI/bge-small-en"
    model_kwargs = {"device": "cpu"}
    encode_kwargs = {"normalize_embeddings": True}
    hf = HuggingFaceBgeEmbeddings(
        model_name=model_name, model_kwargs=model_kwargs, encode_kwargs=encode_kwargs
    )
    
    loader = PyMuPDFLoader(pdf_path)
    documents = loader.load()
    print(len(documents))

    all_splits = [doc.page_content for doc in documents]
    
    vectorstore = Chroma.from_texts(texts=all_splits, embedding=hf)
    return vectorstore

def get_vectorstore_with_doc_from_word(word_path):
    model_name = "BAAI/bge-small-en"
    model_kwargs = {"device": "cpu"}
    encode_kwargs = {"normalize_embeddings": True}
    hf = HuggingFaceBgeEmbeddings(
        model_name=model_name, model_kwargs=model_kwargs, encode_kwargs=encode_kwargs
    )
    
    loader = Docx2txtLoader(word_path)
    documents = loader.load()
    text_splitter = CharacterTextSplitter(
        separator="Page :",
    )

    # all_splits = text_splitter.split_text(data)
    print(len(documents))
    print("all splits ........................")
    all_splits = text_splitter.split_text(documents[0].page_content)
    print(len(all_splits))
    vectorstore = Chroma.from_texts(texts=all_splits, embedding=hf)
    return vectorstore