alsojulha commited on
Commit
5647527
·
verified ·
1 Parent(s): eb1570b

Update indexing.py

Browse files
Files changed (1) hide show
  1. indexing.py +31 -62
indexing.py CHANGED
@@ -1,63 +1,32 @@
1
- """
2
- Indexing with vector database
3
- """
4
-
5
- from pathlib import Path
6
- import re
7
-
8
  import chromadb
9
-
10
- from unidecode import unidecode
11
-
12
- from langchain_community.document_loaders import PyPDFLoader
13
- from langchain.text_splitter import RecursiveCharacterTextSplitter
14
- from langchain_chroma import Chroma
15
- from langchain_huggingface import HuggingFaceEmbeddings
16
-
17
-
18
-
19
- def load_doc(list_file_path, chunk_size, chunk_overlap):
20
- """Carrega documentos PDF e divide em chunks"""
21
- loaders = [PyPDFLoader(x) for x in list_file_path]
22
- pages = []
23
- for loader in loaders:
24
- pages.extend(loader.load())
25
-
26
- text_splitter = RecursiveCharacterTextSplitter(
27
- chunk_size=chunk_size,
28
- chunk_overlap=chunk_overlap
29
- )
30
- doc_splits = text_splitter.split_documents(pages)
31
- return doc_splits
32
-
33
-
34
- def create_collection_name(filepath):
35
- """Cria nome da coleção com base no nome do arquivo PDF"""
36
- collection_name = Path(filepath).stem
37
- collection_name = collection_name.replace(" ", "-")
38
- collection_name = unidecode(collection_name)
39
- collection_name = re.sub("[^A-Za-z0-9]+", "-", collection_name)
40
- collection_name = collection_name[:50]
41
- if len(collection_name) < 3:
42
- collection_name += "xyz"
43
- if not collection_name[0].isalnum():
44
- collection_name = "A" + collection_name[1:]
45
- if not collection_name[-1].isalnum():
46
- collection_name = collection_name[:-1] + "Z"
47
- return collection_name
48
-
49
-
50
- def create_db(splits, collection_name):
51
- """Cria banco vetorial com os embeddings"""
52
- embedding = HuggingFaceEmbeddings(
53
- model_name="sentence-transformers/paraphrase-multilingual-mpnet-base-v2"
54
- )
55
- chromadb.api.client.SharedSystemClient.clear_system_cache()
56
- new_client = chromadb.EphemeralClient()
57
- vectordb = Chroma.from_documents(
58
- documents=splits,
59
- embedding=embedding,
60
- client=new_client,
61
- collection_name=collection_name,
62
- )
63
- return vectordb
 
1
+ # indexing.py
 
 
 
 
 
 
2
  import chromadb
3
+ from chromadb.config import Settings
4
+ from sentence_transformers import SentenceTransformer
5
+
6
+ # Inicializa o modelo de embedding
7
+ embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
8
+
9
+ # Inicializa o cliente ChromaDB com persistência local
10
+ chroma_client = chromadb.Client(Settings(
11
+ chroma_db_impl="duckdb+parquet",
12
+ persist_directory="./chroma_db" # Certifique-se de que essa pasta está no .gitignore
13
+ ))
14
+
15
+ # Cria ou recupera a coleção
16
+ collection = chroma_client.get_or_create_collection(name="document_chunks")
17
+
18
+ def index_chunks(chunks):
19
+ """
20
+ Recebe uma lista de chunks de texto e adiciona ao banco vetorial.
21
+ """
22
+ embeddings = embedding_model.encode(chunks).tolist()
23
+ ids = [f"chunk_{i}" for i in range(len(chunks))]
24
+ collection.add(documents=chunks, embeddings=embeddings, ids=ids)
25
+
26
+ def query_relevant_chunk(query_text, n_results=1):
27
+ """
28
+ Realiza uma busca vetorial e retorna os chunks mais relevantes.
29
+ """
30
+ query_embedding = embedding_model.encode([query_text]).tolist()[0]
31
+ results = collection.query(query_embeddings=[query_embedding], n_results=n_results)
32
+ return results["documents"][0] if results["documents"] else []