62 lines
1.5 KiB
PHP
62 lines
1.5 KiB
PHP
<?php
|
|
/**
|
|
* Voice Transcribe Proxy Endpoint
|
|
* POST /v1/voice/transcribe
|
|
*
|
|
* Proxies audio file to Groq STT (Whisper) safely keeping API keys on backend.
|
|
*/
|
|
|
|
declare(strict_types=1);
|
|
|
|
use App\Middleware\AuthMiddleware;
|
|
use App\Middleware\RateLimitMiddleware;
|
|
|
|
// Rate limit: 20 per minute
|
|
RateLimitMiddleware::check(20, 60);
|
|
|
|
$decoded = AuthMiddleware::check();
|
|
|
|
if (!isset($_FILES['audio']) || $_FILES['audio']['error'] !== UPLOAD_ERR_OK) {
|
|
json_error('ملف الصوت مطلوب', 422);
|
|
}
|
|
|
|
$apiKey = env('GROQ_API_KEY');
|
|
if (!$apiKey) {
|
|
json_error('Groq API Key غير متوفر', 500);
|
|
}
|
|
|
|
// Ensure it's a valid audio file (basic check)
|
|
$tmpPath = $_FILES['audio']['tmp_name'];
|
|
|
|
$cfile = curl_file_create($tmpPath, $_FILES['audio']['type'], $_FILES['audio']['name']);
|
|
|
|
$postData = [
|
|
'file' => $cfile,
|
|
'model' => 'whisper-large-v3',
|
|
'language' => 'ar',
|
|
'response_format' => 'json'
|
|
];
|
|
|
|
$ch = curl_init('https://api.groq.com/openai/v1/audio/transcriptions');
|
|
curl_setopt_array($ch, [
|
|
CURLOPT_POST => true,
|
|
CURLOPT_POSTFIELDS => $postData,
|
|
CURLOPT_RETURNTRANSFER => true,
|
|
CURLOPT_HTTPHEADER => [
|
|
'Authorization: Bearer ' . $apiKey
|
|
]
|
|
]);
|
|
|
|
$response = curl_exec($ch);
|
|
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
|
$error = curl_error($ch);
|
|
curl_close($ch);
|
|
|
|
if ($httpCode !== 200) {
|
|
error_log("Groq Error: $response | $error");
|
|
json_error('فشل في تحويل الصوت إلى نص', 500);
|
|
}
|
|
|
|
$data = json_decode($response, true);
|
|
json_success(['text' => $data['text'] ?? ''], 'تم التحويل بنجاح');
|