news_classifier / app.py
TetorisAce's picture
register environment variable: HF_Token with the private variable
04cbd96 verified
from transformers import pipeline, AutoTokenizer, AutoModelForSequenceClassification
import gradio as gr
import os
os.environ['HF_TOKEN'] = os.getenv('HF_API_KEY')
class Model():
def __init__(self, model_name):
self.model_name = model_name
self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)
self.model = AutoModelForSequenceClassification.from_pretrained(self.model_name)
self.pipeline = pipeline("text-classification", model=self.model, tokenizer=self.tokenizer)
def predict(self, text:str):
"predict news topic"
if text:
try:
prediction = self.pipeline(text)
return prediction[0]['label'].capitalize(), f"{prediction[0]['score']*100:.4f}%"
except Exception as e:
return e, e
else:
return 'Type your news article or select an example first...', 'Type your news article or select an example first...'
# model instance
model_name = "TetorisAce/bbc-news-topic-classifier-merged"
model = Model(model_name)
with gr.Blocks() as app:
title = "News Topic Classifier"
description = (
"This demo fine-tunes a RoBERTa-based model (`textattack/roberta-base-ag-news`) "
"to classify BBC news articles into five categories. It showcases transfer learning in NLP—"
"leveraging a high-performing AG News model to adapt quickly to a new domain with limited data.\n\n"
"**Labels**: Business, Entertainment, Politics, Sport, and Tech.\n\n"
"**Validation Loss**: 0.297721\n\n"
"**Accuracy**: 0.907988\n\n"
"**F1 Score**: 0.906632\n\n\n\n"
"⚠️ **Performance Note:** This model is quantized for reduced memory usage. "
"When running on a **CPU environment**, inference speed may be significantly slower "
"due to limited quantization optimizations. "
"For optimal performance, please use a **GPU** runtime."
)
with gr.Row():
gr.Markdown(f"# {title}\n\n{description}")
with gr.Row():
with gr.Column():
input_text = gr.TextArea(
label="Input Text",
placeholder="Paste or type your news article here...",
lines=10)
true_label = gr.Dropdown(
label="True Label (Optional)",
choices=["Business", "Entertainment", "Politics", "Sport", "Tech"],
value=None,
allow_custom_value=True,
interactive=True,
)
submit_btn = gr.Button(value="Classify")
with gr.Column():
outputs = [gr.Text(label="Prediction"), gr.Text(label="Confidence")]
submit_btn.click(model.predict, inputs=[input_text], outputs=outputs)
with gr.Row():
gr.Markdown("## Sample Data for testing")
examples = gr.Examples(
examples = [
["fiat mulls ferrari market listing ferrari could be listed on the stock market as part of an overhaul of fiat s carmaking operations the financial times has reported. it said fiat was set to restructure its business after reaching a $2bn (1.53bn euros; £1.05bn) settlement with gm about fiat s ownership. steps being considered include listing ferrari and bringing maserati and alfa romeo closer together it said. despite strong sales of alfa romeo fiat s car business is making a loss. under the proposals - which the paper said could be announced within days - the iconic sportscar maker could be listed separately on the market. fiat owns a 56% stake in ferrari -best known for its dominant formula one motor racing team - having first bought into the business in 1969. it considered floating ferrari in 2002 but opted to sell a minority stake to italian bank mediobanca for 775m euros ($1bn). that sale valued ferrari - which owns the maserati brand - at 2.3bn euros. the price tag would change if maserati was stripped out. the financial times said fiat may transfer maserati within its wholly- owned alfa romeo division in an effort to exploit commercial synergies. such a move would help alfa romeo and maserati to share marketing distribution and research & development costs. maserati and ferrari sell about 10 000 cars between them and both companies broke even in 2003. fiat italy s largest private sector employer did not comment on the reported changes. fiat recently negotiated an end to its alliance with general motors. the us firm agreed to pay $2bn to exit an agreement under which it could have been liable to buy fiat outright. analysts said the reported restructuring was evidence of the greater flexibility which fiat now had to develop the business.",
"Business"],
["jugnot tops french actor league actor gerard jugnot - star of the oscar-nominated film the chorus - has beaten gerard depardieu to become france s best-paid actor of 2004. jugnot made 5.45m euros (£3.77m) last year according to a table drawn up by france s le figaro newspaper. in the chorus (les choristes) jugnot plays an inspiring music teacher at a school for troubled boys in 1949. despite starring in five films in 2004 depardieu made 3.35m euros (£2.31m) putting him third place in the chart. his name [depardieu] is no longer sufficient to guarantee the success of a film said le figaro newspaper. the chorus which jugnot also co-produced has drawn an audience of nearly nine million people since its release last year. godzilla star jean reno was france s second best-paid actor in 2004 earning 3.55m euros (£2.45m) . his roles include a recent uncredited cameo in the oscar-nominated hotel rwanda. the highest-ranking woman on le figaro s list was audrey tautou in 10th place earning 885 000 euros (£611 000). she starred in jean-pierre jeunet s a very long engagement (un long dimanche de fiancailles) and is also lined up to co-star with tom hanks in ron howard s the da vinci code. the chorus is nominated for best foreign film at sunday s oscar ceremony. on saturday it will compete for the title of best film against fellow nominee a very long engagement in france s cesar film awards.",
"Entertainment"],
["radcliffe will compete in london paula radcliffe will compete in the flora london marathon this year after deciding her schedule for 2005. the 31-year-old won the race in 2002 on her marathon debut defended her title 12 months later and will now seek a third title in the 17 april race. it doesn t get any better than this for the 25th anniversary said race director david bedford. after announcing the greatest men s field ever we now have the greatest women s distance runner ever. three years ago radcliffe smashed the women s world record in two hours 18 minutes 15 seconds. the bedford star returned to london 12 months later lowering her mixed-race world record of 2:17:18 which she set in chicago in october 2003 by one minute 53 secs. radcliffe s career took a setback when she failed to complete the olympic marathon and later dropped out of the athens 10 000m last august. but the 31-year-old bounced back to win the new york marathon in november. radcliffe however passed up the chance to go for the big city marathon grand slam. with wins in chicago london and new york only the boston marathon remains to be conquered but that takes place a day after london. boston is definitely a race i want to do at some point but london is very special to me said radcliffe. i don t pick races thinking about things like pressure. i pick the ones in my heart i really want to do. i love the atmosphere crowds and course and know it will always be a great quality race. it is also the 25th anniversary this year which adds to the occasion.",
"Sport"],
["2d metal slug offers retro fun like some drill sergeant from the past metal slug 3 is a wake-up call to today s gamers molly-coddled with slick visuals and fancy trimmings. with its hand-animated sprites and 2d side-scrolling this was even considered retro when released in arcades four years ago. but a more frantic shooter you will not find at the end of your joypad this year. and yes that includes halo 2. simply choose your grunt and wade through five 2d side-scrolling levels of the most hectic video game blasting you will ever encounter. it is also the toughest game you are likely to play as hordes of enemies and few lives pile the pressure on. players must battle soldiers snowmen zombies giant crabs and aliens not to mention the huge screen-filling bosses that guard each of the five levels. the shoot-anything-that-moves gameplay is peppered with moments of old-school genius. fans of robotic gastropods should note the title refers instead to the vast array of vehicles on offer in a game stuffed with bizarre hardware. tanks jets and submarines can be commandeered as well as cannon-toting camels elephants and ostriches - more weaponry on offer than in an acre of iraq. doling out justice is a joy thanks to ultra responsive controls and while this is a tough nut to crack it is addictive enough to have you gagging for that one last go. and at a mere £20 metal slug 3 is as cheap as sliced fried spuds as the man says. of course most of you will ignore this lacking as it does the visual fireworks of modern blasters. but at a time when blockbuster titles offer only a fresh lick of paint in favour of real innovation metal slug 3 is a fresh gasp of air from an era when the xbox was not even a twinkle in bill gates eye.",
"Tech"],
["soros group warns of kazakh close the open society institute (osi) financed by billionaire george soros has accused kazakhstan officials of trying to close down its local office. a demand for unpaid taxes and fines of $600 000 (£425 000) is politically motivated the osi claimed adding that it paid the money in october. the organisation has found itself in trouble after being accused of helping to topple georgia s former president. it denies having any role but offices have had to close across the region. the osi shut its office in moscow last year and has withdrawn from uzbekistan and belarus. in the ukraine earlier this year mr soros - who took on the bank of england in the 1990s - and won was pelted by protestors. this legal prosecution can be considered an attempt by the government to force soros foundation-kazakhstan to cease its activities in kazakhstan and shut its doors for kazakh citizens and organisations the osi said. the osi aims to promote democratic and open market-based societies. since the break up of the soviet union in 1991 kazakhstan has been dominated by its president nursultan abish-uly nazarbayev. he has powers for life while insulting the president and officials has been made a criminal offence. the government controls the printing presses and most radio and tv transmission facilities. it operates the country s national radio and tv networks. recent elections were criticised as flawed and the opposition claimed there was widespread vote rigging. supporters however say he brings much needed stability to a region where islamic militancy is on the rise. they also credit him with promoting inter-ethnic accord and pushing through harsh reforms.",
"Politics"]
],
inputs=[input_text, true_label]
)
if __name__ == "__main__":
app.launch()