Я помогу вам спроектировать GTK приложение с описанным функционалом. Давайте разработаем это поэтапно.
Этап 1: Структура проекта
Создадим структуру проекта:
chatgpt-assistant/
├── debian/
│ ├── control
│ ├── rules
│ ├── compat
│ └── chatgpt-assistant.install
├── src/
│ ├── main.py
│ ├── ui/
│ │ ├── __init__.py
│ │ ├── main_window.py
│ │ └── settings_window.py
│ ├── audio/
│ │ ├── __init__.py
│ │ ├── speech_recognition.py
│ │ └── text_to_speech.py
│ ├── search/
│ │ ├── __init__.py
│ │ ├── file_search.py
│ │ └── web_search.py
│ └── api/
│ ├── __init__.py
│ └── chatgpt_client.py
├── icons/
│ └── chatgpt-assistant.png
├── chatgpt-assistant.desktop
└── setup.py
Этап 2: Основной файл приложения (main.py)
#!/usr/bin/env python3
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GLib, Gio
import sys
import os
import threading
from pathlib import Path
# Добавляем путь к модулям
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from ui.main_window import MainWindow
from audio.speech_recognition import SpeechRecognizer
class ChatGPTAssistant(Gtk.Application):
def __init__(self):
super().__init__(
application_id='com.chatgpt.assistant',
flags=Gio.ApplicationFlags.FLAGS_NONE
)
self.window = None
self.speech_recognizer = None
def do_activate(self):
if not self.window:
self.window = MainWindow(self)
self.window.show_all()
# Инициализация распознавания речи
self.speech_recognizer = SpeechRecognizer(self.window)
self.speech_recognizer.start_listening()
self.window.present()
def do_startup(self):
Gtk.Application.do_startup(self)
# Создаем действия приложения
quit_action = Gio.SimpleAction.new("quit", None)
quit_action.connect("activate", self.on_quit)
self.add_action(quit_action)
settings_action = Gio.SimpleAction.new("settings", None)
settings_action.connect("activate", self.on_settings)
self.add_action(settings_action)
def on_quit(self, action, param):
if self.speech_recognizer:
self.speech_recognizer.stop_listening()
self.quit()
def on_settings(self, action, param):
if self.window:
self.window.show_settings()
def main():
app = ChatGPTAssistant()
return app.run(sys.argv)
if __name__ == "__main__":
sys.exit(main())
Этап 3: Главное окно (ui/main_window.py)
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('WebKit2', '4.0')
from gi.repository import Gtk, GLib, Pango, WebKit2
import threading
import json
import os
from datetime import datetime
from ui.settings_window import SettingsWindow
from api.chatgpt_client import ChatGPTClient
from search.file_search import FileSearcher
from search.web_search import WebSearcher
from audio.text_to_speech import TextToSpeech
class MainWindow(Gtk.ApplicationWindow):
def __init__(self, app):
super().__init__(application=app, title="ChatGPT Assistant")
self.set_default_size(800, 600)
self.set_position(Gtk.WindowPosition.CENTER)
# Загрузка настроек
self.settings = self.load_settings()
# Инициализация компонентов
self.chatgpt_client = ChatGPTClient(self.settings)
self.file_searcher = FileSearcher()
self.web_searcher = WebSearcher()
self.tts = TextToSpeech()
# Создание UI
self.create_ui()
def create_ui(self):
# Основной контейнер
vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
self.add(vbox)
# Заголовок
headerbar = Gtk.HeaderBar()
headerbar.set_show_close_button(True)
headerbar.props.title = "ChatGPT Assistant"
self.set_titlebar(headerbar)
# Кнопка настроек
settings_button = Gtk.Button()
settings_button.set_image(Gtk.Image.new_from_icon_name("preferences-system", Gtk.IconSize.BUTTON))
settings_button.connect("clicked", self.on_settings_clicked)
headerbar.pack_end(settings_button)
# Область чата
scrolled = Gtk.ScrolledWindow()
scrolled.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
vbox.pack_start(scrolled, True, True, 0)
# WebView для отображения чата
self.webview = WebKit2.WebView()
self.webview.load_html(self.get_initial_html(), None)
scrolled.add(self.webview)
# Панель ввода
input_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6)
input_box.set_margin_left(6)
input_box.set_margin_right(6)
input_box.set_margin_bottom(6)
vbox.pack_start(input_box, False, False, 0)
# Поле ввода текста
self.entry = Gtk.Entry()
self.entry.set_placeholder_text("Введите сообщение или скажите 'GPT'...")
self.entry.connect("activate", self.on_send_message)
input_box.pack_start(self.entry, True, True, 0)
# Кнопка отправки
send_button = Gtk.Button(label="Отправить")
send_button.connect("clicked", self.on_send_message)
input_box.pack_start(send_button, False, False, 0)
# Индикатор записи
self.recording_label = Gtk.Label(label="🎤 Слушаю...")
self.recording_label.set_no_show_all(True)
input_box.pack_start(self.recording_label, False, False, 0)
def get_initial_html(self):
return """
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
margin: 0;
padding: 20px;
background-color: #f5f5f5;
}
.message {
margin-bottom: 15px;
padding: 10px 15px;
border-radius: 10px;
max-width: 70%;
}
.user-message {
background-color: #007bff;
color: white;
margin-left: auto;
text-align: right;
}
.assistant-message {
background-color: white;
border: 1px solid #e0e0e0;
}
.search-results {
background-color: #f0f0f0;
padding: 10px;
margin: 10px 0;
border-radius: 5px;
}
.search-results h4 {
margin-top: 0;
color: #333;
}
.search-item {
margin: 5px 0;
}
.search-item a {
color: #007bff;
text-decoration: none;
}
.search-item a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<div id="chat-container">
<div class="message assistant-message">
Привет! Я ChatGPT Assistant. Вы можете задать мне вопрос текстом или голосом, сказав "GPT".
</div>
</div>
<script>
function addMessage(content, isUser) {
const container = document.getElementById('chat-container');
const messageDiv = document.createElement('div');
messageDiv.className = 'message ' + (isUser ? 'user-message' : 'assistant-message');
messageDiv.innerHTML = content;
container.appendChild(messageDiv);
window.scrollTo(0, document.body.scrollHeight);
}
function addSearchResults(results) {
const container = document.getElementById('chat-container');
const resultsDiv = document.createElement('div');
resultsDiv.className = 'search-results';
resultsDiv.innerHTML = results;
container.appendChild(resultsDiv);
window.scrollTo(0, document.body.scrollHeight);
}
</script>
</body>
</html>
"""
def on_send_message(self, widget):
text = self.entry.get_text().strip()
if not text:
return
self.entry.set_text("")
self.process_message(text)
def process_message(self, text):
# Добавляем сообщение пользователя
self.add_message_to_chat(text, True)
# Обработка в отдельном потоке
thread = threading.Thread(target=self._process_message_thread, args=(text,))
thread.daemon = True
thread.start()
def _process_message_thread(self, text):
try:
# Поиск файлов
file_results = self.file_searcher.search(text)
if file_results:
GLib.idle_add(self.add_search_results, "Файлы", file_results)
# Поиск в интернете
web_results = self.web_searcher.search(text)
if web_results:
GLib.idle_add(self.add_search_results, "Интернет", web_results)
# Запрос к ChatGPT
response = self.chatgpt_client.get_response(text)
GLib.idle_add(self.add_message_to_chat, response, False)
# Озвучивание ответа
if self.settings.get('tts_enabled', True):
self.tts.speak(response)
except Exception as e:
GLib.idle_add(self.add_message_to_chat, f"Ошибка: {str(e)}", False)
def add_message_to_chat(self, text, is_user):
escaped_text = GLib.markup_escape_text(text)
script = f"addMessage('{escaped_text}', {str(is_user).lower()});"
self.webview.run_javascript(script, None, None, None)
def add_search_results(self, title, results):
html = f"<h4>{title}:</h4>"
for result in results[:5]: # Показываем первые 5 результатов
if 'path' in result: # Файл
html += f'<div class="search-item">📄 <a href="file://{result["path"]}">{result["name"]}</a></div>'
else: # Веб-результат
html += f'<div class="search-item">🌐 <a href="{result["url"]}">{result["title"]}</a></div>'
script = f"addSearchResults(`{html}`);"
self.webview.run_javascript(script, None, None, None)
def on_settings_clicked(self, button):
self.show_settings()
def show_settings(self):
dialog = SettingsWindow(self, self.settings)
response = dialog.run()
if response == Gtk.ResponseType.OK:
self.settings = dialog.get_settings()
self.save_settings()
self.apply_settings()
dialog.destroy()
def apply_settings(self):
# Применяем новые настройки
self.chatgpt_client.update_settings(self.settings)
self.tts.enabled = self.settings.get('tts_enabled', True)
def load_settings(self):
config_dir = os.path.expanduser("~/.config/chatgpt-assistant")
config_file = os.path.join(config_dir, "settings.json")
if os.path.exists(config_file):
with open(config_file, 'r') as f:
return json.load(f)
return {
'autostart': False,
'use_api_key': True,
'api_key': '',
'username': '',
'password': '',
'tts_enabled': True
}
def save_settings(self):
config_dir = os.path.expanduser("~/.config/chatgpt-assistant")
os.makedirs(config_dir, exist_ok=True)
config_file = os.path.join(config_dir, "settings.json")
with open(config_file, 'w') as f:
json.dump(self.settings, f, indent=2)
def show_recording(self, show):
if show:
self.recording_label.show()
else:
self.recording_label.hide()
def on_voice_command(self, text):
"""Вызывается при распознавании голосовой команды"""
GLib.idle_add(self.process_message, text)
Этап 4: Окно настроек (ui/settings_window.py)
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
import os
import subprocess
class SettingsWindow(Gtk.Dialog):
def __init__(self, parent, settings):
super().__init__(title="Настройки", parent=parent, flags=0)
self.add_buttons(
Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
Gtk.STOCK_OK, Gtk.ResponseType.OK
)
self.set_default_size(400, 300)
self.settings = settings.copy()
self.create_ui