#importing all the libraries needed
import streamlit as st
import pandas as pd
from datasets import load_dataset
#adding the css presentation from the styles file in utils
from utils.styles import load_css
load_css()
#loading the dataset from hugging face
@st.cache_data
def load_news_data():
dataset = load_dataset("SuchithTissera/News_dataset")
return pd.DataFrame(dataset['train'])
news_dataset = load_news_data()
#creating helpers to handle any issues
def normalize_label(label):
return str(label).lower().replace("_", " ").strip()
def pretty_label(label):
return str(label).replace("_", " ").title()
#writing the title and the content
st.markdown('
🧩 Classification Mini-Game
', unsafe_allow_html=True)
st.markdown("""In this page, users can test their classification
skills by classifying news snippets used in our training dataset.
""",unsafe_allow_html=True)
st.markdown("""
- Users may play the game with 5 or 10 rounds.
""",unsafe_allow_html=True)
#dividing the page
st.divider()
#categories for the game
CATEGORIES = ["Business", "Opinion", "Political_gossip", "Sports", "World_news"]
#keywords for the game
defaults = {
"game_started": False,
"questions": None,
"current_round": 0,
"score": 0,
"total_rounds": 5,
"answered": False,
"selected_option": None,
"game_finished": False,
}
#session state initializing
for key, value in defaults.items():
if key not in st.session_state:
st.session_state[key] = value
#important functions to run the game
#for starting the game
def start_game(round_count):
sampled = news_dataset.sample(n=round_count).reset_index(drop=True)
st.session_state.questions = sampled
st.session_state.total_rounds = round_count
st.session_state.current_round = 0
st.session_state.score = 0
st.session_state.answered = False
st.session_state.game_started = True
st.session_state.game_finished = False
#for restarting the game
def restart_game():
for key, value in defaults.items():
st.session_state[key] = value
#code related to running the game
if st.session_state.game_finished:
#game over related code
score = st.session_state.score
total = st.session_state.total_rounds
percentage = (score / total) * 100 if total > 0 else 0
#getting the scores and the gameover text
st.markdown('',unsafe_allow_html=True)
st.markdown(f'Your score: {score}/{total}
',unsafe_allow_html=True)
#getting the percentages
if percentage >= 75:
st.markdown(f' Percentage Score: {percentage:.2f}%
',unsafe_allow_html=True)
else:
st.markdown(f' Percentage Score: {percentage:.2f}%
',unsafe_allow_html=True)
if st.button("Play Again"):
restart_game()
st.rerun()
#related to starting the game
elif not st.session_state.game_started:
#getting the start screen and text
st.markdown('',unsafe_allow_html=True)
st.markdown('Select number of rounds:
',unsafe_allow_html=True)
round_choice = st.radio("",[5, 10],horizontal=True)
if st.button("Start Game"):
start_game(round_choice)
st.rerun()
#whilst playing the game
else:
#logic related to the current stage of the game
q_idx = st.session_state.current_round
row = st.session_state.questions.iloc[q_idx]
#text related to the current stage of the game
st.markdown(f'',unsafe_allow_html=True)
st.write("**Content:**")
st.info(row["content"])
#text related to answers
selected = st.radio("Choose the correct category:", CATEGORIES, key=f"q_{q_idx}")
#logic related to answers
if not st.session_state.answered:
if st.button("Submit Answer"):
#logic related to checking answer
st.session_state.selected_option = selected
st.session_state.answered = True
if normalize_label(selected) == normalize_label(row["class"]):
st.session_state.score += 1
st.rerun()
else:
#logic related to giving the output
correct_ans = row["class"]
if normalize_label(st.session_state.selected_option) == normalize_label(correct_ans):
st.success(f"Correct! The answer is {pretty_label(correct_ans)}.")
else:
st.error(f"Wrong! The correct answer was {pretty_label(correct_ans)}.")
if st.button("Next Round"):
if st.session_state.current_round + 1 >= st.session_state.total_rounds:
st.session_state.game_finished = True
else:
st.session_state.current_round += 1
st.session_state.answered = False
st.rerun()