n1th1sh commited on
Commit
3a36c0b
Β·
verified Β·
1 Parent(s): db07968

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +359 -103
app.py CHANGED
@@ -1,113 +1,369 @@
 
 
 
 
 
 
 
 
 
 
 
1
  import os
 
 
2
  import gradio as gr
3
- from transformers import pipeline, AutoTokenizer, AutoModelForTokenClassification
4
- from key_store import (
5
- generate_api_key, validate_key, increment_usage,
6
- revoke_key, delete_key, list_keys
7
- )
8
-
9
- # ── Load your private HF model ────────────────────────────────────────────────
10
- HF_TOKEN = os.environ.get("HF_TOKEN")
11
- MODEL_ID = "Wardline/CLOAK_V2.2.11"
12
-
13
- tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, token=HF_TOKEN)
14
- model = AutoModelForTokenClassification.from_pretrained(MODEL_ID, token=HF_TOKEN)
15
- ner_pipe = pipeline("ner", model=model, tokenizer=tokenizer, aggregation_strategy="simple")
16
-
17
- # ── Stitcher: merge split sub-word tokens ─────────────────────────────────────
18
- def stitch_entities(raw_entities: list) -> list:
19
- merged = []
20
- for r in raw_entities:
21
- if (merged
22
- and merged[-1]["entity_group"] == r["entity_group"]
23
- and merged[-1]["end"] == r["start"]):
24
- merged[-1]["word"] += r["word"].replace(" ", "")
25
- merged[-1]["end"] = r["end"]
26
- else:
27
- merged.append(dict(r)) # copy so we don't mutate the original
28
- return merged
29
-
30
- # ── PII detection ─────────────────────────────────────────────────────────────
31
- def detect_pii(text: str, api_key: str) -> dict:
32
- entry = validate_key(api_key)
33
- if not entry:
34
- return {"error": "Invalid or revoked API key.", "entities": []}
35
- increment_usage(api_key)
36
-
37
- raw = ner_pipe(text)
38
- entities = stitch_entities(raw)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  return {
41
- "text": text,
42
- "entities": [
43
- {
44
- "entity": e["entity_group"],
45
- "word": e["word"],
46
- "score": round(e["score"], 4),
47
- "start": e["start"],
48
- "end": e["end"],
49
- }
50
- for e in entities
51
- ],
52
  }
53
 
54
- # ── Key management helpers ─────────────────────────────────────────────────���──
55
- def create_key(label):
56
- if not label.strip():
57
- return "Please enter a label.", get_key_table()
58
- key = generate_api_key(label.strip())
59
- return f"βœ… New key created (save it now):\n\n{key}", get_key_table()
60
 
61
- def get_key_table():
62
- rows = list_keys()
63
- if not rows:
64
- return []
65
- return [[r["label"], r["key_preview"], r["status"], r["usage"], r["created_at"]] for r in rows]
 
 
66
 
67
- def do_revoke(full_key):
68
- revoke_key(full_key.strip())
69
- return "Key revoked.", get_key_table()
70
 
71
- def do_delete(full_key):
72
- delete_key(full_key.strip())
73
- return "Key deleted.", get_key_table()
 
74
 
