VietTung04 commited on
Commit
f432659
·
verified ·
1 Parent(s): ad525d8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -1
app.py CHANGED
@@ -1,3 +1,62 @@
1
  import gradio as gr
 
 
 
2
 
3
- gr.load("models/VietTung04/videberta-base-topic-classification").launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import torch
3
+ # Load model directly
4
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
5
 
6
+ tokenizer = AutoTokenizer.from_pretrained("VietTung04/videberta-base-topic-classification")
7
+ model = AutoModelForSequenceClassification.from_pretrained("VietTung04/videberta-base-topic-classification")
8
+
9
+ def preprocess_fn(text):
10
+ stopword_path = 'vietnamese-stopwords.txt'
11
+
12
+ with open(stopword_path, 'r', encoding='utf-8') as file:
13
+ stopwords = file.read().splitlines()
14
+
15
+ def remove_stopwords(tokens):
16
+ return [word for word in tokens if word not in stopwords]
17
+ text = re.sub(r'http\S+', ' ', text) # Remove URLs
18
+ text = re.sub(r'#\w+', ' ', text) # Remove hashtags
19
+ text = re.sub(r'@\w+', ' ', text) # Remove mentions
20
+ text = re.sub(r'\d+', ' ', text) # Remove numbers
21
+ text = re.sub(r'[^\w\sđĐàÀảẢãÃáÁạẠăĂằẰẳẲẵẴắẮặẶâÂầẦẩẨẫẪấẤậẬèÈẻẺẽẼéÉẹẸêÊềỀểỂễỄếẾệỆìÌỉỈĩĨíÍịỊòÒỏỎõÕóÓọỌôÔồỒổỔỗỖốỐộỘơƠờỜởỞỡỠớỚợỢùÙủỦũŨúÚụỤưƯừỪửỬữỮứỨựỰỳỲỷỶỹỸýÝỵỴ]', ' ', text) # Remove special characters
22
+ # Tokenize Vietnamese text
23
+ tokens = word_tokenize(' '.join(text.split()).lower())
24
+
25
+ # Remove stop words
26
+ tokens = remove_stopwords(tokens)
27
+
28
+ return ' '.join(tokens)
29
+
30
+ def predict_topic(text):
31
+ inputs = tokenizer(
32
+ preprocess_fn(text),
33
+ truncation=True,
34
+ padding='max_length',
35
+ max_length=512,
36
+ add_special_tokens=True,
37
+ return_tensors='pt'
38
+ )
39
+ inputs = {key: value.to(device) for key, value in inputs.items()}
40
+ with torch.no_grad():
41
+ outputs = model(**inputs)
42
+ logits = outputs.logits
43
+ probabilities = torch.softmax(logits, dim=1).cpu().numpy()[0]
44
+
45
+ # Get the top 3 classes
46
+ top3_indices = probabilities.argsort()[-3:][::-1]
47
+ top3_probabilities = probabilities[top3_indices]
48
+ top3_classes = [model.config.id2label[idx] for idx in top3_indices] # Assuming your model has this attribute
49
+
50
+ return {top3_classes[i]: float(top3_probabilities[i]) for i in range(3)}
51
+
52
+ # Define the Gradio interface
53
+ iface = gr.Interface(
54
+ fn=predict_topic,
55
+ inputs=gr.Textbox(lines=2, placeholder="Enter your text here..."),
56
+ outputs=gr.Label(num_top_classes=3),
57
+ title="Text Classification",
58
+ description="Enter text to classify it into different categories and get the probability for each class."
59
+ )
60
+
61
+ # Launch the interface
62
+ iface.launch()