vignesh1234 commited on
Commit
8ca8159
·
verified ·
1 Parent(s): baee266

Upload tools/guard_v3.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. tools/guard_v3.py +33 -0
tools/guard_v3.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Guard v3 runtime: binary unsafe model + category head + per-category thresholds (sexual and slur lower).
2
+ Same interface as guard.Guard / guard_small.SmallGuard. Loaded by guard.Guard() when data/index/guard_v3.pkl exists
3
+ (GUARD_BACKEND=v2 forces the previous small guard)."""
4
+ import os, pickle
5
+
6
+ CATS = ("sexual", "slur", "profanity", "violence", "self_harm", "other")
7
+
8
+ def score_texts(pkg, texts):
9
+ """Returns (labels, categories, p_unsafe) applying the category-aware thresholds."""
10
+ p = pkg["binary"].predict_proba(list(texts))[:, 1]
11
+ cats = list(pkg["category"].predict(list(texts)))
12
+ thr = pkg.get("category_thresholds", {}); g = float(pkg.get("general_threshold", 0.5))
13
+ labels = []
14
+ for pi, c in zip(p, cats):
15
+ t = float(thr.get(c, g))
16
+ labels.append("unsafe" if pi >= t else "safe")
17
+ return labels, cats, p
18
+
19
+ class GuardV3:
20
+ def __init__(self, enabled=True, path="data/index/guard_v3.pkl", **kw):
21
+ self.enabled = enabled; self.path = path; self._pkg = None; self.model_name = "guard_v3(tfidf-lr+category)"
22
+ def _load(self):
23
+ if self._pkg is None: self._pkg = pickle.load(open(self.path, "rb"))
24
+ def classify_batch(self, texts, role="user", prompts=None):
25
+ if not self.enabled: return [{"label": "safe", "categories": [], "raw": "", "disabled": True} for _ in texts]
26
+ self._load(); labels, cats, p = score_texts(self._pkg, texts)
27
+ thr = self._pkg.get("category_thresholds", {}); g = self._pkg.get("general_threshold", 0.5)
28
+ return [{"label": l, "categories": [c] if l == "unsafe" else [], "raw": f"p_unsafe={pi:.3f} cat={c} thr={thr.get(c, g)}"} for l, c, pi in zip(labels, cats, p)]
29
+ def classify(self, text, role="user", prompt=None):
30
+ return self.classify_batch([text], role, [prompt])[0]
31
+ def refusal_text(self, lang):
32
+ from guard import refusal_text
33
+ return refusal_text(lang)