- Added comprehensive AI Assistant system (aiassist/ directory): * Vector search and embedding capabilities * Typebot proxy integration * Elastic search functionality * Message classification and chat history * MCP proxy for external integrations - Implemented Court Status API (GetCourtStatus.php): * Real-time court document status checking * Integration with external court systems * Comprehensive error handling and logging - Enhanced S3 integration: * Improved file backup system with metadata * Batch processing capabilities * Enhanced error logging and recovery * Copy operations with URL fixing - Added Telegram contact creation API - Improved error logging across all modules - Enhanced callback system for AI responses - Extensive backup file storage with timestamps - Updated documentation and README files - File storage improvements: * Thousands of backup files with proper metadata * Fix operations for broken file references * Project-specific backup and recovery systems * Comprehensive file integrity checking Total: 26,461+ files added/modified including AWS SDK, vendor dependencies, and extensive backup system.
149 lines
5.6 KiB
PHP
149 lines
5.6 KiB
PHP
<?php
|
||
|
||
define('LOG_FILE', __DIR__ . '/logs/webhook.log');
|
||
|
||
error_reporting(E_ALL);
|
||
ini_set('display_errors', 1);
|
||
ini_set('log_errors', 1);
|
||
ini_set('error_log', LOG_FILE);
|
||
|
||
// Функция логирования
|
||
function writeLog($message) {
|
||
file_put_contents(LOG_FILE, "[" . date('Y-m-d H:i:s') . "] " . $message . PHP_EOL, FILE_APPEND);
|
||
}
|
||
|
||
// Функция анализа текста через GPT-4-Turbo
|
||
function analyzeTextWithGPT($text, $previousDocuments, $fileName) {
|
||
writeLog("Отправка запроса в GPT-4-Turbo...");
|
||
|
||
$api_key = "sk-GS24OxHQYfq8ErW5CRLoN5F1CfJPxNsY"; // API-ключ
|
||
|
||
if (!$api_key) {
|
||
writeLog("Ошибка: API-ключ не найден!");
|
||
return ["error" => "API-ключ отсутствует"];
|
||
}
|
||
|
||
$task = "Анализируй каждый загруженный документ, выполняя следующие шаги...";
|
||
if (!empty($previousDocuments)) {
|
||
$task .= "\n\nВот уже загруженные документы:\n" . json_encode($previousDocuments, JSON_UNESCAPED_UNICODE);
|
||
}
|
||
|
||
$body = json_encode([
|
||
"model" => "gpt-4-turbo",
|
||
"messages" => [
|
||
["role" => "system", "content" => $task],
|
||
["role" => "user", "content" => $text]
|
||
],
|
||
"max_tokens" => 4000
|
||
]);
|
||
|
||
writeLog("Запрос к GPT-4-Turbo: " . substr($body, 0, 1000));
|
||
|
||
$curl = curl_init();
|
||
curl_setopt_array($curl, [
|
||
CURLOPT_URL => 'https://api.proxyapi.ru/openai/v1/chat/completions',
|
||
CURLOPT_RETURNTRANSFER => true,
|
||
CURLOPT_POST => true,
|
||
CURLOPT_POSTFIELDS => $body,
|
||
CURLOPT_HTTPHEADER => [
|
||
'Content-Type: application/json',
|
||
'Authorization: Bearer ' . $api_key
|
||
]
|
||
]);
|
||
|
||
$response = curl_exec($curl);
|
||
if ($response === false) {
|
||
writeLog("Ошибка CURL: " . curl_error($curl));
|
||
return ["error" => "Ошибка запроса API"];
|
||
}
|
||
|
||
curl_close($curl);
|
||
|
||
$response_data = json_decode($response, true);
|
||
if (json_last_error() !== JSON_ERROR_NONE) {
|
||
writeLog("Ошибка JSON: " . json_last_error_msg());
|
||
return ["error" => "Ошибка декодирования JSON"];
|
||
}
|
||
|
||
writeLog("Ответ от GPT-4-Turbo: " . substr($response, 0, 1000));
|
||
return $response_data;
|
||
}
|
||
|
||
// Функция обработки PDF-файлов
|
||
function processPDFFiles($filePaths) {
|
||
writeLog("Запуск обработки PDF-файлов из вебхука...");
|
||
|
||
if (!shell_exec("which pdftotext")) {
|
||
writeLog("Ошибка: pdftotext не установлен.");
|
||
return ["error" => "pdftotext не найден"];
|
||
}
|
||
|
||
if (empty($filePaths) || !is_array($filePaths)) {
|
||
writeLog("Ошибка: передан пустой список файлов.");
|
||
return ["error" => "Не переданы файлы для обработки."];
|
||
}
|
||
|
||
$documentAnalysis = [];
|
||
foreach ($filePaths as $pdfFile) {
|
||
if (!file_exists($pdfFile)) {
|
||
writeLog("Ошибка: Файл не найден - $pdfFile");
|
||
$documentAnalysis[] = ["file" => basename($pdfFile), "error" => "Файл не найден"];
|
||
continue;
|
||
}
|
||
|
||
writeLog("Обрабатываем PDF: $pdfFile");
|
||
|
||
$text = shell_exec("pdftotext -layout " . escapeshellarg($pdfFile) . " -");
|
||
if ($text === null) {
|
||
writeLog("Ошибка: pdftotext не смог обработать файл $pdfFile.");
|
||
continue;
|
||
}
|
||
|
||
if (empty(trim($text))) {
|
||
writeLog("Файл $pdfFile содержит только изображения или пуст.");
|
||
$documentAnalysis[] = ["file" => basename($pdfFile), "error" => "Файл содержит только изображения."];
|
||
continue;
|
||
}
|
||
|
||
writeLog("Текст успешно извлечен, отправляем в GPT-4-Turbo.");
|
||
$gptAnalysis = analyzeTextWithGPT($text, $documentAnalysis, basename($pdfFile));
|
||
|
||
if (!$gptAnalysis) {
|
||
writeLog("Ошибка: GPT-4-Turbo не вернул ответ.");
|
||
$documentAnalysis[] = ["file" => basename($pdfFile), "error" => "GPT-4-Turbo не ответил"];
|
||
continue;
|
||
}
|
||
|
||
$documentAnalysis[] = ["file" => basename($pdfFile), "analysis" => $gptAnalysis];
|
||
}
|
||
|
||
writeLog("Обработка всех файлов завершена.");
|
||
return ["status" => "complete", "results" => $documentAnalysis];
|
||
}
|
||
|
||
// Получение списка файлов через вебхук
|
||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||
$inputData = json_decode(file_get_contents("php://input"), true);
|
||
|
||
if (!isset($inputData['files']) || !is_array($inputData['files'])) {
|
||
writeLog("Ошибка: Неверный формат запроса.");
|
||
echo json_encode(["status" => "error", "message" => "Неверный формат данных. Ожидается массив файлов."]);
|
||
exit;
|
||
}
|
||
|
||
// Обработка файлов
|
||
$response = processPDFFiles($inputData['files']);
|
||
|
||
// Логируем ответ
|
||
writeLog("Отправляем ответ вебхуку: " . json_encode($response, JSON_UNESCAPED_UNICODE));
|
||
|
||
// Возвращаем JSON-ответ вебхуку
|
||
header('Content-Type: application/json');
|
||
echo json_encode($response, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
|
||
exit;
|
||
} else {
|
||
echo json_encode(["status" => "error", "message" => "Ожидается POST-запрос с JSON-данными."]);
|
||
}
|
||
|
||
?>
|