Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
from datasets import load_dataset
|
| 4 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
| 5 |
+
from sklearn.metrics import accuracy_score, f1_score
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
# --- CONFIGURATION ---
|
| 9 |
+
# REPLACE THIS WITH YOUR UPLOADED MODEL NAME!
|
| 10 |
+
MODEL_REPO = "angelperedo01/proj2"
|
| 11 |
+
DATASET_NAME = "nvidia/Aegis-AI-Content-Safety-Dataset-2.0"
|
| 12 |
+
MAX_SAMPLES = 200 # Limit samples for the demo so it doesn't take hours
|
| 13 |
+
|
| 14 |
+
def get_text_and_label(example):
|
| 15 |
+
"""
|
| 16 |
+
Your custom logic to parse the NVIDIA dataset labels.
|
| 17 |
+
"""
|
| 18 |
+
text = example.get('prompt', '')
|
| 19 |
+
label = None
|
| 20 |
+
|
| 21 |
+
# Try 'prompt_label' first
|
| 22 |
+
if 'prompt_label' in example:
|
| 23 |
+
raw_label = example['prompt_label']
|
| 24 |
+
if isinstance(raw_label, str):
|
| 25 |
+
raw_lower = raw_label.lower()
|
| 26 |
+
if any(x in raw_lower for x in ['unsafe', 'harmful', 'toxic', 'attack']):
|
| 27 |
+
label = 1
|
| 28 |
+
elif any(x in raw_lower for x in ['safe', 'benign']):
|
| 29 |
+
label = 0
|
| 30 |
+
else:
|
| 31 |
+
try: label = int(raw_label)
|
| 32 |
+
except: label = 1 if 'unsafe' in raw_lower else 0
|
| 33 |
+
else:
|
| 34 |
+
label = int(raw_label)
|
| 35 |
+
|
| 36 |
+
# Default to Safe (0) if we really can't find it
|
| 37 |
+
if label is None: label = 0
|
| 38 |
+
return text, label
|
| 39 |
+
|
| 40 |
+
def run_live_evaluation(progress=gr.Progress()):
|
| 41 |
+
# 1. Load Model & Data
|
| 42 |
+
yield "Loading Model from Hub...", "-", "-", []
|
| 43 |
+
|
| 44 |
+
try:
|
| 45 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_REPO)
|
| 46 |
+
model = AutoModelForSequenceClassification.from_pretrained(MODEL_REPO)
|
| 47 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 48 |
+
model.to(device)
|
| 49 |
+
model.eval()
|
| 50 |
+
except Exception as e:
|
| 51 |
+
yield f"Error loading model: {str(e)}", "Error", "Error", []
|
| 52 |
+
return
|
| 53 |
+
|
| 54 |
+
# Load Dataset (Streaming or small slice for speed)
|
| 55 |
+
yield "Loading NVIDIA Dataset...", "-", "-", []
|
| 56 |
+
try:
|
| 57 |
+
# Try test split, fallback to train
|
| 58 |
+
ds = load_dataset(DATASET_NAME, split="test")
|
| 59 |
+
except:
|
| 60 |
+
ds = load_dataset(DATASET_NAME, split="train")
|
| 61 |
+
|
| 62 |
+
# Shuffle and select subset for the demo
|
| 63 |
+
ds = ds.shuffle(seed=42).select(range(MAX_SAMPLES))
|
| 64 |
+
|
| 65 |
+
true_labels = []
|
| 66 |
+
predictions = []
|
| 67 |
+
logs = [] # To store misclassifications
|
| 68 |
+
|
| 69 |
+
# 2. The Evaluation Loop
|
| 70 |
+
for i, item in enumerate(progress.tqdm(ds, desc="Evaluating...")):
|
| 71 |
+
text, true_label = get_text_and_label(item)
|
| 72 |
+
true_labels.append(true_label)
|
| 73 |
+
|
| 74 |
+
# Tokenize
|
| 75 |
+
inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=256).to(device)
|
| 76 |
+
|
| 77 |
+
# Predict
|
| 78 |
+
with torch.no_grad():
|
| 79 |
+
logits = model(**inputs).logits
|
| 80 |
+
pred = torch.argmax(logits, dim=-1).item()
|
| 81 |
+
predictions.append(pred)
|
| 82 |
+
|
| 83 |
+
# Log Errors (If prediction is wrong)
|
| 84 |
+
if pred != true_label:
|
| 85 |
+
status = "🔴 MISS"
|
| 86 |
+
logs.insert(0, [status, text[:80] + "...", "Safe" if true_label==0 else "Unsafe", "Safe" if pred==0 else "Unsafe"])
|
| 87 |
+
else:
|
| 88 |
+
# Optional: Log successes too if you want, but it clutters the view
|
| 89 |
+
pass
|
| 90 |
+
|
| 91 |
+
# Update UI every 5 steps
|
| 92 |
+
if i % 5 == 0 or i == len(ds)-1:
|
| 93 |
+
acc = accuracy_score(true_labels, predictions)
|
| 94 |
+
f1 = f1_score(true_labels, predictions, zero_division=0)
|
| 95 |
+
|
| 96 |
+
status_msg = f"Processed {i+1}/{MAX_SAMPLES}"
|
| 97 |
+
yield status_msg, f"{acc:.2%}", f"{f1:.2f}", logs[:10] # Show last 10 errors
|
| 98 |
+
|
| 99 |
+
# --- UI LAYOUT ---
|
| 100 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 101 |
+
gr.Markdown(f"## 🛡️ Live Safety Model Evaluation")
|
| 102 |
+
gr.Markdown(f"Running `{MODEL_REPO}` on `{DATASET_NAME}` (Live Inference)")
|
| 103 |
+
|
| 104 |
+
with gr.Row():
|
| 105 |
+
start_btn = gr.Button("▶️ Start Live Test", variant="primary")
|
| 106 |
+
|
| 107 |
+
with gr.Row():
|
| 108 |
+
with gr.Column():
|
| 109 |
+
status_box = gr.Label(value="Ready", label="Status")
|
| 110 |
+
with gr.Column():
|
| 111 |
+
acc_box = gr.Label(value="-", label="Current Accuracy")
|
| 112 |
+
with gr.Column():
|
| 113 |
+
f1_box = gr.Label(value="-", label="Current F1 Score")
|
| 114 |
+
|
| 115 |
+
gr.Markdown("### 🚨 Recent Misclassifications (Live Feed)")
|
| 116 |
+
log_table = gr.Dataframe(
|
| 117 |
+
headers=["Status", "Text Snippet", "True Label", "Predicted"],
|
| 118 |
+
datatype=["str", "str", "str", "str"],
|
| 119 |
+
row_count=10
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
start_btn.click(
|
| 123 |
+
fn=run_live_evaluation,
|
| 124 |
+
inputs=None,
|
| 125 |
+
outputs=[status_box, acc_box, f1_box, log_table]
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
demo.queue().launch()
|