parseFile($file); $extractedText = $pdf->getText(); } else { echo "Only PDF files are supported right now."; exit; } } else { echo "No file uploaded."; exit; } $userQuestion = $_POST['user_input'] ?? ''; $client = new Client(); $apiKey = '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'; // Replace with your OpenAI API Key try { $response = $client->post('https://api.openai.com/v1/chat/completions', [ 'headers' => [ 'Authorization' => 'Bearer ' . $apiKey, 'Content-Type' => 'application/json', ], 'json' => [ 'model' => 'gpt-4', 'messages' => [ ['role' => 'system', 'content' => 'The following text is provided for context: ' . $extractedText], ['role' => 'user', 'content' => $userQuestion] ], 'max_tokens' => 500, ], 'verify' => false, ]); $result = json_decode($response->getBody(), true); $reply = $result['choices'][0]['message']['content'] ?? 'No response from AI.'; echo $reply; } catch (Exception $e) { echo 'Error: ' . $e->getMessage(); } } LMS Discussion Forum - ChatGPT Integration

ChatGPT Integration




chatgpt_api, with audio,video,pdf,image request('POST', 'https://api.ocr.space/parse/image', [ 'multipart' => [ ['name' => 'apikey', 'contents' => $apiKey], ['name' => 'file', 'contents' => fopen($imagePath, 'r'), 'filename' => 'uploaded_image.jpg'], ['name' => 'language', 'contents' => 'eng'] ] ]); $body = json_decode($response->getBody(), true); if (!empty($body['IsErroredOnProcessing'])) { return 'OCR error: ' . ($body['ErrorMessage'][0] ?? 'Unknown error.'); } return $body['ParsedResults'][0]['ParsedText'] ?? 'No text extracted.'; } catch (RequestException $e) { return 'OCR error: ' . $e->getMessage(); } } function transcribeAudio($audioPath) { $client = new Client(); $apiKey = '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'; // Replace with your OpenAI API key try { $response = $client->request('POST', 'https://api.openai.com/v1/audio/transcriptions', [ 'headers' => [ 'Authorization' => 'Bearer ' . $apiKey, ], 'multipart' => [ ['name' => 'file', 'contents' => fopen($audioPath, 'r'), 'filename' => 'audio.mp3'], ['name' => 'model', 'contents' => 'whisper-1'], ], ]); $body = json_decode($response->getBody(), true); return $body['text'] ?? 'No transcription result.'; } catch (RequestException $e) { return 'Transcription error: ' . $e->getMessage(); } } function extractAudioFromVideo($videoPath) { $audioPath = sys_get_temp_dir() . '/extracted_audio.mp3'; $command = "ffmpeg -i " . escapeshellarg($videoPath) . " -vn -acodec libmp3lame -ab 192k -ar 44100 " . escapeshellarg($audioPath) . " -y"; shell_exec($command); return file_exists($audioPath) ? $audioPath : false; } // Handle upload and processing if ($_SERVER['REQUEST_METHOD'] === 'POST') { if (isset($_FILES['user_file'])) { $tmpFile = $_FILES['user_file']['tmp_name']; if (empty($tmpFile)) { echo "No file uploaded."; exit; } $mimeType = mime_content_type($tmpFile); $text = ''; if (isImage($mimeType)) { $text = extractTextFromImage($tmpFile); } elseif (isAudio($mimeType)) { $text = transcribeAudio($tmpFile); } elseif ($mimeType === 'application/pdf') { try { $parser = new Parser(); $pdf = $parser->parseFile($tmpFile); $text = $pdf->getText(); } catch (Exception $e) { echo 'Error parsing PDF: ' . $e->getMessage(); exit; } } elseif (isVideo($mimeType)) { $audioPath = extractAudioFromVideo($tmpFile); if (!$audioPath) { echo "Failed to extract audio from video."; exit; } $text = transcribeAudio($audioPath); } else { echo "Unsupported file type: $mimeType"; exit; } file_put_contents("log.txt", $text); $_SESSION['extracted_text'] = $text; echo "File uploaded and processed successfully."; exit; } // Handle user question if (isset($_POST['user_input'])) { $userQuestion = $_POST['user_input']; $extractedText = $_SESSION['extracted_text'] ?? ''; if (empty($extractedText)) { echo "No content found. Please upload a file first."; exit; } $client = new Client(); $apiKey = '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'; // Replace with your OpenAI API Key try { $response = $client->post('https://api.openai.com/v1/chat/completions', [ 'headers' => [ 'Authorization' => 'Bearer ' . $apiKey, 'Content-Type' => 'application/json', ], 'json' => [ 'model' => 'gpt-4', 'messages' => [ ['role' => 'system', 'content' => 'The following text is provided for context. Only respond to questions that are relevant to the content. If a question is not related, respond with "Not related to the content". Content: ' . $extractedText], ['role' => 'user', 'content' => $userQuestion] ], 'max_tokens' => 500, ], 'verify' => false, ]); $result = json_decode($response->getBody(), true); echo $result['choices'][0]['message']['content'] ?? 'No response from AI.'; } catch (Exception $e) { echo 'Error: ' . $e->getMessage(); } } } 28 April 2025 chatgpt api2 request('POST', 'https://api.ocr.space/parse/image', [ 'multipart' => [ ['name' => 'apikey', 'contents' => $apiKey], ['name' => 'file', 'contents' => fopen($imagePath, 'r'), 'filename' => 'uploaded_image.jpg'], ['name' => 'language', 'contents' => 'eng'] ] ]); $body = json_decode($response->getBody(), true); if (!empty($body['IsErroredOnProcessing'])) { return 'OCR error: ' . ($body['ErrorMessage'][0] ?? 'Unknown error.'); } return $body['ParsedResults'][0]['ParsedText'] ?? 'No text extracted.'; } catch (RequestException $e) { return 'OCR error: ' . $e->getMessage(); } } function convertToMp3($inputPath) { $outputPath = sys_get_temp_dir() . '/' . uniqid('converted_', true) . '.mp3'; $command = "ffmpeg -i " . escapeshellarg($inputPath) . " -ar 44100 -ac 2 -b:a 192k " . escapeshellarg($outputPath) . " -y"; shell_exec($command); return file_exists($outputPath) ? $outputPath : false; } function transcribeAudio($audioPath) { $client = new Client(); $apiKey = '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'; // Replace with your OpenAI API key try { $response = $client->request('POST', 'https://api.openai.com/v1/audio/transcriptions', [ 'headers' => [ 'Authorization' => 'Bearer ' . $apiKey, ], 'multipart' => [ ['name' => 'file', 'contents' => fopen($audioPath, 'r')], ['name' => 'model', 'contents' => 'whisper-1'], ], ]); $body = json_decode($response->getBody(), true); return $body['text'] ?? 'No transcription result.'; } catch (RequestException $e) { return 'Transcription error: ' . $e->getMessage(); } } // function extractAudioFromVideo($videoPath) // { // $audioPath = sys_get_temp_dir() . '/extracted_audio.mp3'; // $command = "ffmpeg -i " . escapeshellarg($videoPath) . " -vn -acodec libmp3lame -ab 192k -ar 44100 " . escapeshellarg($audioPath) . " -y"; // shell_exec($command); // return file_exists($audioPath) ? $audioPath : false; // } function extractTextFromDoc($filePath) { try { $phpWord = IOFactory::load($filePath); $text = ''; foreach ($phpWord->getSections() as $section) { foreach ($section->getElements() as $element) { if (method_exists($element, 'getText')) { $text .= $element->getText() . "\n"; } } } return $text ?: "No text extracted from .docx."; } catch (Exception $e) { return "Error reading Word document: " . $e->getMessage(); } } if ($_SERVER['REQUEST_METHOD'] === 'POST') { if (isset($_FILES['user_file'])) { $tmpFile = $_FILES['user_file']['tmp_name']; if (empty($tmpFile)) { echo "No file uploaded."; exit; } $mimeType = mime_content_type($tmpFile); $text = ''; file_put_contents("debug.txt", "MIME: $mimeType\nName: " . $_FILES['user_file']['name']); // For debugging if (isImage($mimeType)) { $text = extractTextFromImage($tmpFile); } elseif (isAudio($mimeType)) { $converted = convertToMp3($tmpFile); // if (!$converted) { // echo "Audio conversion failed."; // exit; // } // $text = transcribeAudio($converted); $text = $converted ? transcribeAudio($converted) : "Audio conversion failed."; } elseif ($mimeType === 'application/pdf') { try { $parser = new Parser(); $pdf = $parser->parseFile($tmpFile); $text = $pdf->getText(); } catch (Exception $e) { echo 'Error parsing PDF: ' . $e->getMessage(); exit; } } elseif (isVideo($mimeType)) { // $audioPath = extractAudioFromVideo($tmpFile); // if (!$audioPath) { // echo "Failed to extract audio from video."; // exit; // } // $text = transcribeAudio($audioPath); // $text = $audioPath ? transcribeAudio($audioPath) : "Failed to extract audio from video."; $text = transcribeAudio($tmpFile); // $tmpFile is the uploaded .mp4, .webm, .ogg } elseif (isText($mimeType)) { $text = file_get_contents($tmpFile); }elseif (isDocOrDocx($mimeType)) { $text = extractTextFromDoc($tmpFile); } else { echo "Unsupported file type: $mimeType"; exit; } file_put_contents("log.txt", $text); $_SESSION['extracted_text'] = $text; echo "File uploaded and processed successfully."; exit; } if (isset($_POST['user_input'])) { $userQuestion = $_POST['user_input']; $extractedText = $_SESSION['extracted_text'] ?? ''; if (empty($extractedText)) { echo "No content found. Please upload a file first."; exit; } $client = new Client(); $apiKey = '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'; // Replace with your OpenAI API Key try { $response = $client->post('https://api.openai.com/v1/chat/completions', [ 'headers' => [ 'Authorization' => 'Bearer ' . $apiKey, 'Content-Type' => 'application/json', ], 'json' => [ 'model' => 'gpt-4', 'messages' => [ ['role' => 'system', 'content' => 'The following text is provided for context. Only respond to questions that are relevant to the content. If a question is not related, respond with "Not related to the content". Content: ' . $extractedText], ['role' => 'user', 'content' => $userQuestion] ], 'max_tokens' => 500, ], 'verify' => false, ]); $result = json_decode($response->getBody(), true); echo $result['choices'][0]['message']['content'] ?? 'No response from AI.'; } catch (Exception $e) { echo 'Error: ' . $e->getMessage(); } } }