Власник – Сухачов Денис Павлович
https://chatgpt.com/canvas/shared/67baf0da57c08191992242a6f61d3e59
import os
import sqlite3
import tkinter as tk
from tkinter import filedialog, messagebox
import threading
import cv2
import speech_recognition as sr
import PyPDF2
from PIL import Image, ImageTk
import numpy as np
import pyttsx3
import logging
# Налаштування логування
logging.basicConfig(level=logging.INFO, format=’%(asctime)s [%(levelname)s] %(message)s’)
# Ініціалізація бази даних
DB_PATH = “cognitive_system.db”
def initialize_database():
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute(”’CREATE TABLE IF NOT EXISTS files (
id INTEGER PRIMARY KEY AUTOINCREMENT,
filename TEXT,
filetype TEXT,
filepath TEXT,
processed_data TEXT)”’)
cursor.execute(”’CREATE TABLE IF NOT EXISTS training_sessions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
start_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
status TEXT)”’)
cursor.execute(”’CREATE TABLE IF NOT EXISTS conversations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_input TEXT,
response TEXT,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP)”’)
conn.commit()
conn.close()
initialize_database()
class CognitiveTrainingApp:
def __init__(self, root):
self.root = root
self.root.title(“Когнітивна система – Тренувальний інтерфейс”)
self.root.geometry(“600×500”)
# Голосовий двигун
self.engine = pyttsx3.init()
# Кнопка для завантаження файлів
self.upload_btn = tk.Button(root, text=”Завантажити файл”, command=self.upload_file)
self.upload_btn.pack(pady=10)
# Поле для виводу статусу
self.status_label = tk.Label(root, text=”Очікування завантаження…”)
self.status_label.pack(pady=10)
# Поле для зображення (якщо завантажене)
self.image_label = tk.Label(root)
self.image_label.pack()
# Кнопка запуску навчання
self.train_btn = tk.Button(root, text=”Розпочати навчання”, command=self.start_training)
self.train_btn.pack(pady=10)
# Голосовий чат
self.chat_label = tk.Label(root, text=”Введіть текст для розмови:”)
self.chat_label.pack(pady=10)
self.chat_entry = tk.Entry(root, width=50)
self.chat_entry.pack(pady=5)
self.chat_button = tk.Button(root, text=”Відправити”, command=self.respond_to_text)
self.chat_button.pack(pady=5)
self.uploaded_file = None
def upload_file(self):
file_path = filedialog.askopenfilename()
if file_path:
file_ext = os.path.splitext(file_path)[1].lower()
self.uploaded_file = file_path
self.status_label.config(text=f”Файл завантажено: {os.path.basename(file_path)}”)
self.process_file(file_path, file_ext)
def process_file(self, file_path, file_ext):
processed_data = “”
if file_ext in [‘.png’, ‘.jpg’, ‘.jpeg’, ‘.bmp’]:
processed_data = “Оброблене зображення”
self.process_image(file_path)
elif file_ext in [‘.mp4’, ‘.avi’, ‘.mov’]:
processed_data = “Оброблене відео”
self.process_video(file_path)
elif file_ext in [‘.wav’, ‘.mp3’]:
processed_data = self.process_audio(file_path)
elif file_ext in [‘.pdf’, ‘.docx’, ‘.txt’]:
processed_data = self.process_text(file_path)
else:
messagebox.showwarning(“Непідтримуваний формат”, “Цей формат файлу не підтримується”)
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute(“INSERT INTO files (filename, filetype, filepath, processed_data) VALUES (?, ?, ?, ?)”,
(os.path.basename(file_path), file_ext, file_path, processed_data))
conn.commit()
conn.close()
def process_image(self, file_path):
image = Image.open(file_path)
image.thumbnail((300, 300))
img = ImageTk.PhotoImage(image)
self.image_label.config(image=img)
self.image_label.image = img
logging.info(“Оброблено зображення: %s”, file_path)
def process_video(self, file_path):
cap = cv2.VideoCapture(file_path)
ret, frame = cap.read()
if ret:
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
image = Image.fromarray(frame)
image.thumbnail((300, 300))
img = ImageTk.PhotoImage(image)
self.image_label.config(image=img)
self.image_label.image = img
logging.info(“Оброблено відео: %s”, file_path)
cap.release()
def process_audio(self, file_path):
recognizer = sr.Recognizer()
with sr.AudioFile(file_path) as source:
audio = recognizer.record(source)
try:
text = recognizer.recognize_google(audio, language=”uk-UA”)
self.status_label.config(text=f”Розпізнаний текст: {text[:50]}…”)
logging.info(“Розпізнано аудіо: %s”, text)
return text
except sr.UnknownValueError:
logging.warning(“Не вдалося розпізнати аудіо”)
except sr.RequestError as e:
logging.error(“Помилка сервісу розпізнавання: %s”, e)
return “”
def process_text(self, file_path):
text_content = “”
if file_path.endswith(‘.pdf’):
with open(file_path, “rb”) as f:
reader = PyPDF2.PdfReader(f)
text_content = ” “.join([page.extract_text() for page in reader.pages if page.extract_text()])
elif file_path.endswith(‘.txt’):
with open(file_path, “r”, encoding=’utf-8′) as f:
text_content = f.read()
self.status_label.config(text=f”Завантажено текст: {text_content[:50]}…”)
logging.info(“Оброблено текстовий файл: %s”, file_path)
return text_content
def respond_to_text(self):
user_input = self.chat_entry.get()
if user_input:
self.engine.say(user_input)
self.engine.runAndWait()
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute(“INSERT INTO conversations (user_input, response) VALUES (?, ?)”, (user_input, user_input))
conn.commit()
conn.close()
logging.info(“Відповідь: %s”, user_input)
if __name__ == “__main__”:
root = tk.Tk()
app = CognitiveTrainingApp(root)
root.mainloop()




