0% found this document useful (0 votes)
5 views19 pages

Python Project

The document outlines a project for a Smart Class Performance Analyzer that utilizes Natural Language Processing to automate the sentiment analysis of student feedback. It highlights the limitations of existing feedback systems and proposes a Python-based solution that classifies sentiments as Positive, Negative, or Neutral, featuring a user-friendly interface and interactive dashboard. The project aims to enhance educational institutions' ability to derive actionable insights from student feedback efficiently.

Uploaded by

sohamdev3785
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views19 pages

Python Project

The document outlines a project for a Smart Class Performance Analyzer that utilizes Natural Language Processing to automate the sentiment analysis of student feedback. It highlights the limitations of existing feedback systems and proposes a Python-based solution that classifies sentiments as Positive, Negative, or Neutral, featuring a user-friendly interface and interactive dashboard. The project aims to enhance educational institutions' ability to derive actionable insights from student feedback efficiently.

Uploaded by

sohamdev3785
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PUNJAB COLLEGE OF TECHNICAL EDUCATION

PROJECT FILE
On
Smart Class Performance Analyzer
PYTHON (UGCA – 19214)

Submitted To: Submitted By:

Ms. Anika Bhandari NITHIN RAMESH(2446073)

Assistant Professor of CSE NAVJOT SINGH(2446070)

NAVNEET SINGH(2446071)
Chapter 1: Introduction to Project
1.1 Background
In the modern educational landscape, student feedback is a critical component for
continuous improvement. It provides invaluable insights into teaching methodologies,
curriculum effectiveness, and faculty performance. Traditionally, this feedback is
collected through paper-based forms or simple digital surveys, resulting in a massive
volume of unstructured textual data. Manually analyzing this data to extract
meaningful sentiments is a time-consuming, labor-intensive, and often subjective
process.
1.2 Problem Statement
Educational institutions lack an efficient, automated system to process and analyze
the qualitative feedback provided by students. This leads to a significant delay in
identifying areas of excellence and concerns, preventing timely interventions and
actionable insights. There is a clear need for a system that can automatically classify
the sentiment behind student comments, providing a quantitative measure of
feedback at scale.
1.3 Proposed Solution
The Student Feedback Sentiment Classifier is a Python-based software solution
designed to address this challenge. It leverages Natural Language Processing (NLP)
techniques to automatically analyze student feedback and classify its sentiment as
Positive, Negative, or Neutral. The system features a user-friendly Graphical User
Interface (GUI) and an interactive dashboard that visually presents key metrics, such
as top-praised faculty and a list of critical feedback, enabling administrators to make
data-driven decisions swiftly.
1.4 Report Outline
This report documents the entire lifecycle of the project, from the study of existing
systems to the design and proposed implementation of the new system, including its
objectives, features, modules, and development plan.

Chapter 2: Study of Existing System


2.1 Current Methods
The existing systems for handling student feedback are predominantly manual or
semi-automated:
 Paper-based Forms: Physical forms are distributed, collected, and manually
read by staff or faculty committees.
 Basic Digital Surveys: Tools like Google Forms or Microsoft Forms are used to
collect feedback, but the analysis of open-ended responses still requires
manual reading and categorization.
 Simple Analytical Tools: Some institutions might use basic keyword spotting
(e.g., counting the occurrence of "good" or "bad"), which lacks the nuance to
understand context and sarcasm.
2.2 Limitations of the Existing System
 Time-Consuming: Manual processing of hundreds or thousands of comments
is extremely slow.
 Subjectivity: Human analysis is prone to bias and inconsistency.
 Lack of Scalability: The process does not scale well with an increasing number
of students or courses.
 No Real-time Analysis: Insights are delayed, sometimes for months, reducing
their immediate impact.
 Difficulty in Aggregation: It is challenging to generate a holistic view of faculty
performance or common issues across departments.

Chapter 3: Study of Proposed System


3.1 System Overview
The proposed "Student Feedback Sentiment Classifier" is an automated, web-based
or desktop application that uses NLP libraries to intelligently interpret student
feedback. The core of the system is its sentiment analysis engine, which can be
implemented using two approaches: the rule-based TextBlob library or the more
advanced, pre-trained Transformers model (like BERT).
3.2 Advantages of the Proposed System
 Efficiency: Processes large volumes of text in seconds.
 Objectivity: Provides consistent, unbiased sentiment scores based on
algorithms.
 Actionable Insights: The dashboard highlights top performers and critical
