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); return $body['ParsedResults'][0]['ParsedText'] ?? 'No text extracted.'; } catch (RequestException $e) { return 'OCR error: ' . $e->getMessage(); } } if ($_SERVER['REQUEST_METHOD'] === 'POST') { if (isset($_FILES['user_file'])) { if (!empty($_FILES['user_file']['tmp_name'])) { $combinedText = ""; $parser = new Parser(); foreach ($_FILES['user_file']['tmp_name'] as $tmpFile) { $mimeType = mime_content_type($tmpFile); if (isImage($mimeType)) { // 👇 Added: Extract text from image $text = extractTextFromImage($tmpFile); $combinedText .= "\n" . $text; } else { try { $pdf = $parser->parseFile($tmpFile); $text = $pdf->getText(); $combinedText .= "\n" . $text; } catch (Exception $e) { echo 'Error parsing PDF: ' . $e->getMessage(); exit; } } } file_put_contents("log.txt", $combinedText); // Optional log $_SESSION['extracted_text'] = $combinedText; echo "All PDFs uploaded and processed successfully."; exit; } } if (isset($_POST['user_input'])) { $userQuestion = $_POST['user_input']; $extractedText = $_SESSION['extracted_text'] ?? ''; if (empty($extractedText)) { echo "No PDF 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); $reply = $result['choices'][0]['message']['content'] ?? 'No response from AI.'; echo $reply; } catch (Exception $e) { echo 'Error: ' . $e->getMessage(); } } }