[*] добавил классы ML. промежуточная фиксация

This commit is contained in:
rsgrinko committed 2023-04-05 15:49:38 +03:00
1 parent 43861e52ab
commit 059aebe4e2
10 files changed
+432 -232

No files matched your search

+1 -1
View File
@@ -14,7 +14,7 @@ build-job: # This job runs in the build stage, which runs first.
- composer install
- echo "Compile complete."
- echo "Running Unit-tests..."
- ./vendor/bin/phpunit tests
- ./vendor/bin/phpunit --testdox tests
unit-test-job: # This job runs in the test stage.
stage: test # It only starts when the job in the build stage completes successfully.
+1 -1
View File
@@ -77,7 +77,7 @@
/**
* Параметры SQL базы
*/
const DB_HOST = 'localhost';
const DB_HOST = 'dev.it-stories.ru';//'localhost';
const DB_USER = 'rsgrinko_delta';
const DB_PASSWORD = '2670135';
const DB_NAME = 'rsgrinko_delta';
@@ -0,0 +1,59 @@
<?php
namespace Core\ExternalServices;
class ChatGPT
{
private string $token;
private const BASE_URL = 'https://api.openai.com/v1/chat/completions';
public function __construct(string $token = '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')
{
$this->token = $token;
}
public function ask(string $question, $context = [])
{
$url = 'https://api.openai.com/v1/chat/completions';
$headers = [
'Authorization: Bearer ' .$this->token,
//"OpenAI-Organization: YOUR-Organization-ID",
'Content-Type: application/json',
];
// Define messages
$messages = [];
$messages[] = ['role' => 'user', 'content' => $question];
$messages = array_merge($context, $messages);
$data = [
'model' => 'gpt-3.5-turbo',
'messages' => $messages,
'max_tokens' => 1600,
'temperature' => 0.5,
];
// init curl
$curl = curl_init(self::BASE_URL);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);//
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
$error = curl_errno($curl);
curl_close($curl);
if ($error) {
return 'Error:' . $error;
}
return json_decode($result,true);
}
}
@@ -345,6 +345,7 @@
} else {
$this->eventType = null;
}
$this->setChat($this->eventChatId);
}
return $this;
}
@@ -360,6 +361,7 @@
}
/**
* Получение конкретного типа
*
@@ -370,6 +372,16 @@
return $this->messageType;
}
/**
* Получение сообщения, полученного от пользователя
*
* @return string|null
*/
public function getMessage(): ?string
{
return $this->event['message'];
}
/**
* Получить собранные данные по текущему событию
*
@@ -231,15 +231,18 @@
*/
public static function __callStatic(string $name, ?array $arguments): void
{
$message = 'Команда ' . self::$cmd . ' не найдена.' . PHP_EOL;
/*$message = 'Команда ' . self::$cmd . ' не найдена.' . PHP_EOL;
if (!empty($arguments)) {
$message .= 'Аргументы: ' . implode(', ', $arguments) . PHP_EOL;
}
if (self::getEventType() !== 'callback') {
$message .= '<code>' . print_r(self::$data, true) . '</code>';
}
}*/
//ChatGPT connect...
$gptObject = new ChatGPT();
Telegram::sendChatAction(self::getChatId()); // печатает...
Telegram::execute(self::getChatId(), $message, '', self::getInlineKeyboard(), self::getKeyboard());
//Telegram::execute(self::getChatId(), $message, '', self::getInlineKeyboard(), self::getKeyboard());
Telegram::execute(self::getChatId(), htmlspecialchars($gptObject->ask($name)), '', self::getInlineKeyboard(), self::getKeyboard());
}
/**
@@ -390,222 +393,4 @@
self::getKeyboard()
);
}
/**
* Команда /online
*
* @return void
*/
public static function commandOnline(): void
{
Online::removeInactive();
$result = Online::getOnline();
$message = '<b>Посетители онлайн (' . count($result) . ')</b>' . PHP_EOL;
foreach ($result as $key => $item) {
$message .= '✔ <b>Пользователь #' . ($key + 1) . '</b> ' . PHP_EOL . '<b>IP:</b> ' . $item['ip'] . PHP_EOL . '<b>Страница:</b> <code>'
. $item['page'] . '</code>' . PHP_EOL . '<b>Referer:</b> <code>' . (!empty(
trim(
$item['referer']
)
) ? SystemFunctions::getBaseUrl($item['referer']) : 'нет') . '</code>' . PHP_EOL . '<b>Бот:</b> ' . (SystemFunctions::isSearchBot(
$item['useragent']
) ?? 'нет') . PHP_EOL . '<b>Последняя активность:</b> ' . SystemFunctions::secToString(time() - (int)$item['last_active'])
. PHP_EOL . '<b>Геозона:</b> ' . SystemFunctions::gluingLocationToString(
['country' => $item['country'], 'region' => $item['region'], 'city' => $item['city']]
) . PHP_EOL . PHP_EOL;
}
Telegram::sendChatAction(self::getChatId()); // печатает...
Telegram::execute(self::getChatId(), $message, '', self::getInlineKeyboard(), self::getKeyboard());
}
/**
* Команда /fail2ban
*
* @return void
*/
public static function commandFail2ban(): void
{
$result = Fail2ban::getBlockedIpList('10', 'last_active', 'DESC');
$message = '<b>Список заблокированных IP (' . Fail2ban::getBlockedIpCount() . ' из ' . Fail2ban::getAllIpCount() . ')</b>' . PHP_EOL;
foreach ($result as $key => $item) {
$message .= '🚩 <b> ' . $item['ip'] . '</b> ' . PHP_EOL . '<b>Попыток:</b> ' . $item['attempts'] . PHP_EOL . '<b>Активность:</b> '
. SystemFunctions::secToString(time() - $item['last_active']) . PHP_EOL . '<b>Геозона:</b> '
. SystemFunctions::gluingLocationToString(
['country' => $item['country'], 'region' => $item['region'], 'city' => $item['city']]
) . PHP_EOL . PHP_EOL;
}
Telegram::sendChatAction(self::getChatId()); // печатает...
Telegram::execute(self::getChatId(), $message, '', self::getInlineKeyboard(), self::getKeyboard());
}
/**
* Команда /deploy
*
* @return void
*/
public static function commandDeploy(): void
{
SystemFunctions::deploymentFromGit();
Telegram::sendChatAction(self::getChatId()); // печатает...
Telegram::execute(self::getChatId(), 'Произведен деплоймент из ветки <b>master</b>', '', self::getInlineKeyboard(), self::getKeyboard());
}
/**
* Команда /stat
*
* @return void
*/
public static function commandStat(): void
{
self::setInlineKeyboard(
[
[
['text' => 'Очистка кэша', 'callback_data' => self::getPreparedCallbackData('clearcache')],
['text' => 'Сброс Opcache', 'callback_data' => self::getPreparedCallbackData('clearopcache')],
],
]
);
$countCacheElements = \FCCache::getCountElements();
$cacheSize = \FCCache::getCacheSize();
$usersOnline = Online::getOnlineCount();
$countBlockedIp = Fail2ban::getBlockedIpCount();
$countAllIp = Fail2ban::getAllIpCount();
$arOpcache = opcache_get_status();
$message = '📱 <b>Статистика по проекту</b>' . PHP_EOL . '<b>В кэше:</b> ' . $countCacheElements . ' ' . SystemFunctions::numWord(
$countCacheElements,
['элемент', 'элемента', 'элементов']
) . PHP_EOL . '<b>Размер кэша:</b> ' . SystemFunctions::convertBytes($cacheSize) . PHP_EOL . '<b>В Opcache:</b> '
. $arOpcache['opcache_statistics']['num_cached_scripts'] . ' ' . SystemFunctions::numWord(
$arOpcache['opcache_statistics']['num_cached_scripts'],
['элемент', 'элемента', 'элементов']
) . PHP_EOL . '<b>Opcache (используется):</b> ' . SystemFunctions::convertBytes($arOpcache['memory_usage']['used_memory']) . PHP_EOL
. '<b>Opcache (свободно):</b> ' . SystemFunctions::convertBytes($arOpcache['memory_usage']['free_memory']) . PHP_EOL
. '<b>Opcache (битая):</b> ' . SystemFunctions::convertBytes($arOpcache['memory_usage']['wasted_memory']) . PHP_EOL
. '<b>Opcache (всего):</b> 512Mb' . PHP_EOL . '<b>Онлайн на сайте:</b> ' . $usersOnline . ' ' . SystemFunctions::numWord(
$usersOnline,
['посетитель', 'посетителя', 'посетителей']
) . PHP_EOL . '<b>Заблокировано:</b> ' . $countBlockedIp . ' ' . SystemFunctions::numWord(
$countBlockedIp,
['адрес', 'адреса', 'адресов']
) . ' из ' . $countAllIp;
Telegram::sendChatAction(self::getChatId()); // печатает...
Telegram::execute(self::getChatId(), $message, '', self::getInlineKeyboard(), self::getKeyboard());
}
/**
* Команда /yastat
*
* @return void
*/
public static function commandYaStat(): void
{
$objectYandex = new Yandex(
YANDEX_APP_ID, YANDEX_APP_SECRET, YANDEX_REDIRECT_URL
);
$objectYandex->loadConfig()->refreshToken();
$objectYandex->save();
$query = [
'oauth_token' => $objectYandex->getAccessToken(),
'dimension_field' => 'date|day',
'period' => 'thisyear',
'entity_field' => 'page_level',
'field' => 'partner_wo_nds',
'lang' => 'ru',
'pretty' => '0',
];
$result = $objectYandex->request(
'partner2.yandex.ru',
'api/statistics2/get.json',
$query
);
$day_price = [];
foreach ($result['data']['points'] as $k => $item) {
$day = date("d") - 1;
if ($day == 0) {
$day = 1;
} elseif ($day < 9) {
$day = '0' . $day;
}
if ($item['dimensions']['date'][0] == date("Y-m-") . $day) {
$day_price['yesterday'] = $item['measures'][0]['partner_wo_nds'];
}
if ($item['dimensions']['date'][0] == date("Y-m-d")) {
$day_price['today'] = $item['measures'][0]['partner_wo_nds'];
}
}
$day_price['today'] = $day_price['today'] ?? '0';
$day_price['yesterday'] = $day_price['yesterday'] ?? '0';
$message = '<b>Статистика РСЯ</b>' . PHP_EOL . 'Доход за сегодня: ' . $day_price['today'] . ' р.' . PHP_EOL . 'Доход за вчера: '
. $day_price['yesterday'] . ' р.' . PHP_EOL . 'Курс доллара: ' . SystemFunctions::getExchangeRates('USD', 2) . ' р.';
Telegram::sendChatAction(self::getChatId()); // печатает...
Telegram::execute(self::getChatId(), $message, '', self::getInlineKeyboard(), self::getKeyboard());
}
/**
* Команда /getcam
*
* @return void
*/
public static function commandGetCam(): void
{
$image = SystemFunctions::getCamScreen();
Telegram::sendChatAction(self::getChatId()); // печатает...
Telegram::execute(
self::getChatId(),
'Снимок сделан ' . date('d.m.Y H:i:s', strtotime('+3 hours')),
$image,
self::getInlineKeyboard(),
self::getKeyboard()
);
}
/**
* Команда /clearcache
*
* @return void
*/
public static function commandClearCache(): void
{
opcache_reset();
$cacheSize = SystemFunctions::convertBytes(\FCCache::getCacheSize());
\FCCache::clearCache();
Telegram::sendChatAction(self::getChatId()); // печатает...
Telegram::execute(self::getChatId(), 'Кэш очищен. Удалено ' . $cacheSize, '', self::getInlineKeyboard(), self::getKeyboard());
}
/**
* Callback очистка кэша
*
* @return void
*/
public static function callbackClearcache(): void
{
$cacheSize = SystemFunctions::convertBytes(\FCCache::getCacheSize());
\FCCache::clearCache();
Telegram::answerCallbackQuery(self::getEventData()['callback_id'], 'Файловый кэш очищен. Удалено ' . $cacheSize, true);
}
/**
* Callback очистка Opcache
*
* @return void
*/
public static function callbackClearOpcache(): void
{
opcache_reset();
Telegram::answerCallbackQuery(self::getEventData()['callback_id'], 'Opcache очищен.', false);
}
}
+209
View File
@@ -0,0 +1,209 @@
<?php
namespace Core\ML;
class NeuroNetwork
{
/** @var string $storageFile Файл-хранилище весов */
private $storageFile;
/** @var array $arValues Файл-хранилище весов */
private $arValues;
/**
* @var array $layers Массив массивов нейронов
* [
* [], // Входной слой
* [], // Скрытый слой
* [], // Выходной слой
* ];
*/
private array $layers;
/** @var array Массив синапсов */
private array $synapses;
/**
* Конструктор
*/
public function __construct(?string $storageFile = null)
{
// Хранилище весов
if ($storageFile === null) {
$this->storageFile = $_SERVER['DOCUMENT_ROOT'] . '/neuroSynaps.json';
} else {
$this->storageFile = $storageFile;
}
// Слои нейросети
$this->layers = [
[new Neuron(1), new Neuron(2)],
[new Neuron(3), new Neuron(4), new Neuron(5), new Neuron(6)],
[new Neuron(7)],
];
/** Строим связи нейронов */
$this->generateSynapses();
/*$this->synaps = [
new Synaps($this->layers[0][0], $this->layers[1][0]),
new Synaps($this->layers[0][0], $this->layers[1][1]),
new Synaps($this->layers[0][0], $this->layers[1][2]),
new Synaps($this->layers[0][0], $this->layers[1][3]),
new Synaps($this->layers[0][1], $this->layers[1][0]),
new Synaps($this->layers[0][1], $this->layers[1][1]),
new Synaps($this->layers[0][1], $this->layers[1][2]),
new Synaps($this->layers[0][1], $this->layers[1][3]),
new Synaps($this->layers[1][0], $this->layers[2][0]),
new Synaps($this->layers[1][0], $this->layers[2][1]),
new Synaps($this->layers[1][1], $this->layers[2][0]),
new Synaps($this->layers[1][1], $this->layers[2][1]),
new Synaps($this->layers[1][2], $this->layers[2][0]),
new Synaps($this->layers[1][2], $this->layers[2][1]),
new Synaps($this->layers[1][3], $this->layers[2][0]),
new Synaps($this->layers[1][3], $this->layers[2][1]),
];*/
// Получение сохраненных данных по весам
$this->getSynapsValue();
}
/**
* Генерируем связи между нейронами
*/
private function generateSynapses(): void
{
$synapsId = 1;
$layersCount = count($this->layers);
// Бежим по слоям нейронов (последний нам не нужен) и строим связи
for ($i = 0; $i < $layersCount - 1; $i++) {
$neuronCount = count($this->layers[$i + 1]);
for ($j = 0; $j < $neuronCount; $j++) {
$neuronInCount = count($this->layers[$i]);
for ($k = 0; $k < $neuronInCount; $k++) {
$this->synapses[] = new Synaps(
$synapsId, $this->layers[$i][$k], $this->layers[$i + 1][$j], $this->arValues[$synapsId] ?? null
);
$synapsId++;
}
}
}
}
/**
* Сохранить значения весов синапсов в файл
*
* @param bool $forceUpdate Принудительно перезаписать
*/
private function saveSynapsValue(bool $forceUpdate= false): void
{
$data = [];
foreach ($this->synapses as $synapse) {
/** @var Synaps $synapse */
$data[$synapse->getId()] = $synapse->getValue();
}
if ($forceUpdate || !file_exists($this->storageFile)) {
echo 'SAVED FILE' . PHP_EOL;
file_put_contents($this->storageFile, json_encode($data, JSON_UNESCAPED_UNICODE));
}
}
/**
* Получить значения весов синапсов из файла
*
* @return array Сохраненный раннее массив весов
*/
private function getSynapsValue(): array
{
if (!file_exists($this->storageFile)) {
return [];
}
// Получаем массив весов
$synapsValues = json_decode(file_get_contents($this->storageFile), true);
// Устанавливаем веса для синапсов
foreach ($this->synapses as $synapse) {
/** @var Synaps $synapse */
$synapse->setValue($synapsValues[$synapse->getId()]);
}
$this->arValues = $synapsValues;
// Возвращаем веса
return $synapsValues;
}
/**
* Мутация веса
*
* @param float|null $shift Величина сдвига для мутации
*
* @throws \Exception
*/
public function mutate(?float $shift = 0.1): self
{
foreach ($this->synapses as $synapse) {
/** @var Synaps $synapse */
$tempValue = random_int((int)(($synapse->getValue() - $shift) * 100), (int)(($synapse->getValue() + $shift) * 100)) / 100;
// Ограничиваемся диапазоном 0..1
if ($tempValue < 0) {
$tempValue = 0;
}
if ($tempValue > 1) {
$tempValue = 1;
}
$synapse->setValue($tempValue);
}
$this->saveSynapsValue(true);
return $this;
}
/**
* Запуск обработки
*/
public function run(array $arValue): array
{
foreach ($arValue as $key => $value) {
$this->layers[0][$key]->setValue($value);
}
foreach ($this->synapses as $synapse) {
$this->step($synapse);
}
$result = [];
// Отдаем значения нейронов последнего слоя как результат
foreach ($this->layers[2] as $neuron) {
$result[] = $neuron->getValue();
}
$this->saveSynapsValue();
return $result;
//return [$this->layers[2][0]->getValue(), $this->layers[2][1]->getValue()];
}
/**
* Шаг преобразования значений между нейронами
*/
public function step(Synaps $synaps): void
{
/*
// Умножение значения на коэфициент
$synaps->getOutNeuron()->setValue(
$synaps->getInNeuron()->getValue() * $synaps->getValue()
);*/
// Гиперболический тангенс
// https://otus.ru/journal/kak-sozdat-nejroset/
// Функция активации
$synaps->getOutNeuron()->setValue(
tanh($synaps->getInNeuron()->getValue() * $synaps->getValue())
);
}
}
+39
View File
@@ -0,0 +1,39 @@
<?php
namespace Core\ML;
/**
* Класс нейрона
*/
class Neuron
{
/** @var int Идентификатор нейрона */
private int $id;
/** @var float|null Текущее значение */
private ?float $value;
/**
* Конструктор
*
* @param int $id Идентификатор нейрона
*/
public function __construct(int $id)
{
$this->id = $id;
}
/** Получить текущее значение */
public function getValue(): ?float
{
return $this->value;
}
/** Задать текущее значение */
public function setValue(float $value): self
{
$this->value = $value;
return $this;
}
}
+97
View File
@@ -0,0 +1,97 @@
<?php
namespace Core\ML;
/**
* Класс синапса
* является связующим звеном между нейронами
*/
class Synaps
{
/** @var int Идентификатор синапса */
private $id;
/** @var float Вес */
private $value;
/** @var Neuron Входной нейрон */
private Neuron $inNeuron;
/** @var Neuron Выходной нейрон */
private Neuron $outNeuron;
/**
* Конструктор
*
* @param int $id Идентификатор синапса
* @param Neuron $inNeuron Входной нейрон
* @param Neuron $outNeuron Выходной нейрон
* @param float|null $value Значение веса синапса
*
* @throws \Exception
*/
public function __construct(int $id, Neuron $inNeuron, Neuron $outNeuron, float $value = null)
{
$this->inNeuron = $inNeuron;
$this->outNeuron = $outNeuron;
// если мы хотим явно задать вес - задаем, иначе генерируем как-нибудь
if ($value !== null) {
$this->value = $value;
} else {
$this->value = random_int(0, 100) / 100;
}
$this->id = $id;
}
/** Получить id синапса */
public function getId(): int
{
return $this->id;
}
/**
* Получение входящего нейрона
*
* @return Neuron
*/
public function getInNeuron(): Neuron
{
return $this->inNeuron;
}
/**
* Получение выходящего нейрона
*
* @return Neuron
*/
public function getOutNeuron(): Neuron
{
return $this->outNeuron;
}
/**
* Получить вес
*
* @return float Вес
*/
public function getValue(): ?float
{
return $this->value;
}
/**
* Установить вес
*
* @param float $value Вес
* @return $this
*/
public function setValue(float $value): self
{
$this->value = $value;
return $this;
}
}
+7 -3
View File
@@ -2,12 +2,13 @@
use Core\CoreException;
use Core\ExternalServices\Telegram2;
use Core\ExternalServices\ChatGPT;
require_once __DIR__ . '/core/bootstrap.php';
$data = file_get_contents('php://input');
if(empty($data)) {
die('Данные не получены');
//die('Данные не получены');
}
$data = json_decode($data, true);
@@ -15,7 +16,10 @@
$tg = new Telegram2(TELEGRAM_BOT_TOKEN);
$tg->setRemoteRequest($data);
$gptObject = new ChatGPT();
$response = $gptObject->ask($tg->getMessage())['choices'][0]['message']['content'];
$response = htmlspecialchars($response);
$tg->sendMessage($response);
//$res = $tg->setChat(TELEGRAM_ADMIN_CHAT_ID)->updateMessage(121, '');
//sendTelegram(print_r($data, true));
+1 -6
View File
@@ -9,12 +9,7 @@
{
public function testGetAllUserData(): void
{
$testClassMock = $this->getMockBuilder(TestClass::class)->setMethodsExcept(['getAllUserData'])->getMock();
//->getMockBuilder(TestClass::class)
//->setConstructorArgs([1])
//->getMock();
$this->assertTrue(method_exists($testClassMock, 'getAllUserData'), TestClass::class . '\getAllUserData() - метод не найден');
$this->assertTrue(0, 'Сообщение об ошибке');
}
}