Spaces:
Runtime error
Runtime error
Download app.py from wchen22/touchdown-compression-classifier: direct link, hf CLI and curl.
- Browser
- Download file 22.5 kB
-
https://huggingface.co/spaces/wchen22/touchdown-compression-classifier/resolve/e4bdbebf0daebdcfc651caf9db67e1c838dbe3a2/app.py
- Command line
-
hf download hf://spaces/wchen22/touchdown-compression-classifier@e4bdbebf0daebdcfc651caf9db67e1c838dbe3a2/app.py
-
curl -L -o app.py https://huggingface.co/spaces/wchen22/touchdown-compression-classifier/resolve/e4bdbebf0daebdcfc651caf9db67e1c838dbe3a2/app.py
22.5 kB
| from __future__ import annotations | |
| import hashlib | |
| import json | |
| import math | |
| import os | |
| import re | |
| import time | |
| from functools import lru_cache | |
| from pathlib import Path | |
| from typing import Any | |
| from fastapi import FastAPI, HTTPException | |
| CLASSIFIER_MODEL = "microsoft/deberta-v3-small" | |
| CLASSIFIER_ARTIFACT_DIR = os.environ.get("TOUCHDOWN_CLASSIFIER_ARTIFACT_DIR") | |
| API_SCHEMA_VERSION = "0.1.0" | |
| RULES_VERSION = "hf-space-rules-v0.1.0" | |
| LOW_SIGNAL_PATTERNS = [ | |
| re.compile(pattern, re.IGNORECASE) | |
| for pattern in [ | |
| r"\blet me know if you (need|want|have)\b", | |
| r"\bi hope this helps\b", | |
| r"\bas an ai language model\b", | |
| r"\bof course[,!]?\s*$", | |
| r"\bcertainly[,!]?\s*$", | |
| r"\bsure[,!]?\s*$", | |
| ] | |
| ] | |
| app = FastAPI(title="Touchdown Compression Classifier", version="0.1.0") | |
| def _get_tokenizer(): | |
| from transformers import AutoTokenizer | |
| return AutoTokenizer.from_pretrained(CLASSIFIER_MODEL) | |
| def _classifier_manifest() -> dict[str, Any] | None: | |
| if not CLASSIFIER_ARTIFACT_DIR: | |
| return None | |
| path = Path(CLASSIFIER_ARTIFACT_DIR) / "classifier_manifest.json" | |
| if not path.exists(): | |
| return { | |
| "status": "manifest_error", | |
| "error": f"missing classifier manifest: {path}", | |
| } | |
| try: | |
| payload = json.loads(path.read_text(encoding="utf-8")) | |
| except Exception as exc: | |
| return {"status": "manifest_error", "error": str(exc)} | |
| if not isinstance(payload, dict): | |
| return {"status": "manifest_error", "error": "manifest must be an object"} | |
| return payload | |
| def _get_artifact_tokenizer(): | |
| from transformers import AutoTokenizer | |
| return AutoTokenizer.from_pretrained(str(CLASSIFIER_ARTIFACT_DIR)) | |
| def _get_onnx_session(model_path: str): | |
| import onnxruntime as ort | |
| return ort.InferenceSession(model_path, providers=["CPUExecutionProvider"]) | |
| def _find_spans(text: str, needle: str) -> list[tuple[int, int]]: | |
| spans = [] | |
| cursor = 0 | |
| while needle: | |
| index = text.find(needle, cursor) | |
| if index < 0: | |
| return spans | |
| spans.append((index, index + len(needle))) | |
| cursor = index + len(needle) | |
| return spans | |
| def _regex_spans(text: str, pattern: str, flags: int) -> list[tuple[int, int]]: | |
| return [(match.start(), match.end()) for match in re.finditer(pattern, text, flags)] | |
| def _json_line_spans(text: str) -> list[tuple[int, int]]: | |
| spans = [] | |
| cursor = 0 | |
| for line in text.splitlines(keepends=True): | |
| stripped = line.strip() | |
| if stripped and stripped[0] in "[{": | |
| try: | |
| import json | |
| json.loads(stripped) | |
| except Exception: | |
| pass | |
| else: | |
| offset = line.index(stripped[0]) | |
| spans.append((cursor + offset, cursor + offset + len(stripped))) | |
| cursor += len(line) | |
| return spans | |
| def _merge(spans: list[tuple[int, int]]) -> list[tuple[int, int]]: | |
| if not spans: | |
| return [] | |
| ordered = sorted(spans) | |
| merged = [ordered[0]] | |
| for start, end in ordered[1:]: | |
| prev_start, prev_end = merged[-1] | |
| if start <= prev_end: | |
| merged[-1] = (prev_start, max(prev_end, end)) | |
| else: | |
| merged.append((start, end)) | |
| return merged | |
| def _overlaps(spans: list[tuple[int, int]], start: int, end: int) -> bool: | |
| return any(start < span_end and end > span_start for span_start, span_end in spans) | |
| def _manifest_drop_labels(text: str) -> tuple[str, list[dict[str, Any]], str | None]: | |
| manifest = _classifier_manifest() | |
| if not manifest: | |
| return "tokenizer_loaded_no_trained_keep_drop_head", [], None | |
| if manifest.get("status") == "manifest_error": | |
| return "manifest_error", [], str(manifest.get("error")) | |
| onnx_model = Path(CLASSIFIER_ARTIFACT_DIR or "") / str( | |
| manifest.get("onnx_model", "model.onnx") | |
| ) | |
| if onnx_model.exists(): | |
| try: | |
| return ( | |
| str(manifest.get("status") or "trained_keep_drop_head"), | |
| _onnx_labels(text, manifest, onnx_model), | |
| None, | |
| ) | |
| except Exception as exc: | |
| return "local_artifact_error", [], str(exc) | |
| labels: list[dict[str, Any]] = [] | |
| for index, entry in enumerate(manifest.get("drop_phrases") or []): | |
| if isinstance(entry, str): | |
| phrase = entry | |
| score = 1.0 | |
| elif isinstance(entry, dict): | |
| phrase = str(entry.get("text") or "") | |
| score = float(entry.get("score", 1.0)) | |
| else: | |
| continue | |
| cursor = 0 | |
| while phrase: | |
| start = text.find(phrase, cursor) | |
| if start < 0: | |
| break | |
| end = start + len(phrase) | |
| labels.append({ | |
| "token": phrase, | |
| "label": "DROP", | |
| "score": score, | |
| "start": start, | |
| "end": end, | |
| "source": "manifest_drop_phrase", | |
| "classifier_index": index, | |
| }) | |
| cursor = end | |
| return str(manifest.get("status") or "artifact_manifest_loaded"), labels, None | |
| def _softmax(values: list[float]) -> list[float]: | |
| peak = max(values) | |
| exps = [math.exp(value - peak) for value in values] | |
| total = sum(exps) or 1.0 | |
| return [value / total for value in exps] | |
| def _onnx_labels( | |
| text: str, | |
| manifest: dict[str, Any], | |
| model_path: Path, | |
| ) -> list[dict[str, Any]]: | |
| import numpy as np | |
| tokenizer = _get_artifact_tokenizer() | |
| encoded = tokenizer( | |
| text, | |
| add_special_tokens=False, | |
| return_offsets_mapping=True, | |
| return_tensors="np", | |
| truncation=True, | |
| max_length=int(manifest.get("max_length", 512)), | |
| ) | |
| offsets = encoded.pop("offset_mapping")[0] | |
| session = _get_onnx_session(str(model_path)) | |
| input_names = {item.name for item in session.get_inputs()} | |
| inputs = {key: value for key, value in encoded.items() if key in input_names} | |
| logits = session.run(None, inputs)[0][0] | |
| id2label = { | |
| str(key): value | |
| for key, value in (manifest.get("id2label") or {"0": "KEEP", "1": "DROP"}).items() | |
| } | |
| tokens = tokenizer.convert_ids_to_tokens(encoded["input_ids"][0]) | |
| labels = [] | |
| for index, token_logits in enumerate(logits): | |
| probs = _softmax(np.asarray(token_logits, dtype=float).tolist()) | |
| label_id = int(np.argmax(probs)) | |
| start, end = offsets[index] | |
| if int(end) <= int(start): | |
| continue | |
| labels.append({ | |
| "token": tokens[index], | |
| "label": id2label.get(str(label_id), "KEEP"), | |
| "score": round(float(probs[label_id]), 6), | |
| "start": int(start), | |
| "end": int(end), | |
| "source": "onnx_token_classifier", | |
| }) | |
| return labels | |
| def _safe_classifier_drop_ranges( | |
| labels: list[dict[str, Any]], | |
| protected: list[tuple[int, int]], | |
| *, | |
| text_length: int, | |
| min_score: float, | |
| ) -> tuple[list[tuple[int, int]], int, int, int]: | |
| ranges: list[tuple[int, int]] = [] | |
| drop_labels = 0 | |
| blocked = 0 | |
| for item in labels: | |
| if str(item.get("label") or item.get("entity") or "").upper() != "DROP": | |
| continue | |
| drop_labels += 1 | |
| try: | |
| start = int(item["start"]) | |
| end = int(item["end"]) | |
| score = float(item.get("score", 1.0)) | |
| except Exception: | |
| blocked += 1 | |
| continue | |
| if ( | |
| start < 0 | |
| or end > text_length | |
| or end <= start | |
| or score < min_score | |
| or _overlaps(protected, start, end) | |
| ): | |
| blocked += 1 | |
| continue | |
| ranges.append((start, end)) | |
| return _merge(ranges), drop_labels, len(ranges), blocked | |
| def _is_subsequence(candidate: str, original: str) -> bool: | |
| cursor = 0 | |
| for char in candidate: | |
| cursor = original.find(char, cursor) | |
| if cursor < 0: | |
| return False | |
| cursor += 1 | |
| return True | |
| def _sha256_text(value: str) -> str: | |
| return hashlib.sha256(value.encode("utf-8")).hexdigest() | |
| def _receipt_id(payload: dict[str, Any]) -> str: | |
| encoded = json.dumps(payload, sort_keys=True, separators=(",", ":")) | |
| return "tdcr_" + hashlib.sha256(encoded.encode("utf-8")).hexdigest()[:24] | |
| def _protected_spans( | |
| text: str, | |
| protected_values: list[str], | |
| *, | |
| preserve_code: bool, | |
| preserve_json: bool, | |
| ) -> tuple[ | |
| list[tuple[int, int]], | |
| list[tuple[int, int]], | |
| list[tuple[int, int]], | |
| list[tuple[int, int]], | |
| ]: | |
| spans = [] | |
| for value in protected_values: | |
| spans.extend(_find_spans(text, value)) | |
| code_spans = ( | |
| _regex_spans(text, r"```.*?```", re.MULTILINE | re.DOTALL) | |
| if preserve_code | |
| else [] | |
| ) | |
| json_spans = ( | |
| _regex_spans(text, r"```(?:json|JSON)\s*\n.*?```", re.MULTILINE | re.DOTALL) | |
| + _json_line_spans(text) | |
| if preserve_json | |
| else [] | |
| ) | |
| system_spans = ( | |
| _regex_spans(text, r"<system\b[^>]*>.*?</system>", re.MULTILINE | re.DOTALL) | |
| + _regex_spans(text, r"^system\s*:\s*.*$", re.MULTILINE | re.IGNORECASE) | |
| ) | |
| spans.extend(code_spans) | |
| spans.extend(json_spans) | |
| spans.extend(system_spans) | |
| return _merge(spans), code_spans, json_spans, system_spans | |
| def _compress_text(payload: dict[str, Any]) -> dict[str, Any]: | |
| text = payload.get("input") | |
| if not isinstance(text, str): | |
| raise HTTPException(status_code=400, detail="input must be a string") | |
| settings = payload.get("compression_settings") or {} | |
| if not isinstance(settings, dict): | |
| raise HTTPException(status_code=400, detail="compression_settings must be an object") | |
| protected_values = payload.get("protected_spans") or [] | |
| if not isinstance(protected_values, list) or not all( | |
| isinstance(value, str) for value in protected_values | |
| ): | |
| raise HTTPException(status_code=400, detail="protected_spans must be strings") | |
| try: | |
| aggressiveness = float(settings.get("aggressiveness", 0.35)) | |
| except Exception as exc: | |
| raise HTTPException(status_code=400, detail="aggressiveness must be numeric") from exc | |
| if not 0.0 <= aggressiveness <= 1.0: | |
| raise HTTPException(status_code=400, detail="aggressiveness must be 0..1") | |
| started = time.perf_counter() | |
| preserve_code = bool(settings.get("preserve_code", True)) | |
| preserve_json = bool(settings.get("preserve_json", True)) | |
| protected, code_spans, json_spans, system_spans = _protected_spans( | |
| text, | |
| protected_values, | |
| preserve_code=preserve_code, | |
| preserve_json=preserve_json, | |
| ) | |
| classifier_status, classifier_labels, classifier_error = _manifest_drop_labels(text) | |
| classifier_ranges, classifier_drop_labels, classifier_applied, classifier_blocked = ( | |
| _safe_classifier_drop_ranges( | |
| classifier_labels, | |
| protected, | |
| text_length=len(text), | |
| min_score=float(settings.get("classifier_min_drop_score", 0.5)), | |
| ) | |
| ) | |
| seen: set[str] = set() | |
| drops: list[tuple[int, int, str, str]] = [] | |
| cursor = 0 | |
| previous_blank_kept = False | |
| for line in text.splitlines(keepends=True): | |
| start = cursor | |
| end = cursor + len(line) | |
| cursor = end | |
| stripped = line.strip() | |
| normalized = re.sub(r"\s+", " ", stripped).lower() | |
| if _overlaps(protected, start, end): | |
| if normalized: | |
| seen.add(normalized) | |
| previous_blank_kept = False | |
| continue | |
| reason = None | |
| if not stripped and previous_blank_kept: | |
| reason = "extra_blank" | |
| elif len(normalized) > 30 and normalized in seen and aggressiveness >= 0.10: | |
| reason = "duplicate_line" | |
| elif aggressiveness >= 0.20 and any( | |
| pattern.search(stripped) for pattern in LOW_SIGNAL_PATTERNS | |
| ): | |
| reason = "low_signal_phrase" | |
| if reason: | |
| drops.append((start, end, reason, stripped[:120])) | |
| continue | |
| previous_blank_kept = not stripped | |
| if normalized: | |
| seen.add(normalized) | |
| chunks = [] | |
| drop_ranges = _merge([(start, end) for start, end, _, _ in drops] + classifier_ranges) | |
| cursor = 0 | |
| for start, end in drop_ranges: | |
| chunks.append(text[cursor:start]) | |
| cursor = end | |
| chunks.append(text[cursor:]) | |
| output = "".join(chunks) | |
| before = max(1, round(len(text) / 4.0)) | |
| after = max(1, round(len(output) / 4.0)) | |
| saved = max(0, before - after) | |
| missing = [value for value in protected_values if value and value not in output] | |
| code_preserved = all(text[start:end] in output for start, end in code_spans) | |
| json_preserved = all(text[start:end] in output for start, end in json_spans) | |
| system_preserved = all(text[start:end] in output for start, end in system_spans) | |
| decision = "reject" if ( | |
| missing or not code_preserved or not json_preserved or not system_preserved | |
| ) else ( | |
| "high_confidence" if saved > 0 and aggressiveness <= 0.65 else "no_op" | |
| ) | |
| dropped_segments = [ | |
| {"reason": reason, "preview": preview, "start": start, "end": end} | |
| for start, end, reason, preview in drops[:20] | |
| ] | |
| receipt = { | |
| "protected_spans_checked": len(protected_values), | |
| "protected_spans_missing": len(missing), | |
| "code_blocks_detected": len(code_spans), | |
| "code_blocks_preserved": code_preserved, | |
| "json_blocks_detected": len(json_spans), | |
| "json_blocks_preserved": json_preserved, | |
| "system_prompt_spans_detected": len(system_spans), | |
| "system_prompts_preserved": system_preserved, | |
| "decision": decision, | |
| "compressor_latency_ms": round((time.perf_counter() - started) * 1000.0, 3), | |
| "deletion_only": _is_subsequence(output, text), | |
| "deterministic": True, | |
| "rules_version": RULES_VERSION, | |
| "classifier": { | |
| "model": CLASSIFIER_MODEL, | |
| "status": classifier_status, | |
| "artifact_dir_configured": bool(CLASSIFIER_ARTIFACT_DIR), | |
| "artifact_dir": CLASSIFIER_ARTIFACT_DIR, | |
| "error": classifier_error, | |
| "labels_received": len(classifier_labels), | |
| "drop_labels": classifier_drop_labels, | |
| "drop_spans_applied": classifier_applied, | |
| "drop_spans_blocked_by_safety": classifier_blocked, | |
| }, | |
| "dropped_segments_count": len(drops), | |
| "dropped_segments": dropped_segments, | |
| } | |
| receipt["input_sha256"] = _sha256_text(text) | |
| receipt["output_sha256"] = _sha256_text(output) | |
| receipt["removed_sha256"] = _sha256_text( | |
| "".join(text[start:end] for start, end in drop_ranges) | |
| ) | |
| receipt["receipt_id"] = _receipt_id({ | |
| "input_sha256": receipt["input_sha256"], | |
| "output_sha256": receipt["output_sha256"], | |
| "removed_sha256": receipt["removed_sha256"], | |
| "tokens_saved": saved, | |
| "compression_percentage": round(100.0 * saved / before, 1), | |
| "decision": decision, | |
| "rules_version": RULES_VERSION, | |
| "classifier": receipt["classifier"], | |
| "dropped_segments": dropped_segments, | |
| }) | |
| return { | |
| "schema_version": API_SCHEMA_VERSION, | |
| "status": "ok", | |
| "endpoint": "/v1/compress", | |
| "maturity": "measurement_only", | |
| "output": output, | |
| "original_input_tokens": before, | |
| "output_tokens": after, | |
| "tokens_saved": saved, | |
| "compression_percentage": round(100.0 * saved / before, 1), | |
| "receipt": receipt, | |
| } | |
| def _merge_batch_item_payload( | |
| payload: dict[str, Any], | |
| item: Any, | |
| index: int, | |
| ) -> tuple[str | None, dict[str, Any]]: | |
| if isinstance(item, str): | |
| return None, { | |
| "input": item, | |
| "compression_settings": payload.get("compression_settings"), | |
| "protected_spans": payload.get("protected_spans"), | |
| } | |
| if not isinstance(item, dict): | |
| raise ValueError(f"inputs[{index}] must be a string or an object") | |
| item_id = item.get("id") | |
| if item_id is not None and not isinstance(item_id, str): | |
| raise ValueError(f"inputs[{index}].id must be a string") | |
| if "input" not in item: | |
| raise ValueError(f"inputs[{index}].input is required") | |
| top_settings = payload.get("compression_settings") | |
| item_settings = item.get("compression_settings") | |
| if top_settings is not None and not isinstance(top_settings, dict): | |
| raise ValueError("compression_settings must be an object") | |
| if item_settings is not None and not isinstance(item_settings, dict): | |
| raise ValueError(f"inputs[{index}].compression_settings must be an object") | |
| settings = { | |
| **(top_settings or {}), | |
| **(item_settings or {}), | |
| } or None | |
| return item_id, { | |
| "input": item.get("input"), | |
| "compression_settings": settings, | |
| "protected_spans": item.get("protected_spans", payload.get("protected_spans")), | |
| } | |
| def _handle_batch(payload: dict[str, Any]) -> dict[str, Any]: | |
| if "input" in payload: | |
| raise HTTPException(status_code=400, detail="provide either input or inputs, not both") | |
| inputs = payload.get("inputs") | |
| if not isinstance(inputs, list): | |
| raise HTTPException(status_code=400, detail="inputs must be a list") | |
| if not inputs: | |
| raise HTTPException(status_code=400, detail="inputs list is empty") | |
| results: list[dict[str, Any]] = [] | |
| totals = { | |
| "original_input_tokens": 0, | |
| "output_tokens": 0, | |
| "tokens_saved": 0, | |
| } | |
| succeeded = 0 | |
| failed = 0 | |
| for index, item in enumerate(inputs): | |
| item_result: dict[str, Any] = {"index": index} | |
| if isinstance(item, dict) and isinstance(item.get("id"), str): | |
| item_result["id"] = item["id"] | |
| try: | |
| item_id, item_payload = _merge_batch_item_payload(payload, item, index) | |
| if item_id is not None: | |
| item_result["id"] = item_id | |
| result = _compress_text(item_payload) | |
| except HTTPException as exc: | |
| item_result.update({"status": "error", "error": str(exc.detail)}) | |
| failed += 1 | |
| results.append(item_result) | |
| continue | |
| except ValueError as exc: | |
| item_result.update({"status": "error", "error": str(exc)}) | |
| failed += 1 | |
| results.append(item_result) | |
| continue | |
| item_result.update({"status": "ok", **result}) | |
| totals["original_input_tokens"] += int(result["original_input_tokens"]) | |
| totals["output_tokens"] += int(result["output_tokens"]) | |
| totals["tokens_saved"] += int(result["tokens_saved"]) | |
| succeeded += 1 | |
| results.append(item_result) | |
| compression_pct = ( | |
| round(100.0 * totals["tokens_saved"] / totals["original_input_tokens"], 1) | |
| if totals["original_input_tokens"] | |
| else 0.0 | |
| ) | |
| receipt_ids = [ | |
| result["receipt"]["receipt_id"] | |
| for result in results | |
| if result.get("status") == "ok" and result.get("receipt", {}).get("receipt_id") | |
| ] | |
| return { | |
| "schema_version": API_SCHEMA_VERSION, | |
| "status": "ok" if failed == 0 else "partial_error", | |
| "endpoint": "/v1/compress", | |
| "maturity": "measurement_only", | |
| "input_count": len(inputs), | |
| "succeeded": succeeded, | |
| "failed": failed, | |
| **totals, | |
| "compression_percentage": compression_pct, | |
| "receipt_ids": receipt_ids, | |
| "results": results, | |
| } | |
| def _tokens(text: str) -> list[dict[str, Any]]: | |
| started = time.perf_counter() | |
| try: | |
| tokenizer = _get_tokenizer() | |
| encoded = tokenizer( | |
| text, | |
| add_special_tokens=False, | |
| return_offsets_mapping=True, | |
| ) | |
| pieces = tokenizer.convert_ids_to_tokens(encoded["input_ids"]) | |
| offsets = encoded["offset_mapping"] | |
| token_source = "deberta_tokenizer" | |
| except Exception: | |
| matches = list(re.finditer(r"\S+|\s+", text)) | |
| pieces = [match.group(0) for match in matches] | |
| offsets = [(match.start(), match.end()) for match in matches] | |
| token_source = "regex_fallback" | |
| elapsed = round((time.perf_counter() - started) * 1000.0, 3) | |
| return [ | |
| { | |
| "token": piece, | |
| "label": "KEEP", | |
| "score": 1.0, | |
| "start": int(offsets[i][0]), | |
| "end": int(offsets[i][1]), | |
| "source": token_source, | |
| "classifier_latency_ms": elapsed if i == 0 else 0.0, | |
| } | |
| for i, piece in enumerate(pieces) | |
| ] | |
| def health() -> dict[str, Any]: | |
| classifier_status, _, classifier_error = _manifest_drop_labels("") | |
| return { | |
| "status": "ok", | |
| "classifier_model": CLASSIFIER_MODEL, | |
| "classifier_status": classifier_status, | |
| "classifier_artifact_dir_configured": bool(CLASSIFIER_ARTIFACT_DIR), | |
| "classifier_error": classifier_error, | |
| "phase": "rules_api_first", | |
| } | |
| def classify(payload: dict[str, Any]) -> dict[str, Any]: | |
| text = payload.get("input") | |
| if not isinstance(text, str): | |
| raise HTTPException(status_code=400, detail="input must be a string") | |
| classifier_status, artifact_labels, classifier_error = _manifest_drop_labels(text) | |
| labels = artifact_labels or _tokens(text) | |
| return { | |
| "model": CLASSIFIER_MODEL, | |
| "task": "token_classification_keep_drop", | |
| "status": ( | |
| classifier_status if CLASSIFIER_ARTIFACT_DIR or artifact_labels or classifier_error | |
| else "tokenizer_only_until_trained_head" | |
| ), | |
| "artifact_dir_configured": bool(CLASSIFIER_ARTIFACT_DIR), | |
| "error": classifier_error, | |
| "labels": labels, | |
| "note": ( | |
| "This free Space scaffold loads the DeBERTa tokenizer and returns " | |
| "KEEP-only labels until a trained KEEP/DROP head or ONNX export is " | |
| "mounted. Do not treat it as a production compressor." | |
| ), | |
| } | |
| def compress(payload: dict[str, Any]) -> dict[str, Any]: | |
| if "inputs" in payload: | |
| return _handle_batch(payload) | |
| return _compress_text(payload) | |