dgith commited on
Commit
9fde1ea
·
verified ·
1 Parent(s): 95116cb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +97 -72
app.py CHANGED
@@ -17,6 +17,7 @@ from sklearn.svm import OneClassSVM
17
  from sklearn.neighbors import LocalOutlierFactor
18
  from xgboost import XGBClassifier
19
  import time
 
20
 
21
  # ===========================
22
  # MODEL HANDLING
@@ -123,32 +124,42 @@ def create_demo_model():
123
  verification_score = sum([network_suspicious, app_switch_pattern, keystroke_burst])
124
  return (verification_score >= 2) and (confidence >= 0.6)
125
 
126
- # Ensemble prediction function
127
  def ensemble_predict(sample):
128
- sample_scaled = scaler.transform([sample])[0]
129
-
130
- # Get predictions
131
- predictions = []
132
-
133
- # Isolation Forest
134
- if_pred = isolation_forest.predict([sample_scaled])[0]
135
- predictions.append(1 if if_pred == -1 else 0)
136
-
137
- # One-Class SVM
138
- svm_pred = oc_svm.predict([sample_scaled])[0]
139
- predictions.append(1 if svm_pred == -1 else 0)
140
-
141
- # Local Outlier Factor
142
- lof_pred = lof.predict([sample_scaled])[0]
143
- predictions.append(1 if lof_pred == -1 else 0)
144
-
145
- # Calculate confidence
146
- confidence = np.mean(predictions)
147
-
148
- # Apply verification
149
- is_verified = verify_anomaly(sample, predictions, confidence)
150
-
151
- return int(is_verified), confidence, predictions
 
 
 
 
 
 
 
 
 
 
152
 
153
  return {
154
  'scaler': scaler,
@@ -166,56 +177,70 @@ models = load_or_create_model()
166
  ensemble_predict = models['ensemble_predict']
167
 
168
  # ===========================
169
- # PREDICTION FUNCTION
170
  # ===========================
171
  def analyze_behavior(app_switches, network_requests, keystrokes, mouse_movements, time_on_exam):
172
  """Analyzes student behavior for potential AI cheating patterns"""
173
- start_time = time.time()
174
-
175
- # Prepare input data
176
- current_data = [
177
- float(app_switches),
178
- float(network_requests),
179
- float(keystrokes),
180
- float(mouse_movements),
181
- float(time_on_exam)
182
- ]
183
-
184
- # Get prediction
185
- is_anomaly, confidence, _ = ensemble_predict(current_data)
186
-
187
- # Prepare result
188
- if is_anomaly:
189
- result = "⚠️ ALERT: Potential unauthorized AI access detected"
190
- explanation = (
191
- "This behavior shows patterns consistent with accessing unauthorized AI models:\n"
192
- "- High network activity or irregular application switching\n"
193
- "- Unnatural typing patterns (bursts of text after pauses)\n"
194
- "- Reduced time spent on the exam window\n\n"
195
- "This student should be reviewed for potential academic integrity issues."
196
- )
197
- confidence_level = "High" if confidence > 0.8 else "Medium"
198
- else:
199
- result = "✅ NORMAL: No suspicious activity detected"
200
- explanation = (
201
- "This behavior matches typical exam patterns:\n"
202
- "- Consistent time spent on the exam window\n"
203
- "- Normal application switching patterns\n"
204
- "- Regular typing rhythm\n\n"
205
- "No evidence of unauthorized AI model access detected."
206
- )
207
- confidence_level = "High"
208
-
209
- # Calculate processing time (for transparency)
210
- processing_time = (time.time() - start_time) * 1000 # in ms
211
-
212
- return {
213
- "result": result,
214
- "confidence_level": confidence_level,
215
- "confidence_score": f"{confidence:.1%}",
216
- "explanation": explanation,
217
- "processing_time": f"{processing_time:.1f} ms"
218
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
219
 
220
  # ===========================
221
  # EXAMPLES
 
17
  from sklearn.neighbors import LocalOutlierFactor
18
  from xgboost import XGBClassifier
19
  import time
20
+ import traceback
21
 
22
  # ===========================
23
  # MODEL HANDLING
 
124
  verification_score = sum([network_suspicious, app_switch_pattern, keystroke_burst])
125
  return (verification_score >= 2) and (confidence >= 0.6)
126
 
127
+ # FIXED: Corrected ensemble prediction function
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 (returns 2D array of shape (1, 5))
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 ensemble_predict: {str(e)}")
161
+ traceback.print_exc()
162
+ raise e
163
 
164
  return {
165
  'scaler': scaler,
 
177
  ensemble_predict = models['ensemble_predict']
178
 
179
  # ===========================
180
+ # PREDICTION FUNCTION (FIXED)
181
  # ===========================
182
  def analyze_behavior(app_switches, network_requests, keystrokes, mouse_movements, time_on_exam):
183
  """Analyzes student behavior for potential AI cheating patterns"""
184
+ try:
185
+ start_time = time.time()
186
+
187
+ # Prepare input data
188
+ current_data = [
189
+ float(app_switches),
190
+ float(network_requests),
191
+ float(keystrokes),
192
+ float(mouse_movements),
193
+ float(time_on_exam)
194
+ ]
195
+
196
+ # DEBUG: Print input data to verify
197
+ print(f"Input data: {current_data}")
198
+
199
+ # Get prediction
200
+ is_anomaly, confidence, _ = ensemble_predict(current_data)
201
+
202
+ # Prepare result
203
+ if is_anomaly:
204
+ result = "⚠️ ALERT: Potential unauthorized AI access detected"
205
+ explanation = (
206
+ "This behavior shows patterns consistent with accessing unauthorized AI models:\n"
207
+ "- High network activity or irregular application switching\n"
208
+ "- Unnatural typing patterns (bursts of text after pauses)\n"
209
+ "- Reduced time spent on the exam window\n\n"
210
+ "This student should be reviewed for potential academic integrity issues."
211
+ )
212
+ confidence_level = "High" if confidence > 0.8 else "Medium"
213
+ else:
214
+ result = "✅ NORMAL: No suspicious activity detected"
215
+ explanation = (
216
+ "This behavior matches typical exam patterns:\n"
217
+ "- Consistent time spent on the exam window\n"
218
+ "- Normal application switching patterns\n"
219
+ "- Regular typing rhythm\n\n"
220
+ "No evidence of unauthorized AI model access detected."
221
+ )
222
+ confidence_level = "High"
223
+
224
+ # Calculate processing time (for transparency)
225
+ processing_time = (time.time() - start_time) * 1000 # in ms
226
+
227
+ return {
228
+ "result": result,
229
+ "confidence_level": confidence_level,
230
+ "confidence_score": f"{confidence:.1%}",
231
+ "explanation": explanation,
232
+ "processing_time": f"{processing_time:.1f} ms"
233
+ }
234
+ except Exception as e:
235
+ print(f"Error in analyze_behavior: {str(e)}")
236
+ traceback.print_exc()
237
+ return {
238
+ "result": "Error",
239
+ "confidence_level": "Error",
240
+ "confidence_score": "Error",
241
+ "explanation": f"An error occurred: {str(e)}",
242
+ "processing_time": "Error"
243
+ }
244
 
245
  # ===========================
246
  # EXAMPLES