// --- Mock Knowledge Base for MANIT Bhopal --- const KNOWLEDGE_BASE = [ { keywords: /\b(hi|hello|hey|greetings|greet|who are you|about)\b/i, response: `Welcome to MANIT Chat I am your minimalist academic assistant. I can provide detailed insights about Maulana Azad National Institute of Technology (MANIT), Bhopal. Try asking me about: • Placements (packages, recruiters) • Hostels (facilities, rooms) • Departments (branches, courses) • Campus Life (sports, library)` }, { keywords: /\b(placement|recruit|job|salary|lpa|package|hire|hiring)\b/i, response: `Campus Placements MANIT Bhopal is recognized for its outstanding placement performance across all engineering and planning branches. • Top Recruiters: Tech giants and core enterprises visit annually, including Google, Amazon, Microsoft, Goldman Sachs, BPCL, Bajaj Auto, and Tata Motors. • Computer Science (CSE): Average package ranges between 15 to 20 LPA, with placement rates consistently near 95-100%. • Overall Average Package: Approximately 9.5 to 11.5 LPA across all branches. • Highest Package: Has touched 82 LPA in recent recruitment cycles.` }, { keywords: /\b(admis|cutoff|josaa|csab|jee|entrance|rank|how to get in|apply)\b/i, response: `Admission Guidelines Entry into MANIT Bhopal is highly competitive and strictly merit-based: • B.Tech & B.Arch: Admission is purely through the JEE Main examination. Final allocation is conducted via JoSAA (Joint Seat Allocation Authority) or CSAB counselling. • M.Tech & M.Plan: Candidates must possess a valid GATE score and register through the CCMT central portal. • MCA Program: Admission is granted based on ranks secured in the national-level NIMCET exam. • MBA & Ph.D.: Determined via national exam scores (CAT/MAT) followed by institute level interviews.` }, { keywords: /\b(hostel|room|mess|accommodation|living|dining|canteen)\b/i, response: `Residential Hostels MANIT Bhopal features a fully residential campus layout with 10 Hostels: • Male Accommodation: Hostels 1 to 6 and Hostel 8 cater to male students, with shared rooms for juniors and single rooms allocated to seniors. • Female Accommodation: Hostels 7 and 10 are girls' hostels. Hostel 10 is a modern, high-capacity, multi-story building featuring strict 24/7 security. • International Students: Hostel 9 is dedicated to international DASA students and research scholars. • Amenities: Each hostel houses its own cooperative mess, table tennis/badminton courts, high-speed Wi-Fi, and laundry provisions.` }, { keywords: /\b(department|branch|course|cse|ece|mech|civil|chemical|meta|bio|architecture|study|degree)\b/i, response: `Academic Departments MANIT Bhopal offers academic coursework across several engineering and allied disciplines: • Engineering Branches: Computer Science, Electronics & Communication, Electrical, Mechanical, Civil, Chemical, and Materials & Metallurgical Engineering. • Sciences: Biological Science & Bioinformatics, Physics, Chemistry, and Mathematics. • Architecture: The prestigious Department of Architecture & Planning is regularly ranked among the top architecture programs in India.` }, { keywords: /\b(facility|library|sports|campus|wifi|gym|medical|dispensary|lake)\b/i, response: `Campus & Infrastructure Spread across a lush 650-acre campus, MANIT provides high-grade amenities: • Central Library: Stacks more than 120,000 text volumes and gives students licensing to electronic databases like IEEE Xplore, ScienceDirect, and Springer. • Sports Complex: Features a cricket ground, football fields, running tracks, an indoor gym, and basketball, volleyball, and tennis courts. • Medical Dispensary: Offers round-the-clock medical care, basic triage, and free medicine distribution with an on-site ambulance.` }, { keywords: /\b(contact|location|where|address|phone|email|map|reach|city|station|airport)\b/i, response: `Location & Contacts MANIT is located in the central, scenic highlands of Bhopal: • Address: Link Road No. 3, Near Kaliyasot Dam, Bhopal, Madhya Pradesh, India - 462003. • Transit Proximity: - Bhopal Junction Railway Station: ~10 km - Rani Kamlapati (Habibganj) Station: ~6 km - Raja Bhoj Airport (BHO): ~20 km • General Email: pro@manit.ac.in • Web Portal: www.manit.ac.in` } ]; // --- Fallback Response --- const DEFAULT_RESPONSE = `Search Query Processed I couldn't locate details matching those specific terms. However, you can find exhaustive resources on the official MANIT Bhopal Portal (www.manit.ac.in). Alternatively, try asking about: • Placement statistics or top recruiters • Hostels, mess facilities, or campus size • Academic departments (CSE, ECE, Architecture)`; // --- DOM Elements --- const chatForm = document.getElementById('chat-form'); const chatInput = document.getElementById('chat-input'); const sendButton = document.getElementById('send-button'); const chatArea = document.getElementById('chat-area'); const chatWrapper = document.getElementById('chat-wrapper'); // --- Input Visual States --- chatInput.addEventListener('input', () => { if (chatInput.value.trim().length > 0) { sendButton.classList.add('active'); } else { sendButton.classList.remove('active'); } }); // --- Chat Core Controls --- chatForm.addEventListener('submit', (e) => { e.preventDefault(); const queryText = chatInput.value.trim(); if (!queryText) return; // Reset Input chatInput.value = ''; sendButton.classList.remove('active'); // Add User Message addUserMessage(queryText); // Disable input while bot processing toggleInputState(true); // Show Custom Loading State showLoadingState(async (loadingBubble, clearLoadingTimer) => { // Formulate Response const backendData = await getBotResponse(queryText); // 2. Kill the loading animation the exact millisecond the server responds clearLoadingTimer(); loadingBubble.remove(); const message= backendData.reply? backendData.reply: backendData const parsedHTML = marked.parse(message, { breaks: true }); addBotMessage(parsedHTML); }); }); // --- UI Helpers --- function scrollToBottom() { chatArea.scrollTop = chatArea.scrollHeight; } function toggleInputState(disabled) { chatInput.disabled = disabled; sendButton.disabled = disabled; if (disabled) { chatInput.blur(); } else { chatInput.focus(); } } function addUserMessage(text) { const msgDiv = document.createElement('div'); msgDiv.className = 'message user-message'; msgDiv.innerHTML = `
`; msgDiv.querySelector('.message-content').textContent = text; chatWrapper.appendChild(msgDiv); scrollToBottom(); } /** * Creates and cycles loading text phrases */ function showLoadingState(callback) { const loadingDiv = document.createElement('div'); loadingDiv.className = 'loading-bubble'; loadingDiv.innerHTML = `
Thinking... `; chatWrapper.appendChild(loadingDiv); scrollToBottom(); const loadingTextSpan = loadingDiv.querySelector('#loading-text-span'); const phrases = ["Thinking...", "Searching MANIT Database...", "Processing Query..."]; let phraseIndex = 0; // Cycle text phrase with visual fade const cycleInterval = setInterval(() => { loadingTextSpan.classList.add('fade-out'); // Wait for CSS transition to fade out (300ms) before updating text and fading back in setTimeout(() => { phraseIndex = (phraseIndex + 1) % phrases.length; loadingTextSpan.textContent = phrases[phraseIndex]; loadingTextSpan.classList.remove('fade-out'); }, 300); }, 1200); // Provide the DOM node and a cleanup callback const clearLoadingTimer = () => { clearInterval(cycleInterval); }; callback(loadingDiv, clearLoadingTimer); } /** * Maps input queries to responses in the database */ async function getBotResponse(user_query) { try{ // Connect to port 8000 if opened as a local file or viewed on Live Preview (port 3000) const isDevEnv = window.location.protocol === 'file:' || window.location.port === '3000'; const apiBaseUrl = isDevEnv ? 'http://127.0.0.1:8000' : ''; const response= await fetch(`${apiBaseUrl}/chat`,{ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({query:user_query}) }) // 1. THE FIX: Catch server errors BEFORE parsing JSON if (!response.ok) { // Read the raw text (which will be your 401 Unauthorized message) const errorText = await response.text(); console.error(`Backend Error (${response.status}):`, errorText); // Return a safe fallback dictionary so your UI doesn't crash return { reply: `Connection error: Server returned ${response.status}. Please check backend logs.` }; } const data= await response.json() return data } catch(err){ console.log("error in recieving output from server: ",err) return { reply: DEFAULT_RESPONSE }; } } /** * Adds bot response directly and instantly to the chat area. */ function addBotMessage(htmlContent) { // Create container bubble const msgDiv = document.createElement('div'); msgDiv.className = 'message bot-message'; const contentDiv = document.createElement('div'); contentDiv.className = 'message-content'; contentDiv.innerHTML = htmlContent; msgDiv.appendChild(contentDiv); chatWrapper.appendChild(msgDiv); scrollToBottom(); // Instantly restore user input state toggleInputState(false); }