Download EmbeddingManager.py from uiynyny/llama3RAG: direct link, hf CLI and curl.
- Browser
- Download file 2.34 kB
-
https://huggingface.co/spaces/uiynyny/llama3RAG/resolve/main/EmbeddingManager.py
- Command line
-
hf download hf://spaces/uiynyny/llama3RAG/EmbeddingManager.py
-
curl -L -o EmbeddingManager.py https://huggingface.co/spaces/uiynyny/llama3RAG/resolve/main/EmbeddingManager.py
2.34 kB
| import os | |
| from langchain_community.document_loaders import UnstructuredPDFLoader | |
| from langchain_pinecone import PineconeVectorStore | |
| from langchain_huggingface import HuggingFaceEmbeddings | |
| from langchain_text_splitters import RecursiveCharacterTextSplitter | |
| from pinecone import Pinecone | |
| class EmbeddingManager: | |
| def __init__( | |
| self, | |
| model_name: str = "BAAI/bge-small-en", | |
| device: str = 'cpu', | |
| encode_kwargs: dict = None, | |
| host: str = None, | |
| api_key: str = None, | |
| ) -> None: | |
| self.model_name = model_name | |
| self.device = device | |
| self.host = host or os.getenv("PINECONE_HOST") | |
| self.api_key = api_key or os.getenv("PINECONE_API_KEY") | |
| if not self.host or not self.api_key: | |
| raise RuntimeError( | |
| "Provide PINECONE_HOST and PINECONE_API_KEY." | |
| ) | |
| if encode_kwargs is None: | |
| encode_kwargs = {"normalize_embeddings": True} | |
| self.encode_kwargs = encode_kwargs | |
| self.embeddings = HuggingFaceEmbeddings( | |
| model_name=self.model_name, | |
| model_kwargs={"device": self.device}, | |
| encode_kwargs=self.encode_kwargs, | |
| ) | |
| def create_embeddings(self, pdf_path): | |
| if not os.path.exists(pdf_path): | |
| raise FileNotFoundError(f"PDF file not found: {pdf_path}") | |
| loader = UnstructuredPDFLoader(pdf_path) | |
| docs = loader.load() | |
| if not docs: | |
| raise ValueError(f"No documents found in PDF: {pdf_path}") | |
| text_splitter = RecursiveCharacterTextSplitter( | |
| chunk_size=1000, chunk_overlap=250) | |
| splits = text_splitter.split_documents(docs) | |
| if not splits: | |
| raise ValueError("No text splits created from the documents.") | |
| try: | |
| pinecone = Pinecone(api_key=self.api_key) | |
| vector_store = PineconeVectorStore( | |
| index=pinecone.Index(host=self.host), | |
| embedding=self.embeddings, | |
| ) | |
| vector_store.add_documents( | |
| documents=splits, | |
| ) | |
| except Exception as e: | |
| raise RuntimeError(f"Error creating vector store: {e}") | |
| return 0 | |
| if __name__ == "__main__": | |
| manager = EmbeddingManager() | |
| manager.create_embeddings("0ac948a1fc1a65ea7c7dbcddb232cbaf.pdf") | |