Spaces:
Build error

AmazonVM / app.py
mukulmitra82's picture
Update app.py
c6f31fd verified
Raw History Blame Contribute Delete
4.84 kB
import gradio as gr
import os
import PyPDF2
from unstructured.partition.auto import partition
import nltk
from docx import Document
import requests
from sentence_transformers import SentenceTransformer, util
# Ensure NLTK data path is set correctly
nltk.data.path.append("/home/user/nltk_data")
# Download required NLTK resources
nltk.download("punkt")
nltk.download("punkt_tab")
# Get API Key from Hugging Face secrets
gemini_api_key = os.getenv("GEMINI_API_KEY")
# Load pre-trained embedding model
embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
# Function to load and extract text from files
def load_and_extract_text(file_path):
try:
if file_path.endswith(".pdf"):
with open(file_path, "rb") as file:
reader = PyPDF2.PdfReader(file)
return "\n".join(page.extract_text() for page in reader.pages if page.extract_text())
elif file_path.endswith(".docx"):
doc = Document(file_path)
return "\n".join(para.text for para in doc.paragraphs)
elif file_path.endswith(".txt"):
with open(file_path, "r", encoding="utf-8") as file:
return file.read()
else:
elements = partition(file_path)
return "\n".join(str(el) for el in elements)
except Exception as e:
print(f"Error processing {file_path}: {e}")
return ""
# Function to dynamically load all resources
def load_resources(folder_path="."):
resources = {}
for filename in os.listdir(folder_path):
if filename.startswith(".") or filename.endswith((".py", ".md", ".gitattributes")):
continue
file_path = os.path.join(folder_path, filename)
if os.path.isfile(file_path):
print(f"Processing: {filename}")
resources[filename] = load_and_extract_text(file_path)
return resources
# Load resources initially
resources = load_resources()
# Function to find the most relevant section using semantic search
def find_most_relevant_section(query, text):
sections = text.split("\n\n")
section_embeddings = embedding_model.encode(sections)
query_embedding = embedding_model.encode([query])
similarities = util.cos_sim(query_embedding, section_embeddings)
return sections[similarities.argmax()]
# Function to query Gemini API
def query_gemini_api(context, user_input):
url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key={gemini_api_key}"
headers = {"Content-Type": "application/json"}
data = {
"contents": [
{"parts": [{"text": f"Based on this information, answer the user's question: '{user_input}'. If insufficient, say 'I couldn't find relevant information in the uploaded files.'\n\n{context}"}]}
]
}
try:
response = requests.post(url, json=data, headers=headers)
response.raise_for_status()
response_data = response.json()
if "candidates" in response_data and len(response_data["candidates"]) > 0:
return response_data["candidates"][0]["content"]["parts"][0]["text"].strip()
return None
except requests.exceptions.RequestException as e:
print(f"API request failed: {e}")
return None
# Function to generate chatbot response
def generate_bot_response(user_input):
global resources
resources = load_resources() # Reload resources dynamically
relevant_text = ""
for filename, text in resources.items():
relevant_section = find_most_relevant_section(user_input, text)
relevant_text += f"\n\n**From {filename}:**\n{relevant_section}\n"
bot_response = query_gemini_api(relevant_text, user_input) if relevant_text else "I couldn't find relevant information."
return bot_response
# Function to handle chat interaction
def chatbot_response(message, history):
bot_response = generate_bot_response(message)
print("Bot Response:", bot_response)
history.append({"role": "user", "content": message})
history.append({"role": "assistant", "content": bot_response})
return history, ""
# Function to refresh resources manually
def refresh_resources():
global resources
resources = load_resources()
return "Resources reloaded!"
# Define Gradio interface
with gr.Blocks() as demo:
chatbot = gr.Chatbot(type="messages")
msg = gr.Textbox(placeholder="Ask something...", show_label=False)
submit_button = gr.Button("Submit")
refresh_button = gr.Button("Refresh Resources")
state = gr.State([])
msg.submit(chatbot_response, inputs=[msg, state], outputs=[chatbot, msg])
submit_button.click(chatbot_response, inputs=[msg, state], outputs=[chatbot, msg])
refresh_button.click(refresh_resources, outputs=None)
# Launch the Gradio app
demo.launch(debug=True)