Repository navigation
Expand file tree
/
Copy pathapi_examples.py
More file actions
289 lines (245 loc) · 8.63 KB
/
Copy pathapi_examples.py
File metadata and controls
289 lines (245 loc) · 8.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
"""
API Usage Examples for Academic Evaluation System
This script demonstrates how to interact with the ML prediction API endpoints.
Run this after the Django server is started.
"""
import requests
import json
# Base URL - update if different
BASE_URL = "http://localhost:8000"
API_BASE = f"{BASE_URL}/api"
def predict_student_risk(student_data):
"""
Example: Predict risk for student data
"""
url = f"{API_BASE}/predict-risk/"
try:
response = requests.post(url, json=student_data)
response.raise_for_status()
result = response.json()
print("✅ Prediction Success!")
print(f" Prediction: {result['prediction']}")
print(f" Confidence: {result['confidence']:.2%}")
print(f" Risk Score: {result['details']['risk_score']:.1f}%")
print()
return result
except requests.exceptions.RequestException as e:
print(f"❌ Error: {e}")
return None
def get_risk_statistics():
"""
Example: Get system-wide risk statistics
"""
url = f"{API_BASE}/risk-statistics/"
try:
response = requests.get(url)
response.raise_for_status()
stats = response.json()
print("📊 Risk Statistics:")
print(f" Total Students: {stats['overall']['total']}")
print(f" At Risk: {stats['overall']['at_risk']} ({stats['overall']['at_risk_percentage']}%)")
print(f" Safe: {stats['overall']['safe']}")
print()
return stats
except requests.exceptions.RequestException as e:
print(f"❌ Error: {e}")
return None
def update_student_risk(student_id, csrf_token):
"""
Example: Update specific student's risk status
Note: Requires authentication and CSRF token
"""
url = f"{API_BASE}/update-risk/{student_id}/"
headers = {
'X-CSRFToken': csrf_token,
'Cookie': f'csrftoken={csrf_token}'
}
try:
response = requests.post(url, headers=headers)
response.raise_for_status()
result = response.json()
print(f"✅ Updated {student_id}")
print(f" Risk Status: {result['risk_status']}")
print(f" Confidence: {result['risk_confidence']:.2%}")
print()
return result
except requests.exceptions.RequestException as e:
print(f"❌ Error: {e}")
return None
def bulk_predict_students(students_list):
"""
Example: Predict risk for multiple students
"""
results = []
print(f"🔄 Processing {len(students_list)} students...")
print()
for i, student in enumerate(students_list, 1):
print(f"Student {i}/{len(students_list)}: {student.get('name', 'Unknown')}")
result = predict_student_risk(student['data'])
if result:
results.append({
'name': student.get('name'),
'prediction': result['prediction'],
'confidence': result['confidence']
})
return results
# ============================================================================
# Example Usage
# ============================================================================
if __name__ == "__main__":
print("=" * 70)
print("Academic Evaluation System - API Examples")
print("=" * 70)
print()
# Example 1: Predict for a high-performing student
print("Example 1: High-Performing Student")
print("-" * 70)
high_performer = {
"cgpa": 8.5,
"attendance_percentage": 95.0,
"assignment_completion": 98.0,
"participation_score": 90.0,
"assignments_late": 0,
"avg_evaluation_score": 88.0,
"semester": 6,
"absence_count": 2
}
predict_student_risk(high_performer)
# Example 2: Predict for an at-risk student
print("Example 2: At-Risk Student")
print("-" * 70)
at_risk_student = {
"cgpa": 4.2,
"attendance_percentage": 55.0,
"assignment_completion": 50.0,
"participation_score": 45.0,
"assignments_late": 7,
"avg_evaluation_score": 48.0,
"semester": 3,
"absence_count": 22
}
predict_student_risk(at_risk_student)
# Example 3: Borderline student
print("Example 3: Borderline Student")
print("-" * 70)
borderline_student = {
"cgpa": 6.5,
"attendance_percentage": 72.0,
"assignment_completion": 75.0,
"participation_score": 65.0,
"assignments_late": 3,
"avg_evaluation_score": 68.0,
"semester": 5,
"absence_count": 9
}
predict_student_risk(borderline_student)
# Example 4: Get statistics (requires authentication)
print("Example 4: System Statistics")
print("-" * 70)
# Note: This might fail if not authenticated
# get_risk_statistics()
print("⚠️ Requires authentication - run from authenticated session")
print()
# Example 5: Batch prediction
print("Example 5: Batch Prediction")
print("-" * 70)
students_batch = [
{
'name': 'Alice Johnson',
'data': {
"cgpa": 7.8,
"attendance_percentage": 88.0,
"assignment_completion": 92.0,
"participation_score": 85.0,
"assignments_late": 1,
"avg_evaluation_score": 82.0,
"semester": 4,
"absence_count": 4
}
},
{
'name': 'Bob Smith',
'data': {
"cgpa": 5.5,
"attendance_percentage": 68.0,
"assignment_completion": 65.0,
"participation_score": 60.0,
"assignments_late": 5,
"avg_evaluation_score": 58.0,
"semester": 4,
"absence_count": 15
}
},
{
'name': 'Carol Davis',
'data': {
"cgpa": 9.2,
"attendance_percentage": 97.0,
"assignment_completion": 100.0,
"participation_score": 95.0,
"assignments_late": 0,
"avg_evaluation_score": 92.0,
"semester": 7,
"absence_count": 1
}
}
]
batch_results = bulk_predict_students(students_batch)
# Summary
print("=" * 70)
print("Batch Prediction Summary")
print("=" * 70)
for result in batch_results:
status_icon = "🟢" if result['prediction'] == 'Safe' else "🔴"
print(f"{status_icon} {result['name']:<20} {result['prediction']:<10} ({result['confidence']:.1%} confidence)")
print()
print("✅ Examples completed!")
print()
print("Note: For authenticated endpoints (update, bulk-update), you need to:")
print("1. Login to the web interface")
print("2. Extract CSRF token from cookies")
print("3. Pass token in request headers")
print()
print("Or use Django's test client for authenticated requests.")
# ============================================================================
# Integration Example with Custom Application
# ============================================================================
class RiskPredictionClient:
"""
Client class for easy integration with other applications
"""
def __init__(self, base_url="http://localhost:8000"):
self.base_url = base_url
self.api_base = f"{base_url}/api"
def predict(self, cgpa, attendance, assignments, participation,
late_assignments=0, avg_eval=0, semester=1, absences=0):
"""
Simplified prediction method
"""
data = {
"cgpa": cgpa,
"attendance_percentage": attendance,
"assignment_completion": assignments,
"participation_score": participation,
"assignments_late": late_assignments,
"avg_evaluation_score": avg_eval,
"semester": semester,
"absence_count": absences
}
url = f"{self.api_base}/predict-risk/"
response = requests.post(url, json=data)
if response.status_code == 200:
return response.json()
else:
raise Exception(f"API Error: {response.status_code}")
def is_at_risk(self, **kwargs):
"""
Returns True if student is at risk, False otherwise
"""
result = self.predict(**kwargs)
return result['prediction'] == 'At Risk'
# Usage:
# client = RiskPredictionClient()
# at_risk = client.is_at_risk(cgpa=5.0, attendance=60, assignments=55, participation=50)
# if at_risk:
# print("⚠️ Student needs intervention!")