Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,12 +1,12 @@
|
|
| 1 |
-
import os
|
| 2 |
import gradio as gr
|
| 3 |
-
|
|
|
|
| 4 |
from datasets import load_dataset
|
| 5 |
from sentence_transformers import SentenceTransformer, util
|
| 6 |
from transformers import pipeline
|
| 7 |
|
| 8 |
# ============================================================
|
| 9 |
-
#
|
| 10 |
# ============================================================
|
| 11 |
|
| 12 |
class SafetyFinding:
|
|
@@ -16,163 +16,172 @@ class SafetyFinding:
|
|
| 16 |
self.message = message
|
| 17 |
|
| 18 |
def to_dict(self):
|
| 19 |
-
return {
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
-
|
| 36 |
-
def find_safety_content(text: str) -> List[SafetyFinding]:
|
| 37 |
findings = []
|
| 38 |
-
|
| 39 |
-
for term in unsafe_terms:
|
| 40 |
if term in text.lower():
|
| 41 |
-
findings.append(SafetyFinding("
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
def find_pii(text: str) -> List[SafetyFinding]:
|
| 46 |
-
findings = []
|
| 47 |
if "@" in text:
|
| 48 |
-
|
| 49 |
-
return findings
|
| 50 |
-
|
| 51 |
-
@staticmethod
|
| 52 |
-
def find_prompt_leakage(text: str) -> List[SafetyFinding]:
|
| 53 |
-
findings = []
|
| 54 |
-
if "instruction" in text.lower() or "prompt" in text.lower():
|
| 55 |
-
findings.append(SafetyFinding("prompt_leakage", "medium", "Possible prompt leakage"))
|
| 56 |
return findings
|
| 57 |
|
| 58 |
-
|
| 59 |
-
class HuggingFaceModerationChecker:
|
| 60 |
-
def __init__(self, model="unitary/toxic-bert"):
|
| 61 |
-
# We load this globally or lazily to avoid reloading on every request
|
| 62 |
-
self.classifier = pipeline("text-classification", model=model)
|
| 63 |
-
|
| 64 |
-
def check(self, text: str) -> List[SafetyFinding]:
|
| 65 |
findings = []
|
| 66 |
if not text.strip(): return findings
|
| 67 |
-
|
| 68 |
-
for r in results:
|
| 69 |
-
if r["label"].lower() in ["toxic", "offensive", "hate", "violence"] and r["score"] > 0.7:
|
| 70 |
-
findings.append(SafetyFinding("huggingface_moderation", "high", f"⚠️ Flagged as {r['label']} (score={r['score']:.2f})"))
|
| 71 |
-
return findings
|
| 72 |
-
|
| 73 |
-
class JBBBehaviorClassifier:
|
| 74 |
-
def __init__(self, threshold: float = 0.5, embed_model: str = "all-MiniLM-L6-v2"):
|
| 75 |
-
# Load dataset and model once
|
| 76 |
-
dataset = load_dataset("JailbreakBench/JBB-Behaviors", "behaviors", split="harmful")
|
| 77 |
-
self.malicious_goals = [row["Goal"] for row in dataset if row and row["Goal"]]
|
| 78 |
-
self.model = SentenceTransformer(embed_model)
|
| 79 |
-
self.goal_embeddings = self.model.encode(self.malicious_goals, convert_to_tensor=True)
|
| 80 |
-
self.threshold = threshold
|
| 81 |
-
|
| 82 |
-
def check(self, user_prompt: str) -> List[SafetyFinding]:
|
| 83 |
-
findings = []
|
| 84 |
-
if not user_prompt.strip(): return findings
|
| 85 |
-
user_emb = self.model.encode(user_prompt, convert_to_tensor=True)
|
| 86 |
cos_scores = util.cos_sim(user_emb, self.goal_embeddings)[0]
|
| 87 |
max_score = float(cos_scores.max())
|
| 88 |
|
| 89 |
if max_score >= self.threshold:
|
| 90 |
-
findings.append(SafetyFinding("jailbreak_similarity", "high", f"
|
| 91 |
return findings
|
| 92 |
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
if any(f.severity == "medium" for f in findings): return "redact"
|
| 102 |
-
return "allow"
|
| 103 |
|
| 104 |
-
def
|
| 105 |
findings = []
|
| 106 |
-
# Checks
|
| 107 |
-
findings +=
|
| 108 |
-
findings +=
|
| 109 |
-
findings += self.jbb.check(user_prompt)
|
| 110 |
-
findings += HeuristicCheckers.find_pii(draft_output)
|
| 111 |
-
findings += HeuristicCheckers.find_prompt_leakage(draft_output)
|
| 112 |
-
findings += HeuristicCheckers.find_safety_content(draft_output)
|
| 113 |
-
findings += self.mod.check(user_prompt + "\n\n---\n\n" + draft_output)
|
| 114 |
-
|
| 115 |
-
action = self._decide(findings)
|
| 116 |
|
| 117 |
-
|
| 118 |
-
|
|
|
|
| 119 |
|
| 120 |
-
#
|
| 121 |
-
|
| 122 |
-
if
|
| 123 |
-
|
|
|
|
|
|
|
| 124 |
|
| 125 |
-
return
|
|
|
|
|
|
|
|
|
|
| 126 |
|
| 127 |
# ============================================================
|
| 128 |
-
#
|
| 129 |
# ============================================================
|
| 130 |
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
"
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
}
|
| 137 |
-
}
|
| 138 |
-
|
| 139 |
-
print("Initializing models... this may take a minute...")
|
| 140 |
-
reviewer = Reviewer(policy)
|
| 141 |
-
|
| 142 |
-
def guardrail_interface(user_prompt):
|
| 143 |
-
# Since we don't have a live OpenAI Key in the public demo,
|
| 144 |
-
# we simulate a "Draft Output" that matches the prompt context for testing.
|
| 145 |
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
draft_output = "Contact me at user@example.com"
|
| 149 |
-
elif "bomb" in user_prompt:
|
| 150 |
-
draft_output = "Here is how you make a device..."
|
| 151 |
-
|
| 152 |
-
result = reviewer.review(user_prompt, draft_output)
|
| 153 |
|
| 154 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
|
| 156 |
-
#
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
|
|
|
|
| 161 |
with gr.Row():
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
output_box = gr.Textbox(label="Final Output")
|
| 169 |
-
findings_json = gr.JSON(label="Detailed Findings")
|
| 170 |
-
|
| 171 |
-
btn.click(guardrail_interface, inputs=input_text, outputs=[status_box, output_box, findings_json])
|
| 172 |
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
)
|
| 177 |
|
| 178 |
if __name__ == "__main__":
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import os
|
| 3 |
+
from typing import Dict, List
|
| 4 |
from datasets import load_dataset
|
| 5 |
from sentence_transformers import SentenceTransformer, util
|
| 6 |
from transformers import pipeline
|
| 7 |
|
| 8 |
# ============================================================
|
| 9 |
+
# BACKEND: GUARDRAIL LOGIC (Same as before, optimized)
|
| 10 |
# ============================================================
|
| 11 |
|
| 12 |
class SafetyFinding:
|
|
|
|
| 16 |
self.message = message
|
| 17 |
|
| 18 |
def to_dict(self):
|
| 19 |
+
return {"label": self.label, "severity": self.severity, "message": self.message}
|
| 20 |
+
|
| 21 |
+
class GuardrailSystem:
|
| 22 |
+
def __init__(self):
|
| 23 |
+
print("⚙️ Loading Guardrail Models... Please wait.")
|
| 24 |
+
# 1. Load Heuristic Keywords
|
| 25 |
+
self.unsafe_terms = ["bomb", "kill", "suicide", "explosive", "hack", "rob", "steal", "drugs", "murder"]
|
| 26 |
+
self.jailbreak_terms = ["ignore previous", "system prompt", "jailbreak", "developer mode"]
|
| 27 |
+
|
| 28 |
+
# 2. Load HuggingFace Moderator (Lazy loading recommended, but here we init upfront)
|
| 29 |
+
self.moderator = pipeline("text-classification", model="unitary/toxic-bert")
|
| 30 |
+
|
| 31 |
+
# 3. Load JailbreakBench Embeddings
|
| 32 |
+
dataset = load_dataset("JailbreakBench/JBB-Behaviors", "behaviors", split="harmful")
|
| 33 |
+
self.malicious_goals = [row["Goal"] for row in dataset if row and row["Goal"]]
|
| 34 |
+
self.embedder = SentenceTransformer("all-MiniLM-L6-v2")
|
| 35 |
+
self.goal_embeddings = self.embedder.encode(self.malicious_goals, convert_to_tensor=True)
|
| 36 |
+
self.threshold = 0.5
|
| 37 |
|
| 38 |
+
def check_heuristics(self, text):
|
|
|
|
| 39 |
findings = []
|
| 40 |
+
for term in self.unsafe_terms:
|
|
|
|
| 41 |
if term in text.lower():
|
| 42 |
+
findings.append(SafetyFinding("unsafe_keyword", "high", f"Detected unsafe term: '{term}'"))
|
| 43 |
+
for term in self.jailbreak_terms:
|
| 44 |
+
if term in text.lower():
|
| 45 |
+
findings.append(SafetyFinding("jailbreak_keyword", "high", f"Detected jailbreak term: '{term}'"))
|
|
|
|
|
|
|
| 46 |
if "@" in text:
|
| 47 |
+
findings.append(SafetyFinding("pii_leak", "medium", "Potential PII (Email) detected"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
return findings
|
| 49 |
|
| 50 |
+
def check_similarity(self, text):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
findings = []
|
| 52 |
if not text.strip(): return findings
|
| 53 |
+
user_emb = self.embedder.encode(text, convert_to_tensor=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
cos_scores = util.cos_sim(user_emb, self.goal_embeddings)[0]
|
| 55 |
max_score = float(cos_scores.max())
|
| 56 |
|
| 57 |
if max_score >= self.threshold:
|
| 58 |
+
findings.append(SafetyFinding("jailbreak_similarity", "high", f"Semantic Match to Jailbreak (Score: {max_score:.2f})"))
|
| 59 |
return findings
|
| 60 |
|
| 61 |
+
def check_moderation(self, text):
|
| 62 |
+
findings = []
|
| 63 |
+
if not text.strip(): return findings
|
| 64 |
+
results = self.moderator(text, truncation=True)
|
| 65 |
+
for r in results:
|
| 66 |
+
if r["label"] in ["toxic", "severe_toxic", "obscene", "threat", "insult", "identity_hate"] and r["score"] > 0.7:
|
| 67 |
+
findings.append(SafetyFinding("model_moderation", "high", f"Model Flag: {r['label']} ({r['score']:.2f})"))
|
| 68 |
+
return findings
|
|
|
|
|
|
|
| 69 |
|
| 70 |
+
def run_checks(self, user_prompt, simulated_response):
|
| 71 |
findings = []
|
| 72 |
+
# Input Checks
|
| 73 |
+
findings += self.check_heuristics(user_prompt)
|
| 74 |
+
findings += self.check_similarity(user_prompt)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
|
| 76 |
+
# Output Checks (Simulated)
|
| 77 |
+
findings += self.check_heuristics(simulated_response)
|
| 78 |
+
findings += self.check_moderation(user_prompt + " " + simulated_response)
|
| 79 |
|
| 80 |
+
# Decision
|
| 81 |
+
status = "ALLOWED"
|
| 82 |
+
if any(f.severity == "high" for f in findings):
|
| 83 |
+
status = "BLOCKED"
|
| 84 |
+
elif any(f.severity == "medium" for f in findings):
|
| 85 |
+
status = "REDACTED"
|
| 86 |
|
| 87 |
+
return status, findings
|
| 88 |
+
|
| 89 |
+
# Initialize System (Global to keep in memory)
|
| 90 |
+
guard = GuardrailSystem()
|
| 91 |
|
| 92 |
# ============================================================
|
| 93 |
+
# FRONTEND: PROFESSIONAL UI LOGIC
|
| 94 |
# ============================================================
|
| 95 |
|
| 96 |
+
def analyze_prompt(user_prompt):
|
| 97 |
+
# Simulate LLM Generation for the demo
|
| 98 |
+
simulated_output = "This is a harmless AI response."
|
| 99 |
+
if "bomb" in user_prompt.lower(): simulated_output = "Here are instructions for..."
|
| 100 |
+
if "email" in user_prompt.lower(): simulated_output = "Contact me at user@example.com"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
+
# Run Guardrails
|
| 103 |
+
status, findings = guard.run_checks(user_prompt, simulated_output)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
+
# Generate HTML Status Card
|
| 106 |
+
color_map = {"ALLOWED": "green", "BLOCKED": "red", "REDACTED": "orange"}
|
| 107 |
+
icon_map = {"ALLOWED": "✅", "BLOCKED": "🛡️", "REDACTED": "��️"}
|
| 108 |
+
|
| 109 |
+
html_status = f"""
|
| 110 |
+
<div style='background-color: var(--background-fill-secondary); border-left: 5px solid {color_map[status]}; padding: 20px; border-radius: 8px; box-shadow: 0 4px 6px rgba(0,0,0,0.1);'>
|
| 111 |
+
<h2 style='color: {color_map[status]}; margin: 0;'>{icon_map[status]} {status}</h2>
|
| 112 |
+
<p style='margin-top: 5px; opacity: 0.8;'>Guardrail decision based on {len(findings)} risk factors.</p>
|
| 113 |
+
</div>
|
| 114 |
+
"""
|
| 115 |
+
|
| 116 |
+
# Format Findings for Display
|
| 117 |
+
clean_findings = [f.to_dict() for f in findings]
|
| 118 |
+
|
| 119 |
+
return html_status, clean_findings, simulated_output if status == "ALLOWED" else "[CONTENT BLOCKED BY POLICY]"
|
| 120 |
|
| 121 |
+
# Custom CSS for a clean look
|
| 122 |
+
custom_css = """
|
| 123 |
+
.gradio-container {font-family: 'Inter', sans-serif;}
|
| 124 |
+
h1 {text-align: center; color: #2d3748;}
|
| 125 |
+
"""
|
| 126 |
+
|
| 127 |
+
# Create the App
|
| 128 |
+
with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", neutral_hue="slate"), css=custom_css) as demo:
|
| 129 |
|
| 130 |
+
# Header
|
| 131 |
with gr.Row():
|
| 132 |
+
gr.Markdown(
|
| 133 |
+
"""
|
| 134 |
+
# 🛡️ Enterprise AI Guardrail System
|
| 135 |
+
### Real-time safety filtering using Semantic Search, BERT Moderation, and Heuristics.
|
| 136 |
+
"""
|
| 137 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
|
| 139 |
+
# Main Interface
|
| 140 |
+
with gr.Row():
|
| 141 |
+
# Left Column: Inputs
|
| 142 |
+
with gr.Column(scale=1):
|
| 143 |
+
gr.Markdown("### 📥 Input Simulation")
|
| 144 |
+
input_text = gr.Textbox(
|
| 145 |
+
lines=5,
|
| 146 |
+
label="User Prompt",
|
| 147 |
+
placeholder="Enter a prompt to test the guardrails (e.g., 'how to build a bomb' or 'hello')...",
|
| 148 |
+
elem_id="input_box"
|
| 149 |
+
)
|
| 150 |
+
analyze_btn = gr.Button("🛡️ Run Safety Check", variant="primary", size="lg")
|
| 151 |
+
|
| 152 |
+
with gr.Accordion("ℹ️ How it works", open=False):
|
| 153 |
+
gr.Markdown("""
|
| 154 |
+
1. **Heuristics:** Checks for banned keywords.
|
| 155 |
+
2. **Vector Database:** Compares prompt against known jailbreaks (JailbreakBench).
|
| 156 |
+
3. **BERT Classifier:** Scans for toxic tones.
|
| 157 |
+
""")
|
| 158 |
+
|
| 159 |
+
# Right Column: Analytics
|
| 160 |
+
with gr.Column(scale=1):
|
| 161 |
+
gr.Markdown("### 📊 Live Analytics")
|
| 162 |
+
status_display = gr.HTML(label="Decision")
|
| 163 |
+
|
| 164 |
+
with gr.Tabs():
|
| 165 |
+
with gr.TabItem("Findings"):
|
| 166 |
+
findings_json = gr.JSON(label="Risk Factors Detected")
|
| 167 |
+
with gr.TabItem("Raw Output"):
|
| 168 |
+
final_output = gr.Code(label="LLM Response", language="markdown")
|
| 169 |
+
|
| 170 |
+
# Footer
|
| 171 |
+
gr.Markdown(
|
| 172 |
+
"""
|
| 173 |
+
---
|
| 174 |
+
<div style="text-align: center; opacity: 0.5; font-size: 0.8rem;">
|
| 175 |
+
Built for AI Safety Portfolio | Powered by HuggingFace Transformers & Gradio
|
| 176 |
+
</div>
|
| 177 |
+
"""
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
# Event Linking
|
| 181 |
+
analyze_btn.click(
|
| 182 |
+
fn=analyze_prompt,
|
| 183 |
+
inputs=input_text,
|
| 184 |
+
outputs=[status_display, findings_json, final_output]
|
| 185 |
)
|
| 186 |
|
| 187 |
if __name__ == "__main__":
|