Spaces:
Running on Zero
Running on Zero
Upload 6 files
Browse files- README.md +19 -6
- app.py +56 -0
- messages.csv +0 -0
- mmdsys_model.py +76 -0
- requirements.txt +2 -0
- train.py +61 -0
README.md
CHANGED
|
@@ -1,15 +1,28 @@
|
|
| 1 |
---
|
| 2 |
title: MMDSYS
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
colorTo: red
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version: 6.30.0
|
| 8 |
-
python_version: '3.12'
|
| 9 |
app_file: app.py
|
| 10 |
pinned: false
|
| 11 |
-
license:
|
| 12 |
short_description: Message Moderation Detection SYStem
|
| 13 |
---
|
| 14 |
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
title: MMDSYS
|
| 3 |
+
emoji: 🛡️
|
| 4 |
+
colorFrom: indigo
|
| 5 |
colorTo: red
|
| 6 |
sdk: gradio
|
|
|
|
|
|
|
| 7 |
app_file: app.py
|
| 8 |
pinned: false
|
| 9 |
+
license: mit
|
| 10 |
short_description: Message Moderation Detection SYStem
|
| 11 |
---
|
| 12 |
|
| 13 |
+
# MMDSYS: Message Moderation Detection SYStem
|
| 14 |
+
|
| 15 |
+
Classifies a message as **good**, **neutral** or **bad**. If it is bad, it also says
|
| 16 |
+
what type of bad: harassment, sexual, hate, violence, scam_spam or self_harm.
|
| 17 |
+
|
| 18 |
+
## Files
|
| 19 |
+
- `app.py`: Gradio interface
|
| 20 |
+
- `mmdsys_model.py`: features, network and prediction code
|
| 21 |
+
- `train.py`: retrain the model on `messages.csv` (`python train.py`)
|
| 22 |
+
- `messages.csv`: synthetic training data (`text,severity,category`)
|
| 23 |
+
- `requirements.txt`: dependencies
|
| 24 |
+
- `message_model.pt`: **you add this** (trained weights from the notebook)
|
| 25 |
+
|
| 26 |
+
## Notes
|
| 27 |
+
The bundled dataset is synthetic. Treat results as a demo, not a reliable moderator,
|
| 28 |
+
and keep a human in the loop for anything that matters.
|
app.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import gradio as gr
|
| 3 |
+
from mmdsys_model import MODEL_PATH, load_model, classify
|
| 4 |
+
|
| 5 |
+
model = None
|
| 6 |
+
load_error = None
|
| 7 |
+
if os.path.exists(MODEL_PATH):
|
| 8 |
+
try:
|
| 9 |
+
model = load_model(MODEL_PATH)
|
| 10 |
+
except Exception as e: # wrong architecture, corrupt file, etc.
|
| 11 |
+
load_error = f"Could not load {MODEL_PATH}: {e}"
|
| 12 |
+
else:
|
| 13 |
+
load_error = f"{MODEL_PATH} not found. Upload your trained weights to the root of this Space."
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def predict(text):
|
| 17 |
+
if model is None:
|
| 18 |
+
raise gr.Error(load_error)
|
| 19 |
+
if not text or not text.strip():
|
| 20 |
+
return None, None, ""
|
| 21 |
+
severity, types = classify(model, text)
|
| 22 |
+
verdict = max(severity, key=severity.get)
|
| 23 |
+
if types:
|
| 24 |
+
top = max(types, key=types.get)
|
| 25 |
+
summary = f"BAD: {top} ({types[top]:.0%})"
|
| 26 |
+
else:
|
| 27 |
+
summary = verdict.upper()
|
| 28 |
+
return severity, types, summary
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
EXAMPLES = [
|
| 32 |
+
"Thanks so much, that was really helpful!",
|
| 33 |
+
"The meeting is at 3pm in room 204.",
|
| 34 |
+
"nobody likes you, just disappear",
|
| 35 |
+
"Congratulations!! You won a free iPhone, click this link now",
|
| 36 |
+
"I'm going to hurt you, watch your back",
|
| 37 |
+
"I need to kill the process that's hanging on the server",
|
| 38 |
+
]
|
| 39 |
+
|
| 40 |
+
with gr.Blocks(title="MMDSYS") as demo:
|
| 41 |
+
gr.Markdown("# 🛡️ MMDSYS\n**Message Moderation Detection SYStem**: good, neutral or bad, "
|
| 42 |
+
"and if bad, what type.")
|
| 43 |
+
if load_error:
|
| 44 |
+
gr.Markdown(f"⚠️ {load_error}")
|
| 45 |
+
inp = gr.Textbox(label="Message", lines=3, placeholder="Type a message to check...")
|
| 46 |
+
btn = gr.Button("Check message", variant="primary")
|
| 47 |
+
verdict = gr.Textbox(label="Verdict", interactive=False)
|
| 48 |
+
with gr.Row():
|
| 49 |
+
sev_out = gr.Label(label="Severity", num_top_classes=3)
|
| 50 |
+
type_out = gr.Label(label="Type of bad (only shown when bad)", num_top_classes=6)
|
| 51 |
+
gr.Examples(EXAMPLES, inputs=inp)
|
| 52 |
+
btn.click(predict, inp, [sev_out, type_out, verdict])
|
| 53 |
+
inp.submit(predict, inp, [sev_out, type_out, verdict])
|
| 54 |
+
|
| 55 |
+
if __name__ == "__main__":
|
| 56 |
+
demo.launch()
|
messages.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
mmdsys_model.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""MMDSYS model code. Must match the notebook the weights were trained with."""
|
| 2 |
+
import re, zlib
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
|
| 7 |
+
SEVERITY = ["good", "neutral", "bad"]
|
| 8 |
+
CATEGORIES = ["harassment", "sexual", "hate", "violence", "scam_spam", "self_harm"]
|
| 9 |
+
BAD = SEVERITY.index("bad")
|
| 10 |
+
BUCKETS = 2 ** 18
|
| 11 |
+
MODEL_PATH = "message_model.pt"
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def featurize(text):
|
| 15 |
+
"""Text -> list of hashed feature ids (words + word bigrams + char 3-5 grams)."""
|
| 16 |
+
words = re.findall(r"[\w']+|[^\w\s]", text.lower())
|
| 17 |
+
feats = []
|
| 18 |
+
for i, w in enumerate(words):
|
| 19 |
+
feats.append("w:" + w)
|
| 20 |
+
if i:
|
| 21 |
+
feats.append("b:" + words[i - 1] + "_" + w)
|
| 22 |
+
padded = f"<{w}>"
|
| 23 |
+
for n in (3, 4, 5):
|
| 24 |
+
for j in range(len(padded) - n + 1):
|
| 25 |
+
feats.append("c:" + padded[j:j + n])
|
| 26 |
+
return [zlib.crc32(f.encode()) % BUCKETS for f in feats]
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def collate(batch):
|
| 30 |
+
ids, offsets, sev, cat = [], [], [], []
|
| 31 |
+
pos = 0
|
| 32 |
+
for text, s, c in batch:
|
| 33 |
+
f = featurize(text) or [0]
|
| 34 |
+
offsets.append(pos)
|
| 35 |
+
ids.extend(f)
|
| 36 |
+
pos += len(f)
|
| 37 |
+
sev.append(s)
|
| 38 |
+
cat.append(c)
|
| 39 |
+
return (torch.tensor(ids), torch.tensor(offsets),
|
| 40 |
+
torch.tensor(sev), torch.tensor(cat))
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class MessageNet(nn.Module):
|
| 44 |
+
def __init__(self, dim=128, hidden=256):
|
| 45 |
+
super().__init__()
|
| 46 |
+
self.embed = nn.EmbeddingBag(BUCKETS, dim, mode="mean")
|
| 47 |
+
self.body = nn.Sequential(
|
| 48 |
+
nn.Linear(dim, hidden), nn.ReLU(), nn.Dropout(0.3),
|
| 49 |
+
nn.Linear(hidden, hidden), nn.ReLU(), nn.Dropout(0.3),
|
| 50 |
+
)
|
| 51 |
+
self.severity = nn.Linear(hidden, len(SEVERITY))
|
| 52 |
+
self.category = nn.Linear(hidden, len(CATEGORIES))
|
| 53 |
+
|
| 54 |
+
def forward(self, ids, offsets):
|
| 55 |
+
h = self.body(self.embed(ids, offsets))
|
| 56 |
+
return self.severity(h), self.category(h)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def load_model(path=MODEL_PATH, device="cpu"):
|
| 60 |
+
model = MessageNet().to(device)
|
| 61 |
+
model.load_state_dict(torch.load(path, map_location=device))
|
| 62 |
+
model.eval()
|
| 63 |
+
return model
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def classify(model, text, device="cpu"):
|
| 67 |
+
"""Returns (severity_scores, type_scores_or_None)."""
|
| 68 |
+
ids, off, _, _ = [t.to(device) for t in collate([(text, 0, -100)])]
|
| 69 |
+
with torch.no_grad():
|
| 70 |
+
ls, lc = model(ids, off)
|
| 71 |
+
ps, pc = F.softmax(ls, 1)[0], F.softmax(lc, 1)[0]
|
| 72 |
+
severity = {k: float(v) for k, v in zip(SEVERITY, ps)}
|
| 73 |
+
types = None
|
| 74 |
+
if int(ps.argmax()) == BAD:
|
| 75 |
+
types = {k: float(v) for k, v in zip(CATEGORIES, pc)}
|
| 76 |
+
return severity, types
|
requirements.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
--extra-index-url https://download.pytorch.org/whl/cpu
|
| 2 |
+
torch
|
train.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Retrain MMDSYS on messages.csv. Usage: python train.py [messages.csv]"""
|
| 2 |
+
import csv, random, sys
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
from mmdsys_model import SEVERITY, CATEGORIES, MODEL_PATH, MessageNet, collate
|
| 6 |
+
|
| 7 |
+
DATA = sys.argv[1] if len(sys.argv) > 1 else "messages.csv"
|
| 8 |
+
EPOCHS, BATCH, LR = 12, 64, 2e-3
|
| 9 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 10 |
+
|
| 11 |
+
data = []
|
| 12 |
+
with open(DATA, newline="", encoding="utf-8") as f:
|
| 13 |
+
for r in csv.DictReader(f):
|
| 14 |
+
sev = r["severity"].strip().lower()
|
| 15 |
+
cat = (r.get("category") or "").strip().lower()
|
| 16 |
+
if sev not in SEVERITY:
|
| 17 |
+
continue
|
| 18 |
+
c = CATEGORIES.index(cat) if (sev == "bad" and cat in CATEGORIES) else -100
|
| 19 |
+
data.append((r["text"], SEVERITY.index(sev), c))
|
| 20 |
+
|
| 21 |
+
random.seed(0)
|
| 22 |
+
random.shuffle(data)
|
| 23 |
+
cut = max(1, int(len(data) * 0.9))
|
| 24 |
+
train_set, val_set = data[:cut], data[cut:] or data[:cut]
|
| 25 |
+
print(f"{len(train_set)} train / {len(val_set)} validation")
|
| 26 |
+
|
| 27 |
+
counts = torch.bincount(torch.tensor([s for _, s, _ in train_set]), minlength=3).float()
|
| 28 |
+
w_sev = (counts.sum() / (3 * counts.clamp(min=1))).to(device)
|
| 29 |
+
model = MessageNet().to(device)
|
| 30 |
+
opt = torch.optim.AdamW(model.parameters(), lr=LR, weight_decay=1e-4)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def step(batch):
|
| 34 |
+
ids, off, sev, cat = [t.to(device) for t in batch]
|
| 35 |
+
ls, lc = model(ids, off)
|
| 36 |
+
loss = F.cross_entropy(ls, sev, weight=w_sev)
|
| 37 |
+
if (cat != -100).any():
|
| 38 |
+
loss = loss + F.cross_entropy(lc, cat, ignore_index=-100)
|
| 39 |
+
return loss, ls, lc, sev, cat
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
for epoch in range(1, EPOCHS + 1):
|
| 43 |
+
model.train()
|
| 44 |
+
random.shuffle(train_set)
|
| 45 |
+
for i in range(0, len(train_set), BATCH):
|
| 46 |
+
loss, *_ = step(collate(train_set[i:i + BATCH]))
|
| 47 |
+
opt.zero_grad(); loss.backward(); opt.step()
|
| 48 |
+
model.eval()
|
| 49 |
+
sev_ok = cat_ok = cat_n = 0
|
| 50 |
+
with torch.no_grad():
|
| 51 |
+
for i in range(0, len(val_set), 256):
|
| 52 |
+
_, ls, lc, sev, cat = step(collate(val_set[i:i + 256]))
|
| 53 |
+
sev_ok += (ls.argmax(1) == sev).sum().item()
|
| 54 |
+
m = cat != -100
|
| 55 |
+
cat_n += m.sum().item()
|
| 56 |
+
cat_ok += (lc.argmax(1)[m] == cat[m]).sum().item()
|
| 57 |
+
print(f"epoch {epoch:2d} severity acc {sev_ok/len(val_set):.3f} "
|
| 58 |
+
f"category acc {cat_ok/max(cat_n,1):.3f}")
|
| 59 |
+
|
| 60 |
+
torch.save(model.state_dict(), MODEL_PATH)
|
| 61 |
+
print("saved", MODEL_PATH)
|