Spaces:
Sleeping
Sleeping
Update app.py
Browse files2 unmodified lines34567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301312 unmodified linesimport osimport pandas as pdfrom sklearn.metrics.pairwise import cosine_similarityfrom InstructorEmbedding import INSTRUCTOR"""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")class InformationRetrieval():def __init__(self, datapath):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)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: ")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_dictmytextir = 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.contentresponse += tokenyield 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)",),],)if __name__ == "__main__":demo.launch()2 unmodified lines34567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491502 unmodified linesimport osimport pandas as pdfrom sklearn.metrics.pairwise import cosine_similarityfrom sentence_transformers import SentenceTransformerfrom dotenv import load_dotenvfrom huggingface_hub import HfApiimport zipfileimport jsonfrom sklearn.metrics.pairwise import cosine_similarityload_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_KEYapi = 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 = filepathstry: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 = Nonedef 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(f"Error encoding query: {e}")return {}embeddings_dict = {}for i, text in enumerate(self.text_data):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]] = similarityexcept 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_dictdef process_zip_file(zip_file):try:zip_filepath = zip_file.namefilepaths = []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('._'):continueif 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 filepathsextracted_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(share=True)
app.py+133-114