Qarvexium commited on
Commit
87dd345
·
verified ·
1 Parent(s): 250bbcd

Upload 7 files

Browse files
NoInsult.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import numpy as np
4
+ import torch
5
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
6
+ from safetensors import safe_open
7
+
8
+ MODEL_DIR = "./NoInsult/"
9
+
10
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
11
+
12
+ with safe_open(f"{MODEL_DIR}/model.safetensors", framework="pt", device="cpu") as f:metadata = f.metadata() or {};name = metadata.get("name", "Unknown Model");author = metadata.get("author", "Unknown Author");print(f"Loading {name} by {author}")
13
+
14
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_DIR)
15
+ model = AutoModelForSequenceClassification.from_pretrained(MODEL_DIR).to(device)
16
+ model.eval()
17
+
18
+ with open(os.path.join(MODEL_DIR, "thresholds.json"), "r", encoding="utf-8") as f:config = json.load(f)
19
+
20
+ LABELS = config["labels"]
21
+ THRESHOLDS = np.array(config["thresholds"], dtype=np.float32)
22
+
23
+ print("Labels:", LABELS)
24
+ print("Thresholds:", THRESHOLDS.tolist())
25
+
26
+
27
+ @torch.no_grad()
28
+ def predict(texts, max_length=256):
29
+ """texts: str or list[str]. Returns list of dicts per input text."""
30
+ single = isinstance(texts, str)
31
+ if single:texts = [texts]
32
+ enc = tokenizer(
33
+ texts,
34
+ truncation=True,
35
+ max_length=max_length,
36
+ padding=True,
37
+ return_tensors="pt",
38
+ ).to(device)
39
+
40
+ logits = model(**enc).logits
41
+ probs = torch.sigmoid(logits).cpu().numpy()
42
+
43
+ results = []
44
+ for row in probs:
45
+ flags = (row >= THRESHOLDS)
46
+ results.append({
47
+ "scores": {label: float(p) for label, p in zip(LABELS, row)},
48
+ "flags": {label: bool(f) for label, f in zip(LABELS, flags)},
49
+ "any_flagged": bool(flags.any()),
50
+ })
51
+
52
+ return results[0] if single else results
53
+
54
+
55
+ if __name__ == "__main__":
56
+ examples = [
57
+ "Have a great day, thanks for the help!",
58
+ "You are such an idiot, shut up.",
59
+ ]
60
+ for text, result in zip(examples, predict(examples)):
61
+ print("\nText:", text)
62
+ for label in LABELS:
63
+ marker = "⚠️ " if result["flags"][label] else " "
64
+ print(f" {marker}{label:18s} {result['scores'][label]:.4f}")
65
+ print(" any_flagged:", result["any_flagged"])
NoInsult/config.json ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_cross_attention": false,
3
+ "architectures": [
4
+ "BertForSequenceClassification"
5
+ ],
6
+ "attention_probs_dropout_prob": 0.1,
7
+ "bos_token_id": null,
8
+ "classifier_dropout": null,
9
+ "dtype": "float32",
10
+ "eos_token_id": null,
11
+ "hidden_act": "gelu",
12
+ "hidden_dropout_prob": 0.1,
13
+ "hidden_size": 768,
14
+ "id2label": {
15
+ "0": "toxicity",
16
+ "1": "severe_toxicity",
17
+ "2": "obscene",
18
+ "3": "threat",
19
+ "4": "insult",
20
+ "5": "identity_attack",
21
+ "6": "sexual_explicit"
22
+ },
23
+ "initializer_range": 0.02,
24
+ "intermediate_size": 3072,
25
+ "is_decoder": false,
26
+ "label2id": {
27
+ "identity_attack": 5,
28
+ "insult": 4,
29
+ "obscene": 2,
30
+ "severe_toxicity": 1,
31
+ "sexual_explicit": 6,
32
+ "threat": 3,
33
+ "toxicity": 0
34
+ },
35
+ "layer_norm_eps": 1e-12,
36
+ "max_position_embeddings": 512,
37
+ "model_type": "bert",
38
+ "num_attention_heads": 12,
39
+ "num_hidden_layers": 12,
40
+ "pad_token_id": 0,
41
+ "position_embedding_type": "absolute",
42
+ "problem_type": "multi_label_classification",
43
+ "tie_word_embeddings": true,
44
+ "transformers_version": "5.0.0",
45
+ "type_vocab_size": 2,
46
+ "use_cache": false,
47
+ "vocab_size": 30522
48
+ }
NoInsult/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f494a163eab544d8efc48fb330cf084a15ab8ce45b705e9c140f80384aa1aa62
3
+ size 437974036
NoInsult/thresholds.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "labels": [
3
+ "toxicity",
4
+ "severe_toxicity",
5
+ "obscene",
6
+ "threat",
7
+ "insult",
8
+ "identity_attack",
9
+ "sexual_explicit"
10
+ ],
11
+ "thresholds": [
12
+ 0.909860372543335,
13
+ 0.5,
14
+ 0.983537495136261,
15
+ 0.9544731974601746,
16
+ 0.9325506091117859,
17
+ 0.9784075617790222,
18
+ 0.9820615649223328
19
+ ]
20
+ }
NoInsult/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
NoInsult/tokenizer_config.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "backend": "tokenizers",
3
+ "cls_token": "[CLS]",
4
+ "do_basic_tokenize": true,
5
+ "do_lower_case": true,
6
+ "is_local": false,
7
+ "mask_token": "[MASK]",
8
+ "model_max_length": 1000000000000000019884624838656,
9
+ "never_split": null,
10
+ "pad_token": "[PAD]",
11
+ "sep_token": "[SEP]",
12
+ "strip_accents": null,
13
+ "tokenize_chinese_chars": true,
14
+ "tokenizer_class": "BertTokenizer",
15
+ "unk_token": "[UNK]"
16
+ }
use.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from NoInsult import predict
2
+
3
+ result = predict("I will fuck you up, you piece of shit.")
4
+ print(result["flags"]) # {'toxicity': True, 'severe_toxicity': False, ...}
5
+ print(result["scores"]) # raw sigmoid probabilities per label