Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
"""
|
| 2 |
SEB AI Monitoring System - Hugging Face Space Implementation
|
| 3 |
-
Optimized for Hugging Face Free Tier
|
| 4 |
|
| 5 |
Business Value: Demonstrates real-time detection of unauthorized AI access during exams
|
| 6 |
with minimal resource usage, perfect for the free tier constraints.
|
|
@@ -18,166 +18,162 @@ from sklearn.neighbors import LocalOutlierFactor
|
|
| 18 |
from xgboost import XGBClassifier
|
| 19 |
import time
|
| 20 |
import traceback
|
|
|
|
|
|
|
| 21 |
|
| 22 |
# ===========================
|
| 23 |
# MODEL HANDLING
|
| 24 |
# ===========================
|
| 25 |
-
|
| 26 |
-
"""
|
| 27 |
-
model_path = "seb_ai_monitor_model_demo.pkl"
|
| 28 |
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
"""Creates a lightweight model specifically optimized for Hugging Face free tier"""
|
| 38 |
-
# Generate minimal synthetic data for demonstration
|
| 39 |
-
np.random.seed(42)
|
| 40 |
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
])
|
| 52 |
-
|
| 53 |
-
# Anomalous behavior patterns
|
| 54 |
-
for _ in range(7): # Reduced dataset size
|
| 55 |
-
anomaly_start = np.random.randint(5, 35)
|
| 56 |
-
anomaly_duration = np.random.randint(3, 7)
|
| 57 |
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 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 |
-
lof.fit(X_train_scaled)
|
| 106 |
-
|
| 107 |
-
# Train XGBoost verifier with reduced complexity
|
| 108 |
-
xgb_verifier = XGBClassifier(
|
| 109 |
-
n_estimators=30, # Reduced from 100
|
| 110 |
-
max_depth=3, # Reduced from 5
|
| 111 |
-
learning_rate=0.1,
|
| 112 |
-
random_state=42
|
| 113 |
-
)
|
| 114 |
-
xgb_verifier.fit(
|
| 115 |
-
scaler.transform(df[feature_columns]),
|
| 116 |
-
df['is_anomaly']
|
| 117 |
-
)
|
| 118 |
|
| 119 |
-
|
| 120 |
-
|
| 121 |
network_suspicious = sample[1] > 3
|
| 122 |
app_switch_pattern = (sample[0] > 5) and (sample[4] < 30)
|
| 123 |
keystroke_burst = (sample[2] > 5) and (sample[2] < 8)
|
| 124 |
verification_score = sum([network_suspicious, app_switch_pattern, keystroke_burst])
|
| 125 |
return (verification_score >= 2) and (confidence >= 0.6)
|
| 126 |
|
| 127 |
-
|
| 128 |
-
def ensemble_predict(sample):
|
| 129 |
"""Makes prediction using the ensemble with verification."""
|
| 130 |
try:
|
| 131 |
# Ensure sample is a numpy array with correct shape (1, 5)
|
| 132 |
-
sample_array = np.array(sample).reshape(1, -1)
|
| 133 |
|
| 134 |
-
# Scale the sample
|
| 135 |
-
sample_scaled = scaler.transform(sample_array)
|
| 136 |
|
| 137 |
# Get predictions from each model
|
| 138 |
predictions = []
|
| 139 |
|
| 140 |
# Isolation Forest
|
| 141 |
-
if_pred = isolation_forest.predict(sample_scaled)[0]
|
| 142 |
predictions.append(1 if if_pred == -1 else 0)
|
| 143 |
|
| 144 |
# One-Class SVM
|
| 145 |
-
svm_pred = oc_svm.predict(sample_scaled)[0]
|
| 146 |
predictions.append(1 if svm_pred == -1 else 0)
|
| 147 |
|
| 148 |
# Local Outlier Factor
|
| 149 |
-
lof_pred = lof.predict(sample_scaled)[0]
|
| 150 |
predictions.append(1 if lof_pred == -1 else 0)
|
| 151 |
|
| 152 |
# Calculate confidence (fraction of models detecting anomaly)
|
| 153 |
confidence = np.mean(predictions)
|
| 154 |
|
| 155 |
# Apply verification
|
| 156 |
-
is_verified = verify_anomaly(sample, predictions, confidence)
|
| 157 |
|
| 158 |
return int(is_verified), confidence, predictions
|
| 159 |
except Exception as e:
|
| 160 |
-
print(f"Error in
|
| 161 |
traceback.print_exc()
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
return {
|
| 165 |
-
'scaler': scaler,
|
| 166 |
-
'isolation_forest': isolation_forest,
|
| 167 |
-
'oc_svm': oc_svm,
|
| 168 |
-
'lof': lof,
|
| 169 |
-
'xgb_verifier': xgb_verifier,
|
| 170 |
-
'verify_anomaly': verify_anomaly,
|
| 171 |
-
'ensemble_predict': ensemble_predict,
|
| 172 |
-
'feature_columns': feature_columns
|
| 173 |
-
}
|
| 174 |
|
| 175 |
-
#
|
| 176 |
-
|
| 177 |
-
|
| 178 |
|
| 179 |
# ===========================
|
| 180 |
-
# PREDICTION FUNCTION
|
| 181 |
# ===========================
|
| 182 |
def analyze_behavior(app_switches, network_requests, keystrokes, mouse_movements, time_on_exam):
|
| 183 |
"""Analyzes student behavior for potential AI cheating patterns"""
|
|
@@ -194,10 +190,12 @@ def analyze_behavior(app_switches, network_requests, keystrokes, mouse_movements
|
|
| 194 |
]
|
| 195 |
|
| 196 |
# DEBUG: Print input data to verify
|
| 197 |
-
print(f"
|
| 198 |
|
| 199 |
# Get prediction
|
| 200 |
-
is_anomaly, confidence,
|
|
|
|
|
|
|
| 201 |
|
| 202 |
# Prepare result
|
| 203 |
if is_anomaly:
|
|
@@ -232,21 +230,22 @@ def analyze_behavior(app_switches, network_requests, keystrokes, mouse_movements
|
|
| 232 |
"processing_time": f"{processing_time:.1f} ms"
|
| 233 |
}
|
| 234 |
except Exception as e:
|
| 235 |
-
|
|
|
|
| 236 |
traceback.print_exc()
|
| 237 |
return {
|
| 238 |
-
"result": "Error",
|
| 239 |
-
"confidence_level": "
|
| 240 |
-
"confidence_score": "
|
| 241 |
-
"explanation": f"An error occurred: {str(e)}",
|
| 242 |
-
"processing_time": "
|
| 243 |
}
|
| 244 |
|
| 245 |
# ===========================
|
| 246 |
# EXAMPLES
|
| 247 |
# ===========================
|
| 248 |
examples = [
|
| 249 |
-
[2, 0, 2.5, 3, 55],
|
| 250 |
[10, 6, 3.0, 3, 20], # High-risk pattern (AI cheating)
|
| 251 |
[5, 1, 1.5, 4, 45], # Borderline case
|
| 252 |
[1, 0, 2.0, 2, 58], # Very normal behavior
|
|
@@ -258,7 +257,7 @@ examples = [
|
|
| 258 |
# ===========================
|
| 259 |
def create_interface():
|
| 260 |
"""Creates the Gradio interface optimized for Hugging Face free tier"""
|
| 261 |
-
with gr.Blocks(title="SEB AI Monitoring System") as demo:
|
| 262 |
gr.Markdown("""
|
| 263 |
# SEB AI Monitoring System
|
| 264 |
|
|
@@ -273,28 +272,64 @@ def create_interface():
|
|
| 273 |
with gr.Row():
|
| 274 |
with gr.Column():
|
| 275 |
gr.Markdown("### Enter Behavioral Metrics")
|
| 276 |
-
app_switches = gr.Slider(
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 281 |
|
| 282 |
-
analyze_btn = gr.Button("Analyze Behavior", variant="primary")
|
| 283 |
|
| 284 |
gr.Examples(
|
| 285 |
examples=examples,
|
| 286 |
inputs=[app_switches, network_requests, keystrokes, mouse_movements, time_on_exam],
|
| 287 |
outputs=None,
|
| 288 |
-
examples_per_page=5
|
|
|
|
| 289 |
)
|
| 290 |
|
| 291 |
with gr.Column():
|
| 292 |
gr.Markdown("### Analysis Results")
|
| 293 |
-
result = gr.Textbox(label="Result", interactive=False)
|
| 294 |
-
confidence_level = gr.Textbox(label="Confidence Level", interactive=False)
|
| 295 |
-
confidence_score = gr.Textbox(label="Confidence Score", interactive=False)
|
| 296 |
explanation = gr.Textbox(label="Explanation", interactive=False, lines=8)
|
| 297 |
-
processing_time = gr.Textbox(label="Processing Time", interactive=False)
|
| 298 |
|
| 299 |
with gr.Tab("How It Works"):
|
| 300 |
gr.Markdown("""
|
|
@@ -314,6 +349,14 @@ def create_interface():
|
|
| 314 |
- Bursts of text after pauses (indicating copying from AI)
|
| 315 |
- Inconsistent typing rhythm
|
| 316 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 317 |
### Business Value
|
| 318 |
|
| 319 |
- **92.3% detection rate** for unauthorized AI access
|
|
@@ -331,9 +374,9 @@ def create_interface():
|
|
| 331 |
- **XGBoost Verification**: Provides explainable verification of anomalies
|
| 332 |
|
| 333 |
The system is optimized for the Hugging Face free tier with:
|
| 334 |
-
- Reduced model complexity
|
| 335 |
-
-
|
| 336 |
-
-
|
| 337 |
""")
|
| 338 |
|
| 339 |
with gr.Tab("About"):
|
|
@@ -358,6 +401,13 @@ def create_interface():
|
|
| 358 |
- **Lightweight implementation** optimized for free tier constraints
|
| 359 |
- **Explainable results** for academic integrity review
|
| 360 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 361 |
## Next Steps
|
| 362 |
|
| 363 |
1. **Pilot deployment** to academic institutions
|
|
@@ -367,6 +417,7 @@ def create_interface():
|
|
| 367 |
*Confidential - For Demonstration Purposes Only*
|
| 368 |
""")
|
| 369 |
|
|
|
|
| 370 |
analyze_btn.click(
|
| 371 |
fn=analyze_behavior,
|
| 372 |
inputs=[app_switches, network_requests, keystrokes, mouse_movements, time_on_exam],
|
|
@@ -385,5 +436,9 @@ def create_interface():
|
|
| 385 |
|
| 386 |
# Launch the interface
|
| 387 |
if __name__ == "__main__":
|
| 388 |
-
|
| 389 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
"""
|
| 2 |
SEB AI Monitoring System - Hugging Face Space Implementation
|
| 3 |
+
Optimized for Hugging Face Free Tier - FIXED VERSION
|
| 4 |
|
| 5 |
Business Value: Demonstrates real-time detection of unauthorized AI access during exams
|
| 6 |
with minimal resource usage, perfect for the free tier constraints.
|
|
|
|
| 18 |
from xgboost import XGBClassifier
|
| 19 |
import time
|
| 20 |
import traceback
|
| 21 |
+
import warnings
|
| 22 |
+
warnings.filterwarnings('ignore')
|
| 23 |
|
| 24 |
# ===========================
|
| 25 |
# MODEL HANDLING
|
| 26 |
# ===========================
|
| 27 |
+
class SEBMonitorModel:
|
| 28 |
+
"""Encapsulates the model and prediction logic"""
|
|
|
|
| 29 |
|
| 30 |
+
def __init__(self):
|
| 31 |
+
self.scaler = None
|
| 32 |
+
self.isolation_forest = None
|
| 33 |
+
self.oc_svm = None
|
| 34 |
+
self.lof = None
|
| 35 |
+
self.xgb_verifier = None
|
| 36 |
+
self.feature_columns = None
|
| 37 |
+
self._initialize_model()
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
+
def _initialize_model(self):
|
| 40 |
+
"""Initialize the lightweight demo model"""
|
| 41 |
+
print("Creating lightweight demo model for free tier...")
|
| 42 |
+
|
| 43 |
+
# Generate minimal synthetic data for demonstration
|
| 44 |
+
np.random.seed(42)
|
| 45 |
+
|
| 46 |
+
# Normal behavior patterns
|
| 47 |
+
normal_data = []
|
| 48 |
+
for _ in range(50): # Reduced dataset size for free tier
|
| 49 |
+
normal_data.append([
|
| 50 |
+
np.random.poisson(lam=2),
|
| 51 |
+
np.random.poisson(lam=0.5),
|
| 52 |
+
np.random.normal(2.5, 0.5),
|
| 53 |
+
np.random.poisson(lam=3),
|
| 54 |
+
np.random.normal(55, 3),
|
| 55 |
+
0 # Normal behavior
|
| 56 |
+
])
|
| 57 |
+
|
| 58 |
+
# Anomalous behavior patterns
|
| 59 |
+
for _ in range(7): # Reduced dataset size
|
| 60 |
+
anomaly_start = np.random.randint(5, 35)
|
| 61 |
+
anomaly_duration = np.random.randint(3, 7)
|
| 62 |
+
|
| 63 |
+
for minute in range(45):
|
| 64 |
+
if anomaly_start <= minute < anomaly_start + anomaly_duration:
|
| 65 |
+
normal_data.append([
|
| 66 |
+
np.random.poisson(lam=8),
|
| 67 |
+
np.random.poisson(lam=5),
|
| 68 |
+
np.random.normal(3.5, 1.5) if minute % 2 == 0 else 0.1,
|
| 69 |
+
np.random.poisson(lam=3),
|
| 70 |
+
np.random.normal(20, 5),
|
| 71 |
+
1 # Anomaly
|
| 72 |
+
])
|
| 73 |
+
|
| 74 |
+
df = pd.DataFrame(normal_data, columns=[
|
| 75 |
+
'app_switches', 'network_requests', 'keystrokes',
|
| 76 |
+
'mouse_movements', 'time_on_exam', 'is_anomaly'
|
| 77 |
])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
+
# Prepare training data
|
| 80 |
+
X_train = df[df['is_anomaly'] == 0][[
|
| 81 |
+
'app_switches', 'network_requests', 'keystrokes',
|
| 82 |
+
'mouse_movements', 'time_on_exam'
|
| 83 |
+
]]
|
| 84 |
+
self.feature_columns = X_train.columns.tolist()
|
| 85 |
+
|
| 86 |
+
# Scale the features
|
| 87 |
+
self.scaler = StandardScaler()
|
| 88 |
+
X_train_scaled = self.scaler.fit_transform(X_train)
|
| 89 |
+
|
| 90 |
+
# Train lightweight models (reduced complexity for free tier)
|
| 91 |
+
self.isolation_forest = IsolationForest(
|
| 92 |
+
n_estimators=50, # Reduced from 150
|
| 93 |
+
contamination=0.05,
|
| 94 |
+
random_state=42
|
| 95 |
+
)
|
| 96 |
+
self.isolation_forest.fit(X_train_scaled)
|
| 97 |
+
|
| 98 |
+
self.oc_svm = OneClassSVM(
|
| 99 |
+
nu=0.05,
|
| 100 |
+
kernel='linear', # Using linear kernel for faster inference
|
| 101 |
+
gamma='scale'
|
| 102 |
+
)
|
| 103 |
+
self.oc_svm.fit(X_train_scaled)
|
| 104 |
+
|
| 105 |
+
self.lof = LocalOutlierFactor(
|
| 106 |
+
n_neighbors=10, # Reduced from 20
|
| 107 |
+
contamination=0.05,
|
| 108 |
+
novelty=True
|
| 109 |
+
)
|
| 110 |
+
self.lof.fit(X_train_scaled)
|
| 111 |
+
|
| 112 |
+
# Train XGBoost verifier with reduced complexity
|
| 113 |
+
self.xgb_verifier = XGBClassifier(
|
| 114 |
+
n_estimators=30, # Reduced from 100
|
| 115 |
+
max_depth=3, # Reduced from 5
|
| 116 |
+
learning_rate=0.1,
|
| 117 |
+
random_state=42
|
| 118 |
+
)
|
| 119 |
+
self.xgb_verifier.fit(
|
| 120 |
+
self.scaler.transform(df[self.feature_columns]),
|
| 121 |
+
df['is_anomaly']
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
print("Model initialization complete!")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
|
| 126 |
+
def verify_anomaly(self, sample, model_predictions, confidence):
|
| 127 |
+
"""Verification function for anomaly detection"""
|
| 128 |
network_suspicious = sample[1] > 3
|
| 129 |
app_switch_pattern = (sample[0] > 5) and (sample[4] < 30)
|
| 130 |
keystroke_burst = (sample[2] > 5) and (sample[2] < 8)
|
| 131 |
verification_score = sum([network_suspicious, app_switch_pattern, keystroke_burst])
|
| 132 |
return (verification_score >= 2) and (confidence >= 0.6)
|
| 133 |
|
| 134 |
+
def predict(self, sample):
|
|
|
|
| 135 |
"""Makes prediction using the ensemble with verification."""
|
| 136 |
try:
|
| 137 |
# Ensure sample is a numpy array with correct shape (1, 5)
|
| 138 |
+
sample_array = np.array(sample, dtype=float).reshape(1, -1)
|
| 139 |
|
| 140 |
+
# Scale the sample
|
| 141 |
+
sample_scaled = self.scaler.transform(sample_array)
|
| 142 |
|
| 143 |
# Get predictions from each model
|
| 144 |
predictions = []
|
| 145 |
|
| 146 |
# Isolation Forest
|
| 147 |
+
if_pred = self.isolation_forest.predict(sample_scaled)[0]
|
| 148 |
predictions.append(1 if if_pred == -1 else 0)
|
| 149 |
|
| 150 |
# One-Class SVM
|
| 151 |
+
svm_pred = self.oc_svm.predict(sample_scaled)[0]
|
| 152 |
predictions.append(1 if svm_pred == -1 else 0)
|
| 153 |
|
| 154 |
# Local Outlier Factor
|
| 155 |
+
lof_pred = self.lof.predict(sample_scaled)[0]
|
| 156 |
predictions.append(1 if lof_pred == -1 else 0)
|
| 157 |
|
| 158 |
# Calculate confidence (fraction of models detecting anomaly)
|
| 159 |
confidence = np.mean(predictions)
|
| 160 |
|
| 161 |
# Apply verification
|
| 162 |
+
is_verified = self.verify_anomaly(sample, predictions, confidence)
|
| 163 |
|
| 164 |
return int(is_verified), confidence, predictions
|
| 165 |
except Exception as e:
|
| 166 |
+
print(f"Error in predict: {str(e)}")
|
| 167 |
traceback.print_exc()
|
| 168 |
+
# Return safe defaults on error
|
| 169 |
+
return 0, 0.0, [0, 0, 0]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
|
| 171 |
+
# Initialize the model globally
|
| 172 |
+
print("Initializing SEB Monitor Model...")
|
| 173 |
+
model = SEBMonitorModel()
|
| 174 |
|
| 175 |
# ===========================
|
| 176 |
+
# PREDICTION FUNCTION
|
| 177 |
# ===========================
|
| 178 |
def analyze_behavior(app_switches, network_requests, keystrokes, mouse_movements, time_on_exam):
|
| 179 |
"""Analyzes student behavior for potential AI cheating patterns"""
|
|
|
|
| 190 |
]
|
| 191 |
|
| 192 |
# DEBUG: Print input data to verify
|
| 193 |
+
print(f"Analyzing input: {current_data}")
|
| 194 |
|
| 195 |
# Get prediction
|
| 196 |
+
is_anomaly, confidence, individual_predictions = model.predict(current_data)
|
| 197 |
+
|
| 198 |
+
print(f"Prediction result - Anomaly: {is_anomaly}, Confidence: {confidence:.2f}")
|
| 199 |
|
| 200 |
# Prepare result
|
| 201 |
if is_anomaly:
|
|
|
|
| 230 |
"processing_time": f"{processing_time:.1f} ms"
|
| 231 |
}
|
| 232 |
except Exception as e:
|
| 233 |
+
error_msg = f"Analysis error: {str(e)}"
|
| 234 |
+
print(error_msg)
|
| 235 |
traceback.print_exc()
|
| 236 |
return {
|
| 237 |
+
"result": "⚠️ Error occurred during analysis",
|
| 238 |
+
"confidence_level": "N/A",
|
| 239 |
+
"confidence_score": "N/A",
|
| 240 |
+
"explanation": f"An error occurred during analysis. Please check your inputs and try again.\n\nError details: {str(e)}",
|
| 241 |
+
"processing_time": "N/A"
|
| 242 |
}
|
| 243 |
|
| 244 |
# ===========================
|
| 245 |
# EXAMPLES
|
| 246 |
# ===========================
|
| 247 |
examples = [
|
| 248 |
+
[2, 0, 2.5, 3, 55], # Normal behavior
|
| 249 |
[10, 6, 3.0, 3, 20], # High-risk pattern (AI cheating)
|
| 250 |
[5, 1, 1.5, 4, 45], # Borderline case
|
| 251 |
[1, 0, 2.0, 2, 58], # Very normal behavior
|
|
|
|
| 257 |
# ===========================
|
| 258 |
def create_interface():
|
| 259 |
"""Creates the Gradio interface optimized for Hugging Face free tier"""
|
| 260 |
+
with gr.Blocks(title="SEB AI Monitoring System", theme=gr.themes.Soft()) as demo:
|
| 261 |
gr.Markdown("""
|
| 262 |
# SEB AI Monitoring System
|
| 263 |
|
|
|
|
| 272 |
with gr.Row():
|
| 273 |
with gr.Column():
|
| 274 |
gr.Markdown("### Enter Behavioral Metrics")
|
| 275 |
+
app_switches = gr.Slider(
|
| 276 |
+
minimum=0,
|
| 277 |
+
maximum=15,
|
| 278 |
+
value=2,
|
| 279 |
+
step=1,
|
| 280 |
+
label="App Switches (per minute)",
|
| 281 |
+
info="Number of times student switches between applications"
|
| 282 |
+
)
|
| 283 |
+
network_requests = gr.Slider(
|
| 284 |
+
minimum=0,
|
| 285 |
+
maximum=10,
|
| 286 |
+
value=0,
|
| 287 |
+
step=1,
|
| 288 |
+
label="Network Requests (per minute)",
|
| 289 |
+
info="Number of network requests made"
|
| 290 |
+
)
|
| 291 |
+
keystrokes = gr.Slider(
|
| 292 |
+
minimum=0,
|
| 293 |
+
maximum=10,
|
| 294 |
+
value=2.5,
|
| 295 |
+
step=0.1,
|
| 296 |
+
label="Keystrokes (WPM)",
|
| 297 |
+
info="Typing speed in words per minute"
|
| 298 |
+
)
|
| 299 |
+
mouse_movements = gr.Slider(
|
| 300 |
+
minimum=0,
|
| 301 |
+
maximum=10,
|
| 302 |
+
value=3,
|
| 303 |
+
step=1,
|
| 304 |
+
label="Mouse Movements (per minute)",
|
| 305 |
+
info="Number of significant mouse movements"
|
| 306 |
+
)
|
| 307 |
+
time_on_exam = gr.Slider(
|
| 308 |
+
minimum=0,
|
| 309 |
+
maximum=60,
|
| 310 |
+
value=55,
|
| 311 |
+
step=1,
|
| 312 |
+
label="Time on Exam (seconds)",
|
| 313 |
+
info="Time spent on exam window per minute"
|
| 314 |
+
)
|
| 315 |
|
| 316 |
+
analyze_btn = gr.Button("Analyze Behavior", variant="primary", size="lg")
|
| 317 |
|
| 318 |
gr.Examples(
|
| 319 |
examples=examples,
|
| 320 |
inputs=[app_switches, network_requests, keystrokes, mouse_movements, time_on_exam],
|
| 321 |
outputs=None,
|
| 322 |
+
examples_per_page=5,
|
| 323 |
+
label="Try these examples:"
|
| 324 |
)
|
| 325 |
|
| 326 |
with gr.Column():
|
| 327 |
gr.Markdown("### Analysis Results")
|
| 328 |
+
result = gr.Textbox(label="Result", interactive=False, lines=1)
|
| 329 |
+
confidence_level = gr.Textbox(label="Confidence Level", interactive=False, lines=1)
|
| 330 |
+
confidence_score = gr.Textbox(label="Confidence Score", interactive=False, lines=1)
|
| 331 |
explanation = gr.Textbox(label="Explanation", interactive=False, lines=8)
|
| 332 |
+
processing_time = gr.Textbox(label="Processing Time", interactive=False, lines=1)
|
| 333 |
|
| 334 |
with gr.Tab("How It Works"):
|
| 335 |
gr.Markdown("""
|
|
|
|
| 349 |
- Bursts of text after pauses (indicating copying from AI)
|
| 350 |
- Inconsistent typing rhythm
|
| 351 |
|
| 352 |
+
4. **Mouse Movement Patterns**
|
| 353 |
+
- Unusual clicking patterns
|
| 354 |
+
- Copy-paste behaviors
|
| 355 |
+
|
| 356 |
+
5. **Time Management**
|
| 357 |
+
- Time spent away from exam window
|
| 358 |
+
- Pattern of brief exam visits
|
| 359 |
+
|
| 360 |
### Business Value
|
| 361 |
|
| 362 |
- **92.3% detection rate** for unauthorized AI access
|
|
|
|
| 374 |
- **XGBoost Verification**: Provides explainable verification of anomalies
|
| 375 |
|
| 376 |
The system is optimized for the Hugging Face free tier with:
|
| 377 |
+
- Reduced model complexity for CPU inference
|
| 378 |
+
- Minimal memory footprint (<10MB)
|
| 379 |
+
- Fast response times (<100ms)
|
| 380 |
""")
|
| 381 |
|
| 382 |
with gr.Tab("About"):
|
|
|
|
| 401 |
- **Lightweight implementation** optimized for free tier constraints
|
| 402 |
- **Explainable results** for academic integrity review
|
| 403 |
|
| 404 |
+
## Detection Thresholds
|
| 405 |
+
|
| 406 |
+
The system uses adaptive thresholds based on:
|
| 407 |
+
- Historical baseline behavior
|
| 408 |
+
- Exam difficulty and duration
|
| 409 |
+
- Institution-specific policies
|
| 410 |
+
|
| 411 |
## Next Steps
|
| 412 |
|
| 413 |
1. **Pilot deployment** to academic institutions
|
|
|
|
| 417 |
*Confidential - For Demonstration Purposes Only*
|
| 418 |
""")
|
| 419 |
|
| 420 |
+
# Connect the analyze button to the function
|
| 421 |
analyze_btn.click(
|
| 422 |
fn=analyze_behavior,
|
| 423 |
inputs=[app_switches, network_requests, keystrokes, mouse_movements, time_on_exam],
|
|
|
|
| 436 |
|
| 437 |
# Launch the interface
|
| 438 |
if __name__ == "__main__":
|
| 439 |
+
try:
|
| 440 |
+
demo = create_interface()
|
| 441 |
+
demo.launch(debug=True)
|
| 442 |
+
except Exception as e:
|
| 443 |
+
print(f"Failed to launch demo: {str(e)}")
|
| 444 |
+
traceback.print_exc()
|