|
| 1 | +import os |
| 2 | +from tqdm import tqdm |
| 3 | +from langchain import OpenAI |
| 4 | + |
| 5 | +from langchain.tools import Tool |
| 6 | + |
| 7 | +#Memory Document Loader (Unstructured) |
| 8 | +from langchain.embeddings.openai import OpenAIEmbeddings |
| 9 | +from langchain.text_splitter import CharacterTextSplitter |
| 10 | +from langchain.chains import RetrievalQA |
| 11 | + |
| 12 | +from langchain.document_loaders.unstructured import UnstructuredBaseLoader |
| 13 | +from unstructured.cleaners.core import clean_extra_whitespace |
| 14 | +from unstructured.partition.html import partition_html |
| 15 | +from unstructured.partition.pdf import partition_pdf |
| 16 | +from typing import IO, Any, Callable, Dict, List, Optional, Sequence, Union |
| 17 | + |
| 18 | +import weaviate |
| 19 | +from langchain.vectorstores import Weaviate |
| 20 | + |
| 21 | +WEAVIATE_URL = os.getenv('WEAVIATE_URL') |
| 22 | +WEAVIATE_API_KEY = os.getenv('WEAVIATE_API_KEY') |
| 23 | +OPENAI_API_KEY = os.getenv('OPENAI_API_KEY') |
| 24 | + |
| 25 | +# Essa versão da classe aplica corretamente os _post_processors. |
| 26 | +# Talvez valha um pull request depois. |
| 27 | +class FixedUnstructuredFileLoader(UnstructuredBaseLoader): |
| 28 | + def __init__( |
| 29 | + self, |
| 30 | + file_path: Union[str, List[str]], |
| 31 | + mode: str = "paged", |
| 32 | + **unstructured_kwargs: Any, |
| 33 | + ): |
| 34 | + """Initialize with file path.""" |
| 35 | + self.file_path = file_path |
| 36 | + super().__init__(mode=mode, **unstructured_kwargs) |
| 37 | + |
| 38 | + |
| 39 | + def _get_elements(self) -> List: |
| 40 | + from unstructured.partition.auto import partition |
| 41 | + elements = partition(filename=self.file_path, **self.unstructured_kwargs) |
| 42 | + return self._post_process_elements(elements) |
| 43 | + |
| 44 | + def _post_process_elements(self, elements): |
| 45 | + """Applies post-processing functions to extracted unstructured elements. |
| 46 | + Post-processing functions are Element -> Element callables passed |
| 47 | + in using the post_processors kwarg when the loader is instantiated.""" |
| 48 | + print("Post processing...") |
| 49 | + for element in elements: |
| 50 | + for post_processor in self.post_processors: |
| 51 | + element.apply(post_processor) |
| 52 | + return elements |
| 53 | + |
| 54 | + def _get_metadata(self) -> dict: |
| 55 | + return {"source": self.file_path} |
| 56 | + |
| 57 | + |
| 58 | + |
| 59 | +class Library: |
| 60 | + def __init__(self, llm=OpenAI()): |
| 61 | + self.client = weaviate.Client( |
| 62 | + url=WEAVIATE_URL, |
| 63 | + auth_client_secret=weaviate.AuthApiKey(WEAVIATE_API_KEY), |
| 64 | + additional_headers={"X-OpenAI-Api-Key": OPENAI_API_KEY} |
| 65 | + ) |
| 66 | + self.llm = llm |
| 67 | + self.tools = [] |
| 68 | + |
| 69 | + def create_index(self, index_name): |
| 70 | + print(f"Criando índice {index_name}") |
| 71 | + self.client.schema.create_class({ |
| 72 | + "class": index_name, |
| 73 | + "properties": [ |
| 74 | + { |
| 75 | + "name": "text", |
| 76 | + "dataType": ["text"], |
| 77 | + }, |
| 78 | + { |
| 79 | + "name": "source", |
| 80 | + "dataType": ["text"], |
| 81 | + "description": "The source path of the file" |
| 82 | + } |
| 83 | + ], |
| 84 | + "vectorizer": "text2vec-openai" |
| 85 | + }) |
| 86 | + |
| 87 | + def check_existing_file(self, filename, index_name): |
| 88 | + #checa se o arquivo já esta indexado |
| 89 | + print(f"Verificando se o arquivo {filename} já está indexado...") |
| 90 | + file_indexed = self.client.query.get(index_name, "source").with_where({ |
| 91 | + "path": ["source"], |
| 92 | + "operator": "Equal", |
| 93 | + "valueText": filename |
| 94 | + }).with_limit(1).do() |
| 95 | + |
| 96 | + check = file_indexed and len(file_indexed["data"]["Get"][index_name]) == 1 |
| 97 | + return(check) |
| 98 | + |
| 99 | + def load_file_embeddings(self, filename, index_name): |
| 100 | + if self.check_existing_file(filename, index_name): |
| 101 | + print(f"Arquivo {filename} já carregado") |
| 102 | + return None |
| 103 | + print(f"Carregando {filename}") |
| 104 | + loader = FixedUnstructuredFileLoader(filename, mode="paged", post_processors = [])#replace_art, clean_extra_whitespace |
| 105 | + documents = loader.load() |
| 106 | + text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) |
| 107 | + texts = text_splitter.split_documents(documents) |
| 108 | + |
| 109 | + #dirty fix for pdf coordinates |
| 110 | + #ao invés disso ele precisa iterar e criar os datatypes correspondentes pra classe |
| 111 | + clear_texts = [] |
| 112 | + for index,text in enumerate(texts): |
| 113 | + if text.metadata.get('coordinates'): |
| 114 | + texts[index].metadata['coordinates'] = None |
| 115 | + |
| 116 | + embeddings = OpenAIEmbeddings() |
| 117 | + |
| 118 | + |
| 119 | + print("Subindo no Weaviate...") |
| 120 | + db = Weaviate.from_documents(texts, embedding=None, index_name=index_name, client=self.client, by_text=False) |
| 121 | + |
| 122 | + def build_tool(self, index_name, description): |
| 123 | + print("Construindo ferramenta") |
| 124 | + from langchain.retrievers import WeaviateHybridSearchRetriever |
| 125 | + retriever = WeaviateHybridSearchRetriever( |
| 126 | + client=self.client, |
| 127 | + index_name=index_name, |
| 128 | + text_key="text", |
| 129 | + attributes=[], |
| 130 | + create_schema_if_missing=False |
| 131 | + ) |
| 132 | + |
| 133 | + tool_fn = RetrievalQA.from_chain_type( |
| 134 | + llm=self.llm, chain_type="stuff", retriever=retriever |
| 135 | + ) |
| 136 | + |
| 137 | + tool = Tool(name=f"Biblioteca {index_name}", |
| 138 | + func=tool_fn.run, |
| 139 | + description=description) |
| 140 | + |
| 141 | + return tool |
| 142 | + |
| 143 | + def generate_tools_for_library(self, library_path): |
| 144 | + print("Generating tools for library...") |
| 145 | + subfolders = [f for f in os.listdir(library_path) if os.path.isdir(os.path.join(library_path, f)) and not f.startswith('.')] |
| 146 | + for index_name in tqdm(subfolders, desc="Processing subfolders"): |
| 147 | + index_path = os.path.join(library_path, index_name) |
| 148 | + index_name_camel_case = ''.join(word.capitalize() for word in index_name.split('_')) |
| 149 | + description_file_path = os.path.join(index_path, 'description.txt') |
| 150 | + if os.path.exists(description_file_path): |
| 151 | + with open(description_file_path, 'r') as description_file: |
| 152 | + description = description_file.read().strip() |
| 153 | + else: |
| 154 | + print(f"Warning: description.txt not found in {index_path}. Skipping.") |
| 155 | + continue |
| 156 | + for filename in os.listdir(index_path): |
| 157 | + file_path = os.path.join(index_path, filename) |
| 158 | + if os.path.isfile(file_path) and filename != 'description.txt': |
| 159 | + self.load_file_embeddings(file_path, index_name_camel_case) |
| 160 | + tool = self.build_tool(index_name_camel_case, description) |
| 161 | + self.tools.append(tool) |
| 162 | + return self.tools |
| 163 | + |
| 164 | + |
0 commit comments