Нужно улучшить код во первых иногда gpt выдает надпись иероглифами, а не на русском языке,
Во вторых нужно добавить для точности расчетов, чтобы выполнялись следующие расчеты
label_157 -  label_156 это значение заносилось в label_159
  


import sys
import io
import os
from PyQt6.QtCore import pyqtSlot
from PyQt6.QtWidgets import QApplication, QMainWindow, QMessageBox
from Authorization import Ui_Authorization
from Registration import Ui_Registration
from MainWindow import Ui_MainWindow

from g4f.client import Client

DATA_FILE = "user_data.txt"

# Configure stdout for UTF-8 encoding
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding="utf-8")

class AuthorizationWindow(QMainWindow, Ui_Authorization):
    def __init__(self):
        super(AuthorizationWindow, self).__init__()
        self.setupUi(self)

        self.pushButton_3.clicked.connect(self.open_registration)
        self.pushButton.clicked.connect(self.login)

        self.user_data = self.load_user_data()

    def load_user_data(self):
        if not os.path.exists(DATA_FILE):
            return {}

        user_data = {}
        with open(DATA_FILE, "r") as file:
            for line in file:
                parts = line.strip().split(",")
                if len(parts) == 2:
                    username, password = parts
                    email = ""
                elif len(parts) == 3:
                    username, password, email = parts
                else:
                    continue 
                user_data[username] = {"password": password, "email": email}
        return user_data

    def save_user_data(self):
        with open(DATA_FILE, "w") as file:
            for username, data in self.user_data.items():
                file.write(f"{username},{data['password']},{data['email']}\n")

    @pyqtSlot()
    def open_registration(self):
        self.registration_window = RegistrationWindow(self)
        self.registration_window.show()

    @pyqtSlot()
    def login(self):
        username = self.lineEdit.text()
        password = self.lineEdit_2.text()

        msg_box = QMessageBox(self)
        msg_box.setStyleSheet("background-color: white;")

        if username in self.user_data and self.user_data[username]["password"] == password:
            msg_box.setText("Вы успешно вошли в систему!")
            msg_box.setIcon(QMessageBox.Icon.Information)

            self.main_window = MainWindowWindow(self)
            self.main_window.show()
            self.close()
        else:
            msg_box.setText("Неверный логин или пароль!")
            msg_box.setIcon(QMessageBox.Icon.Warning)
        
        msg_box.exec()

class RegistrationWindow(QMainWindow, Ui_Registration):
    def __init__(self, auth_window):
        super(RegistrationWindow, self).__init__()
        self.setupUi(self)
        self.auth_window = auth_window
        self.pushButton.clicked.connect(self.save_registration)

    @pyqtSlot()
    def save_registration(self):
        email = self.lineEdit_3.text()
        username = self.lineEdit.text()
        password = self.lineEdit_2.text()
        confirm_password = self.lineEdit_4.text()

        msg_box = QMessageBox(self)
        msg_box.setStyleSheet("background-color: white;")

        if password != confirm_password:
            msg_box.setText("Пароли не совпадают!")
            msg_box.setIcon(QMessageBox.Icon.Warning)
            msg_box.exec()
            return

        self.auth_window.user_data[username] = {"password": password, "email": email}
        self.auth_window.save_user_data()
        msg_box.setText("Регистрация успешна!")
        msg_box.setIcon(QMessageBox.Icon.Information)
        msg_box.exec()

        self.close()

class MainWindowWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, auth_window):
        super(MainWindowWindow, self).__init__()
        self.setupUi(self)
        self.auth_window = auth_window
        self.initialize_signals()
        self.tabWidget.setCurrentIndex(0)

        # Initialize GPT client
        self.client = Client()

    def initialize_signals(self):
        self.comboBox_3.currentIndexChanged.connect(self.handle_comboBox_3_change)
        self.comboBox_6.currentIndexChanged.connect(self.handle_comboBox_6_change)
        self.pushButton_2.clicked.connect(self.handle_push_button_2)
        self.pushButton_3.clicked.connect(self.handle_push_button_3)
        self.pushButton_2.clicked.connect(self.switch_to_tab8)
        self.pushButton_3.clicked.connect(self.switch_to_tab7)
        self.pushButton_4.clicked.connect(self.handle_addition)

    def handle_comboBox_3_change(self, index):
        if index == 0:
            self.tabWidget.setCurrentIndex(0)
        elif index == 1:
            self.tabWidget.setCurrentIndex(1)

    def handle_comboBox_6_change(self, index):
        if index == 0:
            self.tabWidget.setCurrentIndex(2)

    def handle_push_button_2(self):
        self.tabWidget_3.setCurrentIndex(1)

    def handle_push_button_3(self):
        self.tabWidget_3.setCurrentIndex(0)

    def switch_to_tab8(self):
        self.tabWidget_2.setCurrentIndex(1)

    def switch_to_tab7(self):
        self.tabWidget_2.setCurrentIndex(0)

    @pyqtSlot()
    def handle_addition(self):
        # List to collect results and potential errors
        results = []

        # 1 год
        try:
            num1 = float(self.lineEdit_110.text())
            num2 = float(self.lineEdit_126.text())
            num3 = float(self.lineEdit_86.text())

            result = (num1 + num2)/num3
            self.label_156.setText(str(result))
            results.append(f"Result 1: {result}")
        except ValueError:
            self.label_156.setText("Ошибка ввода")
            results.append("Result 1: Ошибка ввода")

        try:
            num3 = float(self.lineEdit_86.text())
            num4 = float(self.lineEdit_29.text())
            num5 = float(self.lineEdit_23.text())

            result2 = (num3 - num4)/num5
            self.label_172.setText(str(result2))
            results.append(f"Result 2: {result2}")
        except ValueError:
            self.label_172.setText("Ошибка ввода")
            results.append("Result 2: Ошибка ввода")

        try:
            num3 = float(self.lineEdit_86.text())
            num6 = float(self.lineEdit_127.text())

            result3 = num3/num6
            self.label_180.setText(str(result3))
            results.append(f"Result 3: {result3}")
        except ValueError:
            self.label_180.setText("Ошибка ввода")
            results.append("Result 3: Ошибка ввода")

        try:
            num3 = float(self.lineEdit_86.text())
            num1 = float(self.lineEdit_110.text())
            num2 = float(self.lineEdit_126.text())

            result4 = num3/(num1+num2)
            self.label_164.setText(str(result4))
            results.append(f"Result 4: {result4}")
        except ValueError:
            self.label_164.setText("Ошибка ввода")
            results.append("Result 4: Ошибка ввода")

        try:
            num3 = float(self.lineEdit_86.text())
            num1 = float(self.lineEdit_110.text())
            num6 = float(self.lineEdit_127.text())

            result5 = (num3+num1)/(num6)
            self.label_148.setText(str(result5))
            results.append(f"Result 5: {result5}")
        except ValueError:
            self.label_148.setText("Ошибка ввода")
            results.append("Result 5: Ошибка ввода")

        #2 год   
        try:
            num21 = float(self.lineEdit_116.text())
            num22 = float(self.lineEdit_146.text())
            num23 = float(self.lineEdit_93.text())

            result21 = (num21 + num22)/num23
            self.label_158.setText(str(result21))
            results.append(f"Result 21: {result21}")
        except ValueError:
            self.label_158.setText("Ошибка ввода")
            results.append("Result 21: Ошибка ввода")
        
        try:
            num23 = float(self.lineEdit_93.text())
            num24 = float(self.lineEdit_47.text())
            num25 = float(self.lineEdit_66.text())

            result22 = (num23 - num24)/num25
            self.label_173.setText(str(result22))
            results.append(f"Result 22: {result22}")
        except ValueError:
            self.label_173.setText("Ошибка ввода")
            results.append("Result 22: Ошибка ввода")

        try:
            num23 = float(self.lineEdit_93.text())
            num26 = float(self.lineEdit_147.text())

            result23 = num23/num26
            self.label_181.setText(str(result23))
            results.append(f"Result 23: {result23}")
        except ValueError:
            self.label_181.setText("Ошибка ввода")
            results.append("Result 23: Ошибка ввода")

        try:
            num23 = float(self.lineEdit_93.text())
            num21 = float(self.lineEdit_116.text())
            num22 = float(self.lineEdit_146.text())

            result24 = num23/(num21+num22)
            self.label_165.setText(str(result24))
            results.append(f"Result 24: {result24}")
        except ValueError:
            self.label_165.setText("Ошибка ввода")
            results.append("Result 24: Ошибка ввода")
        try:
            num23 = float(self.lineEdit_93.text())
            num21 = float(self.lineEdit_116.text())
            num26 = float(self.lineEdit_147.text())

            result25 = (num23+num21)/(num26)
            self.label_149.setText(str(result25))
            results.append(f"Result 25: {result25}")
        except ValueError:
            self.label_149.setText("Ошибка ввода")
            results.append("Result 25: Ошибка ввода")

        #3 год   
        try:
            num31 = float(self.lineEdit_117.text())
            num32 = float(self.lineEdit_145.text())
            num33 = float(self.lineEdit_100.text())

            result31 = (num31 + num32)/num33
            self.label_157.setText(str(result31))
            results.append(f"Result 31: {result31}")
        except ValueError:
            self.label_157.setText("Ошибка ввода")
            results.append("Result 31: Ошибка ввода")

        try:
            num33 = float(self.lineEdit_100.text())
            num34 = float(self.lineEdit_48.text())
            num35 = float(self.lineEdit_71.text())

            result32 = (num33 - num34)/num35
            self.label_174.setText(str(result32))
            results.append(f"Result 32: {result32}")
        except ValueError:
            self.label_174.setText("Ошибка ввода")
            results.append("Result 32: Ошибка ввода")


        try:
            num33 = float(self.lineEdit_100.text())
            num36 = float(self.lineEdit_148.text())

            result33 = num33/num36
            self.label_182.setText(str(result33))
            results.append(f"Result 33: {result33}")
        except ValueError:
            self.label_182.setText("Ошибка ввода")
            results.append("Result 33: Ошибка ввода")

        try:
            num33 = float(self.lineEdit_100.text())
            num31 = float(self.lineEdit_117.text())
            num32 = float(self.lineEdit_145.text())

            result34 = num33/(num31+num32)
            self.label_166.setText(str(result34))
            results.append(f"Result 34: {result34}")
        except ValueError:
            self.label_166.setText("Ошибка ввода")
            results.append("Result 34: Ошибка ввода")

        try:
            num33 = float(self.lineEdit_100.text())
            num31 = float(self.lineEdit_117.text())
            num36 = float(self.lineEdit_148.text())

            result35 = (num33+num31)/(num36)
            self.label_150.setText(str(result35))
            results.append(f"Result 35: {result35}")
        except ValueError:
            self.label_150.setText("Ошибка ввода")
            results.append("Result 35: Ошибка ввода")

        # Call GPT to analyze results
        self.analyze_with_gpt(" ".join(results))

    def analyze_with_gpt(self, text):
        messages = [{"role": "user", "content": text}]
        response = self.client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=messages,
        )
        analyzed_text = response.choices[0].message.content
        self.label_139.setText(analyzed_text)

def main():
    app = QApplication(sys.argv)

    auth_window = AuthorizationWindow()
    auth_window.show()

    sys.exit(app.exec())

if __name__ == "__main__":
    main()