[+] добавлен Phinx и миграции

[-] удалены мусорные файлы
[*] скорректирован composer.json
This commit is contained in:
rsgrinko committed 2023-04-05 22:46:51 +03:00
1 parent 24bb9a6830
commit cde08cff9b
33 files changed
+1011 -1983

No files matched your search

-203
View File
@@ -1,203 +0,0 @@
<?php
/**
* Copyright (c) 2022 Roman Grinko <rsgrinko@gmail.com>
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Core\Helpers;
use Core\CoreException;
class Ascii
{
/**
* @var \GdImage Изображение
*/
private $image;
/**
* @var string $file Полный путь до изображения
*/
private string $file;
/**
* @var int $pixelSize Размер пикселя
*/
private int $pixelSize = 1;
/**
* @var int $quality Качество
*/
private int $quality = 1;
/**
* @var bool $isUseColor Флаг использования цвета
*/
public bool $isUseColor = false;
/**
* @var array|string[] $chars Массив символов для рисования
*/
public array $chars = ['@', '#', '+', '\'', ';', ':', ',', '.', '`', ' '];
/**
* @var string $colorChar Символ для цветного рисования
*/
public string $colorChar = '#';
/**
* Конструктор
*
* @param string $file Полный путь к изображению
*
* @throws CoreException
*/
public function __construct(string $file)
{
$this->file = $file;
if (!file_exists($file)) {
throw new CoreException('Изображение ' . $this->file . ' недоступно.');
}
switch (exif_imagetype($file)) {
case IMAGETYPE_GIF:
$this->image = imagecreatefromgif($this->file);
break;
case IMAGETYPE_JPEG:
$this->image = imagecreatefromjpeg($this->file);
break;
case IMAGETYPE_PNG:
$this->image = imagecreatefrompng($this->file);
break;
case IMAGETYPE_WBMP:
$this->image = imagecreatefromwbmp($this->file);
break;
case IMAGETYPE_XBM:
$this->image = imagecreatefromxbm($this->file);
break;
default:
throw new CoreException('Неподдерживаемый формат изображения.');
break;
}
}
/**
* Установка размера пикселя
*
* @param int $size Размер пикселя
*
* @return $this
*/
public function setPixelSize(int $size): self
{
$this->pixelSize = $size;
return $this;
}
/**
* Установка флага Цветного/ЧБ изображения
*
* @param bool $isUseColor Флаг использования цвета
*
* @return $this
*/
public function setUseColor(bool $isUseColor = true): self
{
$this->isUseColor = $isUseColor;
return $this;
}
/**
* Получение ASCII изображения
*
* @return string ASCII изображение
*/
public function draw(): string
{
$width = imagesx($this->image);
$height = imagesy($this->image);
if ($this->isUseColor === true) {
$pixel_color = imagecolorat($this->image, 1, 1);
$rgb = imagecolorsforindex($this->image, $pixel_color);
$output = '<span style="color: ' . $this->rgbToHex($rgb['red'], $rgb['green'], $rgb['blue']) . ';">';
} else {
$output = '';
}
for ($y = 0; $y < $height; $y += $this->quality) {
for ($x = 0; $x < $width; $x += $this->quality) {
$pixel_color = imagecolorat($this->image, $x, $y);
$rgb = imagecolorsforindex($this->image, $pixel_color);
if ($this->isUseColor === true) {
if ($x > $this->quality && $y > $this->quality && $pixel_color === imagecolorat($this->image, $x - $this->quality, $y)) {
$char = $this->colorChar;
} else {
$char = '</span><span style="color: ' . $this->rgbToHex($rgb['red'], $rgb['green'], $rgb['blue']) . ';">'
. $this->colorChar;
}
} else {
$brightness = $rgb['red'] + $rgb['green'] + $rgb['blue'];
$brightness = round($brightness / (765 / (count($this->chars) - 1)));
$char = $this->chars[$brightness];
}
$output .= $char;
}
$output .= PHP_EOL;
}
if ($this->isUseColor === true) {
$output .= '</span>';
}
$result = '<pre style="font: ' . $this->pixelSize * 2 . 'px/' . $this->pixelSize . 'px monospace;">';
$result .= $output;
$result .= '</pre>';
return $result;
}
/**
* Преобразование цвета из RDB в HEX
*
* @param int $red Красный
* @param int $green Зеленый
* @param int $blue Синий
*
* @return string Цвет в HEX
*/
private function rgbToHex(int $red, int $green, int $blue): string
{
$hex = '#';
$hex .= str_pad(dechex($red), 2, '0', STR_PAD_LEFT);
$hex .= str_pad(dechex($green), 2, '0', STR_PAD_LEFT);
$hex .= str_pad(dechex($blue), 2, '0', STR_PAD_LEFT);
return $hex;
}
/**
* Деструктор
*/
public function __destruct()
{
imagedestroy($this->image);
}
}
-118
View File
@@ -1,118 +0,0 @@
<?php
/**
* Copyright (c) 2022 Roman Grinko <rsgrinko@gmail.com>
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Core\Helpers;
class Crypto
{
/**
* @var string|null $key Ключ шифрования
*/
private $key = CRYPTO_KEY;
/**
* @var string $method Метод шифрования
*/
private $method = 'AES-192-CBC';
/**
* @var string $algorithm Алгоритм
*/
private $algorithm = 'sha256';
/**
* Конструктор
*/
public function __construct()
{
}
/**
* Деструктор
*/
public function __destruct()
{
unset($this->key);
unset($this->method);
}
/**
* Генерация ключа шифрования
*
* @return string Ключ
*/
public static function generateKey(): string
{
return bin2hex(openssl_random_pseudo_bytes(40));
}
/**
* @param string $key
*
* @return Crypto
*/
public function setKey(string $key): self
{
$this->key = $key;
return $this;
}
/**
* Шифрование данных
*
* @param string $string Строка
*
* @return string
*/
public function encode(string $string): string
{
$ivLength = openssl_cipher_iv_length($this->method);
$iv = openssl_random_pseudo_bytes($ivLength);
$cipherTextRaw = openssl_encrypt($string, $this->method, $this->key, OPENSSL_RAW_DATA, $iv);
$hmac = hash_hmac($this->algorithm, $cipherTextRaw, $this->key, true);
$cipherText = base64_encode($iv . $hmac . $cipherTextRaw);
return $cipherText;
}
/**
* Расшифровка данных
*
* @param string $string Зашифрованная строка
*
* @return string|null
*/
public function decode(string $string): ?string
{
$c = base64_decode($string);
$ivLength = openssl_cipher_iv_length($this->method);
$iv = substr($c, 0, $ivLength);
$hmac = substr($c, $ivLength, $sha2len = 32);
$cipherTextRaw = substr($c, $ivLength + $sha2len);
$result = openssl_decrypt($cipherTextRaw, $this->method, $this->key, OPENSSL_RAW_DATA, $iv);
$calcMac = hash_hmac($this->algorithm, $cipherTextRaw, $this->key, true);
if (hash_equals($hmac, $calcMac)) {
return $result;
}
return null;
}
}
-209
View File
@@ -1,209 +0,0 @@
<?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
@@ -1,39 +0,0 @@
<?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
@@ -1,97 +0,0 @@
<?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;
}
}