Spaces:
Build error
Build error
Update app.py
Browse files12345678910117 unmodified lines192021222324252627282930314 unmodified lines3637383940414243import gradio as grimport requests# Replace with your Gemini API keygemini_api_key = 'AIzaSyCJBozoq3J5jTemmn_XF6EnWpoRQkA8NCg'# Function to generate bot response from the Gemini APIdef generate_bot_response(user_input):url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key={gemini_api_key}"headers = {"Content-Type": "application/json",7 unmodified lines}response = requests.post(url, json=data, headers=headers)print("API Response:", response.text) # Debug: Print the raw API responseresponse_data = response.json()if "candidates" in response_data and len(response_data["candidates"]) > 0:bot_message = response_data["candidates"][0]["content"]["parts"][0]["text"].strip()print("Extracted Bot Message:", bot_message) # Debug: Print the extracted messagereturn bot_messageelse:return "Sorry, I couldn't generate a response."4 unmodified linesprint("Bot Response:", bot_response) # Debug: Print the bot's response# Update the history in the correct format for Gradiohistory.append({"role": "user", "content": message}) # Add user messagehistory.append({"role": "assistant", "content": bot_response}) # Add bot responseprint("Updated History:", history) # Debug: Print the updated historyreturn history, "" # Return updated history and clear the input box1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697 unmodified lines777879808182838485864 unmodified lines9192939495969798import gradio as grimport requestsimport osimport PyPDF2from docx import Documentfrom unstructured.partition.auto import partition# Replace with your Gemini API keygemini_api_key = 'AIzaSyCJBozoq3J5jTemmn_XF6EnWpoRQkA8NCg'# Function to load and extract text from a filedef load_and_extract_text(file_path):if file_path.endswith(".pdf"):# Extract text from PDFwith open(file_path, "rb") as file:reader = PyPDF2.PdfReader(file)text = ""for page in reader.pages:text += page.extract_text()return textelif file_path.endswith(".docx"):# Extract text from DOCXdoc = Document(file_path)text = "\n".join([para.text for para in doc.paragraphs])return textelif file_path.endswith(".txt"):# Extract text from TXTwith open(file_path, "r") as file:text = file.read()return textelse:# Use unstructured for other file typeselements = partition(file_path)text = "\n".join([str(el) for el in elements])return text# Function to load all resources from a folderdef load_resources(folder_path):resources = {}for filename in os.listdir(folder_path):file_path = os.path.join(folder_path, filename)if os.path.isfile(file_path):text = load_and_extract_text(file_path)resources[filename] = textreturn resources# Load resources from the current directory (or a specific folder)resources = load_resources(".")print("Loaded Resources:", list(resources.keys()))# Function to generate bot response from the Gemini APIdef generate_bot_response(user_input):# Step 1: Search the resources for relevant informationrelevant_text = ""for filename, text in resources.items():if user_input.lower() in text.lower():relevant_text += f"\n\nFrom {filename}:\n{text}\n"# Step 2: If relevant text is found, return itif relevant_text:return relevant_text# Step 3: If no relevant text is found, query the Gemini APIurl = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key={gemini_api_key}"headers = {"Content-Type": "application/json",7 unmodified lines}response = requests.post(url, json=data, headers=headers)response_data = response.json()if "candidates" in response_data and len(response_data["candidates"]) > 0:bot_message = response_data["candidates"][0]["content"]["parts"][0]["text"].strip()return bot_messageelse:return "Sorry, I couldn't generate a response."4 unmodified linesprint("Bot Response:", bot_response) # Debug: Print the bot's response# Update the history in the correct format for Gradiohistory.append({"role": "user", "content": message})history.append({"role": "assistant", "content": bot_response})print("Updated History:", history) # Debug: Print the updated historyreturn history, "" # Return updated history and clear the input box
app.py+60-5