Token Classification
Transformers
ONNX
Safetensors
distilbert
logging
text-cleaning
korean
japanese
chinese
slopdam
Instructions to use slopdam/chatter-tagger with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use slopdam/chatter-tagger with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("token-classification", model="slopdam/chatter-tagger")# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForTokenClassification tokenizer = AutoTokenizer.from_pretrained("slopdam/chatter-tagger") model = AutoModelForTokenClassification.from_pretrained("slopdam/chatter-tagger", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Inference module with the guard
Browse files- chatter.py +127 -0
chatter.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: MIT
|
| 2 |
+
"""Remove chatty openers ("Great news!", "Heads up:", "살펴보겠습니다.") from log lines.
|
| 3 |
+
|
| 4 |
+
from slopdam import clean
|
| 5 |
+
from chatter import ChatterTagger
|
| 6 |
+
|
| 7 |
+
tagger = ChatterTagger("slopdam/chatter-tagger")
|
| 8 |
+
tagger([clean("Great news! Successfully deployed api — 3 pods")])
|
| 9 |
+
# ['Successfully deployed api: 3 pods']
|
| 10 |
+
|
| 11 |
+
Run slopdam first: the model was trained on slopdam's `reader` output. It only deletes; it never
|
| 12 |
+
writes new text. Every deletion also has to pass `guard`, a fixed set of rules (one run of whole
|
| 13 |
+
words at the start of a line, ending in punctuation or a Korean connective, no digits, paths, file
|
| 14 |
+
names or key=value), so a line the model is unsure about comes back unchanged.
|
| 15 |
+
"""
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import re
|
| 19 |
+
|
| 20 |
+
KEEP, DELETE, UPPER = 0, 1, 2
|
| 21 |
+
MAX_PIECES = 256
|
| 22 |
+
|
| 23 |
+
LINE_START = re.compile(r"[ \t]*(?:[-*+•][ \t]+|#{1,6}[ \t]+|\d+[.)][ \t]+)?")
|
| 24 |
+
UNSAFE = re.compile(r"[0-9/\\_=@]|\.\w|\w\.\w")
|
| 25 |
+
# An opener ends in punctuation, or (Korean only) in a connective ending such as -면, -로, -히.
|
| 26 |
+
OPENER_END = re.compile(r"(?:[,:!?.…]|[가-힣]*[면로히도피대럼과만데])$")
|
| 27 |
+
MIXED = re.compile(r"[A-Za-z].*[가-힣]|[가-힣].*[A-Za-z]", re.S) # "orders에서" is content
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def rebuild(text: str, offsets: list, labels: list) -> str:
|
| 31 |
+
"""Apply piece tags to text. Spaces after a deleted piece are dropped (line breaks stay);
|
| 32 |
+
leading gaps are kept."""
|
| 33 |
+
out, pos, deleted = [], 0, False
|
| 34 |
+
for (s, e), t in zip(offsets, labels):
|
| 35 |
+
gap = text[pos:s]
|
| 36 |
+
out.append(gap if not deleted or pos == 0 else "\n" * gap.count("\n"))
|
| 37 |
+
if t != DELETE:
|
| 38 |
+
piece = text[s:e]
|
| 39 |
+
out.append(piece[:1].upper() + piece[1:] if t == UPPER else piece)
|
| 40 |
+
deleted, pos = t == DELETE, e
|
| 41 |
+
if not deleted:
|
| 42 |
+
out.append(text[pos:])
|
| 43 |
+
return "".join(out)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def whole_words(offsets: list, labels: list) -> list:
|
| 47 |
+
"""Let the first piece of each word decide for the whole word, so a word is never cut in half."""
|
| 48 |
+
out, first = [], KEEP
|
| 49 |
+
for i, ((s, _), t) in enumerate(zip(offsets, labels)):
|
| 50 |
+
if i == 0 or s != offsets[i - 1][1]:
|
| 51 |
+
first = t
|
| 52 |
+
out.append(t)
|
| 53 |
+
else:
|
| 54 |
+
out.append(DELETE if first == DELETE else KEEP)
|
| 55 |
+
return out
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def guard(text: str, offsets: list, labels: list) -> list:
|
| 59 |
+
"""The safety envelope around the model. Per line, deletions are kept only if they form one
|
| 60 |
+
run of whole pieces starting where the line's text starts (after a list or heading marker),
|
| 61 |
+
leave something behind, end in punctuation or a Korean connective ending, and contain no
|
| 62 |
+
digits, paths, file names, key=value or a mix of Latin and Hangul. Upper-casing
|
| 63 |
+
is kept only on the first piece after that run. Any other line is left exactly as it was."""
|
| 64 |
+
out = list(labels)
|
| 65 |
+
line_start = 0
|
| 66 |
+
lines = []
|
| 67 |
+
for line in text.split("\n"):
|
| 68 |
+
lines.append((line_start, line_start + len(line)))
|
| 69 |
+
line_start += len(line) + 1
|
| 70 |
+
for a, b in lines:
|
| 71 |
+
idx = [i for i, (s, _) in enumerate(offsets) if a <= s < b]
|
| 72 |
+
if not idx or all(labels[i] == KEEP for i in idx):
|
| 73 |
+
continue
|
| 74 |
+
start = LINE_START.match(text, a, b).end()
|
| 75 |
+
run = [i for i in idx if labels[i] == DELETE]
|
| 76 |
+
first_kept = next((i for i in idx if labels[i] != DELETE and offsets[i][0] >= start), None)
|
| 77 |
+
span = text[offsets[run[0]][0] : offsets[run[-1]][1]] if run else ""
|
| 78 |
+
ok = not run or (
|
| 79 |
+
offsets[run[0]][0] == start
|
| 80 |
+
and run == list(range(run[0], run[-1] + 1))
|
| 81 |
+
and first_kept is not None
|
| 82 |
+
and first_kept == run[-1] + 1
|
| 83 |
+
and not UNSAFE.search(span)
|
| 84 |
+
and OPENER_END.search(span)
|
| 85 |
+
and not MIXED.search(span)
|
| 86 |
+
)
|
| 87 |
+
uppers = [i for i in idx if labels[i] == UPPER]
|
| 88 |
+
ok = ok and all(i == first_kept and run for i in uppers)
|
| 89 |
+
if not ok:
|
| 90 |
+
for i in idx:
|
| 91 |
+
out[i] = KEEP
|
| 92 |
+
return out
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def predict(model, tok, texts: list, device, batch: int = 64, use_guard: bool = True) -> list:
|
| 96 |
+
import torch
|
| 97 |
+
|
| 98 |
+
model.eval()
|
| 99 |
+
out = []
|
| 100 |
+
with torch.no_grad():
|
| 101 |
+
for i in range(0, len(texts), batch):
|
| 102 |
+
chunk = texts[i : i + batch]
|
| 103 |
+
enc = tok(chunk, return_offsets_mapping=True, add_special_tokens=False, padding=True,
|
| 104 |
+
truncation=True, max_length=MAX_PIECES, return_tensors="pt")
|
| 105 |
+
offsets = enc.pop("offset_mapping")
|
| 106 |
+
pred = model(**{k: v.to(device) for k, v in enc.items()}).logits.argmax(-1).cpu()
|
| 107 |
+
for k, text in enumerate(chunk):
|
| 108 |
+
n = int(enc["attention_mask"][k].sum())
|
| 109 |
+
spans = offsets[k, :n].tolist()
|
| 110 |
+
labels = whole_words(spans, pred[k, :n].tolist())
|
| 111 |
+
out.append(rebuild(text, spans, guard(text, spans, labels) if use_guard else labels))
|
| 112 |
+
return out
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class ChatterTagger:
|
| 116 |
+
"""Load the tagger from the Hub (or a local folder) and strip openers from lines of text."""
|
| 117 |
+
|
| 118 |
+
def __init__(self, path: str = "slopdam/chatter-tagger", device: str = "cpu"):
|
| 119 |
+
import torch
|
| 120 |
+
from transformers import AutoModelForTokenClassification, AutoTokenizer
|
| 121 |
+
|
| 122 |
+
self.device = torch.device(device)
|
| 123 |
+
self.tok = AutoTokenizer.from_pretrained(path)
|
| 124 |
+
self.model = AutoModelForTokenClassification.from_pretrained(path).to(self.device)
|
| 125 |
+
|
| 126 |
+
def __call__(self, texts: list, batch: int = 64) -> list:
|
| 127 |
+
return predict(self.model, self.tok, list(texts), self.device, batch)
|