75
- # ── Gradio UI ─────────────────────────────────────────────────────────────────
76
- with gr.Blocks(title="PII Detection API") as demo:
77
- gr.Markdown("# PII Detection API\nPowered by your private Hugging Face model.")
78
-
79
- with gr.Tab("Detect PII"):
80
- with gr.Row():
81
- api_key_in = gr.Textbox(label="API key", placeholder="pii_sk_...")
82
- text_in = gr.Textbox(label="Input text", lines=4,
83
- placeholder="Enter text to scan for PII...")
84
- detect_btn = gr.Button("Detect PII", variant="primary")
85
- output_json = gr.JSON(label="Results")
86
- detect_btn.click(fn=detect_pii, inputs=[text_in, api_key_in], outputs=output_json)
87
-
88
- with gr.Tab("API Key Management"):
89
- gr.Markdown("### Create a new key")
90
- with gr.Row():
91
- label_in = gr.Textbox(label="Key label", placeholder="e.g. production")
92
- create_btn = gr.Button("Generate key")
93
- create_msg = gr.Textbox(label="New key (copy now!)", interactive=False, lines=2)
94
-
95
- gr.Markdown("### All keys")
96
- key_df = gr.DataFrame(
97
- value=get_key_table(),
98
- headers=["Label", "Key preview", "Status", "Usage", "Created"],
99
- interactive=False,
100
- )
101
-
102
- gr.Markdown("### Revoke or delete a key")
103
- with gr.Row():
104
- manage_key_in = gr.Textbox(label="Full API key", placeholder="pii_sk_...")
105
- revoke_btn = gr.Button("Revoke")
106
- delete_btn = gr.Button("Delete", variant="stop")
107
- manage_msg = gr.Textbox(label="Result", interactive=False)
108
-
109
- create_btn.click(create_key, inputs=label_in, outputs=[create_msg, key_df])
110
- revoke_btn.click(do_revoke, inputs=manage_key_in, outputs=[manage_msg, key_df])
111
- delete_btn.click(do_delete, inputs=manage_key_in, outputs=[manage_msg, key_df])
112
-
113
- demo.launch()
 
1
+ """
2
+ CLOAK PII Demo β€” ONNX INT8 CPU inference + Gradio UI + REST /detect API.
3
+ Downloads model.int8.onnx from HF Hub at startup.
4
+ Set HF_TOKEN secret in Space settings if the repo is private.
5
+ The /detect endpoint is what the CLOAK API (Next.js) calls via callHfSpace:
6
+ POST /detect Authorization: Bearer <API_SECRET> {"text": "..."}
7
+ -> {entities, nested, redacted_text, model, processing_time_ms}
8
+ """
9
+
10
+ import html as _html
11
+ import json
12
  import os
13
+ import time
14
+
15
  import gradio as gr
