- 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.
136 lines
5.6 KiB
PHP
136 lines
5.6 KiB
PHP
<?php
|
||
define('SCAN_DIR', 'scanpdf');
|
||
define('LOG_FILE', 'logs/CheckPDF.log');
|
||
|
||
error_reporting(E_ALL);
|
||
ini_set('display_errors', 1);
|
||
ini_set('log_errors', 1);
|
||
ini_set('error_log', LOG_FILE);
|
||
|
||
// Функция логирования
|
||
function logMessage($message) {
|
||
file_put_contents(LOG_FILE, date('Y-m-d H:i:s') . " - " . $message . "\n", FILE_APPEND);
|
||
}
|
||
|
||
function AnalyzeTextWithGPT($text, $previousDocuments, $fileName) {
|
||
logMessage("Отправка запроса в GPT-4-Turbo...");
|
||
|
||
$api_key = "sk-GS24OxHQYfq8ErW5CRLoN5F1CfJPxNsY"; // API-ключ
|
||
|
||
if (!$api_key) {
|
||
logMessage("Ошибка: API-ключ не найден!");
|
||
return ["error" => "API-ключ отсутствует"];
|
||
}
|
||
|
||
// Инструкция пользователю вместо system prompt
|
||
$task = "Анализируй текст документа и выполни следующие шаги:
|
||
|
||
1. Определи тип документа (договор, претензия, ответ на претензию, подтверждение оплаты и т. д.).
|
||
2. Проверь, соответствует ли название файла его содержимому.
|
||
3. Если файл связан с ранее загруженными, обнови анализ.
|
||
4. Определи стороны спора (истец, ответчик), если применимо.
|
||
5. Проверь текст на наличие нецензурной лексики.
|
||
6. Вынеси вердикт: 'Прошло модерацию' или 'Не прошло модерацию' с указанием причин.
|
||
|
||
📌 Важно:
|
||
- Если документ связан с ранее загруженными, укажи, как он влияет на анализ.
|
||
- Если документ новый, обработай его отдельно.";
|
||
|
||
if (!empty($previousDocuments)) {
|
||
$task .= "\n\nРанее загруженные документы:\n" . json_encode($previousDocuments, JSON_UNESCAPED_UNICODE);
|
||
}
|
||
|
||
$body = json_encode([
|
||
"model" => "o1-mini", // Используется модель без system prompt
|
||
"messages" => [
|
||
["role" => "user", "content" => $task], // Инструкция как ввод пользователя
|
||
["role" => "user", "content" => $text] // Сам текст документа
|
||
],
|
||
"max_completion_tokens" => 4000
|
||
]);
|
||
|
||
logMessage("Запрос к GPT-4-Turbo: " . substr($body, 0, 1000));
|
||
|
||
$curl = curl_init();
|
||
curl_setopt_array($curl, [
|
||
CURLOPT_URL => 'https://api.proxyapi.ru/openai/v1/chat/completions', // Исправленный URL
|
||
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) {
|
||
logMessage("Ошибка CURL: " . curl_error($curl));
|
||
return ["error" => "Ошибка запроса API"];
|
||
}
|
||
|
||
curl_close($curl);
|
||
|
||
$response_data = json_decode($response, true);
|
||
if (json_last_error() !== JSON_ERROR_NONE) {
|
||
logMessage("Ошибка JSON: " . json_last_error_msg());
|
||
return ["error" => "Ошибка декодирования JSON"];
|
||
}
|
||
|
||
logMessage("Ответ от GPT-4-Turbo: " . substr($response, 0, 1000));
|
||
return $response_data;
|
||
}
|
||
|
||
|
||
// Функция обработки PDF-файлов
|
||
function processPDFFiles() {
|
||
logMessage("Запуск обработки PDF-файлов...");
|
||
|
||
if (!shell_exec("which pdftotext")) {
|
||
logMessage("Ошибка: pdftotext не установлен.");
|
||
return json_encode(["error" => "pdftotext не найден"]);
|
||
}
|
||
|
||
$files = glob(SCAN_DIR . '/*.pdf');
|
||
if (empty($files)) {
|
||
logMessage("Нет файлов для обработки.");
|
||
return json_encode(["error" => "Нет файлов в директории " . SCAN_DIR]);
|
||
}
|
||
|
||
$documentAnalysis = [];
|
||
foreach ($files as $pdfFile) {
|
||
logMessage("Обрабатываем PDF: $pdfFile");
|
||
|
||
$text = shell_exec("pdftotext -layout " . escapeshellarg($pdfFile) . " -");
|
||
if ($text === null) {
|
||
logMessage("Ошибка: pdftotext не смог обработать файл $pdfFile.");
|
||
continue;
|
||
}
|
||
|
||
if (empty(trim($text))) {
|
||
logMessage("Файл $pdfFile содержит только изображения или пуст.");
|
||
$documentAnalysis[] = ["file" => basename($pdfFile), "error" => "Файл содержит только изображения."];
|
||
continue;
|
||
}
|
||
|
||
logMessage("Текст успешно извлечен, отправляем в GPT-4-Turbo.");
|
||
$gptAnalysis = AnalyzeTextWithGPT($text, $documentAnalysis, basename($pdfFile));
|
||
|
||
if (!$gptAnalysis) {
|
||
logMessage("Ошибка: GPT-4-Turbo не вернул ответ.");
|
||
$documentAnalysis[] = ["file" => basename($pdfFile), "error" => "GPT-4-Turbo не ответил"];
|
||
continue;
|
||
}
|
||
|
||
$documentAnalysis[] = ["file" => basename($pdfFile), "analysis" => $gptAnalysis];
|
||
}
|
||
|
||
logMessage("Обработка всех файлов завершена.");
|
||
return json_encode(["status" => "complete", "results" => $documentAnalysis], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
|
||
}
|
||
|
||
// Запуск обработки
|
||
echo processPDFFiles();
|
||
|
||
?>
|