Files
crm.clientright.ru/include/utils/GPT2.php

190 lines
6.7 KiB
PHP
Raw Normal View History

<?php
/*********************************************************************************
* Набор методов для работы с Yandex GPT и ChatGPT через прокладку proxyapi.ru
* All Rights Reserved.
* Contributor(s): Илья Руденко itsaturn@yandex.ru
********************************************************************************/
require_once 'include/utils/utils.php';
function VerbTransfer($list) {
$body = '{
"modelUri": "gpt://b1gvol62rds4n2e5gnm3/yandexgpt-lite",
"completionOptions": {
"stream": false,
"temperature": 0.01,
"maxTokens": 1000
},
"messages": [
{
"role": "system",
"text": "Перепиши фразы, изменив глаголы во второе лицо множественное число, настоящее время"
},
{
"role": "user",
"text": "'.$list.'"
}
]
}';
$logstring = date('Y-m-d H:i:s').' Тело запроса:'.PHP_EOL.$body.PHP_EOL;
file_put_contents('logs/GPT.log', $logstring, FILE_APPEND);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://llm.api.cloud.yandex.net/foundationModels/v1/completion',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $body,
CURLOPT_HTTPHEADER => array(
'Authorization: '.$apikey,
'x-folder-id: b1gvol62rds4n2e5gnm3',
'Content-Type: application/json'),
));
$response = curl_exec($curl);
$response = str_replace('\n', '', $response);
$logstring = date('Y-m-d H:i:s').' Ответ от нейросети:'.PHP_EOL.$response.PHP_EOL;
file_put_contents('logs/GPT.log', $logstring, FILE_APPEND);
curl_close($curl);
$response = json_decode($response, true);
$output = $response['result']['alternatives'][0]['message']['text'];
return $output;
}
function ChangeFlithy($text) {
$output = SendRequest('Замени в тексте матерные слова и выражения звездочками. От себя ничего не добавляний и никакой редактуры не делай - никакого креатива! Только замена мата на звездочки', $text);
return $output;
}
function CheckFlithy($text) {
$output = SendRequest('Проверь текст. Если найдешь в нем матерные слова и выражения - верни 1. Если нет - верни 0', $text);
return $output;
}
function SendRequest($task, $text) {
$text = str_replace(array("\r\n", "\n", "\r"), " ", $text);
$body = '{"model": "gpt-3.5-turbo","messages": [{"role": "system","content": "'.$task.'"},{"role": "user","content": "'.$text.'"}],"temperature": 0.01}';
$logstring = date('Y-m-d H:i:s').' Тело запроса:'.PHP_EOL.$body.PHP_EOL;
file_put_contents('logs/GPT.log', $logstring, FILE_APPEND);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.proxyapi.ru/openai/v1/chat/completions',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $body,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'Authorization: Bearer sk-GS24OxHQYfq8ErW5CRLoN5F1CfJPxNsY'
),
));
$response = curl_exec($curl);
$logstring = date('Y-m-d H:i:s').' Ответ от нейросети:'.PHP_EOL.$response.PHP_EOL;
file_put_contents('logs/GPT.log', $logstring, FILE_APPEND);
if ($response == 'Internal Server Error') {
sleep(10);
$response = curl_exec($curl);
$logstring = date('Y-m-d H:i:s').' Ответ от нейросети:'.PHP_EOL.$response.PHP_EOL;
file_put_contents('logs/GPT.log', $logstring, FILE_APPEND);
}
curl_close($curl);
$response = json_decode($response, true);
$output = $response['choices'][0]['message']['content'];
return $output;
}
function CheckPDF($PDFFile) {
$files = pdf2jpg($PDFFile); // Разобрали PDF на набор JPG-ов
$result = [];
$result['status'] = true;
$page = 1;
foreach ($files as $jpg) {
//echo $jpg.'<br>';
$link = 'https://crm.clientright.ru/tmp/'.basename($jpg);
$found = AnalyzeImage('Проанализируй содержимое и определи - есть в нем матерные слова и выражения в любых склонениях? Ответ представь одной цифрой без дополнительных комментариев - при наличии матерных слов верни 1, при отсутствии верни 0', $link);
if ($found) {
if ($result['status'] == true) { // нашли первое нарушение в файле
$result['pages'] = []; // создадим массив со списком страниц с нарушениями
$result['status'] = false;
}
$result['pages'][] = $page;
}
unlink($jpg); // Удаляем файл, он нам больше не нужен
$page++;
}
return $result;
}
function AnalyzeImage($task, $image) {
$body = '{"model": "gpt-4-vision-preview","messages": [{"role": "user","content": [{"type": "text","text": "'.$task.'"},{"type": "image_url","image_url": {"url": "'.$image.'"}}]}],"max_tokens": 300}';
$logstring = date('Y-m-d H:i:s').' Тело запроса:'.PHP_EOL.$body.PHP_EOL;
file_put_contents('logs/GPT.log', $logstring, FILE_APPEND);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.proxyapi.ru/openai/v1/chat/completions',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $body,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'Authorization: Bearer sk-GS24OxHQYfq8ErW5CRLoN5F1CfJPxNsY'
),
));
$response = curl_exec($curl);
$logstring = date('Y-m-d H:i:s').' Ответ от нейросети:'.PHP_EOL.$response.PHP_EOL;
file_put_contents('logs/GPT.log', $logstring, FILE_APPEND);
if ($response == 'Internal Server Error') {
sleep(10);
$response = curl_exec($curl);
$logstring = date('Y-m-d H:i:s').' Ответ от нейросети:'.PHP_EOL.$response.PHP_EOL;
file_put_contents('logs/GPT.log', $logstring, FILE_APPEND);
}
curl_close($curl);
$response = json_decode($response, true);
$result = $response['choices'][0]['message']['content'];
if ($result == '0') {
$output = false;
} else {
$output = true;
}
return $output;
}
?>