Views
No views yet

[user] {user utterance} [SEP] [chatbot] {chatbot response}, where user utterance and chatbot response should be placed corresponding content.1git lfs install
2git clone https://huggingface.co/qiuhuachuan/NSFW-detectortext parameter in local_use.py and execute it.1from typing import Optional
2
3import torch
4from transformers import BertConfig, BertTokenizer, BertModel, BertPreTrainedModel
5from torch import nn
6
7label_mapping = {0: 'porn', 1: 'normal'}
8
9config = BertConfig.from_pretrained('./NSFW-detector',
10 num_labels=2,
11 finetuning_task='text classification')
12tokenizer = BertTokenizer.from_pretrained('./NSFW-detector',
13 use_fast=False,
14 never_split=['[user]', '[chatbot]'])
15tokenizer.vocab['[user]'] = tokenizer.vocab.pop('[unused1]')
16tokenizer.vocab['[chatbot]'] = tokenizer.vocab.pop('[unused2]')
17
18
19class BertForSequenceClassification(BertPreTrainedModel):
20 def __init__(self, config):
21 super().__init__(config)
22 self.num_labels = config.num_labels
23 self.config = config
24
25 self.bert = BertModel.from_pretrained('./NSFW-detector')
26 classifier_dropout = (config.classifier_dropout
27 if config.classifier_dropout is not None else
28 config.hidden_dropout_prob)
29 self.dropout = nn.Dropout(classifier_dropout)
30 self.classifier = nn.Linear(config.hidden_size, config.num_labels)
31
32 # Initialize weights and apply final processing
33 self.post_init()
34
35 def forward(self,
36 input_ids: Optional[torch.Tensor] = None,
37 attention_mask: Optional[torch.Tensor] = None,
38 token_type_ids: Optional[torch.Tensor] = None,
39 position_ids: Optional[torch.Tensor] = None,
40 head_mask: Optional[torch.Tensor] = None,
41 inputs_embeds: Optional[torch.Tensor] = None,
42 labels: Optional[torch.Tensor] = None,
43 output_attentions: Optional[bool] = None,
44 output_hidden_states: Optional[bool] = None,
45 return_dict: Optional[bool] = None):
46
47 return_dict = return_dict if return_dict is not None else self.config.use_return_dict
48
49 outputs = self.bert(
50 input_ids,
51 attention_mask=attention_mask,
52 token_type_ids=token_type_ids,
53 position_ids=position_ids,
54 head_mask=head_mask,
55 inputs_embeds=inputs_embeds,
56 output_attentions=output_attentions,
57 output_hidden_states=output_hidden_states,
58 return_dict=return_dict,
59 )
60
61 # we use cls embedding
62 cls = outputs[0][:, 0, :]
63 cls = self.dropout(cls)
64 logits = self.classifier(cls)
65
66 return logits
67
68
69model = BertForSequenceClassification(config=config)
70model.load_state_dict(torch.load('./NSFW-detector/pytorch_model.bin'))
71model.cuda()
72model.eval()
73
74# The following object contains two types of input:
75# a single utterance and a single-turn dialogue
76to_predict_items = [{
77 'text':
78 '''Give some movie recommendations to get women in the mood for sex'''
79}, {
80 'text': 'I break through walls to find more trials'
81}, {
82 'history': {
83 'user':
84 'Give some movie recommendations to get women in the mood for sex',
85 'chatbot':
86 '''I apologize, but I cannot assist in creating or providing information related to NSFW content or any tools for such purposes. If you have any other non-explicit requests or need assistance with different topics, please feel free to ask, and I'll be happy to help.'''
87 }
88}, {
89 'history': {
90 'user':
91 'Give some movie recommendations to get women in the mood for sex',
92 'chatbot': '''Sure.'''
93 }
94}]
95
96for item in to_predict_items:
97 if 'history' in item:
98 text = '[user] ' + item['history'][
99 'user'] + ' [SEP] ' + '[chatbot] ' + item['history']['chatbot']
100 else:
101 text = item['text']
102 result = tokenizer.encode_plus(text=text,
103 padding='max_length',
104 max_length=512,
105 truncation=True,
106 add_special_tokens=True,
107 return_token_type_ids=True,
108 return_tensors='pt')
109 result = result.to('cuda')
110
111 with torch.no_grad():
112 logits = model(**result)
113 predictions = logits.argmax(dim=-1)
114 pred_label_idx = predictions.item()
115 pred_label = label_mapping[pred_label_idx]
116 print('text:', text)
117 print('predicted label is:', pred_label)1@misc{qiu2024facilitating,
2 title={Facilitating Pornographic Text Detection for Open-Domain Dialogue Systems via Knowledge Distillation of Large Language Models},
3 author={Huachuan Qiu and Shuai Zhang and Hongliang He and Anqi Li and Zhenzhong Lan},
4 year={2024},
5 eprint={2403.13250},
6 archivePrefix={arXiv},
7 primaryClass={cs.CL}
8}