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|
|
|
|
|
| 40 |
return {
|
| 41 |
-
"
|
| 42 |
-
"
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 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
|
| 62 |
-
|
| 63 |
-
if not
|
| 64 |
-
|
| 65 |
-
|
|
|
|
|
|
|
| 66 |
|
| 67 |
-
def do_revoke(full_key):
|
| 68 |
-
revoke_key(full_key.strip())
|
| 69 |
-
return "Key revoked.", get_key_table()
|
| 70 |
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
return "
|
|
|
|
| 74 |
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
)
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 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")))
|
|
|
|
|
|