Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,129 +3,148 @@ from huggingface_hub import InferenceClient
|
|
| 3 |
import os
|
| 4 |
import pandas as pd
|
| 5 |
from sklearn.metrics.pairwise import cosine_similarity
|
| 6 |
-
from
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
-
"""
|
| 9 |
-
For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
|
| 10 |
-
"""
|
| 11 |
-
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
| 12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
|
|
|
| 14 |
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
self.text_data = []
|
| 19 |
-
self.filepaths =
|
| 20 |
-
try:
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
except Exception as e:
|
| 37 |
-
print(e)
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
model = INSTRUCTOR('hkunlp/instructor-large')
|
| 41 |
-
|
| 42 |
-
if whatineed is None:
|
| 43 |
-
whatineed = input("Which document are you looking to retrieve: ")
|
| 44 |
-
|
| 45 |
embeddings_dict = {}
|
| 46 |
-
|
| 47 |
-
embeddings_a = model.encode([['The text I provide:', whatineed]])
|
| 48 |
-
|
| 49 |
for i, text in enumerate(self.text_data):
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
def
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
):
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
gr.
|
| 118 |
-
gr.
|
| 119 |
-
gr.Slider(
|
| 120 |
-
minimum=0.1,
|
| 121 |
-
maximum=1.0,
|
| 122 |
-
value=0.95,
|
| 123 |
-
step=0.05,
|
| 124 |
-
label="Top-p (nucleus sampling)",
|
| 125 |
-
),
|
| 126 |
],
|
|
|
|
| 127 |
)
|
| 128 |
|
| 129 |
-
|
| 130 |
if __name__ == "__main__":
|
| 131 |
-
demo.launch()
|
|
|
|
| 3 |
import os
|
| 4 |
import pandas as pd
|
| 5 |
from sklearn.metrics.pairwise import cosine_similarity
|
| 6 |
+
from sentence_transformers import SentenceTransformer
|
| 7 |
+
from dotenv import load_dotenv
|
| 8 |
+
from huggingface_hub import HfApi
|
| 9 |
+
import zipfile
|
| 10 |
+
import json
|
| 11 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
| 14 |
+
|
| 15 |
+
load_dotenv()
|
| 16 |
+
|
| 17 |
+
API_KEY = os.getenv("api_key")
|
| 18 |
+
|
| 19 |
+
if API_KEY is None:
|
| 20 |
+
raise ValueError("API key not found. Make sure you have a valid .env file with the 'api_key' variable.")
|
| 21 |
|
| 22 |
+
os.environ["HUGGINGFACE_HUB_TOKEN"] = API_KEY
|
| 23 |
|
| 24 |
+
api = HfApi()
|
| 25 |
+
|
| 26 |
+
models = api.list_models()
|
| 27 |
+
print(models)
|
| 28 |
+
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta", token=API_KEY)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class InformationRetrieval:
|
| 32 |
+
def __init__(self, filepaths):
|
| 33 |
+
|
| 34 |
self.text_data = []
|
| 35 |
+
self.filepaths = filepaths
|
| 36 |
+
try:
|
| 37 |
+
for filepath in self.filepaths:
|
| 38 |
+
|
| 39 |
+
try:
|
| 40 |
+
with open(filepath, 'r', encoding='utf-8') as file:
|
| 41 |
+
content = file.read()
|
| 42 |
+
except UnicodeDecodeError:
|
| 43 |
+
with open(filepath, 'r', encoding='ISO-8859-1') as file:
|
| 44 |
+
content = file.read()
|
| 45 |
+
self.text_data.append(content)
|
| 46 |
+
print("Files loaded successfully.")
|
| 47 |
+
except Exception as e:
|
| 48 |
+
print(f"Error reading files: {e}")
|
| 49 |
+
self.text_data = []
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
try:
|
| 53 |
+
self.model = SentenceTransformer('all-MiniLM-L6-v2')
|
| 54 |
+
print("Sentence Transformer model loaded successfully.")
|
| 55 |
+
except Exception as e:
|
| 56 |
+
print(f"Error loading model: {e}")
|
| 57 |
+
self.model = None
|
| 58 |
+
def encode_and_retrieve(self, query):
|
| 59 |
+
if not query:
|
| 60 |
+
query = "default text"
|
| 61 |
+
|
| 62 |
+
if not self.model:
|
| 63 |
+
print("Model is not initialized.")
|
| 64 |
+
return {}
|
| 65 |
+
|
| 66 |
+
try:
|
| 67 |
+
query_embedding = self.model.encode([query])
|
| 68 |
+
query_embedding = query_embedding.reshape(1, -1)
|
| 69 |
except Exception as e:
|
| 70 |
+
print(f"Error encoding query: {e}")
|
| 71 |
+
return {}
|
| 72 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
embeddings_dict = {}
|
| 74 |
+
|
|
|
|
|
|
|
| 75 |
for i, text in enumerate(self.text_data):
|
| 76 |
+
try:
|
| 77 |
+
truncated_text = text[:1000]
|
| 78 |
+
|
| 79 |
+
doc_embedding = self.model.encode([truncated_text])
|
| 80 |
+
|
| 81 |
+
if doc_embedding.ndim == 3:
|
| 82 |
+
doc_embedding = doc_embedding.reshape(doc_embedding.shape[0], -1)
|
| 83 |
+
elif doc_embedding.ndim == 1:
|
| 84 |
+
doc_embedding = doc_embedding.reshape(1, -1)
|
| 85 |
+
|
| 86 |
+
similarity = cosine_similarity(query_embedding, doc_embedding)[0][0]
|
| 87 |
+
embeddings_dict[self.filepaths[i]] = similarity
|
| 88 |
+
except Exception as e:
|
| 89 |
+
print(f"Error processing document {self.filepaths[i]}: {e}")
|
| 90 |
+
|
| 91 |
+
sorted_embeddings = sorted(embeddings_dict.items(), key=lambda item: item[1], reverse=True)
|
| 92 |
+
|
| 93 |
+
result_dict = {path: score for path, score in sorted_embeddings}
|
| 94 |
+
return result_dict
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def process_zip_file(zip_file):
|
| 99 |
+
try:
|
| 100 |
+
zip_filepath = zip_file.name
|
| 101 |
+
filepaths = []
|
| 102 |
+
with zipfile.ZipFile(zip_filepath, 'r') as zip_ref:
|
| 103 |
+
zip_ref.extractall("extracted_files")
|
| 104 |
+
for filename in zip_ref.namelist():
|
| 105 |
+
if filename.startswith('__MACOSX/') or filename.startswith('._'):
|
| 106 |
+
continue
|
| 107 |
+
if filename.endswith('.txt'):
|
| 108 |
+
filepaths.append(os.path.join("extracted_files", filename))
|
| 109 |
+
return {"files": filepaths}
|
| 110 |
+
except Exception as e:
|
| 111 |
+
return {"error": f"Error processing zip file: {e}"}
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def respond(zip_file, query):
|
| 116 |
+
if zip_file is None:
|
| 117 |
+
return {"error": "Please upload a .zip file containing the data."}
|
| 118 |
+
|
| 119 |
+
filepaths = process_zip_file(zip_file)
|
| 120 |
+
if "error" in filepaths:
|
| 121 |
+
return filepaths
|
| 122 |
+
|
| 123 |
+
extracted_files = filepaths["files"]
|
| 124 |
+
print(f"Extracted files: {extracted_files}")
|
| 125 |
+
|
| 126 |
+
ir_model = InformationRetrieval(extracted_files)
|
| 127 |
+
|
| 128 |
+
ir_results = ir_model.encode_and_retrieve(query)
|
| 129 |
+
|
| 130 |
+
if not ir_results:
|
| 131 |
+
return json.dumps({"error": "No results found for the given query."})
|
| 132 |
+
|
| 133 |
+
results = []
|
| 134 |
+
for filepath, score in ir_results.items():
|
| 135 |
+
results.append({"score": float(score), "file": filepath})
|
| 136 |
+
|
| 137 |
+
return json.dumps({"results": results})
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
demo = gr.Interface(
|
| 141 |
+
fn=respond,
|
| 142 |
+
inputs=[
|
| 143 |
+
gr.File(type="filepath", label="Upload .zip Folder"),
|
| 144 |
+
gr.Textbox(label="Enter your query")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
],
|
| 146 |
+
outputs=gr.JSON(),
|
| 147 |
)
|
| 148 |
|
|
|
|
| 149 |
if __name__ == "__main__":
|
| 150 |
+
demo.launch(share=True)
|