TextScout2 / app.py
CarolineDelva's picture
Update app.py
0a74639 verified
Raw History Blame Contribute Delete
6.22 kB
import os
import zipfile
import json
from fileconverter import convert_pdf_file_to_txt_file
from docx import Document
import gradio as gr
from dotenv import load_dotenv
from huggingface_hub import InferenceClient
from sentence_transformers import SentenceTransformer
from sklearn.metrics.pairwise import cosine_similarity
from huggingface_hub import HfApi
api = HfApi()
models = api.list_models()
print(models)
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
MAX_FILE_SIZE_MB = 100
class InformationRetrieval:
def __init__(self, filepaths):
self.text_data = []
self.filepaths = filepaths
for filepath in self.filepaths:
try:
content = self.read_file_with_encoding(filepath, 'utf-8')
except (UnicodeDecodeError, ValueError):
content = self.read_binary_or_convert(filepath)
if not content.startswith("Error processing file"):
self.text_data.append(content)
self.model = SentenceTransformer('all-MiniLM-L6-v2')
def read_file_with_encoding(self, filepath, encoding):
try:
with open(filepath, 'r', encoding=encoding, errors='ignore') as file:
return file.read()
except Exception as e:
print(f"Error reading {filepath} with encoding {encoding}: {e}")
raise e
def read_binary_or_convert(self, filepath):
try:
if filepath.lower().endswith('.pdf'):
return convert_pdf_file_to_txt_file(filepath)
elif filepath.lower().endswith('.docx'):
return self.convert_docx_file_to_txt_file(filepath)
else:
with open(filepath, 'rb') as file:
return file.read(512).decode(errors='ignore')
except Exception as e:
print(f"Error converting {filepath}: {e}")
return f"Error processing file: {filepath}"
@staticmethod
def convert_docx_file_to_txt_file(filepath):
try:
doc = Document(filepath)
return "\n".join(paragraph.text for paragraph in doc.paragraphs)
except Exception as e:
print(f"Error converting DOCX file {filepath}: {e}")
return f"Error processing DOCX file: {filepath}"
def encode_and_retrieve(self, query):
if not self.model:
return {"error": "Model initialization failed."}
query_embedding = self.model.encode([query]).reshape(1, -1)
embeddings_dict = {}
for i, text in enumerate(self.text_data):
truncated_text = text[:1000]
doc_embedding = self.model.encode([truncated_text]).reshape(1, -1)
similarity = cosine_similarity(query_embedding, doc_embedding)[0][0]
embeddings_dict[self.filepaths[i]] = similarity
return sorted(embeddings_dict.items(), key=lambda x: x[1], reverse=True)
def process_zip_file(zip_file):
if not os.path.exists("extracted_files"):
os.makedirs("extracted_files")
try:
with zipfile.ZipFile(zip_file.name, 'r') as zip_ref:
zip_ref.extractall("extracted_files")
filepaths = []
total_size = 0
for filename in zip_ref.namelist():
if "__MACOSX" in filename or filename.startswith(".DS_Store") or filename.startswith("."):
continue
file_path = os.path.join("extracted_files", filename)
if os.path.isdir(file_path):
continue
total_size += os.path.getsize(file_path)
if total_size > MAX_FILE_SIZE_MB * 1024 * 1024:
return {"error": f"Total file size exceeds {MAX_FILE_SIZE_MB}MB. Please upload smaller files."}
filepaths.append(file_path)
return filepaths
except Exception as e:
return {"error": str(e)}
class ChatBot:
def __init__(self, text_data):
self.text_data = "\n".join(text_data)
def answer_question(self, question):
prompt = f"Given the following text data, answer the question:\n\n{self.text_data}\n\nQuestion: {question}\nAnswer:"
try:
response = client.text_generation(prompt)
generated_text = response.get("generated_text", "No response generated")
return generated_text
except Exception as e:
return f"An error occurred: {str(e)}"
def chatbot_response(zip_file, user_input):
if not zip_file:
return {"error": "No .zip file provided."}
filepaths = process_zip_file(zip_file)
if "error" in filepaths:
return filepaths
ir_model = InformationRetrieval(filepaths)
chatbot = ChatBot(ir_model.text_data)
response = chatbot.answer_question(user_input)
return response
def respond(zip_file, user_input):
if not zip_file:
return {"error": "No .zip file provided."}
filepaths = process_zip_file(zip_file)
if "error" in filepaths:
return filepaths
ir_model = InformationRetrieval(filepaths)
return ir_model.encode_and_retrieve(user_input)
demo = gr.Blocks()
with demo:
gr.Markdown("### Document Information Retrieval and Chatbot")
with gr.Tab("Upload Files and Retrieve Info"):
with gr.Row():
zip_input = gr.File(type="filepath", label="Upload .zip Folder")
query_input = gr.Textbox(label="Enter your query")
retrieve_button = gr.Button("Retrieve")
retrieve_output = gr.JSON(label="Results")
retrieve_button.click(
fn=respond,
inputs=[zip_input, query_input],
outputs=retrieve_output
)
with gr.Tab("Chatbot"):
with gr.Row():
zip_input_chat = gr.File(type="filepath", label="Upload .zip Folder")
chat_input = gr.Textbox(label="Ask a question")
chat_button = gr.Button("Ask")
chat_output = gr.Textbox(label="Chatbot Response")
chat_button.click(
fn=chatbot_response,
inputs=[zip_input_chat, chat_input],
outputs=chat_output
)
if __name__ == "__main__":
demo.launch(share=True)