Spaces:
Sleeping
Sleeping
Download app.py from CarolineDelva/TextScout: direct link, hf CLI and curl.
- Browser
- Download file 4.34 kB
-
https://huggingface.co/spaces/CarolineDelva/TextScout/resolve/main/app.py
- Command line
-
hf download hf://spaces/CarolineDelva/TextScout/app.py
-
curl -L -o app.py https://huggingface.co/spaces/CarolineDelva/TextScout/resolve/main/app.py
4.34 kB
| import gradio as gr | |
| from huggingface_hub import InferenceClient | |
| import os | |
| import pandas as pd | |
| from sklearn.metrics.pairwise import cosine_similarity | |
| from sentence_transformers import SentenceTransformer | |
| from huggingface_hub import HfApi | |
| import zipfile | |
| import json | |
| from sklearn.metrics.pairwise import cosine_similarity | |
| api = HfApi() | |
| models = api.list_models() | |
| print(models) | |
| client = InferenceClient("HuggingFaceH4/zephyr-7b-beta") | |
| class InformationRetrieval: | |
| def __init__(self, filepaths): | |
| self.text_data = [] | |
| 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(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]] = 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(share=True) | |