Spaces:
Sleeping
Sleeping
Update app.py
Browse files2 unmodified lines345667891011891011121314151617181920212223151617242526272829303132333419202122232425262728293031323334353536373839404142434445464748495051525354555657585960616263646566676869373839404142434470717273464748747550515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241257677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481291491311502 unmodified linesimport os import pandas as pd from sklearn.metrics.pairwise import cosine_similarityfrom InstructorEmbedding import INSTRUCTORfrom sentence_transformers import SentenceTransformerfrom dotenv import load_dotenvfrom huggingface_hub import HfApiimport zipfileimport json
"""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"""client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
from sklearn.metrics.pairwise import cosine_similarity
load_dotenv()
API_KEY = os.getenv("api_key")
if API_KEY is None: raise ValueError("API key not found. Make sure you have a valid .env file with the 'api_key' variable.")
os.environ["HUGGINGFACE_HUB_TOKEN"] = API_KEY
class InformationRetrieval(): def __init__(self, datapath):api = HfApi()
models = api.list_models()print(models)client = InferenceClient("HuggingFaceH4/zephyr-7b-beta", token=API_KEY)
class InformationRetrieval: def __init__(self, filepaths): self.text_data = [] self.filepaths = [] try: if os.path.isdir(datapath): for text in os.listdir(datapath): fullpath = os.path.join(datapath, text) if text.endswith('.txt'): with open(fullpath, 'r', encoding='utf-8') as file: content = file.read() self.text_data.append(content) self.filepaths.append(fullpath) else: raise TypeError("This is not a right directory.") except FileNotFoundError as e: print(f"File not found: {e}") except TypeError as e: print(e) self.filepaths = filepaths try: for filepath in self.filepaths: try: with open(filepath, 'r', encoding='utf-8') as file: content = file.read() except UnicodeDecodeError: with open(filepath, 'r', encoding='ISO-8859-1') as file: content = file.read() self.text_data.append(content) print("Files loaded successfully.") except Exception as e: print(f"Error reading files: {e}") self.text_data = []
try: self.model = SentenceTransformer('all-MiniLM-L6-v2') print("Sentence Transformer model loaded successfully.") except Exception as e: print(f"Error loading model: {e}") self.model = None def encode_and_retrieve(self, query): if not query: query = "default text"
if not self.model: print("Model is not initialized.") return {}
try: query_embedding = self.model.encode([query]) query_embedding = query_embedding.reshape(1, -1) except Exception as e: print(e) def model(self, whatineed=None): model = INSTRUCTOR('hkunlp/instructor-large')
if whatineed is None: whatineed = input("Which document are you looking to retrieve: ") print(f"Error encoding query: {e}") return {}
embeddings_dict = {} embeddings_a = model.encode([['The text I provide:', whatineed]])
for i, text in enumerate(self.text_data): embeddings_b = model.encode([['The text I am searching through:', text]])
similarities = cosine_similarity(embeddings_a, embeddings_b)
embeddings_dict[self.filepaths[i]] = (embeddings_b, similarities) # print(f"Embeddings for '{self.filepaths[i]}': {embeddings_b}") sorted_embeddings = sorted(embeddings_dict.items(), key=lambda item: item[1][1][0][0], reverse=True)
empty_dict = {} for path, (embedding, similarity) in sorted_embeddings: #print(f"File Path: {path}, Similarity: {similarity[0][0]}") empty_dict[path] =similarity[0][0] print(empty_dict) return empty_dict
mytextir = InformationRetrieval('data')#mytextir.model()
def respond( message, history: list[tuple[str, str]], system_message, max_tokens, temperature, top_p,): ir_results = mytextir.model(message) messages = [{"role": "system", "content": system_message}] response = f"IR Results:\n{ir_results}\n\n"
for val in history: if val[0]: messages.append({"role": "user", "content": val[0]}) if val[1]: messages.append({"role": "assistant", "content": val[1]})
messages.append({"role": "user", "content": message})
for message in client.chat_completion( messages, max_tokens=max_tokens, stream=True, temperature=temperature, top_p=top_p, ): token = message.choices[0].delta.content
response += token yield response
"""For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface"""demo = gr.ChatInterface( respond, additional_inputs=[ gr.Textbox(value="You are a friendly Chatbot.", label="System message"), gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"), gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"), gr.Slider( minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)", ), try: truncated_text = text[:1000]
doc_embedding = self.model.encode([truncated_text])
if doc_embedding.ndim == 3: doc_embedding = doc_embedding.reshape(doc_embedding.shape[0], -1) elif doc_embedding.ndim == 1: doc_embedding = doc_embedding.reshape(1, -1)
similarity = cosine_similarity(query_embedding, doc_embedding)[0][0] embeddings_dict[self.filepaths[i]] = similarity except Exception as e: print(f"Error processing document {self.filepaths[i]}: {e}")
sorted_embeddings = sorted(embeddings_dict.items(), key=lambda item: item[1], reverse=True)
result_dict = {path: score for path, score in sorted_embeddings} return result_dict
def process_zip_file(zip_file): try: zip_filepath = zip_file.name filepaths = [] with zipfile.ZipFile(zip_filepath, 'r') as zip_ref: zip_ref.extractall("extracted_files") for filename in zip_ref.namelist(): if filename.startswith('__MACOSX/') or filename.startswith('._'): continue if filename.endswith('.txt'): filepaths.append(os.path.join("extracted_files", filename)) return {"files": filepaths} except Exception as e: return {"error": f"Error processing zip file: {e}"}
def respond(zip_file, query): if zip_file is None: return {"error": "Please upload a .zip file containing the data."}
filepaths = process_zip_file(zip_file) if "error" in filepaths: return filepaths
extracted_files = filepaths["files"] print(f"Extracted files: {extracted_files}")
ir_model = InformationRetrieval(extracted_files) ir_results = ir_model.encode_and_retrieve(query)
if not ir_results: return json.dumps({"error": "No results found for the given query."})
results = [] for filepath, score in ir_results.items(): results.append({"score": float(score), "file": filepath})
return json.dumps({"results": results})
demo = gr.Interface( fn=respond, inputs=[ gr.File(type="filepath", label="Upload .zip Folder"), gr.Textbox(label="Enter your query") ], outputs=gr.JSON(), )
if __name__ == "__main__": demo.launch() demo.launch(share=True)app.py+133-114