добавил обновление списков в реальном времени
исправил поиск пользователя убрал лишние qDebug
This commit is contained in:
+27
-45
@@ -25,44 +25,27 @@ void CommandProcessor::setContext(const Context& context)
|
||||
|
||||
QString CommandProcessor::generateResponse(QString userIndex, const QString &command, const QString &message)
|
||||
{
|
||||
qDebug() << "generateResponse: userIndex =" << userIndex << "command =" << command;
|
||||
|
||||
// Сначала пробуем найти пользователя по displayName
|
||||
QString username = "";
|
||||
if (m_context.userManager) {
|
||||
User* user = m_context.userManager->findUser(userIndex);
|
||||
User* user = m_context.userManager->findUserById(userIndex);
|
||||
if (user) {
|
||||
username = user->displayName;
|
||||
qDebug() << "Найден пользователь:" << username;
|
||||
} else {
|
||||
qDebug() << "Пользователь не найден в UserManager по displayName:" << userIndex;
|
||||
|
||||
// Попробуем найти по ID
|
||||
user = m_context.userManager->findUserById(userIndex);
|
||||
if (user) {
|
||||
username = user->displayName;
|
||||
qDebug() << "Найден пользователь по ID:" << username;
|
||||
}
|
||||
username = user->displayName;
|
||||
}
|
||||
}
|
||||
|
||||
if (username.isEmpty()) {
|
||||
// Если не нашли в UserManager, используем переданное имя
|
||||
username = userIndex;
|
||||
qDebug() << "Используем переданное имя:" << username;
|
||||
}
|
||||
|
||||
Command cmd = findCommand(command);
|
||||
if (cmd.command.isEmpty()) {
|
||||
qDebug() << "Команда не найдена:" << command;
|
||||
return "";
|
||||
}
|
||||
|
||||
qDebug() << "Найдена команда:" << cmd.command << "ответ:" << cmd.response;
|
||||
|
||||
QString fullCommand = command + (message.isEmpty() ? "" : " " + message);
|
||||
QString result = processCommand(username, fullCommand, cmd.response);
|
||||
qDebug() << "Итоговый результат:" << result;
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -175,26 +158,18 @@ QString CommandProcessor::parseRandomNumbers(const QString &response)
|
||||
QRegularExpression regex("\\[\\[([^\\]]+)\\]\\]");
|
||||
QRegularExpressionMatchIterator matches = regex.globalMatch(response);
|
||||
|
||||
qDebug() << "parseRandomNumbers: исходная строка:" << response;
|
||||
qDebug() << "Найдено совпадений:" << matches.hasNext();
|
||||
|
||||
while (matches.hasNext()) {
|
||||
QRegularExpressionMatch match = matches.next();
|
||||
QString rangeName = match.captured(1);
|
||||
qDebug() << "Найден диапазон:" << rangeName;
|
||||
|
||||
if (m_context.randomManager) {
|
||||
int randomNumber = m_context.randomManager->getRandomValue(rangeName);
|
||||
qDebug() << "Получено случайное число:" << randomNumber << "для диапазона" << rangeName;
|
||||
result.replace("[[" + rangeName + "]]", QString::number(randomNumber));
|
||||
} else {
|
||||
qDebug() << "RandomManager не инициализирован!";
|
||||
int fallbackNumber = QRandomGenerator::global()->bounded(1, 101);
|
||||
result.replace("[[" + rangeName + "]]", QString::number(fallbackNumber));
|
||||
}
|
||||
}
|
||||
|
||||
qDebug() << "Результат после замены:" << result;
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -271,7 +246,6 @@ QString CommandProcessor::parseBan(const QString &response, const QString &sende
|
||||
if (m_context.twitchAPI) {
|
||||
if (m_context.userManager) {
|
||||
User* user = m_context.userManager->findUser(sender);
|
||||
qDebug() << user->displayName;
|
||||
if (user && !user->id.isEmpty()) {
|
||||
if (banSeconds > 0) {
|
||||
m_context.twitchAPI->banUserTime(user->id, banSeconds);
|
||||
@@ -487,7 +461,6 @@ QString CommandProcessor::getPeriodEnding(int n, int r)
|
||||
QString CommandProcessor::parseNeuralTemplates(const QString &response, const QString &sender, const QString ¶meters)
|
||||
{
|
||||
QString result = response;
|
||||
qDebug() << "parseNeuralTemplates: входная строка:" << response;
|
||||
|
||||
// Исправленное регулярное выражение
|
||||
QRegularExpression regex("<\\|([^<]+)<\\|");
|
||||
@@ -500,11 +473,9 @@ QString CommandProcessor::parseNeuralTemplates(const QString &response, const QS
|
||||
matchCount++;
|
||||
QRegularExpressionMatch match = matches.next();
|
||||
QString templateName = match.captured(1).trimmed();
|
||||
qDebug() << "Найден шаблон:" << templateName << "на позиции" << match.capturedStart();
|
||||
|
||||
if (m_context.neuralTemplateManager) {
|
||||
QString templateText = m_context.neuralTemplateManager->getTemplateText(templateName);
|
||||
qDebug() << "Текст шаблона:" << templateText;
|
||||
|
||||
if (!templateText.isEmpty()) {
|
||||
// Заменяем плейсхолдеры в шаблоне
|
||||
@@ -512,8 +483,6 @@ QString CommandProcessor::parseNeuralTemplates(const QString &response, const QS
|
||||
processedTemplate.replace("[TO]", parameters);
|
||||
processedTemplate.replace("[USERNAME]", sender);
|
||||
|
||||
qDebug() << "Шаблон после замены плейсхолдеров:" << processedTemplate;
|
||||
|
||||
// Получаем ответ от нейросети
|
||||
QString aiResponse;
|
||||
if (m_context.neuralManager) {
|
||||
@@ -539,7 +508,6 @@ QString CommandProcessor::parseNeuralTemplates(const QString &response, const QS
|
||||
});
|
||||
|
||||
// Отправляем запрос к нейросети
|
||||
qDebug() << "Отправляем запрос к нейросети:" << processedTemplate;
|
||||
m_context.neuralManager->sendMessage(processedTemplate);
|
||||
|
||||
// Таймаут 30 секунд
|
||||
@@ -551,16 +519,11 @@ QString CommandProcessor::parseNeuralTemplates(const QString &response, const QS
|
||||
|
||||
if (errorOccurred) {
|
||||
aiResponse = QString("Ошибка нейросети: %1").arg(errorMessage);
|
||||
qDebug() << "Ошибка нейросети:" << errorMessage;
|
||||
} else if (!responseReceived) {
|
||||
aiResponse = "Таймаут при ожидании ответа от нейросети";
|
||||
qDebug() << "Таймаут нейросети";
|
||||
} else {
|
||||
qDebug() << "Получен ответ от нейросети:" << aiResponse;
|
||||
}
|
||||
} else {
|
||||
aiResponse = "Нейросеть недоступна";
|
||||
qDebug() << "NeuralManager не доступен";
|
||||
}
|
||||
|
||||
// Заменяем шаблон на ответ от нейросети
|
||||
@@ -570,7 +533,6 @@ QString CommandProcessor::parseNeuralTemplates(const QString &response, const QS
|
||||
repl.text = aiResponse;
|
||||
replacements.append(repl);
|
||||
} else {
|
||||
qDebug() << "Шаблон не найден или пустой:" << templateName;
|
||||
// Если шаблон не найден, оставляем как есть или заменяем на заглушку
|
||||
Replacement repl;
|
||||
repl.start = match.capturedStart();
|
||||
@@ -579,7 +541,6 @@ QString CommandProcessor::parseNeuralTemplates(const QString &response, const QS
|
||||
replacements.append(repl);
|
||||
}
|
||||
} else {
|
||||
qDebug() << "NeuralTemplateManager не доступен";
|
||||
// Если менеджер не доступен, заменяем на заглушку
|
||||
Replacement repl;
|
||||
repl.start = match.capturedStart();
|
||||
@@ -589,8 +550,6 @@ QString CommandProcessor::parseNeuralTemplates(const QString &response, const QS
|
||||
}
|
||||
}
|
||||
|
||||
qDebug() << "Всего найдено шаблонов:" << matchCount;
|
||||
|
||||
// Выполняем замены с конца к началу
|
||||
std::sort(replacements.begin(), replacements.end(),
|
||||
[](const Replacement &a, const Replacement &b) {
|
||||
@@ -600,8 +559,31 @@ QString CommandProcessor::parseNeuralTemplates(const QString &response, const QS
|
||||
for (const auto &replacement : replacements) {
|
||||
result.replace(replacement.start, replacement.length, replacement.text);
|
||||
}
|
||||
|
||||
qDebug() << "parseNeuralTemplates: результат:" << result;
|
||||
return result;
|
||||
}
|
||||
|
||||
void CommandProcessor::editCommand(const QString &oldCommand,const QString &newCommand,const QString &response)
|
||||
{
|
||||
Command oldCom = findCommand(oldCommand);
|
||||
if (oldCom.command.isEmpty()) return;
|
||||
for (int i = 0; i < m_commands.size(); ++i) {
|
||||
if (m_commands[i].command.compare(oldCommand, Qt::CaseInsensitive) == 0) {
|
||||
// Обновляем команду
|
||||
m_commands[i].command = newCommand;
|
||||
m_commands[i].response = response;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void CommandProcessor::deleteCommand(const QString &commandName)
|
||||
{
|
||||
Command oldCom = findCommand(commandName);
|
||||
if (oldCom.command.isEmpty()) return;
|
||||
for (int i = 0; i < m_commands.size(); ++i) {
|
||||
if (m_commands[i].command.compare(commandName, Qt::CaseInsensitive) == 0) {
|
||||
m_commands.remove(i);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,6 +45,9 @@ public:
|
||||
QString generateResponse(QString userIndex, const QString &command, const QString &message = "");
|
||||
|
||||
void addCommand(const QString &command, const QString &response);
|
||||
void editCommand(const QString &oldCommand,const QString &newCommand,const QString &response);
|
||||
void deleteCommand(const QString &commandName);
|
||||
|
||||
void addCommands(const QVector<Command> &commands);
|
||||
void clearCommands();
|
||||
|
||||
|
||||
+185
-24
@@ -55,8 +55,39 @@ void FSingleGrid::toGrid(QString aName, QString aFile)
|
||||
|
||||
void FSingleGrid::on_btnAdd_clicked()
|
||||
{
|
||||
toGrid(ui->edtName->text(), ui->edtFileName->text());
|
||||
db->SaveTableWidget(ui->sg);
|
||||
QString name = ui->edtName->text().trimmed();
|
||||
QString filePath = ui->edtFileName->text().trimmed();
|
||||
|
||||
if (name.isEmpty()) {
|
||||
QMessageBox::warning(this, "Внимание", "Введите название!");
|
||||
return;
|
||||
}
|
||||
|
||||
if (filePath.isEmpty()) {
|
||||
QMessageBox::warning(this, "Внимание", "Введите путь к файлу!");
|
||||
return;
|
||||
}
|
||||
|
||||
// Добавляем в соответствующий менеджер
|
||||
if (!addToManager(name, filePath)) {
|
||||
QMessageBox::warning(this, "Ошибка",
|
||||
currentManagerType == TemplateManager ?
|
||||
"Не удалось добавить шаблон. Возможно, такое имя уже существует." :
|
||||
"Не удалось добавить файл. Возможно, такое имя уже существует.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Добавляем в таблицу
|
||||
toGrid(name, filePath);
|
||||
|
||||
// Сохраняем в БД
|
||||
if (db) {
|
||||
db->SaveTableWidget(ui->sg);
|
||||
}
|
||||
|
||||
// Очищаем поля
|
||||
ui->edtName->clear();
|
||||
ui->edtFileName->clear();
|
||||
}
|
||||
|
||||
void FSingleGrid::setDatabase(uDataBase *database)
|
||||
@@ -66,62 +97,90 @@ void FSingleGrid::setDatabase(uDataBase *database)
|
||||
|
||||
void FSingleGrid::on_btnDel_clicked()
|
||||
{
|
||||
// Проверяем, есть ли выделенная строка
|
||||
if (!ui->sg->currentItem()) {
|
||||
QMessageBox::warning(this, "Внимание", "Выберите строку для удаления!");
|
||||
return;
|
||||
}
|
||||
|
||||
// Получаем индекс выделенной строки
|
||||
int row = ui->sg->currentItem()->row();
|
||||
QString name = ui->sg->item(row, 0)->text();
|
||||
|
||||
// Удаляем строку
|
||||
// Удаляем из менеджера
|
||||
if (!removeFromManager(name)) {
|
||||
QMessageBox::warning(this, "Ошибка", "Не удалось удалить из менеджера!");
|
||||
return;
|
||||
}
|
||||
|
||||
// Удаляем строку из таблицы
|
||||
ui->sg->removeRow(row);
|
||||
db->SaveTableWidget(ui->sg);
|
||||
|
||||
// Сохраняем в БД
|
||||
if (db) {
|
||||
db->SaveTableWidget(ui->sg);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void FSingleGrid::on_btnEdt_clicked()
|
||||
{
|
||||
// Проверяем, есть ли выделенная строка
|
||||
if (!ui->sg->currentItem()) {
|
||||
QMessageBox::warning(this, "Внимание", "Выберите строку для редактирования!");
|
||||
return;
|
||||
}
|
||||
|
||||
// Получаем индекс выделенной строки
|
||||
int row = ui->sg->currentItem()->row();
|
||||
QString oldName = ui->sg->item(row, 0)->text();
|
||||
QString newName = ui->edtName->text().trimmed();
|
||||
QString newFilePath = ui->edtFileName->text().trimmed();
|
||||
|
||||
// Получаем данные из выбранной строки
|
||||
ui->sg->item(row, 0)->setText(ui->edtName->text());
|
||||
ui->sg->item(row, 1)->setText(ui->edtFileName->text());
|
||||
db->SaveTableWidget(ui->sg);
|
||||
if (newName.isEmpty()) {
|
||||
QMessageBox::warning(this, "Внимание", "Введите новое название!");
|
||||
return;
|
||||
}
|
||||
|
||||
if (newFilePath.isEmpty()) {
|
||||
QMessageBox::warning(this, "Внимание", "Введите новый путь к файлу!");
|
||||
return;
|
||||
}
|
||||
|
||||
// Обновляем в менеджере
|
||||
if (!updateInManager(oldName, newName, newFilePath)) {
|
||||
QMessageBox::warning(this, "Ошибка",
|
||||
currentManagerType == TemplateManager ?
|
||||
"Не удалось обновить шаблон. Возможно, новое имя уже существует." :
|
||||
"Не удалось обновить файл. Возможно, новое имя уже существует.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Обновляем в таблице
|
||||
ui->sg->item(row, 0)->setText(newName);
|
||||
ui->sg->item(row, 1)->setText(newFilePath);
|
||||
|
||||
// Сохраняем в БД
|
||||
if (db) {
|
||||
db->SaveTableWidget(ui->sg);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void FSingleGrid::on_btnOpen_clicked()
|
||||
{
|
||||
// Диалог выбора файла
|
||||
QString fileName = QFileDialog::getOpenFileName(
|
||||
this, // родительское окно
|
||||
"Выберите файл", // заголовок окна
|
||||
QDir::homePath(), // начальная директория
|
||||
"Все файлы (*.*);;" // фильтры файлов
|
||||
this,
|
||||
"Выберите файл",
|
||||
QDir::homePath(),
|
||||
"Все файлы (*.*);;"
|
||||
"Текстовые файлы (*.txt);;"
|
||||
"Аудио (*.mp3);;"
|
||||
"Приложения (*.exe *.bat *.cmd)"
|
||||
);
|
||||
|
||||
// Если файл выбран (не нажата кнопка "Отмена")
|
||||
if (!fileName.isEmpty()) {
|
||||
// Записываем путь к файлу в поле ввода
|
||||
ui->edtFileName->setText(fileName);
|
||||
|
||||
// Опционально: автоматически заполняем поле имени из названия файла
|
||||
if (ui->edtName->text().isEmpty()) {
|
||||
QFileInfo fileInfo(fileName);
|
||||
QString baseName = fileInfo.baseName(); // Имя файла без расширения
|
||||
ui->edtName->setText(baseName);
|
||||
ui->edtName->setText(fileInfo.baseName());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -129,8 +188,110 @@ void FSingleGrid::on_btnOpen_clicked()
|
||||
|
||||
void FSingleGrid::on_sg_cellClicked(int row, int column)
|
||||
{
|
||||
ui->edtName->setText(ui->sg->item(row,0)->text());
|
||||
ui->edtFileName->setText(ui->sg->item(row,1)->text());
|
||||
Q_UNUSED(column);
|
||||
|
||||
if (row >= 0 && row < ui->sg->rowCount()) {
|
||||
ui->edtName->setText(ui->sg->item(row, 0)->text());
|
||||
ui->edtFileName->setText(ui->sg->item(row, 1)->text());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void FSingleGrid::setSoundManager(MediaFileManager *manager)
|
||||
{
|
||||
soundManager = manager;
|
||||
currentManagerType = SoundManager;
|
||||
}
|
||||
|
||||
void FSingleGrid::setTextManager(MediaFileManager *manager)
|
||||
{
|
||||
textManager = manager;
|
||||
currentManagerType = TextManager;
|
||||
}
|
||||
|
||||
void FSingleGrid::setTemplateManager(NeuralTemplateManager *manager)
|
||||
{
|
||||
templateManager = manager;
|
||||
currentManagerType = TemplateManager;
|
||||
}
|
||||
|
||||
void FSingleGrid::setManagerType(ManagerType type)
|
||||
{
|
||||
currentManagerType = type;
|
||||
}
|
||||
|
||||
bool FSingleGrid::addToManager(const QString& name, const QString& filePath)
|
||||
{
|
||||
switch (currentManagerType) {
|
||||
case SoundManager:
|
||||
if (soundManager) {
|
||||
qDebug() << "добавляем ебаный звук";
|
||||
return soundManager->addFile(name, filePath);
|
||||
}
|
||||
break;
|
||||
case TextManager:
|
||||
if (textManager) {
|
||||
qDebug() << "добавляем ебаный текст";
|
||||
return textManager->addFile(name, filePath);
|
||||
}
|
||||
break;
|
||||
case TemplateManager:
|
||||
if (templateManager) {
|
||||
qDebug() << "добавляем ебаный шаблон";
|
||||
return templateManager->addTemplate(name, filePath);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
qDebug() << "добавляем ебаный нихуя";
|
||||
break;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool FSingleGrid::removeFromManager(const QString& name)
|
||||
{
|
||||
switch (currentManagerType) {
|
||||
case SoundManager:
|
||||
if (soundManager) {
|
||||
return soundManager->removeFile(name);
|
||||
}
|
||||
break;
|
||||
case TextManager:
|
||||
if (textManager) {
|
||||
return textManager->removeFile(name);
|
||||
}
|
||||
break;
|
||||
case TemplateManager:
|
||||
if (templateManager) {
|
||||
return templateManager->removeTemplate(name);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool FSingleGrid::updateInManager(const QString& oldName, const QString& newName, const QString& newFilePath)
|
||||
{
|
||||
switch (currentManagerType) {
|
||||
case SoundManager:
|
||||
if (soundManager) {
|
||||
return soundManager->updateFile(oldName, newName, newFilePath);
|
||||
}
|
||||
break;
|
||||
case TextManager:
|
||||
if (textManager) {
|
||||
return textManager->updateFile(oldName, newName, newFilePath);
|
||||
}
|
||||
break;
|
||||
case TemplateManager:
|
||||
if (templateManager) {
|
||||
return templateManager->updateTemplate(oldName, newName, newFilePath);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
|
||||
#include <QWidget>
|
||||
#include <QTableWidget>
|
||||
#include "mediafilemanager.h"
|
||||
#include "neuraltemplatemanager.h"
|
||||
#include "udatabase.h"
|
||||
|
||||
namespace Ui {
|
||||
@@ -14,12 +16,24 @@ class FSingleGrid : public QWidget
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
enum ManagerType {
|
||||
NoManager,
|
||||
SoundManager,
|
||||
TextManager,
|
||||
TemplateManager
|
||||
};
|
||||
explicit FSingleGrid(QWidget *parent = nullptr);
|
||||
~FSingleGrid();
|
||||
void initForm(QString aBlockName, QString aNewName, bool btnOpen = false);
|
||||
void toGrid(QString aName, QString aFile);
|
||||
QTableWidget* tableWidget() const;
|
||||
|
||||
void setDatabase(uDataBase *database);
|
||||
void setSoundManager(MediaFileManager *manager);
|
||||
void setTextManager(MediaFileManager *manager);
|
||||
void setTemplateManager(NeuralTemplateManager *manager);
|
||||
|
||||
void setManagerType(ManagerType type);
|
||||
private slots:
|
||||
void on_btnAdd_clicked();
|
||||
|
||||
@@ -34,6 +48,13 @@ private slots:
|
||||
private:
|
||||
Ui::FSingleGrid *ui;
|
||||
uDataBase *db = nullptr;
|
||||
ManagerType currentManagerType = NoManager;
|
||||
MediaFileManager *soundManager = nullptr;
|
||||
MediaFileManager *textManager = nullptr;
|
||||
NeuralTemplateManager *templateManager = nullptr;
|
||||
bool addToManager(const QString& name, const QString& filePath);
|
||||
bool removeFromManager(const QString& name);
|
||||
bool updateInManager(const QString& oldName, const QString& newName, const QString& newFilePath);
|
||||
};
|
||||
|
||||
#endif // FSINGLEGRID_H
|
||||
|
||||
@@ -8,6 +8,7 @@ MediaFileManager::MediaFileManager()
|
||||
|
||||
bool MediaFileManager::addFile(const QString& name, const QString& filePath)
|
||||
{
|
||||
qDebug() << "Добавляем ебаный файл";
|
||||
// Проверка на пустые значения
|
||||
if (name.isEmpty() || filePath.isEmpty()) {
|
||||
qWarning() << "Имя файла или путь не могут быть пустыми";
|
||||
@@ -99,3 +100,41 @@ int MediaFileManager::findFileIndex(const QString& name) const
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
bool MediaFileManager::renameFile(const QString& oldName, const QString& newName)
|
||||
{
|
||||
int index = findFileIndex(oldName);
|
||||
|
||||
if (index == -1) {
|
||||
qWarning() << "Файл с именем" << oldName << "не найден";
|
||||
return false;
|
||||
}
|
||||
|
||||
// Проверяем, не используется ли новое имя другим файлом
|
||||
if (oldName != newName && contains(newName)) {
|
||||
qWarning() << "Файл с именем" << newName << "уже существует";
|
||||
return false;
|
||||
}
|
||||
|
||||
QString oldPath = mediaFiles[index].filePath;
|
||||
mediaFiles[index].name = newName;
|
||||
|
||||
qDebug() << "Файл переименован:" << oldName << "->" << newName;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool MediaFileManager::updateFilePath(const QString& name, const QString& newFilePath)
|
||||
{
|
||||
int index = findFileIndex(name);
|
||||
|
||||
if (index == -1) {
|
||||
qWarning() << "Файл с именем" << name << "не найден";
|
||||
return false;
|
||||
}
|
||||
|
||||
QString oldPath = mediaFiles[index].filePath;
|
||||
mediaFiles[index].filePath = newFilePath;
|
||||
|
||||
qDebug() << "Путь файла обновлен:" << name << "новый путь:" << newFilePath;
|
||||
return true;
|
||||
}
|
||||
|
||||
+10
-19
@@ -4,47 +4,38 @@
|
||||
#include <QString>
|
||||
#include <QVector>
|
||||
|
||||
// Структура для хранения информации о медиафайле
|
||||
struct MediaFile {
|
||||
QString name; // Имя файла
|
||||
QString filePath; // Полный путь к файлу
|
||||
QString name;
|
||||
QString filePath;
|
||||
|
||||
MediaFile() = default;
|
||||
MediaFile(const QString& name, const QString& filePath)
|
||||
: name(name), filePath(filePath) {}
|
||||
MediaFile(const QString& n, const QString& p) : name(n), filePath(p) {}
|
||||
};
|
||||
|
||||
class MediaFileManager
|
||||
{
|
||||
public:
|
||||
MediaFileManager();
|
||||
~MediaFileManager() = default;
|
||||
|
||||
// Добавление файла
|
||||
bool addFile(const QString& name, const QString& filePath);
|
||||
|
||||
// Удаление файла по имени
|
||||
bool removeFile(const QString& name);
|
||||
|
||||
// Изменение информации о файле
|
||||
bool updateFile(const QString& oldName, const QString& newName, const QString& newFilePath);
|
||||
|
||||
// Получение пути к файлу по имени
|
||||
QString getFilePathByName(const QString& name) const;
|
||||
|
||||
// Получение количества файлов
|
||||
int getFileCount() const;
|
||||
|
||||
// Получение всех файлов (для отладки или отображения)
|
||||
QVector<MediaFile> getAllFiles() const;
|
||||
|
||||
// Проверка существования файла по имени
|
||||
bool contains(const QString& name) const;
|
||||
|
||||
private:
|
||||
QVector<MediaFile> mediaFiles;
|
||||
// Новые методы для управления файлами
|
||||
bool renameFile(const QString& oldName, const QString& newName);
|
||||
bool updateFilePath(const QString& name, const QString& newFilePath);
|
||||
|
||||
// Поиск индекса файла по имени
|
||||
private:
|
||||
int findFileIndex(const QString& name) const;
|
||||
|
||||
QVector<MediaFile> mediaFiles;
|
||||
};
|
||||
|
||||
#endif // MEDIAFILEMANAGER_H
|
||||
|
||||
+69
-15
@@ -8,45 +8,99 @@ NeuralTemplateManager::NeuralTemplateManager(QObject *parent)
|
||||
{
|
||||
}
|
||||
|
||||
void NeuralTemplateManager::addTemplate(const QString &name, const QString &templateText)
|
||||
bool NeuralTemplateManager::addTemplate(const QString &name, const QString &templateText)
|
||||
{
|
||||
// Проверяем, нет ли уже шаблона с таким именем
|
||||
for (int i = 0; i < m_templates.size(); ++i) {
|
||||
if (m_templates[i].name.compare(name, Qt::CaseInsensitive) == 0) {
|
||||
m_templates[i].templateText = templateText;
|
||||
return;
|
||||
}
|
||||
if (name.isEmpty()) {
|
||||
qWarning() << "Имя шаблона не может быть пустым";
|
||||
return false;
|
||||
}
|
||||
m_templates.append({name, templateText});
|
||||
|
||||
if (containsTemplate(name)) {
|
||||
qWarning() << "Шаблон с именем" << name << "уже существует";
|
||||
return false;
|
||||
}
|
||||
|
||||
templates.append(NeuralTemplate(name, templateText));
|
||||
// emit templateAdded(name, templateText);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
QString NeuralTemplateManager::getTemplateText(const QString &name) const
|
||||
{
|
||||
for (const Template &t : m_templates) {
|
||||
if (t.name.compare(name, Qt::CaseInsensitive) == 0) {
|
||||
return t.templateText;
|
||||
int index = findTemplateIndex(name);
|
||||
if (index == -1) {
|
||||
return QString();
|
||||
}
|
||||
return templates[index].templateText;
|
||||
}
|
||||
|
||||
bool NeuralTemplateManager::removeTemplate(const QString& name)
|
||||
{
|
||||
int index = findTemplateIndex(name);
|
||||
|
||||
if (index == -1) {
|
||||
qWarning() << "Шаблон с именем" << name << "не найден";
|
||||
return false;
|
||||
}
|
||||
|
||||
templates.remove(index);
|
||||
// emit templateRemoved(name);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool NeuralTemplateManager::updateTemplate(const QString& oldName, const QString& newName, const QString& newTemplateText)
|
||||
{
|
||||
int index = findTemplateIndex(oldName);
|
||||
|
||||
if (index == -1) {
|
||||
qWarning() << "Шаблон с именем" << oldName << "не найден";
|
||||
return false;
|
||||
}
|
||||
|
||||
// Проверяем, не используется ли новое имя другим шаблоном
|
||||
if (oldName != newName && containsTemplate(newName)) {
|
||||
qWarning() << "Шаблон с именем" << newName << "уже существует";
|
||||
return false;
|
||||
}
|
||||
|
||||
templates[index].name = newName;
|
||||
templates[index].templateText = newTemplateText;
|
||||
|
||||
// emit templateUpdated(oldName, newName, newTemplateText);
|
||||
return true;
|
||||
}
|
||||
|
||||
int NeuralTemplateManager::findTemplateIndex(const QString& name) const
|
||||
{
|
||||
for (int i = 0; i < templates.size(); ++i) {
|
||||
if (templates[i].name == name) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return QString();
|
||||
return -1;
|
||||
}
|
||||
|
||||
bool NeuralTemplateManager::containsTemplate(const QString& name) const
|
||||
{
|
||||
return findTemplateIndex(name) != -1;
|
||||
}
|
||||
|
||||
void NeuralTemplateManager::clear()
|
||||
{
|
||||
m_templates.clear();
|
||||
templates.clear();
|
||||
}
|
||||
|
||||
void NeuralTemplateManager::loadFromTableWidget(QTableWidget *table)
|
||||
{
|
||||
clear();
|
||||
if (!table) return;
|
||||
qDebug()<< "Table Found";
|
||||
for (int row = 0; row < table->rowCount(); ++row) {
|
||||
QTableWidgetItem *nameItem = table->item(row, 0);
|
||||
QTableWidgetItem *templateItem = table->item(row, 1);
|
||||
if (nameItem && templateItem) {
|
||||
QString name = nameItem->text().trimmed();
|
||||
QString templateText = templateItem->text().trimmed();
|
||||
qDebug()<< "Template add " << name;
|
||||
if (!name.isEmpty() && !templateText.isEmpty()) {
|
||||
addTemplate(name, templateText);
|
||||
}
|
||||
|
||||
+15
-7
@@ -12,22 +12,30 @@ class NeuralTemplateManager : public QObject
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
struct Template {
|
||||
QString name;
|
||||
QString templateText;
|
||||
};
|
||||
|
||||
explicit NeuralTemplateManager(QObject *parent = nullptr);
|
||||
|
||||
void addTemplate(const QString &name, const QString &templateText);
|
||||
bool addTemplate(const QString &name, const QString &templateText);
|
||||
bool removeTemplate(const QString& name);
|
||||
bool updateTemplate(const QString& oldName, const QString& newName, const QString& newTemplateText);
|
||||
|
||||
QString getTemplateText(const QString &name) const;
|
||||
void clear();
|
||||
void loadFromTableWidget(QTableWidget *table);
|
||||
bool containsTemplate(const QString& name) const;
|
||||
|
||||
const QVector<Template>& templates() const { return m_templates; }
|
||||
|
||||
private:
|
||||
QVector<Template> m_templates;
|
||||
|
||||
struct NeuralTemplate {
|
||||
QString name;
|
||||
QString templateText;
|
||||
|
||||
NeuralTemplate(const QString& n = "", const QString& t = "")
|
||||
: name(n), templateText(t) {}
|
||||
};
|
||||
QVector<NeuralTemplate> templates;
|
||||
int findTemplateIndex(const QString& name) const;
|
||||
};
|
||||
|
||||
#endif // NEURALTEMPLATEMANAGER_H
|
||||
|
||||
@@ -319,8 +319,6 @@ bool uDataBase::SaveTimers(QTableWidget *tableWidget, const QList<TimerInfo> &ti
|
||||
m_db.rollback();
|
||||
return false;
|
||||
}
|
||||
|
||||
qDebug() << "Saved" << savedRows << "timers to database";
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
+69
-68
@@ -162,11 +162,6 @@ uGeneral::uGeneral(QWidget *parent)
|
||||
// ============================================================================
|
||||
setupAuthHandlers();
|
||||
|
||||
// ============================================================================
|
||||
// ИНИЦИАЛИЗАЦИЯ НЕЙРОННОЙ СЕТИ
|
||||
// ============================================================================
|
||||
initializeNeuralNetwork();
|
||||
|
||||
loadEmoties();
|
||||
|
||||
// Настройка таблицы веб-серверов
|
||||
@@ -416,9 +411,7 @@ void uGeneral::initializeManagers()
|
||||
|
||||
// Менеджер случайных ответов (групп)
|
||||
m_randomResponses = new RandomResponses(this);
|
||||
m_neuralTemplateManager = new NeuralTemplateManager(this);
|
||||
QTableWidget* table = ui->widget_3->tableWidget();
|
||||
m_neuralTemplateManager->loadFromTableWidget(table);
|
||||
|
||||
// Менеджер нейросети (если есть)
|
||||
nnManager = new NeuralNetworkManager(this);
|
||||
// Настройка нейросети (пример)
|
||||
@@ -427,32 +420,38 @@ void uGeneral::initializeManagers()
|
||||
// GigaChat
|
||||
nnManager->setCurrentNetworkType(NeuralNetworkManager::GigaChat);
|
||||
nnManager->setGigaChatCredentials(ui->edtAIP1->text(), ui->edtAIP2->text());
|
||||
qDebug() << "GigaChat";
|
||||
}
|
||||
else if (ui->rbDS->isChecked()) {
|
||||
// DeepSeek
|
||||
nnManager->setCurrentNetworkType(NeuralNetworkManager::DeepSeek);
|
||||
nnManager->setApiKey(NeuralNetworkManager::DeepSeek, ui->edtAIP1->text());
|
||||
|
||||
qDebug() << "DeepSeek";
|
||||
}
|
||||
else if (ui->rbCG->isChecked()) {
|
||||
// ChatGPT
|
||||
nnManager->setCurrentNetworkType(NeuralNetworkManager::ChatGPT);
|
||||
nnManager->setApiKey(NeuralNetworkManager::ChatGPT, ui->edtAIP1->text());
|
||||
qDebug() << "ChatGPT";
|
||||
}
|
||||
else if (ui->RBCustom->isChecked()) {
|
||||
// Ollama
|
||||
nnManager->setCurrentNetworkType(NeuralNetworkManager::Ollama);
|
||||
nnManager->setApiKey(NeuralNetworkManager::Ollama, ui->edtAIP1->text());
|
||||
nnManager->setOllamaUrl(ui->edtAIP2->text());
|
||||
qDebug() << "Ollama";
|
||||
}
|
||||
|
||||
|
||||
m_SoundFiles = new MediaFileManager();
|
||||
|
||||
ui->widget->setSoundManager(m_SoundFiles);
|
||||
ui->widget->setManagerType(FSingleGrid::SoundManager);
|
||||
ui->widget->setDatabase(db);
|
||||
m_TextFiles = new MediaFileManager();
|
||||
ui->widget_2->setTextManager(m_TextFiles); // Нужно создать m_TextFiles
|
||||
ui->widget_2->setManagerType(FSingleGrid::TextManager);
|
||||
ui->widget_2->setDatabase(db);
|
||||
m_neuralTemplateManager = new NeuralTemplateManager(this);
|
||||
ui->widget_3->setTemplateManager(m_neuralTemplateManager);
|
||||
ui->widget_3->setManagerType(FSingleGrid::TemplateManager);
|
||||
ui->widget_3->setDatabase(db);
|
||||
// Менеджер команд
|
||||
m_commandProcessor = new CommandProcessor(this);
|
||||
|
||||
@@ -469,7 +468,10 @@ void uGeneral::initializeManagers()
|
||||
|
||||
// Загрузка звуков
|
||||
loadSoundsFromDatabase();
|
||||
|
||||
// Загрузка текстов
|
||||
loadTextFromDatabase();
|
||||
// Загрузка шаблонов
|
||||
loadTemplatesFromDatabase();
|
||||
|
||||
// Настройка контекста для обработчика команд
|
||||
CommandProcessor::Context context;
|
||||
@@ -531,6 +533,50 @@ void uGeneral::loadSoundsFromDatabase()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Загрузка текстов
|
||||
*/
|
||||
void uGeneral::loadTextFromDatabase()
|
||||
{
|
||||
if (!db || !m_TextFiles) return;
|
||||
|
||||
QTableWidget* table = ui->widget_2->tableWidget();
|
||||
if (!table) return;
|
||||
for (int row = 0; row < table->rowCount(); ++row) {
|
||||
QTableWidgetItem *nameItem = table->item(row, 0);
|
||||
QTableWidgetItem *fileItem = table->item(row, 1);
|
||||
if (nameItem && fileItem) {
|
||||
QString name = nameItem->text().trimmed();
|
||||
QString file = fileItem->text().trimmed();
|
||||
if (!name.isEmpty() && !file.isEmpty()) {
|
||||
m_TextFiles->addFile(name, file);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Загрузка шаблонов
|
||||
*/
|
||||
void uGeneral::loadTemplatesFromDatabase()
|
||||
{
|
||||
if (!db || !m_neuralTemplateManager) return;
|
||||
|
||||
QTableWidget* table = ui->widget_3->tableWidget();
|
||||
if (!table) return;
|
||||
for (int row = 0; row < table->rowCount(); ++row) {
|
||||
QTableWidgetItem *nameItem = table->item(row, 0);
|
||||
QTableWidgetItem *fileItem = table->item(row, 1);
|
||||
if (nameItem && fileItem) {
|
||||
QString name = nameItem->text().trimmed();
|
||||
QString file = fileItem->text().trimmed();
|
||||
if (!name.isEmpty() && !file.isEmpty()) {
|
||||
m_neuralTemplateManager->addTemplate(name, file);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @brief Загрузка случайных диапазонов из таблицы sgRandomInt в RandomManager
|
||||
*/
|
||||
@@ -796,19 +842,6 @@ void uGeneral::setupAuthHandlers()
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Инициализация нейронной сети
|
||||
*/
|
||||
void uGeneral::initializeNeuralNetwork()
|
||||
{
|
||||
nnManager = new NeuralNetworkManager(this);
|
||||
|
||||
// Подключение сигналов менеджера нейронной сети
|
||||
connect(nnManager, &NeuralNetworkManager::responseReceived,
|
||||
this, &uGeneral::onNeuralResponse);
|
||||
connect(nnManager, &NeuralNetworkManager::errorOccurred,
|
||||
this, &uGeneral::onNeuralError);
|
||||
}
|
||||
|
||||
uGeneral::~uGeneral()
|
||||
{
|
||||
@@ -1174,20 +1207,11 @@ void uGeneral::sendRequestToAI(const QString &q)
|
||||
nnManager->sendMessage(q, type);
|
||||
}
|
||||
|
||||
void uGeneral::onNeuralResponse(const QString &response) {
|
||||
// Отправляем ответ в Twitch чат
|
||||
qDebug() << "Ответ нейросети:" << response;
|
||||
}
|
||||
|
||||
void uGeneral::onNeuralError(const QString &error) {
|
||||
|
||||
LogManager::instance()->error("General", "onNeuralError", error);
|
||||
}
|
||||
|
||||
void uGeneral::onSoundGridDoubleClicked()
|
||||
{
|
||||
QTextCursor cursor = ui->textBrowser->textCursor();
|
||||
cursor.insertText("||" + ui->widget->tableWidget()->item(ui->widget->tableWidget()->currentRow(), 0)->text() + "||");
|
||||
|
||||
}
|
||||
|
||||
void uGeneral::onFilesGridDoubleClicked()
|
||||
@@ -1837,28 +1861,6 @@ void uGeneral::on_btnNotifyOpenSub_clicked()
|
||||
ui->edtNotifyFileNameSub->setText(sourceFile);
|
||||
}
|
||||
|
||||
|
||||
|
||||
void uGeneral::onStatus(const QString &statusText, int statusCode)
|
||||
{
|
||||
qDebug() << "[STATUS]" << statusCode << statusText;
|
||||
}
|
||||
|
||||
void uGeneral::onDisconnected(const QString &reason)
|
||||
{
|
||||
qDebug() << "[DISCONNECTED]" << reason;
|
||||
}
|
||||
|
||||
void uGeneral::onJoined(const QString &nickname)
|
||||
{
|
||||
qDebug() << "[JOINED]" << nickname << "joined";
|
||||
}
|
||||
|
||||
void uGeneral::onMessage(const QString &message)
|
||||
{
|
||||
qDebug() << "[MESSAGE]" << message;
|
||||
}
|
||||
|
||||
void uGeneral::playNotify(const bool &isMod, const bool &isVip, const bool &isSub)
|
||||
{
|
||||
// Проверяем модератора (самый высокий приоритет)
|
||||
@@ -2362,6 +2364,8 @@ void uGeneral::on_btnRandomAdd_clicked()
|
||||
|
||||
// Очищаем поля ввода
|
||||
ui->edtRandomRespons->clear();
|
||||
|
||||
m_randomResponses->addResponse(groupName, response);
|
||||
}
|
||||
|
||||
|
||||
@@ -2369,6 +2373,7 @@ void uGeneral::on_btnRandomDel_clicked()
|
||||
{
|
||||
db->DeleteResponse(ui->lbRandomGroup->currentItem()->text(), ui->lbRandomRespons->currentItem()->text());
|
||||
db->LoadRandomResponses(ui->lbRandomGroup->currentItem()->text(), ui->lbRandomRespons);
|
||||
m_randomResponses->removeResponse(ui->lbRandomGroup->currentItem()->text(), ui->lbRandomRespons->currentItem()->text());
|
||||
}
|
||||
|
||||
|
||||
@@ -2376,6 +2381,7 @@ void uGeneral::on_btnRmGroup_clicked()
|
||||
{
|
||||
db->DeleteGroup(ui->lbRandomGroup->currentItem()->text());
|
||||
db->LoadRandomGroups(ui->lbRandomGroup);
|
||||
m_randomResponses->removeGroup(ui->lbRandomGroup->currentItem()->text());
|
||||
}
|
||||
|
||||
void uGeneral::on_btnGetDateFollow_clicked()
|
||||
@@ -2443,7 +2449,7 @@ void uGeneral::on_btnAddCommand_clicked()
|
||||
|
||||
// Сохраняем в БД
|
||||
db->SaveTableWidget(ui->sgCommands);
|
||||
|
||||
m_commandProcessor->addCommand(name, response);
|
||||
LogManager::instance()->info("uGeneral", "on_btnAddCommand_clicked",
|
||||
QString("Добавлена команда: %1").arg(name));
|
||||
}
|
||||
@@ -2463,7 +2469,7 @@ void uGeneral::on_btnRmCommand_clicked()
|
||||
|
||||
ui->sgCommands->removeRow(row);
|
||||
db->SaveTableWidget(ui->sgCommands);
|
||||
|
||||
m_commandProcessor->deleteCommand(commandName);
|
||||
LogManager::instance()->info("uGeneral", "on_btnRmCommand_clicked",
|
||||
QString("Удалена команда: %1").arg(commandName));
|
||||
}
|
||||
@@ -2486,11 +2492,11 @@ void uGeneral::on_btnEdtCommand_clicked()
|
||||
QMessageBox::warning(this, "Внимание", "Введите новое имя команды!");
|
||||
return;
|
||||
}
|
||||
|
||||
QString oldCommand = ui->sgCommands->item(row, 0)->text();
|
||||
ui->sgCommands->item(row, 0)->setText(newName);
|
||||
ui->sgCommands->item(row, 1)->setText(response);
|
||||
db->SaveTableWidget(ui->sgCommands);
|
||||
|
||||
m_commandProcessor->editCommand(oldCommand, newName, response);
|
||||
LogManager::instance()->info("uGeneral", "on_btnEdtCommand_clicked",
|
||||
QString("Отредактирована команда в строке %1").arg(row));
|
||||
}
|
||||
@@ -2507,7 +2513,6 @@ void uGeneral::loadQssFiles()
|
||||
QDir systemStylesDir(systemStylesPath);
|
||||
|
||||
if (systemStylesDir.exists()) {
|
||||
qDebug() << "Системные стили из:" << systemStylesPath;
|
||||
loadStylesFromDirectory(systemStylesDir, "Системные");
|
||||
} else {
|
||||
qWarning() << "Папка системных стилей не найдена:" << systemStylesPath;
|
||||
@@ -2521,7 +2526,6 @@ void uGeneral::loadQssFiles()
|
||||
QDir userStylesDir(userStylesPath);
|
||||
|
||||
if (userStylesDir.exists()) {
|
||||
qDebug() << "Пользовательские стили из:" << userStylesPath;
|
||||
loadStylesFromDirectory(userStylesDir, "Пользовательские");
|
||||
} else {
|
||||
qWarning() << "Папка пользовательских стилей не найдена:" << userStylesPath;
|
||||
@@ -2537,8 +2541,6 @@ void uGeneral::loadQssFiles()
|
||||
qWarning() << "Темы не найдены, создаем базовые";
|
||||
|
||||
}
|
||||
|
||||
qDebug() << "Загружено тем:" << ui->cbTheme->count() - 1; // Минус "Без темы"
|
||||
}
|
||||
|
||||
|
||||
@@ -2954,7 +2956,6 @@ void uGeneral::sendMessageToServer(HttpServerChat *server, const QString &nickna
|
||||
style.timeMsg = server->getMessageTimeout();
|
||||
style.bColor = server->getBackgroundColor();
|
||||
style.transparency = server->getTransparency();
|
||||
qDebug() << "sendMessageToServer";
|
||||
// Убираем HTML теги из обычного текста для совместимости
|
||||
// (если сервер их не поддерживает, можно оставить только для ника)
|
||||
style.nick = nickname; // Ник уже с цветом
|
||||
|
||||
+2
-9
@@ -136,10 +136,6 @@ private slots:
|
||||
// ========================================================================
|
||||
// СЛОТЫ ДЛЯ РАБОТЫ С WEBSOCKET (TWITCH)
|
||||
// ========================================================================
|
||||
void onStatus(const QString &statusText, int statusCode);
|
||||
void onDisconnected(const QString &reason);
|
||||
void onJoined(const QString &nickname);
|
||||
void onMessage(const QString &message);
|
||||
void handleNewMessage(const QString &message);
|
||||
void handleError(const QString &errorMessage);
|
||||
void handleConnected();
|
||||
@@ -156,8 +152,6 @@ private slots:
|
||||
// ========================================================================
|
||||
void onAIResponseReceived(const QString &response);
|
||||
void onAIErrorOccurred(const QString &error);
|
||||
void onNeuralResponse(const QString &response);
|
||||
void onNeuralError(const QString &error);
|
||||
void sendRequestToAI(const QString &q);
|
||||
|
||||
// ========================================================================
|
||||
@@ -452,7 +446,8 @@ private:
|
||||
void loadRandomRangesFromTableWidget();
|
||||
void loadRandomResponseGroupsFromDatabase();
|
||||
void loadSoundsFromDatabase();
|
||||
// Инициализация базы данных
|
||||
void loadTextFromDatabase();
|
||||
void loadTemplatesFromDatabase();
|
||||
void initializeDatabase();
|
||||
// Настройка пользовательского интерфейса
|
||||
void setupUI();
|
||||
@@ -466,8 +461,6 @@ private:
|
||||
void setupUserWidget();
|
||||
// Настройка обработчиков авторизации
|
||||
void setupAuthHandlers();
|
||||
// Инициализация нейронной сети
|
||||
void initializeNeuralNetwork();
|
||||
// Загрузка эмодзи
|
||||
void loadEmoties();
|
||||
void loadChatBadges();
|
||||
|
||||
Reference in New Issue
Block a user