areas, enabling proactive management.
 Scalability: The system can easily handle feedback from a single class or an
entire university.
 User-Friendly: The GUI makes the system accessible to non-technical
administrative staff.
3.3 High-Level Architecture
The system follows a three-tier architecture:
1. Front-end (Presentation Layer): A GUI built with Tkinter or a web framework
(e.g., Streamlit) for input and visualization.
2. Back-end (Logic Layer): Python scripts handling the core logic, including data
preprocessing, sentiment analysis using TextBlob/Transformers, and data
aggregation.
3. Data Storage (Data Layer): A database (e.g., SQLite, PostgreSQL) or CSV/Excel
files to store raw feedback and analysis results.

Chapter 4: Software and Hardware Requirements


4.1 Software Requirements at Time of Development
 Operating System: Windows 10/11, Linux (Ubuntu 20.04+), or macOS
 Programming Language: Python 3.8+
 Python Libraries & Frameworks:
o textblob (For basic sentiment analysis)
o transformers (from Hugging Face, for advanced model-based analysis)
o pandas & numpy (For data manipulation)
o tkinter or streamlit (For building the GUI/Dashboard)
o matplotlib & seaborn or plotly (For data visualization in the dashboard)
o nltk or spacy (For text preprocessing - tokenization, stop-word removal)
o sqlite3 or sqlalchemy (For database interaction)
 Development Environment: Jupyter Notebook, VS Code, or PyCharm
 Version Control: Git
4.2 Hardware Requirements at Time of Development
 Processor: Intel i3 or equivalent (Higher recommended for transformer
models)
 RAM: 8 GB Minimum (16 GB Recommended)
 Hard Disk: 500 MB of free space
 Internet Connection: Required for downloading NLP models and libraries.

Chapter 5: Objectives of Project


The primary objectives of this project are:
1. To design and develop an automated system for classifying the sentiment of
student feedback into Positive, Negative, and Neutral categories.
2. To implement and compare two different NLP approaches (TextBlob and
Transformers) for sentiment analysis.
3. To create an intuitive Graphical User Interface (GUI) that allows users to input
feedback and view the sentiment results.
4. To develop an interactive dashboard that provides visual summaries, including:
o A list of top-praised faculty members.
o A list of critical feedback for immediate attention.
o Overall sentiment distribution (Pie chart/Bar graph).
5. To ensure the system is efficient, accurate, and user-friendly for administrative
staff in educational institutions.

Chapter 6: Features of Project


6.1 Core Features
 Dual Sentiment Analysis Engine: Flexibility to use either TextBlob for quick,
lightweight analysis or a Transformer model for higher accuracy and context
understanding.
 Real-time Sentiment Classification: Instant classification of feedback as it is
entered or uploaded.
 Batch Processing: Capability to analyze a batch of feedback entries from a CSV
or Excel file.
 Interactive Dashboard: A centralized view of all key performance indicators.
 Faculty Performance Ranking: Automated generation of a "Top Praised
Faculty" list based on positive sentiment scores.
 Critical Feedback Alert: A dedicated section listing feedback classified as
negative, allowing for quick intervention.
6.2 Administrative Features
 User-Friendly GUI: Simple and clean interface requiring minimal training.
 Data Export: Ability to export analysis results and dashboard summaries into
standard formats (CSV, PDF).

Chapter 7: Site Map / System Flow


7.1 Application Flowchart
(A diagram would be placed here. The text description is as follows:)
1. Start: Launch the Application.
2. Main Dashboard Loads: Displays overview (sentiment distribution, top faculty).
3. User Action:
o Option A (Single Feedback): User enters a feedback string in the input
box -> Clicks "Analyze" -> Sentiment is displayed
(Positive/Negative/Neutral with polarity score).
o Option B (Batch Upload): User uploads a CSV file containing multiple
feedback entries -> System processes the file -> Results are displayed
and saved.
4. Data Processing: For each feedback text, the system preprocesses the data
and passes it to the selected sentiment analysis model
(TextBlob/Transformers).
5. Database Update: The feedback and its sentiment result are stored in the
database.
6. Dashboard Update: The visualizations (charts, lists) on the dashboard are
updated in real-time to reflect the new data.
7. End: User logs out or closes the application.

Chapter 8: Module wise Description


8.1 Data Input Module
 Purpose: To accept feedback data from the user.
 Functions:
