Replace toxicity model with multi-label classifier

This commit is contained in:
Jordan Wages 2026-08-26 17:00:49 -05:00
commit 1568c787f8
24 changed files with 2581129 additions and 119717 deletions

View file

@ -6,12 +6,7 @@ Toxic Content Filter is a browser extension that automatically identifies and hi
The extension performs all inference locally. Social-media content is never sent to an external classification service. The extension performs all inference locally. Social-media content is never sent to an external classification service.
The initial classifier produces a simple binary classification: The classifier produces independent toxicity-category probabilities. Users enable the categories they want filtered and configure one shared threshold; content is filtered when any enabled category reaches it.
* **Toxic**
* **Non-toxic**
The model should also expose its confidence/probability, allowing the user to configure the threshold at which content is filtered.
## Goals ## Goals
@ -27,16 +22,7 @@ The extension should:
## Classification Model ## Classification Model
The initial implementation will use a small transformer model trained specifically for toxicity classification. The implementation uses `wagesj45/multilabel-toxic-comment-classifier`, a multilingual ModernBERT classifier distributed under Apache-2.0. It produces probability scores for toxicity, severe toxicity, obscene, threat, insult, identity attack, and sexual explicit content.
A candidate is Citizen Lab's multilingual DistilBERT toxicity classifier, which produces:
```text
toxic
not_toxic
```
along with classification probabilities.
The model should be converted to ONNX and quantized as aggressively as practical while retaining acceptable classification accuracy. The model should be converted to ONNX and quantized as aggressively as practical while retaining acceptable classification accuracy.
@ -45,7 +31,7 @@ The deployed extension does not require Python or a native companion application
Conceptually: Conceptually:
```text ```text
DistilBERT toxicity model ModernBERT multi-label toxicity model
| |
v v
ONNX ONNX

View file

