Demo Project: AI Chatbot for College Enquiries

Demo Project: AI Chatbot for College Enquiries

Project Overview:

This AI chatbot will assist users with frequently asked questions related to college admissions, available courses, fee structure, and other general queries. The chatbot will provide quick and automated responses to common inquiries, which helps colleges offer a seamless and responsive experience to prospective students and parents.

Tech Stack:

  1. Backend:
    • Python (for chatbot logic and AI model)
    • Flask (web framework for deployment)
  2. Frontend:
    • HTML/CSS (for user interface)
    • JavaScript (for chatbot interaction)
  3. Database:
    • SQLite or MySQL (for storing course, fee, and college data)
  4. Natural Language Processing (NLP):
    • NLTK or spaCy (for text understanding)
    • OpenAI GPT-4 API or similar models (for AI responses)
  5. Version Control:
    • Git/GitHub (for code management)

To create the complete app starting with the admin panel, we’ll break down everything from the tech stack, IDE, version control (Git), and database into detailed steps to help you understand and build the admin backend of the application.

1. Tech Stack for the Admin Panel

Here’s the technology stack we’ll be using for the admin panel:

  • Frontend:
    • HTML, CSS for the basic structure and styling.
    • JavaScript for handling user interactions on the admin panel.
  • Backend:
    • Python with Flask as the web framework. Flask is simple, easy to use, and perfect for a project like this.
  • Database:
    • SQLite for development (it’s light, file-based, and easy to set up).
    • You can upgrade to MySQL or PostgreSQL for production.
  • Version Control:
    • Git for version control to manage your codebase and track changes.
  • IDE:
    • Use VS Code, PyCharm, or Sublime Text for development. They all support Flask and have great plugin ecosystems for Python development.

2. Setting up the Admin Panel (Step-by-Step)

Step 1: Setting Up the Environment

  1. Install Python: Make sure Python is installed on your system. You can download it from python.org.
  2. Install Virtual Environment (optional but recommended): A virtual environment keeps your project dependencies isolated.
    python -m venv venv
    source venv/bin/activate   # On Windows use `venv\Scripts\activate`
    

     

  3. Install Flask and SQLAlchemy: Install Flask and SQLAlchemy (for database management) using pip:
    pip install flask flask_sqlalchemy flask_login
    

     

Step 2: Setting Up the Project Structure

Set up the folder structure for your project like this:

college-chatbot-admin
├── app.py           # Flask main application
├── models.py        # Database models (Admin, College)
├── templates        # HTML templates for admin panel
│   ├── admin_panel.html
│   ├── login.html
└── static           # Static files (CSS, JavaScript)
    └── style.css

3. Setting Up the Database (SQLite)

Database Models (models.py)

from flask_sqlalchemy import SQLAlchemy
from flask_login import UserMixin

db = SQLAlchemy()

class Admin(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(150), unique=True, nullable=False)
    password = db.Column(db.String(150), nullable=False)

class College(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(200), nullable=False)
    location = db.Column(db.String(100), nullable=False)
    courses = db.Column(db.String(500), nullable=False)
    fees = db.Column(db.String(100), nullable=False)

4. Admin Panel Backend (app.py)

This is the Flask app file that will handle the routes and admin authentication for managing college data.

from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///college_data.db'
app.secret_key = 'your_secret_key'
db = SQLAlchemy(app)
login_manager = LoginManager(app)

# Import models
from models import Admin, College

@login_manager.user_loader
def load_user(admin_id):
    return Admin.query.get(int(admin_id))

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        admin = Admin.query.filter_by(username=username).first()
        if admin and admin.password == password:
            login_user(admin)
            return redirect(url_for('admin_panel'))
    return render_template('login.html')

@app.route('/admin')
@login_required
def admin_panel():
    colleges = College.query.all()
    return render_template('admin_panel.html', colleges=colleges)

@app.route('/add_college', methods=['POST'])
@login_required
def add_college():
    name = request.form.get('name')
    location = request.form.get('location')
    courses = request.form.get('courses')
    fees = request.form.get('fees')
    new_college = College(name=name, location=location, courses=courses, fees=fees)
    db.session.add(new_college)
    db.session.commit()
    return redirect(url_for('admin_panel'))

@app.route('/delete_college/<int:id>')
@login_required
def delete_college(id):
    college = College.query.get(id)
    db.session.delete(college)
    db.session.commit()
    return redirect(url_for('admin_panel'))

@app.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('login'))

if __name__ == '__main__':
    db.create_all()
    app.run(debug=True)