o get_single_feedback(): Captures text input from a text box in the GUI.
o upload_batch_file(): Handles the file upload process, reads the
CSV/Excel file using the pandas library.
8.2 Text Preprocessing Module
 Purpose: To clean and prepare the raw text data for analysis, improving model
accuracy.
 Functions:
o clean_text(text): Converts text to lowercase.
o remove_special_characters(text): Removes punctuation and numbers.
o tokenize_text(text): Breaks text into individual words (tokens).
o remove_stopwords(tokens): Filters out common, non-informative
words (e.g., "the", "is", "in").
8.3 Sentiment Analysis Module
 Purpose: The core engine that classifies the sentiment of the preprocessed
text.
 Functions:
o analyze_with_textblob(cleaned_text): Uses
TextBlob's [Link] property. Returns a score between -1
(Negative) and +1 (Positive). A score around 0 is Neutral.
o analyze_with_transformer(cleaned_text): Loads a pre-trained model
(e.g., cardiffnlp/twitter-roberta-base-sentiment-latest) from
the transformers library. Returns a label (POSITIVE/NEGATIVE/NEUTRAL)
and a confidence score.
8.4 Data Storage Module
 Purpose: To persistently store the feedback text and its corresponding
sentiment result.
 Functions:
o connect_to_database(): Establishes a connection with the SQLite
database.
o insert_record(feedback, sentiment, polarity, faculty_name): Inserts a
new record into the database table.
8.5 Dashboard & Visualization Module
 Purpose: To generate and display insightful visual summaries of the analyzed
data.
 Functions:
o generate_sentiment_pie_chart(): Uses matplotlib to create a pie chart
showing the proportion of Positive, Negative, and Neutral feedback.
o get_top_faculty(limit=5): Queries the database to retrieve faculty with
the highest average positive sentiment score.
o get_critical_feedback(): Queries the database to retrieve all feedback
classified as Negative.
8.6 GUI Module
 Purpose: To provide an interactive interface for the user.
 Functions:
o create_main_window(): Initializes the main application window using
Tkinter/Streamlit.
o create_input_widgets(): Creates text boxes, buttons, and file upload
dialogs.
o display_results(sentiment, score): Updates the GUI with the analysis
result.

Chapter 9: Project Design (Forms)


(This section would include mock-ups or detailed descriptions of the application's
screens. Here is a textual description.)
9.1 Main Dashboard Form
 Header: "Student Feedback Sentiment Analyzer"
 Left Panel (Input Section):
o Text Area labeled "Enter Student Feedback Here"
o "Analyze Sentiment" Button
o "Upload CSV File" Button
o Drop-down menu to select analysis model: "TextBlob" or "Transformer"
 Right Panel (Visualization Section):
o Chart 1: A large Pie Chart titled "Overall Sentiment Distribution".
o List 1: A table titled "Top 5 Praised Faculty" with columns: Faculty Name,
Department, Positive Score.
o List 2: A scrollable table titled "Critical Feedback for Review" with
columns: Feedback Snippet, Faculty Name, Date.
9.2 Result Pop-up Form (For Single Feedback)
 Appears after clicking "Analyze Sentiment".
 Displays the original feedback.
 Shows a label like: "Sentiment: POSITIVE (Confidence: 95%)" with the label
color-coded (Green for Positive, Red for Negative, Yellow for Neutral).

Chapter 10: Project Plan


10.1 Development Methodology
 Methodology Used: Agile Development with iterative sprints.
 Reasoning: Allows for flexible adaptation to changes and incremental addition
of features (e.g., starting with TextBlob and later integrating Transformers).
10.2 Project Timeline & Phases

Duration
Phase Task Description Tools & Technologies
(Weeks)

Requirement Analysis,
1. Planning &
Literature Survey on 2 -
Research
NLP techniques.

2. System Design Creating SRS, 2 [Link], MS Word


Architecture Design,
Duration
Phase Task Description Tools & Technologies
(Weeks)

Database Design.

Coding the Text


3. Core Module Preprocessing and
3 Python, TextBlob, NLTK
Development TextBlob Sentiment
Analysis modules.

Building the user


4. GUI & Python,
interface and
Dashboard 3 Tkinter/Streamlit,
integrating
Development Matplotlib
visualization charts.

Integrating the
5. Advanced
Transformer model Python, Transformers,
Module 2
for sentiment PyTorch/TensorFlow
Integration
analysis.

