ituvtu commited on
Commit
743501d
·
1 Parent(s): dd9cc96

Add application file and requirements

Browse files
Files changed (2) hide show
  1. app.py +82 -0
  2. requirements.txt +3 -0
app.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import pipeline
3
+
4
+
5
+ model_name = "ituvtu/distilbert-ag-news"
6
+
7
+ id2label = {0: "World", 1: "Sports", 2: "Business", 3: "Sci/Tech"}
8
+
9
+ try:
10
+ pipe = pipeline("text-classification", model=model_name)
11
+ print(f"Model {model_name} has been successfully downloaded.")
12
+ except Exception as e:
13
+ print(f"Model loading error: {e}")
14
+
15
+ pipe = lambda text, **kwargs: [{"label": f"ERROR: {e}", "score": 0.0}]
16
+
17
+
18
+ def predict_news_category(text):
19
+
20
+
21
+ predictions = pipe(text, return_all_scores=True)
22
+
23
+ formatted_output = {}
24
+
25
+ try:
26
+ # {"World": 0.1, "Sports": 0.7, ...}
27
+ if predictions and predictions[0]:
28
+ for pred in predictions[0]:
29
+ label_num_str = pred['label']
30
+ score = pred['score']
31
+
32
+ label_index = int(label_num_str.split('_')[-1])
33
+ readable_label = id2label.get(label_index, "Unknown")
34
+
35
+ formatted_output[readable_label] = score
36
+
37
+ except Exception as e:
38
+ return {f"Помилка обробки: {e}": 0.0}
39
+
40
+ return formatted_output
41
+
42
+
43
+ examples = [
44
+ # 0: World
45
+ ["Global leaders meet for climate change summit."],
46
+ ["Tensions rise in Middle East after new treaty."],
47
+ ["Brexit trade deal negotiations stall over fishing rights."],
48
+
49
+ # 1: Sports
50
+ ["Olympic athlete breaks world record in 100m sprint."],
51
+ ["Local football team wins championship."],
52
+ ["Manchester United announces record-breaking sponsorship deal."],
53
+
54
+ # 2: Business
55
+ ["Federal Reserve to announce interest rate decision."],
56
+ ["Stock market hits all-time high amid tech boom."],
57
+ ["Tesla unveils new battery technology, stock soars."],
58
+
59
+ # 3: Sci/Tech
60
+ ["New discovery on Mars could change everything."],
61
+ ["Researchers develop new AI capable of writing code."],
62
+ ["Massive cybersecurity breach exposes government data."]
63
+ ]
64
+
65
+ # Interface
66
+ title = "News classifier (AG News)"
67
+ description = "Enter a news headline, and the DistilBERT model (trained on AG News) will determine its category. Try one of the 12 examples below to test the model!"
68
+
69
+ iface = gr.Interface(
70
+ fn=predict_news_category,
71
+
72
+ inputs=gr.Textbox(lines=3, placeholder="Enter the headline of the news here..."),
73
+
74
+ outputs=gr.Label(),
75
+
76
+ title=title,
77
+ description=description,
78
+ examples=examples
79
+ )
80
+
81
+ # Launch
82
+ iface.launch()
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ gradio
2
+ transformers
3
+ torch