wchen22 commited on
Commit
2343c2a
·
verified ·
1 Parent(s): 2dab644

Add compression classifier artifact support

Browse files
Files changed (3) hide show
  1. README.md +4 -0
  2. app.py +201 -7
  3. requirements.txt +1 -0
README.md CHANGED
@@ -30,6 +30,10 @@ Live Space:
30
  - `/v1/classify` is tokenizer/fallback KEEP-only until a trained KEEP/DROP head
31
  is mounted. `/v1/compress` is rules-first deletion-only compression with
32
  safety receipts.
 
 
 
 
33
 
34
  Deploy:
35
 
 
30
  - `/v1/classify` is tokenizer/fallback KEEP-only until a trained KEEP/DROP head
31
  is mounted. `/v1/compress` is rules-first deletion-only compression with
32
  safety receipts.
33
+ - Mount `classifier_manifest.json`, tokenizer files, and optional `model.onnx`;
34
+ set `TOUCHDOWN_CLASSIFIER_ARTIFACT_DIR` to let the Space use artifact DROP
35
+ labels through ONNX Runtime or the manifest fallback. Those labels still pass
36
+ through protected-span and deletion-only safety gates.
37
 
38
  Deploy:
39
 
app.py CHANGED
@@ -1,13 +1,18 @@
1
  from __future__ import annotations
2
 
 
 
 
3
  import re
4
  import time
5
  from functools import lru_cache
 
6
  from typing import Any
7
 
8
  from fastapi import FastAPI, HTTPException
9
 
10
  CLASSIFIER_MODEL = "microsoft/deberta-v3-small"
 
11
  RULES_VERSION = "hf-space-rules-v0.1.0"
12
  LOW_SIGNAL_PATTERNS = [
13
  re.compile(pattern, re.IGNORECASE)
@@ -31,6 +36,39 @@ def _get_tokenizer():
31
  return AutoTokenizer.from_pretrained(CLASSIFIER_MODEL)
32
 
33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  def _find_spans(text: str, needle: str) -> list[tuple[int, int]]:
35
  spans = []
36
  cursor = 0
@@ -84,6 +122,138 @@ def _overlaps(spans: list[tuple[int, int]], start: int, end: int) -> bool:
84
  return any(start < span_end and end > span_start for span_start, span_end in spans)
85
 
86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
  def _is_subsequence(candidate: str, original: str) -> bool:
88
  cursor = 0
89
  for char in candidate:
@@ -158,6 +328,15 @@ def _compress_text(payload: dict[str, Any]) -> dict[str, Any]:
158
  preserve_code=preserve_code,
159
  preserve_json=preserve_json,
160
  )
 
 
 
 
 
 
 
 
 
161
  seen: set[str] = set()
162
  drops: list[tuple[int, int, str, str]] = []
163
  cursor = 0
@@ -190,7 +369,7 @@ def _compress_text(payload: dict[str, Any]) -> dict[str, Any]:
190
  seen.add(normalized)
191
 
192
  chunks = []
193
- drop_ranges = _merge([(start, end) for start, end, _, _ in drops])
194
  cursor = 0
195
  for start, end in drop_ranges:
196
  chunks.append(text[cursor:start])
@@ -231,9 +410,14 @@ def _compress_text(payload: dict[str, Any]) -> dict[str, Any]:
231
  "rules_version": RULES_VERSION,
232
  "classifier": {
233
  "model": CLASSIFIER_MODEL,
234
- "status": "tokenizer_loaded_no_trained_keep_drop_head",
235
- "labels_received": 0,
236
- "drop_spans_applied": 0,
 
 
 
 
 
237
  },
238
  "dropped_segments_count": len(drops),