Unit Testing,
6. Testing & Integration Testing,
2 -
Debugging and User Acceptance
Testing (UAT).

Finalizing the project


7. Documentation
report and preparing 1 -
& Deployment
for deployment.

Total Estimated
15 Weeks
Duration

Chapter 11: Development Tool


11.1 Primary Development Tool: Python
 Justification: Python is the leading language for data science, machine
learning, and NLP due to its simplicity and a vast ecosystem of powerful
libraries. The availability of libraries like TextBlob, Transformers, Pandas, and
Tkinter makes it the ideal choice for this project, enabling rapid development
and robust performance.
11.2 Key Libraries and Their Roles
 TextBlob: Provides a simple API for common NLP tasks. It is used for the initial,
rule-based sentiment analysis implementation.
 Hugging Face Transformers: Provides thousands of pre-trained models for
advanced NLP. It is used to achieve state-of-the-art accuracy in sentiment
classification.
 Tkinter/Streamlit: Tkinter is Python's standard GUI library, suitable for
building desktop applications. Streamlit is a fantastic alternative for quickly
building interactive web apps for data projects.
 Pandas: The backbone for data manipulation and analysis, especially for
handling batch-uploaded CSV files.
 Matplotlib/Plotly: Industry-standard libraries for creating static, interactive,
and animated visualizations for the dashboard.

Conclusion
The Student Feedback Sentiment Classifier project successfully demonstrates the
application of Natural Language Processing to solve a real-world problem in the
education sector. By automating the sentiment analysis process, the system provides
a scalable, efficient, and objective solution for extracting actionable insights from
student feedback, empowering educational institutions to enhance teaching quality
and student satisfaction.
Future Scope
The project can be enhanced in the following ways:
1. Aspect-Based Sentiment Analysis: Instead of a general sentiment, identify
sentiments towards specific aspects like "teaching style", "punctuality", or
"course material".
2. Sarcasm Detection: Integrate advanced models capable of detecting sarcasm,
which is often misclassified by standard sentiment analyzers.
3. Multi-language Support: Train or use models that can handle feedback in
multiple languages.
4. Advanced Analytics: Integrate predictive analytics to forecast trends in
student satisfaction over time.
5. Cloud Deployment: Deploy the application on a cloud platform (e.g., AWS,
Heroku) to make it accessible as a Software-as-a-Service (SaaS).

Bibliography
 Loria, S. (2018). textblob Documentation. Release 0.15.
 Wolf, T., et al. (2020). "Transformers: State-of-the-Art Natural Language
Processing". Proceedings of the 2020 Conference on Empirical Methods in
Natural Language Processing: System Demonstrations.
 McKinney, W. (2010). "Data Structures for Statistical Computing in Python".
Proceedings of the 9th Python in Science Conference.
 Bird, S., Klein, E., & Loper, E. (2009). "Natural Language Processing with
Python". O'Reilly Media.
 Streamlit Documentation. [Link]

Code

import tkinter as tk
from tkinter import ttk, scrolledtext, messagebox, filedialog
from textblob import TextBlob
import pandas as pd
import sqlite3
import datetime
import os
import csv

DB_FILENAME = "[Link]"

# ---------------------------
# Teacher -> Subjects mapping
# ---------------------------
TEACHERS = {
"Mr. Sanskar Agarwal": ["DSA", "Computer Network"],
"Ms Arti": ["AI/ML", "C++"],
"Mr. Harpreet Singh Dhanoa": ["Computer Network", "AI/ML"],
"Mr Shairy": ["CSA", "BMPD"],
"Ms Simranjeet Kaur": ["C++", "PC Assembly"],
"Ms Nisha Arora": ["JAVA", "Human Value"],
"Ms Kamalpreet Kaur": ["BMPD", "Python"],
"Ms Pratibha Soram": ["C", "English"],
"Ms Pratistha": ["PC Assembly Lab", "PC Assembly"],
"Mr Parteek jain": ["PC Assembly", "English"],
"Mr. Gourav": ["Human Value", "BMPD"],
"Ms. Pratiksha": ["English", "AI/ML"],
"Ms. Anika": ["Python", "Computer Network"],
}

# Normalize teacher names list


TEACHER_LIST = list([Link]())

# ---------------------------
# SQLite helper functions
# ---------------------------
def init_db(db_path=DB_FILENAME):
conn = [Link](db_path)
cur = [Link]()
[Link](
"""
CREATE TABLE IF NOT EXISTS feedback (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp TEXT,
faculty TEXT,
subject TEXT,
feedback TEXT,
sentiment TEXT,
polarity REAL
)
"""
)
[Link]()
return conn

