Building Balita of the Week: Creating an AI-Powered News Quiz Website from Scratch


Recently, I launched Balita of the Week, an app that allows users to answer weekly quizzes on both local and global news. To create the quiz, I initially planned to use AI to identify trending topics, generate questions, and source relevant content. However, I quickly realized that achieving this with a simple prompt was not feasible.

In this article, I will outline how I was able to create a news quiz using a blend of Natural Language Processing (NLP) techniques and Large Language Models (LLMs).

Overview

Below is the diagram showing the final process of the quiz creator.

Quiz Generation Flow

Basically, here are the steps which I'll discuss in detail:

  1. Fetching Headlines: Use a web crawler to gather headlines from articles published in the past week.
  2. Topic Modeling: Input these list of headlines to BERTopic, a topic modeling technique that groups these headlines into topics.
  3. Topic Grading: Use GPT-4o to evaluate the topics based on - based on impact and relevance, generating a "Topic Score" and search terms for the next step.
  4. Relevant Article Search: Using the search terms generated, find related articles using the Bing News API. Select the best article based on criteria like recency and credibility of the source to a name a few (called the "Article Score")
  5. Question Generation: Use GPT-4o to create quiz questions, multiple-choice answers, and explanations, along with a Filipino translation.
  6. Upload the quiz to the database.

To illustrate, I'll be using the quiz for August 2, 2024 as an example.

Fetching Headlines

The first step is to gather headlines from reputable local news organizations. We focus on headlines because some news sites list all articles created on a given day, including just the headline and category.

Using BeautifulSoup, we extract headlines, their categories, and their published dates. These headlines are then clustered into topics.

Each week, 500-600 headlines are collected. To remove irrelevant topics, puff pieces, and editorials, only headlines from the local news, world news, technology, and sports are selected.

Topic Modeling

Initially, I used DBSCAN (Density-Based Spatial Clustering of Applications with Noise) to cluster articles into topics, followed by c-TF-IDF (Class-based Term frequency-inverse document frequency) to extract key terms from the cluster to create the topic name. However, the results were suboptimal due to insufficient data pre-processing.

So I explored other options and ultimately decided to use BERTopic, a more advanced modeling technique that combines HBSCAN (which uses a hierarchal approach to clustering compared to DBSCAN) with c-TF-IDF. This method produces dense clusters with easily interpretable topics while keeping important words in the topic descriptions. Basically, I utilized BERTopic by:

  1. Encoding the headlines into a 384-dim vector space using the all-MiniLM-L6-v2 model
  2. Reducing the dimensions of the embeddings using UMAP.
  3. Cluster the documents using HDBSCAN.
  4. Apply c-TF-IDF to extract the most important words per topic (representative words).

