Views
No views yet
bert-base-multilingual-cased. This model is designed to perform text moderation tasks, specifically categorizing text into 18 different categories. It currently works only with English text.transformers library from Hugging Face and torch.pip install transformers torch1import json
2import torch
3from transformers import BertTokenizer, BertForSequenceClassification
4
5# Load the tokenizer and model
6model_name = "ifmain/ModerationBERT-En-02"
7tokenizer = BertTokenizer.from_pretrained(model_name)
8model = BertForSequenceClassification.from_pretrained(model_name, num_labels=18)
9
10# Device configuration
11device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
12model.to(device)
13
14def predict(text, model, tokenizer):
15 encoding = tokenizer.encode_plus(
16 text,
17 add_special_tokens=True,
18 max_length=128,
19 return_token_type_ids=False,
20 padding='max_length',
21 truncation=True,
22 return_attention_mask=True,
23 return_tensors='pt'
24 )
25 input_ids = encoding['input_ids'].to(device)
26 attention_mask = encoding['attention_mask'].to(device)
27 model.eval()
28 with torch.no_grad():
29 outputs = model(input_ids, attention_mask=attention_mask)
30 predictions = torch.sigmoid(outputs.logits) # Convert logits to probabilities
31 return predictions
32
33# Example usage
34new_text = "Fuck off stuped trash"
35predictions = predict(new_text, model, tokenizer)
36
37# Define the categories
38categories = ['harassment', 'harassment_threatening', 'hate', 'hate_threatening',
39 'self_harm', 'self_harm_instructions', 'self_harm_intent', 'sexual',
40 'sexual_minors', 'violence', 'violence_graphic', 'self-harm',
41 'sexual/minors', 'hate/threatening', 'violence/graphic',
42 'self-harm/intent', 'self-harm/instructions', 'harassment/threatening']
43
44# Convert predictions to a dictionary
45category_scores = {categories[i]: predictions[0][i].item() for i in range(len(categories))}
46
47output = {
48 "text": new_text,
49 "category_scores": category_scores
50}
51
52# Print the result as a JSON with indentation
53print(json.dumps(output, indent=4, ensure_ascii=False))1{
2 "text": "Fuck off stuped trash",
3 "category_scores": {
4 "harassment": 0.9272650480270386,
5 "harassment_threatening": 0.0013139015063643456,
6 "hate": 0.011709265410900116,
7 "hate_threatening": 1.1083522622357123e-05,
8 "self_harm": 0.00039102151640690863,
9 "self_harm_instructions": 0.0002464024000801146,
10 "self_harm_intent": 0.00031603744719177485,
11 "sexual": 0.020730027928948402,
12 "sexual_minors": 0.00018848323088604957,
13 "violence": 0.008375612087547779,
14 "violence_graphic": 2.8763401132891886e-05,
15 "self-harm": 0.00043840022408403456,
16 "sexual/minors": 0.00018241720681544393,
17 "hate/threatening": 1.1130881830467843e-05,
18 "violence/graphic": 2.7211604901822284e-05,
19 "self-harm/intent": 0.00026327319210395217,
20 "self-harm/instructions": 0.00023905260604806244,
21 "harassment/threatening": 0.0012845908058807254
22 }
23}