def insert_feedback_db(conn, timestamp, faculty, subject, feedback, sentiment, polarity):


cur = [Link]()
[Link](
"INSERT INTO feedback (timestamp, faculty, subject, feedback, sentiment, polarity) VALUES (?, ?, ?, ?, ?, ?)",
(timestamp, faculty, subject, feedback, sentiment, polarity)
)
[Link]()
return [Link]

def fetch_all_feedback(conn):
cur = [Link]()
[Link]("SELECT id, timestamp, faculty, subject, feedback, sentiment, polarity FROM feedback ORDER BY id DESC")
rows = [Link]()
cols = ['id', 'timestamp', 'faculty', 'subject', 'feedback', 'sentiment', 'polarity']
df = [Link](rows, columns=cols)
return df

def export_db_to_csv(conn, path):


df = fetch_all_feedback(conn)
df.to_csv(path, index=False)

# ---------------------------
# Main Application Class
# ---------------------------
class FeedbackSentimentApp:
def __init__(self, master):
[Link] = master
[Link]("� Student Feedback Sentiment Classifier (SQLite)")
[Link]("1050x720")

# Database connection
[Link] = init_db(DB_FILENAME)

# Load persisted feedback into DataFrame


try:
self.feedback_df = fetch_all_feedback([Link])
# Keep consistent column names as previous code expects
if not self.feedback_df.empty:
self.feedback_df = self.feedback_df.rename(columns={'faculty': 'Faculty', 'feedback': 'Feedback',
'sentiment': 'Sentiment', 'polarity': 'Polarity',
'subject': 'Subject', 'timestamp': 'Timestamp', 'id': 'ID'})
else:
self.feedback_df = [Link](columns=['ID', 'Timestamp', 'Faculty', 'Subject', 'Feedback', 'Sentiment', 'Polarity'])
except Exception:
# fallback empty df with proper columns
self.feedback_df = [Link](columns=['ID', 'Timestamp', 'Faculty', 'Subject', 'Feedback', 'Sentiment', 'Polarity'])

# Configure grid layout so dashboard expands


master.grid_rowconfigure(1, weight=1)
master.grid_rowconfigure(2, weight=1)
master.grid_columnconfigure(0, weight=1)

# UI creation
self.create_input_section(master)
self.create_dashboard_section(master)

# -----------------------
# Input Section (top)
# -----------------------
def create_input_section(self, parent):
input_frame = [Link](parent, text="� Feedback Input & Classification", padding="10")
input_frame.grid(row=0, column=0, sticky="ew", padx=10, pady=10)
input_frame.grid_columnconfigure(1, weight=1)

# Teacher selection
[Link](input_frame, text="Teacher:").grid(row=0, column=0, padx=5, pady=5, sticky="w")
self.teacher_var = [Link]()
self.teacher_cb = [Link](input_frame, textvariable=self.teacher_var, values=TEACHER_LIST, state="readonly")
self.teacher_cb.grid(row=0, column=1, padx=5, pady=5, sticky="ew")
self.teacher_cb.bind("<<ComboboxSelected>>", self.on_teacher_selected)

# Subject selection (auto-updated)


[Link](input_frame, text="Subject:").grid(row=1, column=0, padx=5, pady=5, sticky="w")
self.subject_var = [Link]()
self.subject_cb = [Link](input_frame, textvariable=self.subject_var, values=[], state="readonly")
self.subject_cb.grid(row=1, column=1, padx=5, pady=5, sticky="ew")

# Feedback text
[Link](input_frame, text="Feedback Text:").grid(row=2, column=0, padx=5, pady=5, sticky="nw")
self.feedback_text = [Link](input_frame, wrap=[Link], width=70, height=6)
self.feedback_text.grid(row=2, column=1, padx=5, pady=5, sticky="ew")

# Buttons: Classify & Admin View


btn_frame = [Link](input_frame)
btn_frame.grid(row=3, column=1, sticky="e", pady=8)
classify_btn = [Link](btn_frame, text="Classify & Submit Feedback", command=self.process_feedback)
classify_btn.grid(row=0, column=0, padx=5)
admin_btn = [Link](btn_frame, text="Open Admin View", command=self.open_admin_view)
admin_btn.grid(row=0, column=1, padx=5)

