import os import docx import requests import gradio as gr from io import BytesIO # ✅ API Key from Hugging Face Secrets API_KEY = os.getenv("GEMINI_API_KEY") # Set this in Hugging Face secrets! # ✅ Function to Download File from Link def download_file_from_link(file_link): """Download a file from the provided link.""" try: response = requests.get(file_link) response.raise_for_status() # Raise an error for bad status codes return BytesIO(response.content) # Return file content as a BytesIO object except Exception as e: return f"❌ Error downloading file: {e}" # ✅ Function to Load and Read File Contents def load_data(file_link): """Read content from the downloaded file.""" file_content = download_file_from_link(file_link) if isinstance(file_content, str): # If an error message is returned return file_content try: doc = docx.Document(file_content) return "\n".join([para.text for para in doc.paragraphs if para.text.strip()]) except Exception as e: return f"❌ Error reading file: {e}" # ✅ Function to Call Google AI Gemini API def call_gemini_api(file_link, user_input): """Send user query + document content to Google AI.""" if not API_KEY: return "❌ Error: API Key not found! Add it as GEMINI_API_KEY in Hugging Face secrets." # Read document content document_content = load_data(file_link) if document_content.startswith("❌"): return document_content # Return error message if file loading failed # Truncate document content to avoid exceeding API limits max_context_length = 4000 # Adjust based on API limits truncated_content = document_content[:max_context_length] # Construct API request url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key={API_KEY}" headers = {"Content-Type": "application/json"} payload = { "contents": [ { "parts": [ {"text": f"Document Context: {truncated_content}\nUser Query: {user_input}"} ] } ] } # Make API call try: response = requests.post(url, json=payload, headers=headers) response.raise_for_status() # Raise an error for bad status codes return response.json().get("candidates", [{}])[0].get("content", "No response from API") except Exception as e: return f"❌ API Error: {e}" # ✅ Gradio Interface iface = gr.Interface( fn=call_gemini_api, inputs=[ gr.Textbox(label="File Link", placeholder="Paste the file link here (e.g., Google Drive link)"), gr.Textbox(label="Ask a question") ], outputs="text", title="📄 AI Chatbot with Real-Time Document Context", description="This chatbot answers questions based on the document fetched from the provided link." ) iface.launch()