-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathtranscribe.php
More file actions
140 lines (124 loc) · 4.49 KB
/
transcribe.php
File metadata and controls
140 lines (124 loc) · 4.49 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
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* OpenAI Whisper transcription proxy endpoint.
* Accepts POST multipart { audio (file), sesskey, courseid, lang }.
* Returns JSON { text: "transcribed text" }.
*
* Used as a fallback for browsers without Web Speech API (e.g. iOS Chrome).
*
* @package local_ai_course_assistant
* @copyright 2025 AI Course Assistant
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
define('AJAX_SCRIPT', true);
require_once('../../config.php');
require_login();
require_sesskey();
header('Content-Type: application/json');
$courseid = optional_param('courseid', 0, PARAM_INT);
if ($courseid > 0) {
$context = context_course::instance($courseid);
} else {
$context = context_system::instance();
}
require_capability('local/ai_course_assistant:use', $context);
// Require the uploaded audio file.
if (empty($_FILES['audio']['tmp_name']) || !is_uploaded_file($_FILES['audio']['tmp_name'])) {
http_response_code(400);
echo json_encode(['error' => 'No audio file provided.']);
exit;
}
// Resolve API key — same priority as tts.php.
$apikey = get_config('local_ai_course_assistant', 'realtime_apikey');
if (empty($apikey)) {
$provider = get_config('local_ai_course_assistant', 'provider');
$mainapikey = get_config('local_ai_course_assistant', 'apikey');
if ($provider === 'openai' && !empty($mainapikey)) {
$apikey = $mainapikey;
}
}
if (empty($apikey)) {
http_response_code(503);
echo json_encode(['error' => 'No OpenAI API key configured for transcription.']);
exit;
}
// Optional ISO 639-1 language hint (e.g. 'en', 'es').
$lang = optional_param('lang', '', PARAM_ALPHA);
$tmpfile = $_FILES['audio']['tmp_name'];
$mimetype = !empty($_FILES['audio']['type']) ? $_FILES['audio']['type'] : 'audio/webm';
// Map MIME type to a file extension Whisper will recognise.
$ext_map = [
'audio/webm' => 'webm',
'audio/ogg' => 'ogg',
'audio/mp4' => 'mp4',
'audio/mpeg' => 'mp3',
'audio/wav' => 'wav',
'audio/x-wav' => 'wav',
];
$ext = $ext_map[$mimetype] ?? 'webm';
$filename = 'audio.' . $ext;
$post = [
'file' => new CURLFile($tmpfile, $mimetype, $filename),
'model' => 'whisper-1',
];
if (!empty($lang)) {
$post['language'] = $lang;
}
$ch = curl_init('https://api.openai.com/v1/audio/transcriptions');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $post,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . $apikey,
],
CURLOPT_TIMEOUT => 30,
]);
$response = curl_exec($ch);
$httpcode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpcode !== 200) {
http_response_code(502);
echo json_encode(['error' => 'Transcription API error ' . $httpcode]);
exit;
}
$data = json_decode($response, true);
if (!isset($data['text'])) {
http_response_code(502);
echo json_encode(['error' => 'Invalid transcription response.']);
exit;
}
// Log Whisper transcription cost: approximate tokens from audio file size.
// Whisper charges per minute (~$0.006/min). Rough estimate: 1MB ≈ 1 min audio.
$filesizebytes = filesize($tmpfile) ?: 0;
$approxminutes = max(0.1, $filesizebytes / 1_000_000);
$approxtokens = (int) ceil($approxminutes * 1000); // Arbitrary unit for rate card matching.
try {
$conv = $DB->get_record('local_ai_course_assistant_convs', [
'userid' => $USER->id, 'courseid' => $courseid > 0 ? $courseid : SITEID,
]);
if ($conv) {
\local_ai_course_assistant\conversation_manager::add_message(
$conv->id, $USER->id, $courseid > 0 ? $courseid : SITEID,
'system', '[Whisper Transcription]',
0, 'openai_whisper', $approxtokens, 0, 'whisper-1'
);
}
} catch (\Throwable $e) {
// Non-critical.
}
echo json_encode(['text' => $data['text']]);