@ -35,18 +35,18 @@ python3 -m pip install -r tools/requirements-model.txt
# Inspect architecture, labels, tokenizer, and resolved source revision. # Inspect architecture, labels, tokenizer, and resolved source revision.
python3 tools/convert_model.py inspect \ python3 tools/convert_model.py inspect \
--model wagesj45/toxic-comment-classifier --model wagesj45/multilabel-toxic-comment-classifier
# Use the immutable commit printed by inspection for a release artifact. # Use the immutable commit printed by inspection for a release artifact.
python3 tools/convert_model.py prepare \ python3 tools/convert_model.py prepare \
--model wagesj45/toxic-comment-classifier \ --model wagesj45/multilabel-toxic-comment-classifier \
--revision <resolved-huggingface-commit> --revision <resolved-huggingface-commit>
python3 tools/convert_model.py validate python3 tools/convert_model.py validate
``` ```
Preparation writes the Transformers.js-compatible files and `model-manifest.json` under `public/models/toxicity/`. The manifest records the source revision, Apache 2.0 license, toxic/non-toxic label indices, maximum sequence length, and int8 quantization format. Source PyTorch/safetensors weights are never copied into the extension. Preparation writes the Transformers.js-compatible files and `model-manifest.json` under `public/models/toxicity/`. The manifest records the source revision, Apache 2.0 license, ordered multi-label category mapping, 512-token maximum sequence length, and int8 quantization format. Source PyTorch/safetensors weights are never copied into the extension.
If the model uses generic labels such as `LABEL_0` and `LABEL_1`, pass `--toxic-index` and `--non-toxic-index` to `prepare`; the command refuses to guess an ambiguous mapping. The bundled [multi-label ModernBERT model](https://huggingface.co/wagesj45/multilabel-toxic-comment-classifier) produces independent scores for toxicity, severe toxicity, obscene, threat, insult, identity attack, and sexual explicit content. Preparation refuses models that do not expose exactly this label set.
VibeGuard injects a lightweight content script on ordinary web pages, but reads and processes content only when a validated site definition matches the page. The extension includes a bundled definition collection for the official Mastodon web interface, Threads, old Reddit, and X. The Threads definition covers both `threads.com` and legacy `threads.net` URLs using semantic and data-attribute selectors; the Reddit definition targets `old.reddit.com`, while the X definition covers both `x.com` and legacy `twitter.com` URLs. The default subscription follows the repository's raw JSON collection and refreshes weekly, while the bundled copy remains available offline. Additional JSON subscriptions, local overrides, and disabled definitions are managed in the options page. Definitions are declarative selectors and URL patterns, never executable code. VibeGuard injects a lightweight content script on ordinary web pages, but reads and processes content only when a validated site definition matches the page. The extension includes a bundled definition collection for the official Mastodon web interface, Threads, old Reddit, and X. The Threads definition covers both `threads.com` and legacy `threads.net` URLs using semantic and data-attribute selectors; the Reddit definition targets `old.reddit.com`, while the X definition covers both `x.com` and legacy `twitter.com` URLs. The default subscription follows the repository's raw JSON collection and refreshes weekly, while the bundled copy remains available offline. Additional JSON subscriptions, local overrides, and disabled definitions are managed in the options page. Definitions are declarative selectors and URL patterns, never executable code.
@ -71,7 +71,7 @@ Inference runs locally through ONNX Runtime's WASM backend using the bundled qua
## Options page ## Options page
Open the extensions options page to change the threshold, filtering mode, and score display. The Site definitions section manages JSON subscriptions, which refresh automatically once per week and can also be refreshed manually. Local overrides can be imported from or exported to JSON and are validated before they are saved. A failed or invalid subscription update leaves the last-known-good definitions active. Open the extensions options page to change the shared category threshold, enabled categories, filtering mode, and score display. A post is filtered when any enabled category reaches the threshold, and a collapsed placeholder identifies the highest-scoring matching category. The Site definitions section manages JSON subscriptions, which refresh automatically once per week and can also be refreshed manually. Local overrides can be imported from or exported to JSON and are validated before they are saved. A failed or invalid subscription update leaves the last-known-good definitions active.
The options page uses the locally bundled [Bulma CSS](https://bulma.io/) v1.0.3 stylesheet. No options-page styling or runtime dependency is loaded from a CDN. The options page uses the locally bundled [Bulma CSS](https://bulma.io/) v1.0.3 stylesheet. No options-page styling or runtime dependency is loaded from a CDN.
@ -88,7 +88,7 @@ VibeGuard requests the following permissions:
## Model and third-party licenses ## Model and third-party licenses
The packaged toxicity model is distributed under the Apache License 2.0. Its source revision, label mapping, sequence length, and quantization details are recorded in `public/models/toxicity/model-manifest.json`. The packaged toxicity model is distributed under the Apache License 2.0. Its source revision, multi-label mapping, sequence length, and quantization details are recorded in `public/models/toxicity/model-manifest.json`.
VibeGuard also bundles [Bulma CSS v1.0.3](https://github.com/jgthms/bulma), which is distributed under the MIT License. The projects own code is licensed under the terms in [LICENSE](LICENSE). VibeGuard also bundles [Bulma CSS v1.0.3](https://github.com/jgthms/bulma), which is distributed under the MIT License. The projects own code is licensed under the terms in [LICENSE](LICENSE).

View file

@ -0,0 +1,197 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object
form, made available under the License, as indicated by a copyright
notice that is included in or attached to the work (an example is
provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work
or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You meet
the following conditions:
(a) You must give any other recipients of the Work or Derivative Works
a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that
You distribute, all copyright, patent, trademark, and attribution
notices from the Source form of the Work, excluding those notices
that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View file

@ -1,37 +1,98 @@
{ {
"activation": "gelu",
"architectures": [ "architectures": [
"DistilBertForSequenceClassification" "ModernBertForSequenceClassification"
], ],
"attention_dropout": 0.1, "attention_bias": false,
"bos_token_id": null, "attention_dropout": 0.0,
"dim": 768, "bos_token_id": 2,
"dropout": 0.1, "classifier_activation": "gelu",
"classifier_bias": false,
"classifier_dropout": 0.0,
"classifier_pooling": "mean",
"cls_token_id": 1,
"decoder_bias": true,
"deterministic_flash_attn": false,
"dtype": "float32", "dtype": "float32",
"eos_token_id": null, "embedding_dropout": 0.0,
"hidden_dim": 3072, "eos_token_id": 1,
"global_attn_every_n_layers": 3,
"gradient_checkpointing": false,
"hidden_activation": "gelu",
"hidden_size": 384,
"id2label": { "id2label": {
"0": "not_toxic", "0": "toxicity",
"1": "toxic" "1": "severe_toxicity",
"2": "obscene",
"3": "threat",
"4": "insult",
"5": "identity_attack",
"6": "sexual_explicit"
}, },
"initializer_cutoff_factor": 2.0,
"initializer_range": 0.02, "initializer_range": 0.02,
"intermediate_size": 1152,
"label2id": { "label2id": {
"not_toxic": 0, "identity_attack": 5,
"toxic": 1 "insult": 4,
"obscene": 2,
"severe_toxicity": 1,
"sexual_explicit": 6,
"threat": 3,
"toxicity": 0
}, },
"max_position_embeddings": 512, "layer_norm_eps": 1e-05,
"model_type": "distilbert", "layer_types": [
"n_heads": 12, "full_attention",
"n_layers": 6, "sliding_attention",
"output_past": true, "sliding_attention",
"full_attention",
"sliding_attention",
"sliding_attention",
"full_attention",
"sliding_attention",
"sliding_attention",
"full_attention",
"sliding_attention",
"sliding_attention",
"full_attention",
"sliding_attention",
"sliding_attention",
"full_attention",
"sliding_attention",
"sliding_attention",
"full_attention",
"sliding_attention",
"sliding_attention",
"full_attention"
],
"local_attention": 128,
"mask_token_id": 4,
"max_position_embeddings": 8192,
"mlp_bias": false,
"mlp_dropout": 0.0,
"model_type": "modernbert",
"norm_bias": false,
"norm_eps": 1e-05,
"num_attention_heads": 6,
"num_hidden_layers": 22,
"pad_token_id": 0, "pad_token_id": 0,
"problem_type": "single_label_classification", "position_embedding_type": "sans_pos",
"qa_dropout": 0.1, "problem_type": "multi_label_classification",
"seq_classif_dropout": 0.2, "rope_parameters": {
"sinusoidal_pos_embds": false, "full_attention": {
"tie_weights_": true, "rope_theta": 160000.0,
"rope_type": "default"
},
"sliding_attention": {
"rope_theta": 160000.0,
"rope_type": "default"
}
},
"sep_token_id": 1,
"sparse_pred_ignore_index": -100,
"sparse_prediction": false,
"tie_word_embeddings": true, "tie_word_embeddings": true,
"transformers_version": "5.15.1", "transformers_version": "5.15.1",
"use_cache": false, "use_cache": false,
"vocab_size": 119547 "vocab_size": 256000
} }

View file

@ -1,15 +1,19 @@
{ {
"source": "wagesj45/toxic-comment-classifier", "source": "wagesj45/multilabel-toxic-comment-classifier",
"revision": "a7d2df2ead42f0bce00b330939574a02266772f5", "revision": "d90fd72e603240957e36d6afc8829d6988decff6",
"architecture": "DistilBertForSequenceClassification", "architecture": "ModernBertForSequenceClassification",
"labels": { "labels": {
"toxic": 1,
"nonToxic": 0,
"names": { "names": {
"not_toxic": 0, "toxicity": 0,
"toxic": 1 "severe_toxicity": 1,
"obscene": 2,
"threat": 3,
"insult": 4,
"identity_attack": 5,
"sexual_explicit": 6
} }
}, },
"scoring": "multi-label-sigmoid",
"maxLength": 512, "maxLength": 512,
"quantization": "int8-dynamic", "quantization": "int8-dynamic",
"runtime": "onnxruntime-web-wasm", "runtime": "onnxruntime-web-wasm",

Binary file not shown.

File diff suppressed because it is too large Load diff

View file

@ -1,15 +1,25 @@
{ {
"backend": "tokenizers", "backend": "tokenizers",
"cls_token": "[CLS]", "bos_token": "<bos>",
"do_lower_case": false, "clean_up_tokenization_spaces": false,
"cls_token": "<bos>",
"eos_token": "<eos>",
"extra_special_tokens": [
"<start_of_turn>",
"<end_of_turn>"
],
"is_local": false, "is_local": false,
"local_files_only": false, "local_files_only": false,
"mask_token": "[MASK]", "mask_token": "<mask>",
"model_max_length": 512, "model_input_names": [
"pad_token": "[PAD]", "input_ids",
"sep_token": "[SEP]", "attention_mask"
"strip_accents": null, ],
"tokenize_chinese_chars": true, "model_max_length": 8192,
"tokenizer_class": "BertTokenizer", "pad_token": "<pad>",
"unk_token": "[UNK]" "padding_side": "right",
"sep_token": "<eos>",
"spaces_between_special_tokens": false,
"tokenizer_class": "TokenizersBackend",
"unk_token": "<unk>"
} }

View file

@ -17,12 +17,18 @@
<p class="subtitle">Configure local toxicity filtering for supported sites.</p> <p class="subtitle">Configure local toxicity filtering for supported sites.</p>
<form id="settings"> <form id="settings">
<div class="field"> <div class="field">
<label class="label" for="threshold">Toxicity threshold: <output id="threshold-value">80%</output></label> <label class="label" for="threshold">Category threshold: <output id="threshold-value">80%</output></label>
<div class="control"> <div class="control">
<input class="slider is-fullwidth" id="threshold" type="range" min="0" max="1" step=".01"> <input class="slider is-fullwidth" id="threshold" type="range" min="0" max="1" step=".01">
</div> </div>
</div> </div>
<fieldset class="field">
<legend class="label">Categories to filter</legend>
<p class="help mb-2">A post is filtered when any selected category reaches the threshold.</p>
<div id="enabled-labels" class="content"></div>
</fieldset>
<div class="field"> <div class="field">
<label class="label" for="filter-mode">Filtering mode</label> <label class="label" for="filter-mode">Filtering mode</label>
<div class="control"> <div class="control">
@ -36,7 +42,7 @@
</div> </div>
<div class="field"> <div class="field">
<label class="checkbox"><input id="show-score" type="checkbox"> Show toxicity score</label> <label class="checkbox"><input id="show-score" type="checkbox"> Show highest matching category score</label>
</div> </div>
<fieldset class="field"> <fieldset class="field">

View file

@ -1,4 +1,4 @@
import type { InferenceResult, Settings } from "../shared/types"; import { TOXICITY_LABELS, type InferenceResult, type Settings, type ToxicityLabel } from "../shared/types";
const HIDDEN = "data-vibeguard-hidden"; const HIDDEN = "data-vibeguard-hidden";
const ORIGINAL_DISPLAY = "data-vibeguard-original-display"; const ORIGINAL_DISPLAY = "data-vibeguard-original-display";
@ -11,7 +11,8 @@ export interface FilterOptions {
} }
export function applyResult(element: Element, result: InferenceResult, settings: Settings, options: FilterOptions = {}): void { export function applyResult(element: Element, result: InferenceResult, settings: Settings, options: FilterOptions = {}): void {
const shouldFilter = result.label === "toxic" && result.probability >= settings.threshold; const selected = selectFilterLabel(result, settings);
const shouldFilter = selected !== undefined;
const postId = options.postId ?? result.id; const postId = options.postId ?? result.id;
if (!shouldFilter) { restore(element, postId); return; } if (!shouldFilter) { restore(element, postId); return; }
@ -31,7 +32,7 @@ export function applyResult(element: Element, result: InferenceResult, settings:
element.insertAdjacentElement("afterend", placeholder); element.insertAdjacentElement("afterend", placeholder);
} }
placeholder.className = "vibeguard-placeholder"; placeholder.className = "vibeguard-placeholder";
const message = `Content hidden as toxic${settings.showScore ? ` (${Math.round(result.probability * 100)}%)` : ""}`; const message = `Content hidden as ${formatLabel(selected!.label)}${settings.showScore ? ` (${Math.round(selected!.probability * 100)}%)` : ""}`;
const button = document.createElement("button"); const button = document.createElement("button");
button.type = "button"; button.type = "button";
button.textContent = "Show"; button.textContent = "Show";
@ -42,6 +43,17 @@ export function applyResult(element: Element, result: InferenceResult, settings:
placeholder.replaceChildren(message, " ", button); placeholder.replaceChildren(message, " ", button);
} }
export function selectFilterLabel(result: InferenceResult, settings: Settings): { label: ToxicityLabel; probability: number } | undefined {
return TOXICITY_LABELS
.filter((label) => settings.enabledLabels.includes(label) && result.scores[label] >= settings.threshold)
.map((label) => ({ label, probability: result.scores[label] }))
.sort((a, b) => b.probability - a.probability)[0];
}
function formatLabel(label: ToxicityLabel): string {
return label.replaceAll("_", " ");
}
export function hasAppliedFilter(element: Element, postId: string, settings: Settings): boolean { export function hasAppliedFilter(element: Element, postId: string, settings: Settings): boolean {
const html = element as HTMLElement; const html = element as HTMLElement;
return element.getAttribute(HIDDEN) === "true" && html.style.display === "none" return element.getAttribute(HIDDEN) === "true" && html.style.display === "none"

View file

@ -1,6 +1,6 @@
import { effectiveDefinitions } from "./definitions"; import { effectiveDefinitions } from "./definitions";
import { DefinitionEngine, hasPotentialDefinitionForUrl, selectDefinition, selectDefinitionForUrl } from "./definition-engine"; import { DefinitionEngine, hasPotentialDefinitionForUrl, selectDefinition, selectDefinitionForUrl } from "./definition-engine";
import { applyResult, hasAppliedFilter, removeOrphanedPlaceholders, restore } from "./filter"; import { applyResult, hasAppliedFilter, removeOrphanedPlaceholders, restore, selectFilterLabel } from "./filter";
import { loadSettings } from "../shared/settings"; import { loadSettings } from "../shared/settings";
import { hashText } from "../shared/hash"; import { hashText } from "../shared/hash";
import { priorityFor } from "../inference/queue"; import { priorityFor } from "../inference/queue";
@ -95,7 +95,7 @@ function runDefinition(settings: Settings, sequence: number): () => void {
for (const [id, result] of results) { for (const [id, result] of results) {
const elements = elementsById.get(id) ?? []; const elements = elementsById.get(id) ?? [];
const shouldFilter = result.label === "toxic" && result.probability >= settings.threshold && !revealedPostIds.has(id); const shouldFilter = selectFilterLabel(result, settings) !== undefined && !revealedPostIds.has(id);
for (const element of elements) { for (const element of elements) {
if (!shouldFilter) restore(element, id); if (!shouldFilter) restore(element, id);
else if (!hasAppliedFilter(element, id, settings)) { else if (!hasAppliedFilter(element, id, settings)) {

View file

@ -1,6 +1,6 @@
import { env, pipeline, type TextClassificationPipeline } from "@huggingface/transformers"; import { env, pipeline, type TextClassificationPipeline } from "@huggingface/transformers";
import { hashText } from "../shared/hash"; import { hashText } from "../shared/hash";
import type { InferenceRequest, InferenceResult } from "../shared/types"; import { TOXICITY_LABELS, type InferenceRequest, type InferenceResult, type ToxicityLabel } from "../shared/types";
import { loadModelManifest, type ModelManifest } from "./model-metadata"; import { loadModelManifest, type ModelManifest } from "./model-metadata";
let classifier: TextClassificationPipeline | undefined; let classifier: TextClassificationPipeline | undefined;
@ -17,22 +17,21 @@ export async function classify(requests: InferenceRequest[], modelBaseUrl: strin
classifier ??= await loadClassifier(modelBaseUrl); classifier ??= await loadClassifier(modelBaseUrl);
const invoke = classifier as unknown as (texts: string[], options: Record<string, unknown>) => Promise<Array<Array<{ label: string; score: number }> | { label: string; score: number }>>; const invoke = classifier as unknown as (texts: string[], options: Record<string, unknown>) => Promise<Array<Array<{ label: string; score: number }> | { label: string; score: number }>>;
const startedAt = performance.now(); const startedAt = performance.now();
// Transformers.js defaults `top_k` to 1. Request both scores because the const outputs = await invoke(requests.map((request) => request.text), { top_k: TOXICITY_LABELS.length, max_length: modelManifest.maxLength });
// filtering threshold is based on the toxic class probability, including
// when the non-toxic class is the model's highest-confidence prediction.
const outputs = await invoke(requests.map((request) => request.text), { top_k: 2, max_length: modelManifest.maxLength });
const modelDurationMs = performance.now() - startedAt; const modelDurationMs = performance.now() - startedAt;
return requests.map((request, index) => { return requests.map((request, index) => {
const output = Array.isArray(outputs[index]) ? outputs[index] : [outputs[index]]; const output = Array.isArray(outputs[index]) ? outputs[index] : [outputs[index]];
const toxic = output.find((item) => resolveOutputIndex(item?.label, modelManifest) === modelManifest.labels.toxic); const scores = Object.fromEntries(TOXICITY_LABELS.map((label) => {
if (!toxic) throw new Error(`Classifier output did not contain toxic label index ${modelManifest.labels.toxic}`); const outputIndex = modelManifest.labels.names[label];
const probability = Math.max(0, Math.min(1, Number(toxic?.score ?? 0))); const score = output.find((item) => resolveOutputIndex(item?.label, modelManifest) === outputIndex)?.score;
if (score === undefined) throw new Error(`Classifier output did not contain ${label} label index ${outputIndex}`);
return [label, Math.max(0, Math.min(1, Number(score)))];
})) as Record<ToxicityLabel, number>;
return { return {
requestId: request.requestId, requestId: request.requestId,
id: request.id, id: request.id,
textHash: hashText(request.text), textHash: hashText(request.text),
label: probability >= 0.5 ? "toxic" : "not_toxic", scores,
probability,
navigationId: request.navigationId, navigationId: request.navigationId,
modelRevision: modelManifest.revision, modelRevision: modelManifest.revision,
modelDurationMs modelDurationMs
@ -49,9 +48,7 @@ async function loadClassifier(modelBaseUrl: string): Promise<TextClassificationP
export function resolveOutputIndex(label: string | undefined, metadata: ModelManifest): number | undefined { export function resolveOutputIndex(label: string | undefined, metadata: ModelManifest): number | undefined {
if (!label) return undefined; if (!label) return undefined;
const normalized = label.toLowerCase().replace(/[\s-]+/g, "_"); const normalized = label.toLowerCase().replace(/[\s-]+/g, "_");
if (normalized === "toxic") return metadata.labels.toxic; const configured = metadata.labels.names[normalized as ToxicityLabel] ?? metadata.labels.names[label as ToxicityLabel];
if (normalized === "not_toxic" || normalized === "non_toxic" || normalized === "non-toxic") return metadata.labels.nonToxic;
const configured = metadata.labels.names[normalized] ?? metadata.labels.names[label];
if (configured !== undefined) return configured; if (configured !== undefined) return configured;
const match = normalized.match(/^label_(\d+)$/); const match = normalized.match(/^label_(\d+)$/);
return match ? Number(match[1]) : undefined; return match ? Number(match[1]) : undefined;

View file

@ -1,12 +1,13 @@
import { TOXICITY_LABELS, type ToxicityLabel } from "../shared/types";
export interface ModelManifest { export interface ModelManifest {
source: string; source: string;
revision: string; revision: string;
architecture: string; architecture: string;
labels: { labels: {
toxic: number; names: Record<ToxicityLabel, number>;
nonToxic: number;
names: Record<string, number>;
}; };
scoring: "multi-label-sigmoid";
maxLength: number; maxLength: number;
quantization: string; quantization: string;
runtime: string; runtime: string;
@ -26,7 +27,9 @@ export function loadModelManifest(modelBaseUrl: string): Promise<ModelManifest>
export function validateManifest(value: ModelManifest): ModelManifest { export function validateManifest(value: ModelManifest): ModelManifest {
if (!value || typeof value.source !== "string" || typeof value.revision !== "string") throw new Error("Invalid VibeGuard model manifest"); if (!value || typeof value.source !== "string" || typeof value.revision !== "string") throw new Error("Invalid VibeGuard model manifest");
if (!Number.isInteger(value.labels?.toxic) || !Number.isInteger(value.labels?.nonToxic) || value.labels.toxic === value.labels.nonToxic || !value.labels?.names) throw new Error("Model manifest has no binary label mapping"); if (value.scoring !== "multi-label-sigmoid" || !value.labels?.names) throw new Error("Model manifest has no multi-label scoring contract");
const labelIndexes = TOXICITY_LABELS.map((label) => value.labels.names[label]);
if (labelIndexes.some((index) => !Number.isInteger(index) || index < 0) || new Set(labelIndexes).size !== TOXICITY_LABELS.length || Object.keys(value.labels.names).length !== TOXICITY_LABELS.length) throw new Error("Model manifest has an invalid label mapping");
if (!Number.isInteger(value.maxLength) || value.maxLength < 8) throw new Error("Model manifest has an invalid maximum length"); if (!Number.isInteger(value.maxLength) || value.maxLength < 8) throw new Error("Model manifest has an invalid maximum length");
return value; return value;
} }

View file

@ -1,6 +1,6 @@
import { loadSettings, saveDefinitionConfiguration, saveSettings } from "../shared/settings"; import { loadSettings, saveDefinitionConfiguration, saveSettings } from "../shared/settings";
import { validateDefinitionConfiguration } from "../shared/site-definitions"; import { validateDefinitionConfiguration } from "../shared/site-definitions";
import type { FilterMode, Settings } from "../shared/types"; import { TOXICITY_LABELS, type FilterMode, type Settings, type ToxicityLabel } from "../shared/types";
import "./style.css"; import "./style.css";
const form = document.querySelector<HTMLFormElement>("#settings"); const form = document.querySelector<HTMLFormElement>("#settings");
@ -8,6 +8,7 @@ const threshold = document.querySelector<HTMLInputElement>("#threshold");
const thresholdValue = document.querySelector<HTMLElement>("#threshold-value"); const thresholdValue = document.querySelector<HTMLElement>("#threshold-value");
const mode = document.querySelector<HTMLSelectElement>("#filter-mode"); const mode = document.querySelector<HTMLSelectElement>("#filter-mode");
const showScore = document.querySelector<HTMLInputElement>("#show-score"); const showScore = document.querySelector<HTMLInputElement>("#show-score");
const enabledLabels = document.querySelector<HTMLElement>("#enabled-labels");
const status = document.querySelector<HTMLElement>("#status"); const status = document.querySelector<HTMLElement>("#status");
const definitions = document.querySelector<HTMLTextAreaElement>("#definitions"); const definitions = document.querySelector<HTMLTextAreaElement>("#definitions");
const importButton = document.querySelector<HTMLButtonElement>("#import-definitions"); const importButton = document.querySelector<HTMLButtonElement>("#import-definitions");
@ -24,6 +25,7 @@ void loadSettings().then((settings) => {
threshold!.value = String(settings.threshold); threshold!.value = String(settings.threshold);
mode!.value = settings.filterMode; mode!.value = settings.filterMode;
showScore!.checked = settings.showScore; showScore!.checked = settings.showScore;
renderEnabledLabels(settings);
definitions!.value = JSON.stringify(definitionConfiguration(settings), null, 2); definitions!.value = JSON.stringify(definitionConfiguration(settings), null, 2);
renderSubscriptions(settings); renderSubscriptions(settings);
updateThresholdLabel(); updateThresholdLabel();
@ -60,7 +62,7 @@ form?.addEventListener("submit", async (event) => {
try { try {
const configuration = parseDefinitionConfiguration(); const configuration = parseDefinitionConfiguration();
await saveDefinitionConfiguration(configuration); await saveDefinitionConfiguration(configuration);
await saveSettings({ threshold: Number(threshold?.value), filterMode: mode?.value as FilterMode, showScore: showScore?.checked }); currentSettings = await saveSettings({ threshold: Number(threshold?.value), filterMode: mode?.value as FilterMode, showScore: showScore?.checked, enabledLabels: selectedLabels() });
showStatus("Saved. Reload matching pages to apply definition changes."); showStatus("Saved. Reload matching pages to apply definition changes.");
} catch (error) { showStatus(error instanceof Error ? error.message : String(error), true); } } catch (error) { showStatus(error instanceof Error ? error.message : String(error), true); }
}); });
@ -96,6 +98,30 @@ function updateThresholdLabel(): void {
if (thresholdValue && threshold) thresholdValue.textContent = `${Math.round(Number(threshold.value) * 100)}%`; if (thresholdValue && threshold) thresholdValue.textContent = `${Math.round(Number(threshold.value) * 100)}%`;
} }
function renderEnabledLabels(settings: Settings): void {
if (!enabledLabels) return;
enabledLabels.replaceChildren(...TOXICITY_LABELS.map((label) => {
const input = document.createElement("input");
input.type = "checkbox";
input.name = "enabled-label";
input.value = label;
input.checked = settings.enabledLabels.includes(label);
const text = document.createTextNode(` ${formatLabel(label)}`);
const wrapper = document.createElement("label");
wrapper.className = "checkbox mr-4";
wrapper.append(input, text);
return wrapper;
}));
}
function selectedLabels(): ToxicityLabel[] {
return TOXICITY_LABELS.filter((label) => document.querySelector<HTMLInputElement>(`input[name="enabled-label"][value="${label}"]`)?.checked);
}
function formatLabel(label: ToxicityLabel): string {
return label.replaceAll("_", " ");
}
function definitionConfiguration(settings?: Settings): { customDefinitions: Settings["customDefinitions"]; disabledDefinitionIds: string[]; subscriptions: Settings["subscriptions"]; subscriptionCollections: Settings["subscriptionCollections"] } { function definitionConfiguration(settings?: Settings): { customDefinitions: Settings["customDefinitions"]; disabledDefinitionIds: string[]; subscriptions: Settings["subscriptions"]; subscriptionCollections: Settings["subscriptionCollections"] } {
return { customDefinitions: settings?.customDefinitions ?? [], disabledDefinitionIds: settings?.disabledDefinitionIds ?? [], subscriptions: settings?.subscriptions ?? [], subscriptionCollections: settings?.subscriptionCollections ?? [] }; return { customDefinitions: settings?.customDefinitions ?? [], disabledDefinitionIds: settings?.disabledDefinitionIds ?? [], subscriptions: settings?.subscriptions ?? [], subscriptionCollections: settings?.subscriptionCollections ?? [] };
} }

View file

@ -1,4 +1,4 @@
import { DEFAULT_SETTINGS, type Settings, type SiteDefinition } from "./types"; import { DEFAULT_SETTINGS, TOXICITY_LABELS, type Settings, type SiteDefinition, type ToxicityLabel } from "./types";
import { validateDefinitionConfiguration } from "./site-definitions"; import { validateDefinitionConfiguration } from "./site-definitions";
import type { DefinitionSubscription } from "./types"; import type { DefinitionSubscription } from "./types";
@ -59,6 +59,7 @@ export function mergeSettings(input?: StoredSettings): Settings {
...DEFAULT_SETTINGS, ...DEFAULT_SETTINGS,
...current, ...current,
threshold: clamp(Number(current.threshold ?? DEFAULT_SETTINGS.threshold), 0, 1), threshold: clamp(Number(current.threshold ?? DEFAULT_SETTINGS.threshold), 0, 1),
enabledLabels: normalizeEnabledLabels(current.enabledLabels),
customDefinitions: definitionConfiguration.valid ? definitionConfiguration.value.customDefinitions : DEFAULT_SETTINGS.customDefinitions, customDefinitions: definitionConfiguration.valid ? definitionConfiguration.value.customDefinitions : DEFAULT_SETTINGS.customDefinitions,
disabledDefinitionIds: definitionConfiguration.valid ? definitionConfiguration.value.disabledDefinitionIds : DEFAULT_SETTINGS.disabledDefinitionIds, disabledDefinitionIds: definitionConfiguration.valid ? definitionConfiguration.value.disabledDefinitionIds : DEFAULT_SETTINGS.disabledDefinitionIds,
subscriptions: definitionConfiguration.valid ? definitionConfiguration.value.subscriptions : [DEFAULT_SUBSCRIPTION], subscriptions: definitionConfiguration.valid ? definitionConfiguration.value.subscriptions : [DEFAULT_SUBSCRIPTION],
@ -66,6 +67,12 @@ export function mergeSettings(input?: StoredSettings): Settings {
}; };
} }
function normalizeEnabledLabels(value: unknown): ToxicityLabel[] {
if (!Array.isArray(value)) return [...TOXICITY_LABELS];
const known = new Set(TOXICITY_LABELS);
return [...new Set(value.filter((label): label is ToxicityLabel => typeof label === "string" && known.has(label as ToxicityLabel)))];
}
export function saveDefinitionConfiguration(configuration: { customDefinitions: SiteDefinition[]; disabledDefinitionIds: string[]; subscriptions?: DefinitionSubscription[]; subscriptionCollections?: Settings["subscriptionCollections"] }): Promise<Settings> { export function saveDefinitionConfiguration(configuration: { customDefinitions: SiteDefinition[]; disabledDefinitionIds: string[]; subscriptions?: DefinitionSubscription[]; subscriptionCollections?: Settings["subscriptionCollections"] }): Promise<Settings> {
const validation = validateDefinitionConfiguration(configuration); const validation = validateDefinitionConfiguration(configuration);
if (!validation.valid) return Promise.reject(new Error(validation.errors.join("\n"))); if (!validation.valid) return Promise.reject(new Error(validation.errors.join("\n")));

View file

@ -1,5 +1,7 @@
export type QueuePriority = 0 | 1 | 2 | 3; export type QueuePriority = 0 | 1 | 2 | 3;
export type FilterMode = "collapse" | "hide"; export type FilterMode = "collapse" | "hide";
export const TOXICITY_LABELS = ["toxicity", "severe_toxicity", "obscene", "threat", "insult", "identity_attack", "sexual_explicit"] as const;
export type ToxicityLabel = typeof TOXICITY_LABELS[number];
export interface SiteDefinition { export interface SiteDefinition {
id: string; id: string;
@ -61,8 +63,7 @@ export interface InferenceResult {
requestId: string; requestId: string;
id: string; id: string;
textHash: string; textHash: string;
label: "toxic" | "not_toxic"; scores: Record<ToxicityLabel, number>;
probability: number;
navigationId: string; navigationId: string;
modelRevision?: string; modelRevision?: string;
/** Duration of the model invocation that produced this result, in milliseconds. */ /** Duration of the model invocation that produced this result, in milliseconds. */
@ -75,6 +76,7 @@ export type InferenceResponse =
export interface Settings { export interface Settings {
threshold: number; threshold: number;
enabledLabels: ToxicityLabel[];
filterMode: FilterMode; filterMode: FilterMode;
showScore: boolean; showScore: boolean;
customDefinitions: SiteDefinition[]; customDefinitions: SiteDefinition[];
@ -91,6 +93,7 @@ export interface PageStatus {
export const DEFAULT_SETTINGS: Settings = { export const DEFAULT_SETTINGS: Settings = {
threshold: 0.8, threshold: 0.8,
enabledLabels: [...TOXICITY_LABELS],
filterMode: "collapse", filterMode: "collapse",
showScore: true, showScore: true,
customDefinitions: [], customDefinitions: [],

View file

@ -6,8 +6,7 @@ const result = (id: string): InferenceResult => ({
requestId: id, requestId: id,
id, id,
textHash: id, textHash: id,
label: "toxic", scores: { toxicity: .9, severe_toxicity: 0, obscene: 0, threat: 0, insult: 0, identity_attack: 0, sexual_explicit: 0 },
probability: .9,
navigationId: "nav" navigationId: "nav"
}); });

View file

@ -1,14 +1,16 @@
import { afterEach, describe, expect, it } from "vitest"; import { afterEach, describe, expect, it } from "vitest";
import { applyResult, removeOrphanedPlaceholders, restore } from "../src/content/filter"; import { applyResult, removeOrphanedPlaceholders, restore, selectFilterLabel } from "../src/content/filter";
import { DEFAULT_SETTINGS } from "../src/shared/types"; import { DEFAULT_SETTINGS } from "../src/shared/types";
const scores = { toxicity: .91, severe_toxicity: .1, obscene: .3, threat: .2, insult: .8, identity_attack: .1, sexual_explicit: .1 };
describe("content filtering", () => { describe("content filtering", () => {
afterEach(() => document.body.replaceChildren()); afterEach(() => document.body.replaceChildren());
it("collapses toxic content and restores it", () => { it("collapses toxic content and restores it", () => {
const element = document.createElement("article"); const element = document.createElement("article");
document.body.append(element); document.body.append(element);
applyResult(element, { requestId: "1", id: "1", textHash: "x", label: "toxic", probability: .91, navigationId: "n" }, DEFAULT_SETTINGS); applyResult(element, { requestId: "1", id: "1", textHash: "x", scores, navigationId: "n" }, DEFAULT_SETTINGS);
expect(element.style.display).toBe("none"); expect(element.style.display).toBe("none");
expect(document.querySelector("[data-vibeguard-placeholder]")).not.toBeNull(); expect(document.querySelector("[data-vibeguard-placeholder]")).not.toBeNull();
restore(element); restore(element);
@ -19,13 +21,19 @@ describe("content filtering", () => {
it("preserves the original display value when filtering is reconciled repeatedly", () => { it("preserves the original display value when filtering is reconciled repeatedly", () => {
const element = document.createElement("article"); const element = document.createElement("article");
document.body.append(element); document.body.append(element);
const result = { requestId: "1", id: "1", textHash: "x", label: "toxic" as const, probability: .91, navigationId: "n" }; const result = { requestId: "1", id: "1", textHash: "x", scores, navigationId: "n" };
applyResult(element, result, DEFAULT_SETTINGS); applyResult(element, result, DEFAULT_SETTINGS);
applyResult(element, result, DEFAULT_SETTINGS); applyResult(element, result, DEFAULT_SETTINGS);
restore(element); restore(element);
expect(element.style.display).toBe(""); expect(element.style.display).toBe("");
}); });
it("uses the highest enabled category above the threshold", () => {
const result = { requestId: "1", id: "1", textHash: "x", scores, navigationId: "n" };
expect(selectFilterLabel(result, { ...DEFAULT_SETTINGS, enabledLabels: ["insult", "threat"], threshold: .5 })).toEqual({ label: "insult", probability: .8 });
expect(selectFilterLabel(result, { ...DEFAULT_SETTINGS, enabledLabels: [], threshold: .5 })).toBeUndefined();
});
it("removes placeholders no longer paired with the current post element", () => { it("removes placeholders no longer paired with the current post element", () => {
const stale = document.createElement("div"); const stale = document.createElement("div");
const orphan = document.createElement("div"); const orphan = document.createElement("div");

View file

@ -23,7 +23,7 @@ class FakeWorker implements InferenceWorker {
terminate(): void { this.terminated = true; } terminate(): void { this.terminated = true; }
reply(): void { reply(): void {
const event = new MessageEvent("message", { data: { results: [{ requestId: request.requestId, id: request.id, textHash: "hash", label: "not_toxic", probability: .1, navigationId: request.navigationId }] } }); const event = new MessageEvent("message", { data: { results: [{ requestId: request.requestId, id: request.id, textHash: "hash", scores: { toxicity: .1, severe_toxicity: 0, obscene: 0, threat: 0, insult: 0, identity_attack: 0, sexual_explicit: 0 }, navigationId: request.navigationId }] } });
this.listeners.get("message")?.forEach((listener) => listener(event)); this.listeners.get("message")?.forEach((listener) => listener(event));
} }
} }

View file

@ -3,25 +3,26 @@ import { validateManifest } from "../src/inference/model-metadata";
import { resolveOutputIndex } from "../src/inference/classifier"; import { resolveOutputIndex } from "../src/inference/classifier";
const manifest = { const manifest = {
source: "wagesj45/toxic-comment-classifier", source: "wagesj45/multilabel-toxic-comment-classifier",
revision: "abc123", revision: "abc123",
architecture: "DistilBertForSequenceClassification", architecture: "ModernBertForSequenceClassification",
labels: { toxic: 1, nonToxic: 0, names: { toxic: 1, non_toxic: 0 } }, labels: { names: { toxicity: 0, severe_toxicity: 1, obscene: 2, threat: 3, insult: 4, identity_attack: 5, sexual_explicit: 6 } },
scoring: "multi-label-sigmoid" as const,
maxLength: 512, maxLength: 512,
quantization: "int8-dynamic", quantization: "int8-dynamic",
runtime: "onnxruntime-web-wasm" runtime: "onnxruntime-web-wasm"
}; };
describe("model contract", () => { describe("model contract", () => {
it("accepts a binary manifest and resolves common output labels", () => { it("accepts a multi-label manifest and resolves output labels", () => {
expect(validateManifest(manifest)).toEqual(manifest); expect(validateManifest(manifest)).toEqual(manifest);
expect(resolveOutputIndex("LABEL_1", manifest)).toBe(1); expect(resolveOutputIndex("LABEL_1", manifest)).toBe(1);
expect(resolveOutputIndex("not-toxic", manifest)).toBe(0); expect(resolveOutputIndex("identity-attack", manifest)).toBe(5);
expect(resolveOutputIndex("toxic", manifest)).toBe(1); expect(resolveOutputIndex("toxicity", manifest)).toBe(0);
}); });
it("rejects incomplete metadata", () => { it("rejects incomplete metadata", () => {
expect(() => validateManifest({ ...manifest, labels: { toxic: 1, nonToxic: 1, names: {} } })).toThrow(); expect(() => validateManifest({ ...manifest, labels: { names: { ...manifest.labels.names, threat: 1 } } })).toThrow();
expect(() => validateManifest({ ...manifest, maxLength: 0 })).toThrow(); expect(() => validateManifest({ ...manifest, maxLength: 0 })).toThrow();
expect(() => validateManifest({ ...manifest, labels: undefined as unknown as typeof manifest.labels })).toThrow(); expect(() => validateManifest({ ...manifest, labels: undefined as unknown as typeof manifest.labels })).toThrow();
}); });

View file

@ -11,11 +11,11 @@ describe("InferenceQueue", () => {
let calls = 0; let calls = 0;
const queue = new InferenceQueue(async (requests) => { const queue = new InferenceQueue(async (requests) => {
calls += 1; calls += 1;
return requests.map((item) => ({ requestId: item.requestId, id: item.id, textHash: "hash", label: "toxic" as const, probability: .9, navigationId: item.navigationId })); return requests.map((item) => ({ requestId: item.requestId, id: item.id, textHash: "hash", scores: { toxicity: .9, severe_toxicity: 0, obscene: 0, threat: 0, insult: 0, identity_attack: 0, sexual_explicit: 0 }, navigationId: item.navigationId }));
}, undefined, 10, 8, 0); }, undefined, 10, 8, 0);
const first = await queue.enqueue(request("a", 0)); const first = await queue.enqueue(request("a", 0));
const second = await queue.enqueue({ ...request("b", 0), text: "text a" }); const second = await queue.enqueue({ ...request("b", 0), text: "text a" });
expect(first.probability).toBe(.9); expect(first.scores.toxicity).toBe(.9);
expect(second.requestId).toBe("b"); expect(second.requestId).toBe("b");
expect(calls).toBe(1); expect(calls).toBe(1);
expect(queue.cacheSize).toBe(1); expect(queue.cacheSize).toBe(1);

View file

@ -24,4 +24,9 @@ describe("legacy settings", () => {
expect(mergeSettings({ cpuThreads: 99 })).not.toHaveProperty("cpuThreads"); expect(mergeSettings({ cpuThreads: 99 })).not.toHaveProperty("cpuThreads");
expect(mergeSettings({ inferenceDevice: "webgpu" } as never)).not.toHaveProperty("inferenceDevice"); expect(mergeSettings({ inferenceDevice: "webgpu" } as never)).not.toHaveProperty("inferenceDevice");
}); });
it("defaults missing categories and removes invalid stored labels", () => {
expect(mergeSettings({}).enabledLabels).toEqual(DEFAULT_SETTINGS.enabledLabels);
expect(mergeSettings({ enabledLabels: ["threat", "threat", "unknown"] as never }).enabledLabels).toEqual(["threat"]);
});
}); });

View file

@ -1,5 +1,5 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""Prepare a pinned Hugging Face binary classifier for VibeGuard.""" """Prepare a pinned Hugging Face multi-label classifier for VibeGuard."""
from __future__ import annotations from __future__ import annotations
import argparse import argparse
@ -11,8 +11,10 @@ import tempfile
from pathlib import Path from pathlib import Path
from typing import Any from typing import Any
DEFAULT_MODEL = "wagesj45/toxic-comment-classifier" DEFAULT_MODEL = "wagesj45/multilabel-toxic-comment-classifier"
DEFAULT_OUTPUT = Path("public/models/toxicity") DEFAULT_OUTPUT = Path("public/models/toxicity")
DEFAULT_MAX_LENGTH = 512
REQUIRED_LABELS = ("toxicity", "severe_toxicity", "obscene", "threat", "insult", "identity_attack", "sexual_explicit")
def make_parser() -> argparse.ArgumentParser: def make_parser() -> argparse.ArgumentParser:
@ -21,9 +23,7 @@ def make_parser() -> argparse.ArgumentParser:
command.add_argument("--model", default=DEFAULT_MODEL) command.add_argument("--model", default=DEFAULT_MODEL)
command.add_argument("--revision", help="Immutable HF commit; required by prepare") command.add_argument("--revision", help="Immutable HF commit; required by prepare")
command.add_argument("--output", type=Path, default=DEFAULT_OUTPUT) command.add_argument("--output", type=Path, default=DEFAULT_OUTPUT)
command.add_argument("--toxic-index", type=int) command.add_argument("--max-length", type=int, default=DEFAULT_MAX_LENGTH)
command.add_argument("--non-toxic-index", type=int)
command.add_argument("--max-length", type=int)
return command return command
@ -62,14 +62,11 @@ def inspect_source(source: Path) -> dict[str, Any]:
} }
def resolve_labels(details: dict[str, Any], toxic_override: int | None, non_toxic_override: int | None) -> tuple[int, int, dict[str, int]]: def resolve_labels(details: dict[str, Any]) -> dict[str, int]:
names = {str(index): value.lower().replace("-", "_").replace(" ", "_") for index, value in details["id2label"].items()} indexed = {value.lower().replace("-", "_").replace(" ", "_"): int(index) for index, value in details["id2label"].items()}
indexed = {name: int(index) for index, name in names.items()} if set(indexed) != set(REQUIRED_LABELS) or len(indexed) != len(REQUIRED_LABELS):
toxic = toxic_override if toxic_override is not None else next((index for name, index in indexed.items() if name in ("toxic", "toxicity")), None) raise ValueError(f"Expected exactly these labels: {', '.join(REQUIRED_LABELS)}")
non_toxic = non_toxic_override if non_toxic_override is not None else next((index for name, index in indexed.items() if name in ("non_toxic", "nontoxic", "clean", "not_toxic")), None) return {label: indexed[label] for label in REQUIRED_LABELS}
if toxic is None or non_toxic is None or toxic == non_toxic:
raise ValueError("Could not resolve distinct labels; pass --toxic-index and --non-toxic-index")
return toxic, non_toxic, indexed
def prepare(args: argparse.Namespace) -> None: def prepare(args: argparse.Namespace) -> None:
@ -78,9 +75,10 @@ def prepare(args: argparse.Namespace) -> None:
license_id = str(source_metadata.get("license") or "").lower() license_id = str(source_metadata.get("license") or "").lower()
if license_id != "apache-2.0": raise SystemExit(f"Expected Apache-2.0 model metadata, found license={source_metadata.get('license')!r}") if license_id != "apache-2.0": raise SystemExit(f"Expected Apache-2.0 model metadata, found license={source_metadata.get('license')!r}")
details = inspect_source(source) details = inspect_source(source)
if details["numLabels"] != 2: raise SystemExit(f"Expected a binary classifier, found {details['numLabels']}") if details["numLabels"] != len(REQUIRED_LABELS): raise SystemExit(f"Expected {len(REQUIRED_LABELS)} labels, found {details['numLabels']}")
toxic, non_toxic, names = resolve_labels(details, args.toxic_index, args.non_toxic_index) names = resolve_labels(details)
max_length = args.max_length or details["maxLength"] or 512 max_length = args.max_length
if max_length > (details["maxLength"] or max_length): raise SystemExit(f"Requested max length {max_length} exceeds model maximum {details['maxLength']}")
with tempfile.TemporaryDirectory(prefix="vibeguard-model-") as temporary: with tempfile.TemporaryDirectory(prefix="vibeguard-model-") as temporary:
export_dir = Path(temporary) / "onnx" export_dir = Path(temporary) / "onnx"
float_model = export_dir / "model.onnx" float_model = export_dir / "model.onnx"
@ -88,12 +86,12 @@ def prepare(args: argparse.Namespace) -> None:
quantized = export_dir / "model_quantized.onnx" quantized = export_dir / "model_quantized.onnx"
quantize(float_model, quantized) quantize(float_model, quantized)
args.output.mkdir(parents=True, exist_ok=True) args.output.mkdir(parents=True, exist_ok=True)
for name in ("tokenizer.json", "tokenizer_config.json", "special_tokens_map.json", "vocab.txt", "merges.txt"): for name in ("tokenizer.json", "tokenizer_config.json", "special_tokens_map.json", "vocab.txt", "merges.txt", "LICENSE"):
if (source / name).exists(): shutil.copy2(source / name, args.output / name) if (source / name).exists(): shutil.copy2(source / name, args.output / name)
shutil.copy2(source / "config.json", args.output / "config.json") shutil.copy2(source / "config.json", args.output / "config.json")
(args.output / "onnx").mkdir(exist_ok=True) (args.output / "onnx").mkdir(exist_ok=True)
shutil.copy2(quantized, args.output / "onnx" / "model_quantized.onnx") shutil.copy2(quantized, args.output / "onnx" / "model_quantized.onnx")
manifest = {"source": args.model, "revision": source_metadata["revision"], "architecture": details["architecture"], "labels": {"toxic": toxic, "nonToxic": non_toxic, "names": names}, "maxLength": max_length, "quantization": "int8-dynamic", "runtime": "onnxruntime-web-wasm", "license": "Apache-2.0"} manifest = {"source": args.model, "revision": source_metadata["revision"], "architecture": details["architecture"], "labels": {"names": names}, "scoring": "multi-label-sigmoid", "maxLength": max_length, "quantization": "int8-dynamic", "runtime": "onnxruntime-web-wasm", "license": "Apache-2.0"}
(args.output / "model-manifest.json").write_text(json.dumps(manifest, indent=2) + "\n") (args.output / "model-manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
print(json.dumps(manifest, indent=2)) print(json.dumps(manifest, indent=2))
@ -146,7 +144,9 @@ def validate(args: argparse.Namespace) -> None:
model_path = args.output / "onnx" / "model_quantized.onnx" model_path = args.output / "onnx" / "model_quantized.onnx"
if not manifest_path.is_file() or not model_path.is_file(): raise SystemExit(f"Missing generated model files under {args.output}") if not manifest_path.is_file() or not model_path.is_file(): raise SystemExit(f"Missing generated model files under {args.output}")
manifest = json.loads(manifest_path.read_text()) manifest = json.loads(manifest_path.read_text())
if manifest.get("quantization") != "int8-dynamic" or str(manifest.get("license")).lower() != "apache-2.0": raise SystemExit("Unexpected model quantization or license") if manifest.get("quantization") != "int8-dynamic" or str(manifest.get("license")).lower() != "apache-2.0" or manifest.get("scoring") != "multi-label-sigmoid": raise SystemExit("Unexpected model quantization, scoring, or license")
names = manifest.get("labels", {}).get("names", {})
if set(names) != set(REQUIRED_LABELS) or len(set(names.values())) != len(REQUIRED_LABELS): raise SystemExit("Unexpected model label mapping")
try: try:
import onnx import onnx
onnx.checker.check_model(str(model_path)) onnx.checker.check_model(str(model_path))

View file

@ -1,5 +1,5 @@
huggingface_hub>=0.27,<1 huggingface_hub>=1.5,<2
transformers>=4.48,<5 transformers>=5.15.1,<6
torch>=2.1,<3 torch>=2.1,<3
onnx>=1.17,<2 onnx>=1.17,<2
onnxruntime>=1.20,<2 onnxruntime>=1.20,<2