# Result display
[Link](input_frame, text="Classification Result:").grid(row=4, column=0, padx=5, pady=5, sticky="w")
self.result_var = [Link]()
self.result_label = [Link](input_frame, textvariable=self.result_var, font=('Arial', 10, 'bold'))
self.result_label.grid(row=4, column=1, padx=5, pady=5, sticky="w")

def on_teacher_selected(self, event=None):


teacher = self.teacher_var.get()
subjects = [Link](teacher, [])
# Update subject combobox values and set first subject as default
self.subject_cb['values'] = subjects
if subjects:
self.subject_var.set(subjects[0])
else:
self.subject_var.set("")

# -----------------------
# Sentiment classification & DB insertion
# -----------------------
def classify_sentiment(self, text):
if not text:
return "N/A", 0.0
analysis = TextBlob(text)
polarity = [Link]
if polarity > 0.1:
sentiment = "Positive"
elif polarity < -0.1:
sentiment = "Negative"
else:
sentiment = "Neutral"
return sentiment, polarity

def process_feedback(self):
faculty = self.teacher_var.get()
subject = self.subject_var.get()
feedback = self.feedback_text.get("1.0", [Link]).strip()
if not faculty:
[Link]("Error", "Please select a teacher.")
return
if not subject:
[Link]("Error", "Please select a subject.")
return
if not feedback:
[Link]("Error", "Please enter some feedback text.")
return

sentiment, polarity = self.classify_sentiment(feedback)


timestamp = [Link]().isoformat(sep=' ', timespec='seconds')

# Insert into SQLite database


try:
row_id = insert_feedback_db([Link], timestamp, faculty, subject, feedback, sentiment, float(polarity))
except Exception as e:
[Link]("Database Error", f"Failed to save feedback to database:\n{e}")
return

# Add to in-memory DataFrame (for dashboard)


new_row = {
'ID': row_id,
'Timestamp': timestamp,
'Faculty': faculty,
'Subject': subject,
'Feedback': feedback,
'Sentiment': sentiment,
'Polarity': polarity
}
self.feedback_df = [Link]([[Link]([new_row]), self.feedback_df], ignore_index=True)

# Update UI
self.result_var.set(f"Sentiment: {sentiment} (Polarity: {polarity:.2f})")
self.feedback_text.delete("1.0", [Link])
self.update_dashboard()
[Link]("Success", f"Feedback for {faculty} ({subject}) saved as {sentiment}.")

# -----------------------
# Dashboard (middle)
# -----------------------
def create_dashboard_section(self, parent):
dashboard_frame = [Link](parent, text="� Sentiment Dashboard", padding="10")
dashboard_frame.grid(row=1, column=0, sticky="nsew", padx=10, pady=10)
dashboard_frame.grid_columnconfigure(0, weight=1)
dashboard_frame.grid_columnconfigure(1, weight=1)
dashboard_frame.grid_rowconfigure(0, weight=1)

# Top praised
praised_frame = [Link](dashboard_frame, text="⭐ Top Praised Faculty (Avg. Positive Polarity)", padding="5")
praised_frame.grid(row=0, column=0, sticky="nsew", padx=5, pady=5)
praised_frame.grid_rowconfigure(0, weight=1)
praised_frame.grid_columnconfigure(0, weight=1)
self.praised_listbox = [Link](praised_frame, wrap=[Link], height=12, state='disabled')
self.praised_listbox.grid(row=0, column=0, sticky="nsew")

# Critical feedback
critical_frame = [Link](dashboard_frame, text="❌ Critical Feedback List (Most Negative)", padding="5")
critical_frame.grid(row=0, column=1, sticky="nsew", padx=5, pady=5)
critical_frame.grid_rowconfigure(0, weight=1)
critical_frame.grid_columnconfigure(0, weight=1)
self.critical_listbox = [Link](critical_frame, wrap=[Link], height=12, state='disabled')
self.critical_listbox.grid(row=0, column=0, sticky="nsew")

# Populate initial dashboard


self.update_dashboard()

def update_dashboard(self):
df = self.feedback_df.copy()

# Clear
self.praised_listbox.config(state='normal')
self.praised_listbox.delete('1.0', [Link])
self.critical_listbox.config(state='normal')
self.critical_listbox.delete('1.0', [Link])

if [Link]:
self.praised_listbox.insert([Link], "No feedback submitted yet.")
self.critical_listbox.insert([Link], "No feedback submitted yet.")
self.praised_listbox.config(state='disabled')
self.critical_listbox.config(state='disabled')
return