16
+ import numpy as np
17
+ import onnxruntime as ort
18
+ import pandas as pd
19
+ from fastapi import FastAPI, HTTPException, Request
20
+ from huggingface_hub import hf_hub_download, login
21
+ from pydantic import BaseModel, Field
22
+ from transformers import AutoTokenizer
23
+
24
+ # ── Config ────────────────────────────────────────────────────────────────────
25
+
26
+ MODEL_REPO = os.getenv("MODEL_REPO", "Wardline/CLOAK_V3.6")
27
+ HF_TOKEN = os.getenv("HF_TOKEN")
28
+ # Bearer token the CLOAK API must send. callHfSpace sends `Bearer ${HF_TOKEN}`,
29
+ # so default API_SECRET to HF_TOKEN β€” the same secret works for both unless set.
30
+ API_SECRET = os.getenv("API_SECRET", HF_TOKEN)
31
+
32
+ MAX_LEN = 512
33
+ STRIDE = 128
34
+ THRESHOLD = 0.0
35
+
36
+ # ── Thread count: read cgroup CPU quota, not sched_getaffinity ────────────────
37
+ # sched_getaffinity returns the host's full CPU set inside Docker containers.
38
+ # The real allocated vCPU count lives in the cgroup CFS quota.
39
+
40
+ def _container_cpu_count() -> int:
41
+ # cgroup v2
42
+ try:
43
+ with open("/sys/fs/cgroup/cpu.max") as f:
44
+ quota, period = f.read().split()
45
+ if quota != "max":
46
+ return max(1, round(int(quota) / int(period)))
47
+ except Exception:
48
+ pass
49
+ # cgroup v1
50
+ try:
51
+ with open("/sys/fs/cgroup/cpu/cpu.cfs_quota_us") as f:
52
+ quota = int(f.read())
53
+ with open("/sys/fs/cgroup/cpu/cpu.cfs_period_us") as f:
54
+ period = int(f.read())
55
+ if quota > 0:
56
+ return max(1, quota // period)
57
+ except Exception:
58
+ pass
59
+ return os.cpu_count() or 2
60
+
61
+ _n_threads = _container_cpu_count()
62
+ print(f"Container CPU count: {_n_threads} (os.cpu_count={os.cpu_count()})")
63
+
64
+ # ── Load at startup ───────────────────────────────────────────────────────────
65
+
66
+ if HF_TOKEN:
67
+ login(token=HF_TOKEN)
68
+
69
+ _config_path = hf_hub_download(MODEL_REPO, "config.json", token=HF_TOKEN)
70
+ _int8_path = hf_hub_download(MODEL_REPO, "model.int8.onnx", token=HF_TOKEN)
71
+
72
+ with open(_config_path, encoding="utf-8") as fh:
73
+ _config = json.load(fh)
74
+
75
+ _id2label = {int(k): v for k, v in _config["id2label"].items()}
76
+ _tokenizer = AutoTokenizer.from_pretrained(MODEL_REPO, subfolder="tokenizer", token=HF_TOKEN)
77
+
78
+ _opts = ort.SessionOptions()
79
+ _opts.intra_op_num_threads = _n_threads
80
+ _opts.inter_op_num_threads = 1
81
+ _opts.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL
82
+ _sess = ort.InferenceSession(_int8_path, sess_options=_opts, providers=["CPUExecutionProvider"])
83
+
84
+ print(f"ONNX INT8 session ready β€” {_n_threads} threads, {len(_id2label)} classes")
85
+
86
+
87
+ # ── Inference ─────────────────────────────────────────────────────────────────
88
+
89
+ def _suppress_same_label(entities: list) -> list:
90
+ kept = []
91
+ for ent in sorted(entities, key=lambda x: -x["score"]):
92
+ if any(k["entity_group"] == ent["entity_group"]
93
+ and ent["start"] < k["end"] and k["start"] < ent["end"] for k in kept):
94
+ continue
95
+ kept.append(ent)
96
+ return kept
97
+
98
+
99
+ def detect(text: str, threshold: float = THRESHOLD):
100
+ enc = _tokenizer(
101
+ text, max_length=MAX_LEN, truncation=True, stride=STRIDE, padding=True,
102
+ return_overflowing_tokens=True, return_offsets_mapping=True, return_tensors="np",
103
+ )
104
+ all_offsets = enc.pop("offset_mapping")
105
+ enc.pop("overflow_to_sample_mapping", None)
106
+
107
+ best: dict = {}
108
+ for w in range(all_offsets.shape[0]):
109
+ feed = {
110
+ "input_ids": enc["input_ids"][w:w + 1].astype(np.int64),
111
+ "attention_mask": enc["attention_mask"][w:w + 1].astype(np.int64),
112
+ }
113
+ logits = _sess.run(["logits"], feed)[0][0] # [classes, L, L]
114
+ offsets = all_offsets[w]
115
+
116
+ cidx, sidx, eidx = np.where(logits > threshold)
117
+ if len(cidx) == 0:
118
+ continue
119
+
120
+ scores = 1.0 / (1.0 + np.exp(-logits[cidx, sidx, eidx]))
121
+ cs = offsets[sidx, 0]
122
+ ce = offsets[eidx, 1]
123
+ keep = cs < ce
124
+ for cid, c0, c1, sc in zip(cidx[keep], cs[keep], ce[keep], scores[keep]):
125
+ key = (int(cid), int(c0), int(c1))
126
+ if key not in best or sc > best[key]["score"]:
127
+ best[key] = {
128
+ "entity_group": _id2label[int(cid)],
129
+ "start": int(c0), "end": int(c1),
130
+ "score": float(sc),
131
+ }
132
+
133
+ doc_len = max(1, len(text))
134
+ cands = [e for e in best.values() if (e["end"] - e["start"]) <= 0.5 * doc_len]
135
+ cands = _suppress_same_label(cands)
136
+
137
+ flat = []
138
+ for ent in sorted(cands, key=lambda x: (-(x["end"] - x["start"]), -x["score"])):
139
+ if any(ent["start"] < k["end"] and k["start"] < ent["end"] for k in flat):
140
+ continue
141
+ flat.append(ent)
142
+ flat = sorted(flat, key=lambda x: x["start"])
143
+ return flat, cands
144
+
145
+
146
+ # ── UI helpers ────────────────────────────────────────────────────────────────
147
+
148
+ COLOR_MAP = {
149
+ "PERSON_NAME": "#FF6B6B", "AADHAAR": "#6a0dad", "PASSPORT_NUMBER": "#1e90ff",
150
+ "PAN": "#ff8c00", "SSN": "#dc143c", "DRIVER_LICENSE": "#ff7f50", "VOTER_ID": "#ff69b4",
151
+ "PHONE_NUMBER": "#20b2aa", "EMAIL": "#2e8b57", "USERNAME": "#3cb371", "PASSWORD": "#8b0000",
152
+ "BANK_ACCOUNT": "#8b4513", "CREDIT_CARD": "#ff1493", "CVV": "#c71585",
153
+ "CREDIT_CARD_EXPIRATION": "#db7093", "UPI_ID": "#4682b4", "MONEY": "#2f4f4f",
154
+ "DATE_OF_BIRTH": "#228b22", "DATE": "#6b8e23", "ADDRESS": "#8b008b",
155
+ "LOCATION": "#008b8b", "ORGANIZATION": "#cd853f", "EMAIL_ADDRESS": "#2e8b57",
156
+ "IP_ADDRESS": "#483d8b", "URL": "#4169e1", "API_KEY": "#800000",
157
+ }
158
+ _FALLBACK = ["#45B7D1", "#96CEB4", "#FFEAA7", "#DDA0DD", "#F7DC6F", "#85C1E9"]
159
+ _extra: dict = {}
160
+
161
+ def _label_color(label: str) -> str:
162
+ if label in COLOR_MAP:
163
+ return COLOR_MAP[label]
164
+ if label not in _extra:
165
+ _extra[label] = _FALLBACK[len(_extra) % len(_FALLBACK)]
166
+ return _extra[label]
167
+
168
+
169
+ def _highlight_html(text: str, cands: list) -> str:
170
+ if not cands:
171
+ return f"<div style='line-height:2.4;font-size:15px;font-family:sans-serif'>{_html.escape(text)}</div>"
172
+
173
+ ents = sorted(cands, key=lambda e: (e["start"], -(e["end"] - e["start"])))
174
+ for e in ents:
175
+ e["_children"] = []
176
+
177
+ roots = []
178
+ for e in ents:
179
+ parent = None
180
+ for c in ents:
181
+ if (c is not e
182
+ and c["start"] <= e["start"] and e["end"] <= c["end"]
183
+ and (c["end"] - c["start"]) > (e["end"] - e["start"])):
184
+ if parent is None or (c["end"] - c["start"]) < (parent["end"] - parent["start"]):
185
+ parent = c
186
+ (parent["_children"] if parent else roots).append(e)
187
+
188
+ def render(lo, hi, children):
189
+ children = sorted(children, key=lambda c: c["start"])
190
+ out, cur = "", lo
191
+ for ch in children:
192
+ if ch["start"] < cur:
193
+ continue
194
+ out += _html.escape(text[cur:ch["start"]])
195
+ color = _label_color(ch["entity_group"])
196
+ label = ch["entity_group"]
197
+ pct = round(ch["score"] * 100, 1)
198
+ inner = render(ch["start"], ch["end"], ch["_children"])
199
+ badge = f'<small style="opacity:.8;font-size:10px"> {label}</small>'
200
+ title = f"{label} {pct}%"
201
+ out += (f'<span style="background:{color};color:white;padding:2px 5px;'
202
+ f'border-radius:4px;font-weight:600;" title="{title}">'
203
+ f'{inner}{badge}</span>')
204
+ cur = ch["end"]
205
+ out += _html.escape(text[cur:hi])
206
+ return out
207
 
208
+ body = render(0, len(text), roots)
209
+ return f"<div style='line-height:2.6;font-size:15px;font-family:sans-serif'>{body}</div>"
210
+
211
+
212
+ def run_analyze(text: str, threshold: float):
213
+ if not text or not text.strip():
214
+ return "<div style='color:#888'>Paste text above and click Analyze.</div>", pd.DataFrame(), "", ""
215
+
216
+ t0 = time.time()
217
+ flat, cands = detect(text, threshold)
218
+ elapsed = round(time.time() - t0, 2)
219
+
220
+ html_out = _highlight_html(text, cands)
221
+
222
+ redacted = text
223
+ for e in sorted(flat, key=lambda x: x["start"], reverse=True):
224
+ redacted = redacted[:e["start"]] + f'[{e["entity_group"]}]' + redacted[e["end"]:]
225
+
226
+ rows = [{
227
+ "Type": e["entity_group"],
228
+ "Text": text[e["start"]:e["end"]].strip(),
229
+ "Confidence": f'{round(e["score"] * 100, 1)}%',
230
+ "Start": e["start"],
231
+ "End": e["end"],
232
+ } for e in flat]
233
+ df = pd.DataFrame(rows)
234
+
235
+ summary = f"{elapsed}s | {len(flat)} entities | {len(text)} chars | {_n_threads} CPU threads"
236
+ return html_out, df, redacted, summary
237
+
238
+
239
+ # ── Gradio UI ─────────────────────────────────────────────────────────────────
240
+
241
+ EXAMPLES = [
242
+ ["My name is John Smith, email john@example.com, SSN 123-45-6789, card 4532 8812 7731 9823.", 0.0],
243
+ ["Patient Priya Sharma, DOB 12/03/1991, Aadhaar 2345 6789 0123, prescribed metformin 500mg.", 0.0],
244
+ ["Invoice to Acme Corp, 400 Market St, San Francisco CA 94105. Contact: +1 415 555 0100.", 0.0],
245
+ ]
246
+
247
+ with gr.Blocks(title="CLOAK PII Detector", theme=gr.themes.Soft()) as demo:
248
+ gr.Markdown(
249
+ "## CLOAK V3.6 β€” PII Detector\n"
250
+ "Detects personally identifiable information using nested NER (ONNX INT8 CPU). "
251
+ "Nested highlighting shows overlapping spans."
252
+ )
253
+
254
+ with gr.Row():
255
+ with gr.Column(scale=3):
256
+ txt_input = gr.Textbox(
257
+ label="Input text",
258
+ placeholder="Paste text here…",
259
+ lines=8, max_lines=30,
260
+ )
261
+ threshold_slider = gr.Slider(
262
+ minimum=-2.0, maximum=6.0, value=0.0, step=0.5,
263
+ label="Detection threshold (higher = fewer, more confident detections)",
264
+ )
265
+ with gr.Row():
266
+ btn = gr.Button("Analyze", variant="primary", scale=2)
267
+ clear_btn = gr.Button("Clear", scale=1)
268
+ summary_box = gr.Textbox(label="", lines=1, interactive=False, show_label=False)
269
+
270
+ gr.Examples(examples=EXAMPLES, inputs=[txt_input, threshold_slider], label="Try an example")
271
+
272
+ highlighted = gr.HTML(label="Highlighted output")
273
+
274
+ with gr.Row():
275
+ with gr.Column():
276
+ entity_table = gr.Dataframe(
277
+ headers=["Type", "Text", "Confidence", "Start", "End"],
278
+ label="Detected entities",
279
+ interactive=False, wrap=True,
280
+ )
281
+ with gr.Column():
282
+ redacted_out = gr.Textbox(label="Redacted text", lines=8, interactive=False)
283
+
284
+ btn.click(
285
+ fn=run_analyze,
286
+ inputs=[txt_input, threshold_slider],
287
+ outputs=[highlighted, entity_table, redacted_out, summary_box],
288
+ )
289
+ txt_input.submit(
290
+ fn=run_analyze,
291
+ inputs=[txt_input, threshold_slider],
292
+ outputs=[highlighted, entity_table, redacted_out, summary_box],
293
+ )
294
+ clear_btn.click(
295
+ fn=lambda: ("", pd.DataFrame(), "", ""),
296
+ outputs=[txt_input, entity_table, redacted_out, summary_box],
297
+ )
298
+
299
+ # ── REST API for the CLOAK backend (callHfSpace contract) ─────────────────────
300
+
301
+ api = FastAPI(title="CLOAK PII API", version="1.0.0")
302
+
303
+
304
+ class DetectRequest(BaseModel):
305
+ text: str = Field(..., min_length=1, max_length=20_000)
306
+
307
+
308
+ def _fmt(text: str, e: dict) -> dict:
309
+ """Shape one entity to the contract the CLOAK API expects."""
310
  return {
311
+ "type": e["entity_group"],
312
+ "text": text[e["start"]:e["end"]].strip(),
313
+ "start": e["start"],
314
+ "end": e["end"],
315
+ "confidence": round(e["score"], 4),
 
 
 
 
 
 
316
  }
317
 
 
 
 
 
 
 
318
 
319
+ def _verify(request: Request):
320
+ auth = request.headers.get("Authorization", "")
321
+ if not auth.startswith("Bearer "):
322
+ raise HTTPException(status_code=401, detail="Missing Authorization header")
323
+ token = auth.removeprefix("Bearer ").strip()
324
+ if not API_SECRET or token != API_SECRET:
325
+ raise HTTPException(status_code=401, detail="Invalid token")
326
 
 
 
 
327
 
328
+ @api.get("/health")
329
+ def health():
330
+ return {"status": "ok", "model": MODEL_REPO, "engine": "onnx-int8-cpu",
331
+ "threads": _n_threads, "classes": len(_id2label)}
332
 
333
+
334
+ @api.post("/detect")
335
+ def detect_api(body: DetectRequest, request: Request):
336
+ _verify(request)
337
+ t0 = time.time()
338
+ try:
339
+ flat, cands = detect(body.text)
340
+ except Exception as exc:
341
+ raise HTTPException(status_code=503, detail=f"Inference failed: {exc}")
342
+
343
+ entities = [_fmt(body.text, e) for e in flat
344
+ if body.text[e["start"]:e["end"]].strip()]
345
+ nested = [_fmt(body.text, e)
346
+ for e in sorted(cands, key=lambda x: (x["start"], -(x["end"] - x["start"])))
347
+ if body.text[e["start"]:e["end"]].strip()]
348
+
349
+ redacted = body.text
350
+ for e in sorted(flat, key=lambda x: x["start"], reverse=True):
351
+ redacted = redacted[:e["start"]] + f'[{e["entity_group"]}]' + redacted[e["end"]:]
352
+
353
+ return {
354
+ "entities": entities,
355
+ "nested": nested,
356
+ "redacted_text": redacted,
357
+ "model": MODEL_REPO,
358
+ "processing_time_ms": int((time.time() - t0) * 1000),
359
+ }
360
+
361
+
362
+ # Mount the Gradio UI at "/" on the same FastAPI app, so one Space serves both
363
+ # the demo UI and the /detect + /health API.
364
+ app = gr.mount_gradio_app(api, demo, path="/")
365
+
366
+
367
+ if __name__ == "__main__":
368
+ import uvicorn
369
+ uvicorn.run(app, host="0.0.0.0", port=int(os.getenv("PORT", "7860")))