Spaces:
Runtime error
Runtime error
Upload
Browse files- utilities/step1.py +35 -0
utilities/step1.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from langchain.spaces import HuggingFaceSpaces
|
| 3 |
+
from langchain.document_loaders import DirectoryLoader, TextLoader
|
| 4 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 5 |
+
from langchain.embeddings import HuggingFaceEmbeddings
|
| 6 |
+
from langchain.vectorstores import FAISS
|
| 7 |
+
|
| 8 |
+
# Define the directory where the documents are located
|
| 9 |
+
directory = "./documents"
|
| 10 |
+
|
| 11 |
+
# Load the documents from the directory using LangChain
|
| 12 |
+
loader = DirectoryLoader(directory, glob="*.txt", loader_cls=TextLoader)
|
| 13 |
+
documents = loader.load()
|
| 14 |
+
|
| 15 |
+
# Split the text data into chunks for faster processing
|
| 16 |
+
splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
|
| 17 |
+
texts = splitter.split_documents(documents)
|
| 18 |
+
|
| 19 |
+
# Create a Hugging Face Embeddings object with the desired model name and device
|
| 20 |
+
model_name = "sentence-transformers/all-MiniLM-L6-v2"
|
| 21 |
+
device = "cpu"
|
| 22 |
+
embeddings = HuggingFaceEmbeddings(model_name, model_kwargs={"device": device})
|
| 23 |
+
|
| 24 |
+
# Use the Hugging Face Spaces API to create a new space based on the document texts
|
| 25 |
+
space_id = f"{os.environ['HUGGINGFACE_SPACES_API']}/{os.environ['HUGGINGFACE_SPACES_USERNAME']}"
|
| 26 |
+
hf_spaces = HuggingFaceSpaces(api_key=os.environ["HUGGINGFACE_SPACES_API"], username=os.environ["HUGGINGFACE_SPACES_USERNAME"])
|
| 27 |
+
response = hf_spaces.create_space(space_id, texts, embeddings)
|
| 28 |
+
|
| 29 |
+
# Save the space ID and token to environment variables
|
| 30 |
+
os.environ["HUGGINGFACE_SPACES_ID"] = response["spaceId"]
|
| 31 |
+
os.environ["HUGGINGFACE_SPACES_TOKEN"] = response["token"]
|
| 32 |
+
|
| 33 |
+
# Use the FAISS library to index the vectors generated by the Hugging Face model
|
| 34 |
+
db = FAISS.from_documents(texts, embeddings)
|
| 35 |
+
db.save_local("faiss_company")
|