import gradio as gr import requests from bs4 import BeautifulSoup from duckduckgo_search import DDGS from openai import OpenAI import os # Initialize OpenAI client client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY")) # ---------- UTILITIES ---------- def scrape_website(url, max_chars=2000): """Fetch text content from a website (limited to max_chars).""" try: r = requests.get(url, timeout=10) soup = BeautifulSoup(r.text, "html.parser") text = " ".join(soup.stripped_strings) return text[:max_chars] except Exception as e: return f"Error fetching {url}: {e}" def search_web(query): """Search the web for additional information.""" try: with DDGS() as ddgs: results = ddgs.text(query, max_results=3) if results: text = "\n\n".join([f"{r['title']}: {r['body']} ({r['href']})" for r in results]) return text except Exception as e: return f"Web search error: {e}" return "No results found." # ---------- MAIN CHAT FUNCTION ---------- def chat_with_iub(history, message): """Main chat logic for IUB ChatBot""" messages = [ {"role": "system", "content": "You are IUB ChatBot, an official AI assistant for The Islamia University of Bahawalpur. Always provide accurate, helpful, and official information based on IUB sources or web search. Answer politely and professionally."} ] for user, bot in history: messages.append({"role": "user", "content": user}) messages.append({"role": "assistant", "content": bot}) # --- Step 1: Gather data from IUB websites --- iub_sites = [ "https://www.iub.edu.pk/", "https://my.iub.edu.pk/", "https://eportal.iub.edu.pk/" ] site_content = "" for site in iub_sites: site_content += scrape_website(site) # --- Step 2: Add live web info --- web_data = search_web(message) # --- Step 3: Create combined context --- context = f""" You are answering as the IUB ChatBot. Here is the latest information from The Islamia University of Bahawalpur official websites: {site_content} Here are additional web search results: {web_data} Now answer the following question clearly and factually: {message} """ # --- Step 4: Send to ChatGPT (OpenAI API) --- chat_completion = client.chat.completions.create( model="gpt-4o-mini", messages=messages + [{"role": "user", "content": context}], ) reply = chat_completion.choices[0].message.content history.append((message, reply)) return history, "" # ---------- GRADIO UI ---------- with gr.Blocks(theme=gr.themes.Soft()) as demo: gr.Markdown(""" # 🎓 The Islamia University of Bahawalpur – IUB ChatBot ### 🤖 This is the Final Year Project **Developed by:** *Mujahid Hussain* **Department:** *Information Technology* **Supervisor:** *Muzamil ur Rehman* --- 💬 Ask any question about IUB: departments, admissions, fees, transport, schedule, or events. IUB ChatBot provides official and up-to-date information using web data and university resources. """) chatbot = gr.Chatbot(height=500) msg = gr.Textbox(label="Ask something about The Islamia University of Bahawalpur...") clear = gr.Button("Clear Chat") state = gr.State([]) def user(user_message, history): return "", history + [[user_message, None]] msg.submit(user, [msg, state], [msg, state], queue=False).then( chat_with_iub, [state, msg], [chatbot, msg] ) clear.click(lambda: ([], ""), None, [chatbot, msg]) demo.launch()