-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathgenerate_mock_exam.php
More file actions
184 lines (155 loc) · 9.16 KB
/
generate_mock_exam.php
File metadata and controls
184 lines (155 loc) · 9.16 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
<?php
include('config.php');
// Azure OpenAI API endpoint and key
$openai_endpoint = "https://ai-graphitestorm8466ai385706727975.openai.azure";
$openai_api_key = "Ax80ppCsRf3baI69t4Ww7WdIgE2ywqwmoxVQk8WXiX5rN2Q6bYv0JQQJ99BCACHYHv6XJ3w3AAAAACOGTC2b";
$openai_version = "2024-11-20";
$openai_model = "gpt-4o";
// Function to create mock exams using Azure OpenAI
function generateMockExams($original_exid, $exname, $description, $subject, $conn)
{
global $openai_endpoint, $openai_api_key, $openai_version, $openai_model;
// Get current date and time for exam scheduling
$current_date = date('Y-m-d H:i:s');
// Set submission time to 7 days from now
$submission_time = date('Y-m-d H:i:s', strtotime('+7 days'));
// Insert two mock exam entries
for ($i = 1; $i <= 2; $i++) {
// Create a mock exam entry
$mock_exam_name = "Mock Test $i: $exname";
$mock_exam_desc = "Practice test $i for $exname. $description";
$sql = "INSERT INTO mock_exm_list (original_exid, mock_number, exname, nq, desp, subt, extime, subject, status)
VALUES ('$original_exid', '$i', '$mock_exam_name', '5', '$mock_exam_desc', '$submission_time', '$current_date', '$subject', 'pending')";
if (mysqli_query($conn, $sql)) {
$mock_exid = mysqli_insert_id($conn);
// Generate questions using Azure OpenAI
$prompt = "Create 5 multiple choice questions for a $subject exam on '$exname'. The exam is described as: '$description'. For each question, provide 4 options and indicate the correct answer. Format the response as a JSON array with each question having the following structure: {\"question\": \"...\", \"option1\": \"...\", \"option2\": \"...\", \"option3\": \"...\", \"option4\": \"...\", \"correct_answer\": \"option1/option2/option3/option4\"}";
try {
// Create Azure OpenAI API request
$request_url = "$openai_endpoint/openai/deployments/$openai_model/chat/completions?api-version=$openai_version";
$headers = [
'Content-Type: application/json',
'api-key: ' . $openai_api_key
];
$data = [
'messages' => [
[
'role' => 'system',
'content' => 'You are an AI assistant that creates high-quality multiple choice questions for educational exams.'
],
[
'role' => 'user',
'content' => $prompt
]
],
'temperature' => 0.7,
'max_tokens' => 2000
];
error_log("Sending request to OpenAI API: $request_url");
$ch = curl_init($request_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$err = curl_error($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
error_log("API Response code: $http_code");
if ($err) {
error_log("cURL Error: " . $err);
// Update mock exam status to error
$update_sql = "UPDATE mock_exm_list SET status = 'error' WHERE mock_exid = '$mock_exid'";
mysqli_query($conn, $update_sql);
} else {
$response_data = json_decode($response, true);
if (isset($response_data['choices'][0]['message']['content'])) {
$content = $response_data['choices'][0]['message']['content'];
// Extract JSON data from the response
preg_match('/\[.*?\]/s', $content, $matches);
if (!empty($matches)) {
$questions_json = $matches[0];
$questions = json_decode($questions_json, true);
if (is_array($questions)) {
// Insert questions into database
for ($j = 0; $j < count($questions); $j++) {
$question = $questions[$j];
$qstn = mysqli_real_escape_string($conn, $question['question']);
$o1 = mysqli_real_escape_string($conn, $question['option1']);
$o2 = mysqli_real_escape_string($conn, $question['option2']);
$o3 = mysqli_real_escape_string($conn, $question['option3']);
$o4 = mysqli_real_escape_string($conn, $question['option4']);
// Determine correct answer
$correct_answer = $question['correct_answer'];
if ($correct_answer == 'option1') {
$ans = $o1;
} elseif ($correct_answer == 'option2') {
$ans = $o2;
} elseif ($correct_answer == 'option3') {
$ans = $o3;
} else {
$ans = $o4;
}
$ans = mysqli_real_escape_string($conn, $ans);
$sno = $j + 1;
$insert_sql = "INSERT INTO mock_qstn_list (mock_exid, qstn, qstn_o1, qstn_o2, qstn_o3, qstn_o4, qstn_ans, sno)
VALUES ('$mock_exid', '$qstn', '$o1', '$o2', '$o3', '$o4', '$ans', '$sno')";
mysqli_query($conn, $insert_sql);
}
// Update mock exam status to ready
$update_sql = "UPDATE mock_exm_list SET status = 'ready' WHERE mock_exid = '$mock_exid'";
mysqli_query($conn, $update_sql);
} else {
// Update mock exam status to error
$update_sql = "UPDATE mock_exm_list SET status = 'error' WHERE mock_exid = '$mock_exid'";
mysqli_query($conn, $update_sql);
error_log("Failed to parse questions JSON: " . $questions_json);
}
} else {
// Update mock exam status to error
$update_sql = "UPDATE mock_exm_list SET status = 'error' WHERE mock_exid = '$mock_exid'";
mysqli_query($conn, $update_sql);
error_log("No JSON found in the response: " . $content);
}
} else {
// Update mock exam status to error
$update_sql = "UPDATE mock_exm_list SET status = 'error' WHERE mock_exid = '$mock_exid'";
mysqli_query($conn, $update_sql);
error_log("Invalid response format: " . json_encode($response_data));
}
}
} catch (Exception $e) {
// Update mock exam status to error
$update_sql = "UPDATE mock_exm_list SET status = 'error' WHERE mock_exid = '$mock_exid'";
mysqli_query($conn, $update_sql);
error_log("Exception: " . $e->getMessage());
}
} else {
error_log("Error creating mock exam: " . mysqli_error($conn));
}
}
}
// API endpoint for generating mock exams
// Only run this code if the file is being accessed directly, not when included in another file
$included_file = get_included_files();
if ($_SERVER['REQUEST_METHOD'] === 'POST' && count($included_file) <= 1) {
// Log incoming request for debugging
error_log("Mock exam request received: " . json_encode($_POST));
// Check if this is an API call with required parameters
if (isset($_POST['exid']) && isset($_POST['exname']) && isset($_POST['desp']) && isset($_POST['subject'])) {
$exid = $_POST['exid'];
$exname = $_POST['exname'];
$description = $_POST['desp'];
$subject = $_POST['subject'];
error_log("Generating mock exams for: $exname (ID: $exid)");
generateMockExams($exid, $exname, $description, $subject, $conn);
header('Content-Type: application/json');
echo json_encode(['status' => 'success', 'message' => 'Mock exams generation initiated']);
exit;
} else {
error_log("Mock exam request missing required parameters: " . json_encode($_POST));
header('Content-Type: application/json');
echo json_encode(['status' => 'error', 'message' => 'Missing required parameters']);
exit;
}
}