239
  "dropped_segments": [
@@ -279,10 +463,13 @@ def _tokens(text: str) -> list[dict[str, Any]]:
279
 
280
  @app.get("/health")
281
  def health() -> dict[str, Any]:
 
282
  return {
283
  "status": "ok",
284
  "classifier_model": CLASSIFIER_MODEL,
285
- "classifier_status": "tokenizer_loaded_no_trained_keep_drop_head",
 
 
286
  "phase": "rules_api_first",
287
  }
288
 
@@ -292,11 +479,18 @@ def classify(payload: dict[str, Any]) -> dict[str, Any]:
292
  text = payload.get("input")
293
  if not isinstance(text, str):
294
  raise HTTPException(status_code=400, detail="input must be a string")
 
 
295
  return {
296
  "model": CLASSIFIER_MODEL,
297
  "task": "token_classification_keep_drop",
298
- "status": "tokenizer_only_until_trained_head",
299
- "labels": _tokens(text),
 
 
 
 
 
300
  "note": (
301
  "This free Space scaffold loads the DeBERTa tokenizer and returns "
302
  "KEEP-only labels until a trained KEEP/DROP head or ONNX export is "
 
1
  from __future__ import annotations
2
 
3
+ import json
4
+ import math
5
+ import os
6
  import re
7
  import time
8
  from functools import lru_cache
9
+ from pathlib import Path
10
  from typing import Any
11
 
12
  from fastapi import FastAPI, HTTPException
13
 
14
  CLASSIFIER_MODEL = "microsoft/deberta-v3-small"
15
+ CLASSIFIER_ARTIFACT_DIR = os.environ.get("TOUCHDOWN_CLASSIFIER_ARTIFACT_DIR")
16
  RULES_VERSION = "hf-space-rules-v0.1.0"
17
  LOW_SIGNAL_PATTERNS = [
18
  re.compile(pattern, re.IGNORECASE)
 
36
  return AutoTokenizer.from_pretrained(CLASSIFIER_MODEL)
37
 
38
 
39
+ @lru_cache(maxsize=1)
40
+ def _classifier_manifest() -> dict[str, Any] | None:
41
+ if not CLASSIFIER_ARTIFACT_DIR:
42
+ return None
43
+ path = Path(CLASSIFIER_ARTIFACT_DIR) / "classifier_manifest.json"
44
+ if not path.exists():
45
+ return {
46
+ "status": "manifest_error",
47
+ "error": f"missing classifier manifest: {path}",
48
+ }
49
+ try:
50
+ payload = json.loads(path.read_text(encoding="utf-8"))
51
+ except Exception as exc:
52
+ return {"status": "manifest_error", "error": str(exc)}
53
+ if not isinstance(payload, dict):
54
+ return {"status": "manifest_error", "error": "manifest must be an object"}
55
+ return payload
56
+
57
+
58
+ @lru_cache(maxsize=1)
59
+ def _get_artifact_tokenizer():
60
+ from transformers import AutoTokenizer
61
+
62
+ return AutoTokenizer.from_pretrained(str(CLASSIFIER_ARTIFACT_DIR))
63
+
64
+
65
+ @lru_cache(maxsize=1)
66
+ def _get_onnx_session(model_path: str):
67
+ import onnxruntime as ort
68
+
69
+ return ort.InferenceSession(model_path, providers=["CPUExecutionProvider"])
70
+
71
+
72
  def _find_spans(text: str, needle: str) -> list[tuple[int, int]]:
73
  spans = []
74
  cursor = 0
 
122
  return any(start < span_end and end > span_start for span_start, span_end in spans)
123
 
124
 
125
+ def _manifest_drop_labels(text: str) -> tuple[str, list[dict[str, Any]], str | None]:
126
+ manifest = _classifier_manifest()
127
+ if not manifest:
128
+ return "tokenizer_loaded_no_trained_keep_drop_head", [], None
129
+ if manifest.get("status") == "manifest_error":
130
+ return "manifest_error", [], str(manifest.get("error"))
131
+ onnx_model = Path(CLASSIFIER_ARTIFACT_DIR or "") / str(
132
+ manifest.get("onnx_model", "model.onnx")
133
+ )
134
+ if onnx_model.exists():
135
+ try:
136
+ return (
137
+ str(manifest.get("status") or "trained_keep_drop_head"),
138
+ _onnx_labels(text, manifest, onnx_model),
139
+ None,
140
+ )
141
+ except Exception as exc:
142
+ return "local_artifact_error", [], str(exc)
143
+ labels: list[dict[str, Any]] = []
144
+ for index, entry in enumerate(manifest.get("drop_phrases") or []):
145
+ if isinstance(entry, str):
146
+ phrase = entry
147
+ score = 1.0
148
+ elif isinstance(entry, dict):
149
+ phrase = str(entry.get("text") or "")
150
+ score = float(entry.get("score", 1.0))
151
+ else:
152
+ continue
153
+ cursor = 0
154
+ while phrase:
155
+ start = text.find(phrase, cursor)
156
+ if start < 0:
157
+ break
158
+ end = start + len(phrase)
159
+ labels.append({
160
+ "token": phrase,
161
+ "label": "DROP",
162
+ "score": score,
163
+ "start": start,
164
+ "end": end,
165
+ "source": "manifest_drop_phrase",
166
+ "classifier_index": index,
167
+ })
168
+ cursor = end
169
+ return str(manifest.get("status") or "artifact_manifest_loaded"), labels, None
170
+
171
+
172
+ def _softmax(values: list[float]) -> list[float]:
173
+ peak = max(values)
174
+ exps = [math.exp(value - peak) for value in values]
175
+ total = sum(exps) or 1.0
176
+ return [value / total for value in exps]
177
+
178
+
179
+ def _onnx_labels(
180
+ text: str,
181
+ manifest: dict[str, Any],
182
+ model_path: Path,
183
+ ) -> list[dict[str, Any]]:
184
+ import numpy as np
185
+
186
+ tokenizer = _get_artifact_tokenizer()
187
+ encoded = tokenizer(
188
+ text,
189
+ add_special_tokens=False,
190
+ return_offsets_mapping=True,
191
+ return_tensors="np",
192
+ truncation=True,
193
+ max_length=int(manifest.get("max_length", 512)),
194
+ )
195
+ offsets = encoded.pop("offset_mapping")[0]
196
+ session = _get_onnx_session(str(model_path))
197
+ input_names = {item.name for item in session.get_inputs()}
198
+ inputs = {key: value for key, value in encoded.items() if key in input_names}
199
+ logits = session.run(None, inputs)[0][0]
200
+ id2label = {
201
+ str(key): value
202
+ for key, value in (manifest.get("id2label") or {"0": "KEEP", "1": "DROP"}).items()
203
+ }
204
+ tokens = tokenizer.convert_ids_to_tokens(encoded["input_ids"][0])
205
+ labels = []
206
+ for index, token_logits in enumerate(logits):
207
+ probs = _softmax(np.asarray(token_logits, dtype=float).tolist())
208
+ label_id = int(np.argmax(probs))
209
+ start, end = offsets[index]
210
+ if int(end) <= int(start):
211
+ continue
212
+ labels.append({
213
+ "token": tokens[index],
214
+ "label": id2label.get(str(label_id), "KEEP"),
215
+ "score": round(float(probs[label_id]), 6),
216
+ "start": int(start),
217
+ "end": int(end),
218
+ "source": "onnx_token_classifier",
219
+ })
220
+ return labels
221
+
222
+
223
+ def _safe_classifier_drop_ranges(
224
+ labels: list[dict[str, Any]],
225
+ protected: list[tuple[int, int]],
226
+ *,
227
+ text_length: int,
228
+ min_score: float,
229
+ ) -> tuple[list[tuple[int, int]], int, int, int]:
230
+ ranges: list[tuple[int, int]] = []
231
+ drop_labels = 0
232
+ blocked = 0
233
+ for item in labels:
234
+ if str(item.get("label") or item.get("entity") or "").upper() != "DROP":
235
+ continue
236
+ drop_labels += 1
237
+ try:
238
+ start = int(item["start"])
239
+ end = int(item["end"])
240
+ score = float(item.get("score", 1.0))
241
+ except Exception:
242
+ blocked += 1
243
+ continue
244
+ if (
245
+ start < 0
246
+ or end > text_length
247
+ or end <= start
248
+ or score < min_score
249
+ or _overlaps(protected, start, end)
250
+ ):
251
+ blocked += 1
252
+ continue
253
+ ranges.append((start, end))
254
+ return _merge(ranges), drop_labels, len(ranges), blocked
255
+
256
+
257
  def _is_subsequence(candidate: str, original: str) -> bool:
258
  cursor = 0
259
  for char in candidate:
 
328
  preserve_code=preserve_code,
329
  preserve_json=preserve_json,
330
  )
331
+ classifier_status, classifier_labels, classifier_error = _manifest_drop_labels(text)
332
+ classifier_ranges, classifier_drop_labels, classifier_applied, classifier_blocked = (
333
+ _safe_classifier_drop_ranges(
334
+ classifier_labels,
335
+ protected,
336
+ text_length=len(text),
337
+ min_score=float(settings.get("classifier_min_drop_score", 0.5)),
338
+ )
339
+ )
340
  seen: set[str] = set()
341
  drops: list[tuple[int, int, str, str]] = []
342
  cursor = 0
 
369
  seen.add(normalized)
370
 
371
  chunks = []
372
+ drop_ranges = _merge([(start, end) for start, end, _, _ in drops] + classifier_ranges)
373
  cursor = 0
374
  for start, end in drop_ranges:
375
  chunks.append(text[cursor:start])
 
410
  "rules_version": RULES_VERSION,
411
  "classifier": {
412
  "model": CLASSIFIER_MODEL,
413
+ "status": classifier_status,
414
+ "artifact_dir_configured": bool(CLASSIFIER_ARTIFACT_DIR),
415
+ "artifact_dir": CLASSIFIER_ARTIFACT_DIR,
416
+ "error": classifier_error,
417
+ "labels_received": len(classifier_labels),
418
+ "drop_labels": classifier_drop_labels,
419
+ "drop_spans_applied": classifier_applied,
420
+ "drop_spans_blocked_by_safety": classifier_blocked,
421
  },
422
  "dropped_segments_count": len(drops),
423
  "dropped_segments": [
 
463
 
464
  @app.get("/health")
465
  def health() -> dict[str, Any]:
466
+ classifier_status, _, classifier_error = _manifest_drop_labels("")
467
  return {
468
  "status": "ok",
469
  "classifier_model": CLASSIFIER_MODEL,
470
+ "classifier_status": classifier_status,
471
+ "classifier_artifact_dir_configured": bool(CLASSIFIER_ARTIFACT_DIR),
472
+ "classifier_error": classifier_error,
473
  "phase": "rules_api_first",
474
  }
475
 
 
479
  text = payload.get("input")
480
  if not isinstance(text, str):
481
  raise HTTPException(status_code=400, detail="input must be a string")
482
+ classifier_status, artifact_labels, classifier_error = _manifest_drop_labels(text)
483
+ labels = artifact_labels or _tokens(text)
484
  return {
485
  "model": CLASSIFIER_MODEL,
486
  "task": "token_classification_keep_drop",
487
+ "status": (
488
+ classifier_status if CLASSIFIER_ARTIFACT_DIR or artifact_labels or classifier_error
489
+ else "tokenizer_only_until_trained_head"
490
+ ),
491
+ "artifact_dir_configured": bool(CLASSIFIER_ARTIFACT_DIR),
492
+ "error": classifier_error,
493
+ "labels": labels,
494
  "note": (
495
  "This free Space scaffold loads the DeBERTa tokenizer and returns "
496
  "KEEP-only labels until a trained KEEP/DROP head or ONNX export is "
requirements.txt CHANGED
@@ -2,3 +2,4 @@ fastapi>=0.110
2
  uvicorn[standard]>=0.29
3
  transformers>=4.40
4
  sentencepiece>=0.2
 
 
2
  uvicorn[standard]>=0.29
3
  transformers>=4.40
4
  sentencepiece>=0.2
5
+ onnxruntime>=1.17