sozday-polnotsennogo-golosov/JARVIS/gui.py

277 lines
10 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# -*- coding: utf-8 -*-
"""Графический интерфейс JARVIS Assistant (PySide6).
Тёмное окно с центральным индикатором-кругом, статусом,
полем текстового ввода и историей последних команд.
"""
from PySide6.QtCore import Qt, QTimer, Signal
from PySide6.QtGui import QColor, QFont
from PySide6.QtWidgets import (
QApplication, QFrame, QHBoxLayout, QLabel, QLineEdit, QListWidget,
QMainWindow, QMessageBox, QPushButton, QVBoxLayout, QWidget,
)
import config
# Цвета тёмной темы
BG_COLOR = "#0f1011"
CARD_COLOR = "#2e2e2e"
ACCENT_COLOR = "#847dff"
TEXT_COLOR = "#ffffff"
MUTED_COLOR = "#b8b8b8"
LISTENING_COLOR = "#7dffb0"
BUSY_COLOR = "#ffb86c"
STATUS_IDLE = "Ожидание команды"
STATUS_LISTENING = "Слушаю..."
STATUS_BUSY = "Выполняю..."
STYLESHEET = """
QMainWindow, QWidget {{ background-color: {bg}; color: {text}; font-family: 'Inter', 'Segoe UI', sans-serif; }}
QLabel#titleLabel {{ font-size: 22px; font-weight: 600; }}
QLabel#statusLabel {{ font-size: 16px; color: {accent}; font-weight: 600; }}
QLabel#commandLabel, QLabel#replyLabel {{ font-size: 14px; color: {muted}; }}
QLabel#userText, QLabel#assistantText {{ font-size: 15px; color: {text}; }}
QFrame#card {{ background-color: {card}; border-radius: 12px; border: 1px solid #3a3a3a; }}
QLineEdit {{ background-color: {card}; border: 1px solid #3a3a3a; border-radius: 8px;
padding: 10px 14px; font-size: 14px; color: {text}; }}
QLineEdit:focus {{ border: 1px solid {accent}; }}
QPushButton {{ border-radius: 8px; padding: 10px 18px; font-size: 14px; font-weight: 600; }}
QPushButton#startBtn {{ background-color: #ffffff; color: #111111; }}
QPushButton#startBtn:hover {{ background-color: #e6e6e6; }}
QPushButton#startBtn:disabled {{ background-color: #555555; color: #999999; }}
QPushButton#stopBtn {{ background-color: transparent; color: {text};
border: 1px solid #4a4a4a; }}
QPushButton#stopBtn:hover {{ border-color: {accent}; color: {accent}; }}
QListWidget {{ background-color: {card}; border: 1px solid #3a3a3a; border-radius: 8px;
font-size: 13px; color: {muted}; padding: 4px; }}
QListWidget::item {{ padding: 4px 6px; }}
QScrollBar:vertical {{ background: transparent; width: 8px; }}
QScrollBar::handle:vertical {{ background: #4a4a4a; border-radius: 4px; }}
""".format(bg=BG_COLOR, text=TEXT_COLOR, card=CARD_COLOR, accent=ACCENT_COLOR, muted=MUTED_COLOR)
class IndicatorWidget(QWidget):
"""Центральный круг-индикатор с плавной пульсацией."""
def __init__(self, parent=None) -> None:
super().__init__(parent)
self.setFixedSize(160, 160)
self._phase = 0.0
self._base_color = QColor(ACCENT_COLOR)
self._active = False
self._timer = QTimer(self)
self._timer.timeout.connect(self._tick)
self._timer.start(40)
def set_state(self, status: str) -> None:
if status == STATUS_LISTENING:
self._base_color = QColor(LISTENING_COLOR)
self._active = True
elif status == STATUS_BUSY:
self._base_color = QColor(BUSY_COLOR)
self._active = True
else:
self._base_color = QColor(ACCENT_COLOR)
self._active = False
def _tick(self) -> None:
self._phase = (self._phase + 0.06) % (2 * 3.14159)
self.update()
def paintEvent(self, event) -> None:
from PySide6.QtGui import QPainter, QPen, QBrush, QRadialGradient
painter = QPainter(self)
painter.setRenderHint(QPainter.Antialiasing)
center = self.rect().center()
# Амплитуда пульсации: активна — заметная, в покое — едва заметная
amplitude = 6.0 if self._active else 1.5
radius = 48 + amplitude * (0.5 + 0.5 * __import__("math").sin(self._phase))
# Внешнее кольцо
pen = QPen(self._base_color)
pen.setWidth(2)
painter.setPen(pen)
painter.setBrush(Qt.NoBrush)
painter.drawEllipse(center, int(radius), int(radius))
# Свечение
glow = QRadialGradient(center, int(radius * 2))
glow_color = QColor(self._base_color)
glow_color.setAlpha(50 if self._active else 18)
glow.setColorAt(0.0, glow_color)
glow.setColorAt(1.0, QColor(0, 0, 0, 0))
painter.setBrush(QBrush(glow))
painter.setPen(Qt.NoPen)
painter.drawEllipse(center, int(radius * 2), int(radius * 2))
# Внутренний круг
painter.setBrush(QColor(CARD_COLOR))
painter.setPen(QPen(self._base_color, 1))
painter.drawEllipse(center, 34, 34)
painter.end()
class MainWindow(QMainWindow):
"""Главное окно приложения."""
# Сигналы для ассистента
start_listening = Signal()
stop_listening = Signal()
text_submitted = Signal(str)
confirmed = Signal(str) # id подтверждённой команды
cancelled = Signal()
def __init__(self) -> None:
super().__init__()
self.setWindowTitle(config.APP_NAME)
self.setMinimumSize(560, 720)
self.resize(560, 720)
central = QWidget()
layout = QVBoxLayout(central)
layout.setContentsMargins(28, 24, 28, 24)
layout.setSpacing(16)
# Заголовок
title = QLabel("JARVIS Assistant")
title.setObjectName("titleLabel")
title.setAlignment(Qt.AlignCenter)
layout.addWidget(title)
# Индикатор
self.indicator = IndicatorWidget()
layout.addWidget(self.indicator, alignment=Qt.AlignCenter)
# Статус
self.status_label = QLabel(STATUS_IDLE)
self.status_label.setObjectName("statusLabel")
self.status_label.setAlignment(Qt.AlignCenter)
layout.addWidget(self.status_label)
# Распознанная команда
command_card = QFrame()
command_card.setObjectName("card")
command_layout = QVBoxLayout(command_card)
command_layout.setContentsMargins(16, 12, 16, 12)
command_label = QLabel("Вы сказали:")
command_label.setObjectName("commandLabel")
self.command_text = QLabel("—")
self.command_text.setObjectName("userText")
self.command_text.setWordWrap(True)
command_layout.addWidget(command_label)
command_layout.addWidget(self.command_text)
layout.addWidget(command_card)
# Ответ помощника
reply_card = QFrame()
reply_card.setObjectName("card")
reply_layout = QVBoxLayout(reply_card)
reply_layout.setContentsMargins(16, 12, 16, 12)
reply_label = QLabel("JARVIS:")
reply_label.setObjectName("replyLabel")
self.reply_text = QLabel("Здравствуйте. Я готов к работе.")
self.reply_text.setObjectName("assistantText")
self.reply_text.setWordWrap(True)
reply_layout.addWidget(reply_label)
reply_layout.addWidget(self.reply_text)
layout.addWidget(reply_card)
# Кнопки
btn_row = QHBoxLayout()
self.start_btn = QPushButton("🎤 Начать прослушивание")
self.start_btn.setObjectName("startBtn")
self.start_btn.clicked.connect(self._on_start)
self.stop_btn = QPushButton("Остановить")
self.stop_btn.setObjectName("stopBtn")
self.stop_btn.setEnabled(False)
self.stop_btn.clicked.connect(self._on_stop)
btn_row.addWidget(self.start_btn)
btn_row.addWidget(self.stop_btn)
layout.addLayout(btn_row)
# Текстовый ввод
self.input_line = QLineEdit()
self.input_line.setPlaceholderText(
"Или напишите команду текстом и нажмите Enter — например: открой калькулятор"
)
self.input_line.returnPressed.connect(self._on_text_submit)
layout.addWidget(self.input_line)
# История команд
history_label = QLabel("История последних команд:")
history_label.setObjectName("replyLabel")
layout.addWidget(history_label)
self.history_list = QListWidget()
self.history_list.setMaximumHeight(140)
layout.addWidget(self.history_list)
layout.addStretch()
self.setCentralWidget(central)
self.setStyleSheet(STYLESHEET)
# ---------- Публичные слоты (вызываются сигналами ассистента) ----------
def set_status(self, status: str) -> None:
self.status_label.setText(status)
self.indicator.set_state(status)
def show_command(self, text: str) -> None:
self.command_text.setText(text)
self.history_list.insertItem(0, text)
while self.history_list.count() > 15:
self.history_list.takeItem(self.history_list.count() - 1)
def show_reply(self, text: str) -> None:
self.reply_text.setText(text)
def ask_confirmation(self, command_id: str, question: str) -> None:
"""Показывает диалог подтверждения опасной команды."""
box = QMessageBox(self)
box.setWindowTitle("Подтверждение")
box.setText(question)
box.setIcon(QMessageBox.Warning)
yes = box.addButton("Да", QMessageBox.YesRole)
no = box.addButton("Отмена", QMessageBox.NoRole)
box.exec()
if box.clickedButton() is yes:
self.confirmed.emit(command_id)
else:
self.cancelled.emit()
# ---------- Обработчики кнопок ----------
def _on_start(self) -> None:
self.start_btn.setEnabled(False)
self.stop_btn.setEnabled(True)
self.start_listening.emit()
def _on_stop(self) -> None:
self.start_btn.setEnabled(True)
self.stop_btn.setEnabled(False)
self.stop_listening.emit()
def _on_text_submit(self) -> None:
text = self.input_line.text().strip()
if not text:
return
self.input_line.clear()
self.text_submitted.emit(text)
def main() -> None:
"""Запуск окна отдельно (для отладки интерфейса)."""
import sys
app = QApplication(sys.argv)
app.setStyleSheet(STYLESHEET)
window = MainWindow()
window.show()
sys.exit(app.exec())
if __name__ == "__main__":
main()