Views
No views yet
transformers library from Hugging Face. You can install it using pip:1!pip install transformers
2!pip install torch
3
4# Import libraries
5from transformers import AutoTokenizer, AutoModelForSequenceClassification
6import huggingface_hub
7import torch
8import json
9
10# Authenticate with your Hugging Face token
11huggingface_hub.login(token='Your HF Access Token')
12
13# Load the model and tokenizer
14model_name = "GANgstersDev/singlish-hate-offensive-finetuned-model-v2.0.1"
15tokenizer = AutoTokenizer.from_pretrained(model_name)
16model = AutoModelForSequenceClassification.from_pretrained(model_name)
17
18
19def classify_text(text):
20 # Tokenize the input text
21 inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True)
22
23 # Perform inference
24 with torch.no_grad():
25 outputs = model(**inputs)
26
27 # Get the predicted class
28 logits = outputs.logits
29 predicted_class_id = torch.argmax(logits, dim=1).item()
30
31 # Map class ID to class label
32 class_labels = ["neither", "offensive", "hate"] # Adjust according to your labels
33 predicted_class_label = class_labels[predicted_class_id]
34
35 return predicted_class_label
36
37
38# Load the model and tokenizer
39model_name = "GANgstersDev/singlish-hate-offensive-finetuned-model-v2.0.1"
40tokenizer = AutoTokenizer.from_pretrained(model_name)
41model = AutoModelForSequenceClassification.from_pretrained(model_name)
42
43# Define function to classify text and return JSON output
44def classify_text(text):
45 # Tokenize the input text
46 inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True)
47
48 # Perform inference
49 with torch.no_grad():
50 outputs = model(**inputs)
51
52 # Get the predicted class
53 logits = outputs.logits
54 predicted_class_id = torch.argmax(logits, dim=1).item()
55
56 # Map class ID to class label
57 class_labels = ["neither", "offensive", "hate"] # Adjust according to your labels
58 predicted_class_label = class_labels[predicted_class_id]
59
60 # Get the category scores
61 category_scores = torch.softmax(logits, dim=1).numpy().flatten()
62
63 # Create JSON output
64 result = {
65 "text": text,
66 "predicted_label": predicted_class_label,
67 "scores": {label: float(score) for label, score in zip(class_labels, category_scores)}
68 }
69
70 return result
71
72# Example usage
73text = "Singlish text goes here"
74result = classify_text(text)
75
76# Print the result as JSON
77print(json.dumps(result, indent=4))