chiruu12 commited on
Commit
f6f790c
·
verified ·
1 Parent(s): 303349a

add demo logic

Browse files
Files changed (1) hide show
  1. unplug_tiny_demo.py +209 -0
unplug_tiny_demo.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Gradio demo for unplug-tiny span detection and redaction."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import html
6
+ import json
7
+ import threading
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ import gradio as gr
12
+
13
+ from unplug import Guard
14
+ from unplug.api.types import Finding, ScanResult
15
+ from unplug.config.guard import GuardConfig
16
+
17
+ DEMO_DIR = Path(__file__).resolve().parent
18
+ EXAMPLES_PATH = DEMO_DIR / "examples.json"
19
+ DISCLAIMER = (
20
+ "**Preview OSS detector — not a production WAF.** "
21
+ "Known gaps: Deepset OOD recall, harmful-non-injection contrast FPR, WildGuard benign FPR."
22
+ )
23
+
24
+ _guard_ml: Guard | None = None
25
+ _guard_regex: Guard | None = None
26
+ _guard_lock = threading.Lock()
27
+
28
+
29
+ def load_examples() -> dict[str, dict[str, str]]:
30
+ with EXAMPLES_PATH.open(encoding="utf-8") as handle:
31
+ return json.load(handle)
32
+
33
+
34
+ def _get_guard(*, use_ml: bool) -> Guard:
35
+ global _guard_ml, _guard_regex
36
+ with _guard_lock:
37
+ if use_ml:
38
+ if _guard_ml is None:
39
+ _guard_ml = Guard.with_tiny(auto_download=True, require_ml=True)
40
+ return _guard_ml
41
+ if _guard_regex is None:
42
+ _guard_regex = Guard(
43
+ scanners=["injection"],
44
+ config=GuardConfig(active_model=None, auto_download_model=False),
45
+ )
46
+ return _guard_regex
47
+
48
+
49
+ def highlight_spans(text: str, findings: list[Finding]) -> str:
50
+ if not text:
51
+ return "<p><em>(empty)</em></p>"
52
+ if not findings:
53
+ return f'<pre style="white-space:pre-wrap">{html.escape(text)}</pre>'
54
+
55
+ spans = sorted(findings, key=lambda f: (f.span_start, f.span_end))
56
+ parts: list[str] = []
57
+ pos = 0
58
+ for finding in spans:
59
+ if finding.span_end <= pos:
60
+ continue
61
+ start = max(finding.span_start, pos)
62
+ if start > pos:
63
+ parts.append(html.escape(text[pos:start]))
64
+ end = min(finding.span_end, len(text))
65
+ snippet = html.escape(text[start:end])
66
+ bg = "#f8d7da" if finding.subcategory == "doc_head" else "#fff3cd"
67
+ title = html.escape(f"{finding.category}/{finding.subcategory} ({finding.score:.2f})")
68
+ parts.append(f'<mark style="background:{bg}" title="{title}">{snippet}</mark>')
69
+ pos = end
70
+ if pos < len(text):
71
+ parts.append(html.escape(text[pos:]))
72
+ return f'<pre style="white-space:pre-wrap">{"".join(parts)}</pre>'
73
+
74
+
75
+ def findings_rows(result: ScanResult) -> list[list[Any]]:
76
+ rows: list[list[Any]] = []
77
+ for finding in result.findings:
78
+ rows.append(
79
+ [
80
+ finding.category,
81
+ finding.subcategory,
82
+ finding.span_start,
83
+ finding.span_end,
84
+ round(finding.score, 3),
85
+ finding.evidence[:120],
86
+ ]
87
+ )
88
+ return rows
89
+
90
+
91
+ def verdict_markdown(result: ScanResult, expected: str | None) -> str:
92
+ lines = [
93
+ f"- **safe:** `{result.safe}`",
94
+ f"- **action:** `{result.action.value}`",
95
+ f"- **risk_score:** `{result.risk_score:.3f}`",
96
+ f"- **latency_ms:** `{result.latency_ms:.1f}`",
97
+ f"- **findings:** `{len(result.findings)}`",
98
+ ]
99
+ if expected:
100
+ actual = "safe" if result.safe else "block"
101
+ match = actual == expected
102
+ status = "match" if match else "mismatch"
103
+ lines.append(f"- **expected:** `{expected}` → **actual:** `{actual}` ({status})")
104
+ return "\n".join(lines)
105
+
106
+
107
+ def scan_text(
108
+ text: str,
109
+ use_ml: bool,
110
+ example_key: str | None,
111
+ ) -> tuple[str, str, str, list[list[Any]], str]:
112
+ if not text.strip():
113
+ return DISCLAIMER, "", "<p><em>Enter text to scan.</em></p>", [], ""
114
+
115
+ examples = load_examples()
116
+ expected = None
117
+ note = ""
118
+ if example_key and example_key in examples:
119
+ expected = examples[example_key]["expected"]
120
+ note = examples[example_key]["note"]
121
+
122
+ guard = _get_guard(use_ml=use_ml)
123
+ result = guard.scan(text, source="user")
124
+
125
+ highlighted = highlight_spans(text, result.findings)
126
+ redacted = result.redacted_text if result.redacted_text is not None else text
127
+ verdict = verdict_markdown(result, expected)
128
+ if note:
129
+ verdict = f"{verdict}\n\n**Example note:** {note}"
130
+
131
+ mode_label = "ML (unplug-tiny)" if use_ml else "regex only"
132
+ header = f"{DISCLAIMER}\n\n**Mode:** {mode_label}"
133
+
134
+ return header, verdict, highlighted, findings_rows(result), redacted
135
+
136
+
137
+ def build_demo() -> gr.Blocks:
138
+ examples = load_examples()
139
+ choices = [(meta["label"], key) for key, meta in examples.items()]
140
+
141
+ with gr.Blocks(title="Unplug Tiny Demo") as demo:
142
+ gr.Markdown(
143
+ "# Unplug Tiny — span injection demo\n\n"
144
+ "Scan text with the dual-head **unplug-tiny-v1** model (`Unplug-AI/unplug-tiny-v1`). "
145
+ "Spans are highlighted; risky regions are redacted in the output panel.\n\n"
146
+ f"{DISCLAIMER}"
147
+ )
148
+
149
+ with gr.Row():
150
+ example_dd = gr.Dropdown(
151
+ choices=choices,
152
+ label="Curated examples",
153
+ value=None,
154
+ )
155
+ use_ml = gr.Checkbox(value=True, label="Use ML model (uncheck for regex only)")
156
+
157
+ text_in = gr.Textbox(
158
+ label="Input text",
159
+ lines=10,
160
+ placeholder="Paste user message, RAG chunk, or tool output…",
161
+ )
162
+
163
+ with gr.Row():
164
+ gr.ClearButton([text_in], value="Clear")
165
+ scan_btn = gr.Button("Scan", variant="primary")
166
+
167
+ gr.Markdown("### Results")
168
+ disclaimer_out = gr.Markdown()
169
+ verdict_out = gr.Markdown(label="Verdict")
170
+ with gr.Row():
171
+ highlight_out = gr.HTML(label="Span highlights")
172
+ redacted_out = gr.Textbox(label="Redacted text", lines=10)
173
+ findings_out = gr.Dataframe(
174
+ headers=["category", "subcategory", "start", "end", "score", "evidence"],
175
+ label="Findings",
176
+ interactive=False,
177
+ )
178
+
179
+ exfil_url = (
180
+ "https://github.com/UnplugAI/Unplug/blob/main/sdk/examples/agent_exfil_demo.py"
181
+ )
182
+ gr.Markdown(
183
+ "### Agent integration\n\n"
184
+ "For hidden webpage injection → tainted session → blocked exfil, "
185
+ f"see [`agent_exfil_demo.py`]({exfil_url})."
186
+ )
187
+
188
+ def load_example(key: str | None) -> str:
189
+ if not key:
190
+ return ""
191
+ return examples[key]["text"]
192
+
193
+ example_dd.change(load_example, inputs=example_dd, outputs=text_in)
194
+
195
+ scan_btn.click(
196
+ scan_text,
197
+ inputs=[text_in, use_ml, example_dd],
198
+ outputs=[disclaimer_out, verdict_out, highlight_out, findings_out, redacted_out],
199
+ )
200
+
201
+ return demo
202
+
203
+
204
+ def main() -> None:
205
+ build_demo().launch()
206
+
207
+
208
+ if __name__ == "__main__":
209
+ main()