Spaces:
Build error
Build error
File size: 4,842 Bytes
4c5fc22 b2bb72d 77c29ec 18c9d75 c375d2a 8a185e7 77c29ec 18c9d75 0906106 18c9d75 0906106 3af7066 a478bdb 3af7066 8a185e7 3af7066 b2bb72d 77c29ec 3af7066 77c29ec 3af7066 77c29ec 3af7066 77c29ec 3af7066 77c29ec 3af7066 77c29ec b2bb72d 3af7066 b2bb72d 3af7066 18c9d75 b2bb72d 3af7066 b2bb72d 3af7066 b2bb72d 8a185e7 3af7066 8a185e7 3af7066 8a185e7 c375d2a 3af7066 c375d2a 3af7066 c375d2a 3af7066 c375d2a 3af7066 c375d2a 3af7066 0906106 3af7066 b2bb72d 8a185e7 b2bb72d 3af7066 c6f31fd b2bb72d 3af7066 ba95c9e d685e55 3af7066 0ec476c b2bb72d 3af7066 0ec476c 3af7066 45792ac 3af7066 0906106 3af7066 ba95c9e 3af7066 ba95c9e d685e55 3af7066 77fdde6 d6e6b91 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 | 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)
|