Views
No views yet
bert-base-uncased model from the transformers library. It has been trained on a balanced dataset annotated for toxicity and is capable of multi-label classification. Each input text can be simultaneously assigned multiple toxicity labels.1import requests
2
3# Your Hugging Face access token header
4headers = {"Authorization": "Bearer *********************"}
5
6# The model endpoint URL
7API_URL = "https://api-inference.huggingface.co/models/ujjawalsah/bert-toxicity-classifier"
8
9# Mapping dictionary from model labels to human-friendly labels
10label_mapping = {
11 "LABEL_0": "toxic",
12 "LABEL_1": "obscene",
13 "LABEL_2": "insult",
14 "LABEL_3": "threat",
15 "LABEL_4": "identity hate"
16}
17
18def query_model(text):
19 payload = {"inputs": text}
20 response = requests.post(API_URL, headers=headers, json=payload)
21 # Check for a successful request
22 if response.status_code == 200:
23 return response.json()
24 else:
25 print("Error:", response.status_code, response.text)
26 return None
27
28def print_readable_result(result):
29 # The model returns a list of lists. We assume we're interested in the first result.
30 predictions = result[0] if isinstance(result, list) and len(result) > 0 else []
31 if not predictions:
32 print("No predictions received.")
33 return
34
35 print("Human-friendly Classification Result:")
36 for pred in predictions:
37 # Convert label to human-readable using mapping and show score as a percentage
38 human_label = label_mapping.get(pred.get("label"), pred.get("label"))
39 score_percentage = pred.get("score", 0) * 100
40 print(f"- {human_label.capitalize()}: {score_percentage:.2f}% confidence")
41
42if __name__ == "__main__":
43 # Example text input
44 text = "You are a wonderful person."
45 result = query_model(text)
46 if result:
47 print_readable_result(result)