# Top praised: group by Faculty compute avg polarity for Positive feedback only
positive_df = df[df['Sentiment'] == 'Positive']
if not positive_df.empty:
praised_summary = positive_df.groupby('Faculty')['Polarity'].mean().sort_values(ascending=False).round(3)
self.praised_listbox.insert([Link], "Rank | Faculty | Avg. Polarity\n", ('header',))
self.praised_listbox.insert([Link], "-"*50 + "\n")
for i, (faculty, avg_polarity) in enumerate(praised_summary.items()):
self.praised_listbox.insert([Link], f"{i+1:<4} | {faculty:<22} | {avg_polarity:.3f}\n")
else:
self.praised_listbox.insert([Link], "No positive feedback recorded yet.")

# Critical: sort by Polarity ascending and show top 5


critical_list = df.sort_values(by='Polarity', ascending=True).head(5)
if not critical_list.empty:
self.critical_listbox.insert([Link], "Top 5 Most Negative Feedback:\n", ('header',))
self.critical_listbox.insert([Link], "-"*70 + "\n")
for _, row in critical_list.iterrows():
snippet = (row['Feedback'][:120] + '...') if len(row['Feedback']) > 120 else row['Feedback']
self.critical_listbox.insert([Link], f"Faculty: {row['Faculty']} | Subject: {[Link]('Subject','')} (Polarity:
{row['Polarity']:.2f})\n")
self.critical_listbox.insert([Link], f" Feedback: {snippet}\n\n")
else:
self.critical_listbox.insert([Link], "No feedback recorded yet.")

# Disable editing
self.praised_listbox.config(state='disabled')
self.critical_listbox.config(state='disabled')

# Styling tag
self.praised_listbox.tag_configure('header', font=('Arial', 10, 'bold'))
self.critical_listbox.tag_configure('header', font=('Arial', 10, 'bold'))
# -----------------------
# Admin View Window
# -----------------------
def open_admin_view(self):
admin_win = [Link]([Link])
admin_win.title("Admin View - Feedback Records")
admin_win.geometry("1000x600")

# Controls on top: Refresh, Export


control_frame = [Link](admin_win)
control_frame.pack(fill='x', padx=10, pady=6)
refresh_btn = [Link](control_frame, text="Refresh", command=lambda: self.populate_admin_table(tree))
refresh_btn.pack(side='left', padx=4)
export_btn = [Link](control_frame, text="Export CSV", command=self.admin_export_csv)
export_btn.pack(side='left', padx=4)

# Treeview for showing records


cols = ("ID", "Timestamp", "Faculty", "Subject", "Feedback", "Sentiment", "Polarity")
tree = [Link](admin_win, columns=cols, show='headings')
for c in cols:
[Link](c, text=c)
# make Feedback column wider
if c == "Feedback":
[Link](c, width=420, anchor='w')
elif c == "Timestamp":
[Link](c, width=140, anchor='center')
elif c == "Faculty":
[Link](c, width=180, anchor='w')
else:
[Link](c, width=100, anchor='w')
[Link](fill='both', expand=True, padx=10, pady=6)

# Populate data
self.populate_admin_table(tree)

def populate_admin_table(self, tree):


# Clear
for r in tree.get_children():
[Link](r)
# Fetch latest from DB
df = fetch_all_feedback([Link])
# Insert into tree
for _, row in [Link]():
[Link]("", [Link], values=(row['id'], row['timestamp'], row['faculty'], row['subject'],
row['feedback'], row['sentiment'], f"{row['polarity']:.3f}"))

def admin_export_csv(self):
path = [Link](defaultextension=".csv", filetypes=[("CSV files","*.csv")], title="Export feedback to
CSV")
if not path:
return
try:
export_db_to_csv([Link], path)
[Link]("Export Successful", f"Exported feedback to:\n{path}")
except Exception as e:
[Link]("Export Failed", f"Could not export CSV:\n{e}")

# -----------------------
# Clean up on close
# -----------------------
def close(self):
try:
[Link]()
except Exception:
pass
[Link]()

# -----------------------
# Entry point
# -----------------------
if __name__ == "__main__":
root = [Link]()
app = FeedbackSentimentApp(root)
# Bind closing to ensure DB closed
[Link]("WM_DELETE_WINDOW", [Link])
[Link]()

Output

You might also like