5. Frontend (Admin Panel UI)

HTML for Login (templates/login.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Login</title>
</head>
<body>
    <h2>Admin Login</h2>
    <form action="/login" method="POST">
        <input type="text" name="username" placeholder="Username" required><br><br>
        <input type="password" name="password" placeholder="Password" required><br><br>
        <input type="submit" value="Login">
    </form>
</body>
</html>

HTML for Admin Panel (templates/admin_panel.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Panel</title>
</head>
<body>
    <h2>College Management Panel</h2>

    <h3>Add New College</h3>
    <form action="/add_college" method="POST">
        <input type="text" name="name" placeholder="College Name" required><br><br>
        <input type="text" name="location" placeholder="Location" required><br><br>
        <input type="text" name="courses" placeholder="Courses (Comma Separated)" required><br><br>
        <input type="text" name="fees" placeholder="Fees" required><br><br>
        <input type="submit" value="Add College">
    </form>

    <h3>Existing Colleges</h3>
    <table border="1">
        <tr>
            <th>Name</th>
            <th>Location</th>
            <th>Courses</th>
            <th>Fees</th>
            <th>Actions</th>
        </tr>
        {% for college in colleges %}
        <tr>
            <td>{{ college.name }}</td>
            <td>{{ college.location }}</td>
            <td>{{ college.courses }}</td>
            <td>{{ college.fees }}</td>
            <td>
                <a href="/delete_college/{{ college.id }}">Delete</a>
            </td>
        </tr>
        {% endfor %}
    </table>

    <a href="/logout">Logout</a>
</body>
</html>

6. Static Files (CSS)

Create a static/style.css file for styling the admin panel and login page.

7. Git Version Control

  1. Initialize Git:
    git init
    

     

  2. Create a .gitignore file to exclude unnecessary files (e.g., virtual environment files):
    venv/
    __pycache__/
    *.pyc
    *.sqlite
    

     

  3. Add and Commit Changes:
    git add .
    git commit -m "Initial commit with admin panel"
    

     

  4. Create a Remote Repository on GitHub and push your code.

8. IDE

For IDE, use:

  • VS Code with Python and Flask extensions.
  • PyCharm, which has built-in support for Python web development.

9. Running the Project

  1. Activate Virtual Environment:
    source venv/bin/activate
    

     

  2. Run the Flask Application:
    python app.py
    

     

  3. Access the App:
    • Admin Login: http://127.0.0.1:5000/login
    • Admin Panel: After logging in, you can manage colleges at http://127.0.0.1:5000/admin

10. Next Steps: Expanding the Admin Panel

Once the admin panel is up and running, you can move on to:

  • Creating the chatbot frontend.
  • Integrating a search functionality.
  • Expanding the authentication system to handle roles.
  • Adding more advanced features like editing colleges and more detailed data reporting.

This setup gives you a robust admin panel to manage your college database. You can then connect the chatbot to dynamically fetch this information from the database.

1. Frontend Stack</h2
The frontend will use the following technologies:

  • HTML: For the structure of the chatbot interface.
  • CSS: For styling the chatbot to look modern and user-friendly.
  • JavaScript: To handle the interaction with the backend (Flask API).
  • Flask: For serving the HTML files and handling requests between the frontend and backend.

2. Frontend Structure

Your folder structure should look like this now:

college-enquiry-bot
├── app.py                   # Main Flask app
├── models.py                # Database models (Admin, College)
├── templates
│   ├── admin_panel.html      # Admin panel to manage data
│   ├── login.html            # Admin login page
│   └── chatbot.html          # Frontend for the chatbot
└── static
    ├── style.css             # CSS file for chatbot and admin panel
    └── chatbot.js            # JavaScript file for chatbot interaction

 

3. Frontend HTML for Chatbot (templates/chatbot.html)

This is the interface that users will see when they interact with the chatbot. It includes an input box for users to type their questions and a display area for the conversation.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>College Enquiry Chatbot</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
    <div class="chat-container">
        <h2>College Enquiry Chatbot</h2>
        <div class="chat-box" id="chat-box"></div>
        <input type="text" id="user-input" placeholder="Ask me about courses, fees, or admissions..." />
        <button id="send-btn" onclick="sendMessage()">Send</button>
    </div>

    <script src="{{ url_for('static', filename='chatbot.js') }}"></script>
</body>
</html>

Explanation:

  • chat-box: This div will display the conversation (both user questions and bot responses).
  • user-input: An input field where users will type their queries.
  • Send Button: The button triggers the sendMessage() function to send the user’s input to the backend.

4. Frontend JavaScript for Chatbot Interaction (static/chatbot.js)

This script handles the interaction between the frontend and backend. It sends the user’s message to the server and displays the bot’s response.

function sendMessage() {
    const userInput = document.getElementById('user-input').value;
    const chatBox = document.getElementById('chat-box');

    // Display the user's message in the chat box
    chatBox.innerHTML += "<p><strong>You:</strong> " + userInput + "</p>";

    // Send the user's message to the backend
    fetch('/get_response', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: 'message=' + encodeURIComponent(userInput)
    })
    .then(response => response.text())
    .then(botResponse => {
        // Display the bot's response in the chat box
        chatBox.innerHTML += "<p><strong>Bot:</strong> " + botResponse + "</p>";

        // Clear the input field for the next message
        document.getElementById('user-input').value = "";
    });
}

Explanation:

  • sendMessage() Function:
    • Gets the user’s input from the input field.
    • Displays the user’s message in the chat-box.
    • Sends the message to the Flask backend (/get_response) using a POST request.
    • Receives the bot’s response and appends it to the chat window.

5. Backend Route to Handle Chatbot Interaction (Update app.py)

Now, we need to define the backend route in app.py that will handle the user’s input, process it, and return an appropriate response.

Update app.py to Include the Chatbot Route:

from flask import Flask, render_template, request, jsonify
from models import College, Admin
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, login_user, login_required, logout_user

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///college_data.db'
app.secret_key = 'your_secret_key'
db = SQLAlchemy(app)
login_manager = LoginManager(app)

@login_manager.user_loader
def load_user(admin_id):
    return Admin.query.get(int(admin_id))

# Chatbot page route
@app.route('/')
def chatbot():
    return render_template('chatbot.html')

# Route to handle chatbot responses
@app.route('/get_response', methods=['POST'])
def get_response():
    user_input = request.form['message'].lower()

    # Basic response logic (You can make this more sophisticated)
    if 'courses' in user_input:
        colleges = College.query.all()
        return "Available courses: " + ', '.join([college.courses for college in colleges])

    elif 'fees' in user_input:
        for college in College.query.all():
            if college.name.lower() in user_input:
                return f"The fees for {college.name} are {college.fees}."
        return "Please specify a valid college for fee information."

    elif 'admission' in user_input:
        return "Admissions are based on an entrance exam followed by an interview."

    else:
        return "I can help with queries related to courses, fees, and admissions. Please ask a specific question."

# Admin routes (already created in the previous steps)
# ...

if __name__ == '__main__':
    db.create_all()
    app.run(debug=True)

Explanation:

  • Route /: Serves the chatbot page (chatbot.html).
  • Route /get_response: Processes the user’s input, queries the database, and returns the bot’s response. It handles requests related to courses, fees, and admissions.
    • For courses: It retrieves all available courses from the database and returns them as a response.
    • For fees: It searches for the college name mentioned in the user’s input and returns the respective fee details.
    • For admissions: It returns a general admission process response.

6. CSS Styling (static/style.css)

Here’s some basic CSS to style the chatbot interface:

body {
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    margin: 0;
}

.chat-container {
    background-color: #fff;
    width: 400px;
    padding: 20px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    border-radius: 8px;
}

.chat-box {
    height: 300px;
    border: 1px solid #ccc;
    padding: 10px;
    overflow-y: scroll;
    margin-bottom: 10px;
    background-color: #f9f9f9;
}

#user-input {
    width: 80%;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
}

#send-btn {
    padding: 10px;
    border: none;
    background-color: #007bff;
    color: white;
    cursor: pointer;
    border-radius: 5px;
}

#send-btn:hover {
    background-color: #0056b3;
}

Explanation:

  • chat-container: Defines the layout for the chatbot interface.
  • chat-box: Displays the conversation and has a scrollbar for overflow.
  • #user-input: Input field styling.
  • #send-btn: Styling for the send button.

5. Running the Application

  1. Start the Flask app:
    python app.py
    

     

  2. Access the Chatbot:
    • Open your browser and navigate to http://127.0.0.1:5000/ to interact with the chatbot.
    • Ask questions related to courses, fees, and admission.

You now have a fully functional frontend for your chatbot, integrated with the backend that pulls information from the database and responds to user queries. The system includes both the chatbot and an admin panel to manage the college data.

You can enhance this further by:

  • Adding more complex Natural Language Processing (NLP) using libraries like spaCy or Rasa.
  • Expanding the types of queries the chatbot can handle.
  • Adding more detailed college information in the database.


Index