(To learn more about BERTopic's algorithm, you can check out their documentation)

For our use case, we've limited the number of topics to be between 8 and 15. We also set that headlines would only be in English.

Below are the 15 topics generated for the week of August 2, 2024. Take note that the topic with the id -1 includes articles that didn't fit the other topics and this will be disregarded.

TopicCountNameRepresentationRepresentative Docs
-162-1_california_suspension_prices_training
california
suspension
prices
training
freezes
evacuation
medicines
filipinos
dti
modernization
22 senators seek suspension of PUV modernization program
DOH freezes prices of 148 essential medicines in select areas
INQToday: 22 senators seek suspension of PUVMP; PNP denies ‘casing’ VP’s house
01510_paris_olympic_ceremony_delgaco
paris
olympic
ceremony
delgaco
pacquiao
philippines
exit
2024
wins
eumir
SCHEDULE: Team USA basketball at Paris Olympics 2024
Team Philippines sails into Paris Olympics 2024 opening ceremony
Paris Olympics: USA ease past South Sudan to reach basketball quarterfinals
1971_duterte_guo_pogo_roque
duterte
guo
pogo
roque
trillanes
probe
cartel
sara
smuggling
suspects
DOJ won’t bar arrest warrants vs suspects in ICC ‘drug war’ case
Trillanes sues Rep. Duterte
VP’s husband
ex-BOC head for drug smuggling
INQToday: Trillanes sues Rep. Duterte
VP’s husband
ex-BOC head for drug smuggling
2342_pvl_meralco_akari_lead
pvl
meralco
akari
lead
cignal
capital1
farm
coffee
bidding
adjusting
PVL: Choco Mucho posts first win at expense of ZUS Coffee
PVL: Still adjusting
Zoi Faki plays limited role in Choco Mucho win
PVL: Marina Tushova powers Capital1 past Choco Mucho with 45 points
3313_pcg_spill_sunken_tanker
pcg
spill
sunken
tanker
manila
seafarers
seals
warns
raincoats
lists
PH Coast Guard battles Bataan oil spill mess with coconut husk boom
PH Coast Guard seals 14 leaking valves of sunken tanker in Manila Bay
PH Coast Guard: Oil spill from sunken tanker in Manila Bay lessened
4314_carina_india_victims_mudslide
carina
india
victims
mudslide
ndrrmc
toll
tropical
landslides
gaemi
crash
11 killed by mudslide in China as tropical storm Gaemi drench region
India landslide toll hits 126 as rain hampers rescue work
India landslide toll hits 160 as rain hampers rescue work
5295_philhealth_regulate_approved_cannabis
philhealth
regulate
approved
cannabis
fda
fund
p20
package
taxis
tally
House OKs bill allowing access to medicinal cannabis on 3rd reading
Recto: Fund transfer from PhilHealth
GOCCs follows Congress’ order
FDA is sole regulator of tobacco products’ health aspects – SC
6286_flooding_dpwh_projects_management
flooding
dpwh
projects
management
mmda
manila
poe
herds
weirs
hackers
Metro Manila flood control plan needs update – Romualdez
Momo
MMDA assures ongoing efforts with 101 NCR flood control projects
Senators grill DPWH chief over lack of nat’l flood control master plan
7257_deped_schools_sy_class
deped
schools
sy
class
start
2025
angara
000
enrollment
rescheduling
15 QC public schools defer opening of classes
143 others ready by Monday
DepEd says over 18 million students enrolled for SY 2024-2025
DepEd: 738 public schools won’t start SY 2024-2025 on July 29
8188_500_japan_talks_ties
500
japan
talks
ties
regardless
aid
upgrade
weapons
roadmap
nuclear
PH lawmakers expect strong US ties regardless of election outcome
US
Japan overhaul security ties amid China’s strategic challenge
Korean shooter Kim Ye-ji’s cool aura captivates social media
9159_habagat_expected_lpa_friday
habagat
expected
lpa
friday
cloudy
typhoon
luzon
heavy
loom
p545
INQToday: Rains to persist in Luzon
Visayas due to habagat; ‘Gil Tulog’ road signs removed
LPA
monsoon
thunderstorms to bring cloudy skies
rains in PH
Cloudy skies
scattered rains expected due to LPA
‘habagat’
101510_gaza_strike_golan_netanyahu
gaza
strike
golan
netanyahu
heights
haniyeh
killed
press
youths
airstrikes
Israel vows retaliation after rocket kills 12 youths in Golan Heights
Deadly strike at Gaza school
rocket kills 12 in Israeli-annexed Golan
Israel army: Hamas military chief Deif killed in earlier Gaza strike
111411_harris_kamala_campaign_extremist
harris
kamala
campaign
extremist
endorse
running
falsely
listen
nominee
obamas
‘Say it to my face
’ Harris dares Trump as White House battle deepens
Kamala Harris raised $200M in first week of White House campaign
Donald Trump falsely suggests Kamala Harris misled voters about her race
121312_2025_dbm_proposed_p6
2025
dbm
proposed
p6
intel
confidential
hearings
allocation
militaristic
salary
Marcos’ office retains P4.5-B confidential
intel fund for 2025 – DBM
House set to receive on Monday the proposed P6.3 trillion budget for 2025
DBM submits proposed P6.3T national budget for 2025 to House
131213_marcos_054_expenses_p1
marcos
054
expenses
p1
leni
leadership
instruments
hike
batangas
proposals
Zubiri: P100 wage hike bill to be a ‘slam dunk’ for Marcos’ leadership
DBM: P1.054-B proposed budget for Marcos’ travel expenses in 2025
INQToday: P1.054-B proposed budget for Marcos’ travel expenses in 2025 – DBM
141014_maduro_victory_caracas_await
maduro
victory
caracas
await
protests
electoral
erupt
fisted
marxist
millions
Venezuela’s Maduro asks top court to audit presidential election
Protests erupt in Caracas
Venezuela vs Maduro’s disputed election win
Venezuela opposition claims election victory as Maduro declared winner

We can see that most articles are related to the Olympics, with its opening ceremony held during this week (July 27).

BERTopic also provides visualization options. Below is the graph showing the embedded headlines reduced to two dimensions.

Headlines and Topics

Some key observations:

  • The model can be pretty specific in identifying topics. For example, the headlines about the PH Budget for 2025 was split into two distinct topics.
    • 12_2025_dbm_proposed_p6 which contains headlines about the actual budget, the deliberations happening in congress, and some opinions from groups.
    • 13_marcos_054_expenses_p1 which also contains the budget headlines (but with Pres. Marcos included in the headline) as well as some articles about the budget allotted for the president's travel expenses.
  • Due to the topic limit, some topics are combined. For instance, the topic 5_philhealth_regulate_approved_cannabis. For the 29 headlines in this topic, the headlines talk about:
    • Cutting down the premiums for PhilHealth (The Universal Healthcare system of the Philippines).
    • The Supreme Court ruling that the FDA is the sole regulator for tobacco products
    • The turnover of PhilHealth funds to other government projects
    • The House approving the Medical Cannabis Act
    • Some other topics about government regulation, diseases, and health advice

Headlines and Topics

BERTopics also visualizes topics over time, which can be insightful for understanding trends.

  • We cans see that the 2024 olympics was discussed the whole week, but peaked by July 31 when events with Philippine athletes are commencing.
  • 1_duterte_guo_pogo_roque peaked during July 29-30 when Harry Roque was in a Senate Hearing about the POGO issue related to Bamban Mayor Alice Guo and indirectly related to former President Rodrigo Duterte.
  • The Venezuelan elections started on Jul 29, so local news sources started focusing on it during that time.

Topics Over Time

For our purposes, we focus on the following datapoints for grading the topics:

  • Topic name
  • Headline count
  • Representative words
  • Representative headlines

Grading and Selecting Topics

To grade the topics, we use the following formula to calculate the Topic Score.

stopic=(wcMaxNorm(ch))+(1wc)simpact100s_{topic} = (w_c \cdot MaxNorm(c_h)) + (1-w_c)\frac{s_{impact}}{100}

The score is a weighted normalized score based on the number of headlines in the topic (chc_h) and the normalized impact score (simpacts_{impact}).

The impact score (simpacts_{impact}) is determined by GPT-4o, which evaluates each topic on a scale of 0-100 based on the following criteria:

  • Impact: Prioritizes topics that represent significant changes or shifts in the status quo.
  • Relevance: Scores higher for topics that engage a broad audience or are widely discussed.
  • Urgency: Gives higher scores to topics addressing immediate issues or crises.
  • Rep Docs Type: Scores lower for puff pieces, editorials, listicles, and clickbait.
  • Conflict: Give a higher score to more engaging stories.

Here is the final ranking of the topics for August 2, 2024:

Graded List

(Note that wcw_c is set at 0.3)

Even though the relevance score for 0_paris_olympic_ceremony_delgaco wasn’t the highest, it ranked first due to the number of headlines. Other top topics include Typhoon Carina and the Gaza conflict.

Along with the impact score, the prompt also generates a 5-6 word search term for finding relevant articles. We select the top 8-10 topics for the quiz, based on a score threshold (currently set at 0.4).

Find Relevant Articles

Although we have representative headlines, they are not the best way to select articles because they come from a limited set of sources. Instead, we use the search terms generated by the LLM to find articles through the Bing News Search API.

We aim to retrieve 5 articles per search term. If fewer than 2 articles are returned, we shorten the search terms until we get at least 3 articles. This usually occurs when there are multiple topics grouped together. For example, the topic 4_carina_india_victims_mudslides with the search term "India mudslide toll Carina NDRRMC landslides" covers both the mudslides/landslides that occur in India and the Philippines (during Typhoon Carina).

Once we have enough articles, we calculate the Article Score (sarticles_{article}):

sarticle=s^source+s^search+s^date+b s_{article} = \hat{s}_{source} + \hat{s}_{search} + \hat{s}_{date} + b

Source Score

s^source\hat{s}_{source} is the weighted score based on the credibility of the news source.

s^source=wsourcessource\hat{s}_{source} = w_{source}s_{source}

where:

{1,if from select local sources0.8,if from select foreign sources 0,otherwise\begin{cases} 1,& \text{if from select local sources}\\ 0.8,& \text{if from select foreign sources }\\ 0,& \text{otherwise} \end{cases}

Search Rank Score

s^search\hat{s}_{search} is the normalized weighted score based on the search rank given by the Bing News Search API.

s^search=wsearchRankNorm(rsearch)\hat{s}_{search} = w_{search} \cdot RankNorm(r_{search})

We use rank normalization to transform the article's rank rsearchr_{search} into a score between 1r\frac{1}{|r|} to 11, where r|r| is the number of articles returned by the api.

Publish Date Score

s^date\hat{s}_{date} is the normalized weighted score based on the recency of the article. We then normalize this rank to get the date score which is then multiplied to the weight to get s^date\hat{s}_{date}.

s^date=wdateRankNorm(rdate)\hat{s}_{date} = w_{date} \cdot RankNorm(r_{date})

Weights

Current weights prioritize search rank (wsearch=0.6w_{search} = 0.6), followed by source credibility (wsource=0.3w_{source} = 0.3), and recency (wdate=0.1w_{date} = 0.1).

Offsets

Additional factors are considered as offsets (bb), such as image availability, source icon, and article length.

b=bimg+bsrc+blenb = b_{img} + b_{src} + b_{len}

To fit the UI, we deduct the score when the article has no image (bimgb_{img}) or if the news source has no icon provided (bsrcb_{src}). To assure that we have enough information about the topic for question generation, we reduce the final score if the word count of the article is less than 500 (blenb_{len}).

For example, here are the five articles found for the search term "Paris 2024 Olympic ceremony Pacquiao exit": Articles List

The article from philstar.com was selected due to its high score, attributed to being from a credible source and the most recent. In contrast, the article from Manila Times received a negative score since it's shorter than our threshold.

Generating Questions

With the selected articles, we use GPT-4o to generate a multiple-choice question based on the top article. The response includes:

  • A question structured with a brief introduction.
  • Four answer choices, with only one correct answer.
  • A one-paragraph explanation providing context, shown after the user answers.

Using the Olympics-related article as an example, the LLM generated the following question: Gen Question EN Gen Question PH

The question focuses on the controversy surrounding the Games' Opening Ceremony.

To refine the question generation, I made several adjustments to the prompt, including:

  • Specifying the type of questions to avoid opinionated responses.
    • Some examples: "Why is the action relevant?", "How would this make a certain group feel?"
  • Ensuring the correct answer isn’t included in the question.
  • Providing translation guidelines to improve the Filipino version's quality. For example, if a phrase is commonly used in English, is a proper noun, or is a technical term, use the English word or phrase. (e.g, United States instead of Estados Unidos or Department of Foreign Affairs instead of Kagawaran ng Ugnayang Panlabas)

Uploading Quizzes

The final step is to upload the quiz to the Firebase Firestore Database, where analytics and user feedback are also stored.

Final Product

Once uploaded, users can access the quiz on the Balita of the Week website. Here are some screenshots: Preview 1 Preview 2

Human in the Loop

I also developed a portal for more controlled quiz creation. This interface allows users to:

  • Select topics manually rather than relying solely on the top-ranked topics. Topics Select

  • Modify search terms and choose the best article. Article Select

  • Generate new questions or add specific instructions for prompt creation. Article Select Article Select

Conclusion

Through this project, I've gained valuable insights into leveraging AI and LLMs to build amazing apps. While LLMs are powerful tools, they are not the ultimate solution. Combining them with traditional methodologies can greatly enhance prompt responses. Additionally, I utilized React Server Components and NextJS' app router to develop faster and more efficient web applications, significantly improving the overall user experience.

Ready to take the quiz? Take the latest quiz here and let's see how well you know the news!

Want to learn more? Have any questions? Feel free to reach out to me at carl@carldegs.com