Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -18,7 +18,129 @@ from langchain_text_splitters import (
|
|
| 18 |
from typing import List, Dict, Any
|
| 19 |
import pandas as pd
|
| 20 |
|
| 21 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
def compare_embeddings(file, query, model_types, model_names, split_strategy, chunk_size, overlap_size, custom_separators, vector_store_type, search_type, top_k):
|
| 24 |
all_results = []
|
|
|
|
| 18 |
from typing import List, Dict, Any
|
| 19 |
import pandas as pd
|
| 20 |
|
| 21 |
+
|
| 22 |
+
nltk.download('punkt', quiet=True)
|
| 23 |
+
|
| 24 |
+
FILES_DIR = './files'
|
| 25 |
+
|
| 26 |
+
MODELS = {
|
| 27 |
+
'HuggingFace': {
|
| 28 |
+
'e5-base-de': "danielheinz/e5-base-sts-en-de",
|
| 29 |
+
'paraphrase-miniLM': "paraphrase-multilingual-MiniLM-L12-v2",
|
| 30 |
+
'paraphrase-mpnet': "paraphrase-multilingual-mpnet-base-v2",
|
| 31 |
+
'gte-large': "gte-large",
|
| 32 |
+
'gbert-base': "gbert-base"
|
| 33 |
+
},
|
| 34 |
+
'OpenAI': {
|
| 35 |
+
'text-embedding-ada-002': "text-embedding-ada-002"
|
| 36 |
+
},
|
| 37 |
+
'Cohere': {
|
| 38 |
+
'embed-multilingual-v2.0': "embed-multilingual-v2.0"
|
| 39 |
+
}
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
class FileHandler:
|
| 43 |
+
@staticmethod
|
| 44 |
+
def extract_text(file_path):
|
| 45 |
+
ext = os.path.splitext(file_path)[-1].lower()
|
| 46 |
+
if ext == '.pdf':
|
| 47 |
+
return FileHandler._extract_from_pdf(file_path)
|
| 48 |
+
elif ext == '.docx':
|
| 49 |
+
return FileHandler._extract_from_docx(file_path)
|
| 50 |
+
elif ext == '.txt':
|
| 51 |
+
return FileHandler._extract_from_txt(file_path)
|
| 52 |
+
else:
|
| 53 |
+
raise ValueError(f"Unsupported file type: {ext}")
|
| 54 |
+
|
| 55 |
+
@staticmethod
|
| 56 |
+
def _extract_from_pdf(file_path):
|
| 57 |
+
with pdfplumber.open(file_path) as pdf:
|
| 58 |
+
return ' '.join([page.extract_text() for page in pdf.pages])
|
| 59 |
+
|
| 60 |
+
@staticmethod
|
| 61 |
+
def _extract_from_docx(file_path):
|
| 62 |
+
doc = docx.Document(file_path)
|
| 63 |
+
return ' '.join([para.text for para in doc.paragraphs])
|
| 64 |
+
|
| 65 |
+
@staticmethod
|
| 66 |
+
def _extract_from_txt(file_path):
|
| 67 |
+
with open(file_path, 'r', encoding='utf-8') as f:
|
| 68 |
+
return f.read()
|
| 69 |
+
|
| 70 |
+
def get_embedding_model(model_type, model_name):
|
| 71 |
+
if model_type == 'HuggingFace':
|
| 72 |
+
return HuggingFaceEmbeddings(model_name=MODELS[model_type][model_name])
|
| 73 |
+
elif model_type == 'OpenAI':
|
| 74 |
+
return OpenAIEmbeddings(model=MODELS[model_type][model_name])
|
| 75 |
+
elif model_type == 'Cohere':
|
| 76 |
+
return CohereEmbeddings(model=MODELS[model_type][model_name])
|
| 77 |
+
else:
|
| 78 |
+
raise ValueError(f"Unsupported model type: {model_type}")
|
| 79 |
+
|
| 80 |
+
def get_text_splitter(split_strategy, chunk_size, overlap_size, custom_separators=None):
|
| 81 |
+
if split_strategy == 'token':
|
| 82 |
+
return TokenTextSplitter(chunk_size=chunk_size, chunk_overlap=overlap_size)
|
| 83 |
+
elif split_strategy == 'recursive':
|
| 84 |
+
return RecursiveCharacterTextSplitter(
|
| 85 |
+
chunk_size=chunk_size,
|
| 86 |
+
chunk_overlap=overlap_size,
|
| 87 |
+
separators=custom_separators or ["\n\n", "\n", " ", ""]
|
| 88 |
+
)
|
| 89 |
+
else:
|
| 90 |
+
raise ValueError(f"Unsupported split strategy: {split_strategy}")
|
| 91 |
+
|
| 92 |
+
def get_vector_store(store_type, texts, embedding_model):
|
| 93 |
+
if store_type == 'FAISS':
|
| 94 |
+
return FAISS.from_texts(texts, embedding_model)
|
| 95 |
+
elif store_type == 'Chroma':
|
| 96 |
+
return Chroma.from_texts(texts, embedding_model)
|
| 97 |
+
else:
|
| 98 |
+
raise ValueError(f"Unsupported vector store type: {store_type}")
|
| 99 |
+
|
| 100 |
+
def get_retriever(vector_store, search_type, search_kwargs=None):
|
| 101 |
+
if search_type == 'similarity':
|
| 102 |
+
return vector_store.as_retriever(search_type="similarity", search_kwargs=search_kwargs)
|
| 103 |
+
elif search_type == 'mmr':
|
| 104 |
+
return vector_store.as_retriever(search_type="mmr", search_kwargs=search_kwargs)
|
| 105 |
+
else:
|
| 106 |
+
raise ValueError(f"Unsupported search type: {search_type}")
|
| 107 |
+
|
| 108 |
+
def process_files(file_path, model_type, model_name, split_strategy, chunk_size, overlap_size, custom_separators):
|
| 109 |
+
if file_path:
|
| 110 |
+
text = FileHandler.extract_text(file_path)
|
| 111 |
+
else:
|
| 112 |
+
text = ""
|
| 113 |
+
for file in os.listdir(FILES_DIR):
|
| 114 |
+
file_path = os.path.join(FILES_DIR, file)
|
| 115 |
+
text += FileHandler.extract_text(file_path)
|
| 116 |
+
|
| 117 |
+
text_splitter = get_text_splitter(split_strategy, chunk_size, overlap_size, custom_separators)
|
| 118 |
+
chunks = text_splitter.split_text(text)
|
| 119 |
+
|
| 120 |
+
embedding_model = get_embedding_model(model_type, model_name)
|
| 121 |
+
|
| 122 |
+
return chunks, embedding_model, len(text.split())
|
| 123 |
+
|
| 124 |
+
def search_embeddings(chunks, embedding_model, vector_store_type, search_type, query, top_k):
|
| 125 |
+
vector_store = get_vector_store(vector_store_type, chunks, embedding_model)
|
| 126 |
+
retriever = get_retriever(vector_store, search_type, {"k": top_k})
|
| 127 |
+
|
| 128 |
+
start_time = time.time()
|
| 129 |
+
results = retriever.get_relevant_documents(query)
|
| 130 |
+
end_time = time.time()
|
| 131 |
+
|
| 132 |
+
return results, end_time - start_time, vector_store
|
| 133 |
+
|
| 134 |
+
def calculate_statistics(results, search_time, vector_store, num_tokens, embedding_model):
|
| 135 |
+
return {
|
| 136 |
+
"num_results": len(results),
|
| 137 |
+
"avg_content_length": sum(len(doc.page_content) for doc in results) / len(results) if results else 0,
|
| 138 |
+
"search_time": search_time,
|
| 139 |
+
"vector_store_size": vector_store._index.ntotal if hasattr(vector_store, '_index') else "N/A",
|
| 140 |
+
"num_documents": len(vector_store.docstore._dict),
|
| 141 |
+
"num_tokens": num_tokens,
|
| 142 |
+
"embedding_vocab_size": embedding_model.client.get_vocab_size() if hasattr(embedding_model, 'client') and hasattr(embedding_model.client, 'get_vocab_size') else "N/A"
|
| 143 |
+
}
|
| 144 |
|
| 145 |
def compare_embeddings(file, query, model_types, model_names, split_strategy, chunk_size, overlap_size, custom_separators, vector_store_type, search_type, top_k):
|
| 146 |
all_results = []
|