Опиши, что делает данный код


from twisted.internet import reactor, protocol
import yaml
import sys
import os
import logging
import re
from twisted.internet import threads
import subprocess
import platform

from src.logic_refactor.test_logic import TestLogic
from src.logic_refactor.image_processing import StaticProcessingLogic, DynamicProcessingLogic
from src.logic_refactor.model_3d import Model3DLogic


class EchoFactory(protocol.Factory):
    def __init__(self, main):
        super().__init__()
        self.main = main

    def buildProtocol(self, addr):
        proto = Echo(self.main)
        proto.factory = self
        return proto


class Echo(protocol.Protocol):
    def __init__(self, main):
        super().__init__()
        self.main = main

    def dataReceived(self, data):
        try:
            if data == "calculate".encode('utf-8'):
                thread_calculate = threads.deferToThread(self.handle_static_calculation)
                #self.handle_static_calculation()
            elif data == "calculate_dynamic".encode('utf-8'):
                thread_calculate_dynamic = threads.deferToThread(self.handle_dynamic_calculation)
                #self.handle_dynamic_calculation()
            elif data == "3d".encode('utf-8'):
                thread_3d = threads.deferToThread(self.handle_3d)
                #self.handle_3d()
            elif data == "show_model".encode('utf-8'):
                #thread_show_model = threads.deferToThread(self.handle_show_model)
                self.handle_show_model()
            elif data == "kill".encode('utf-8'):
                self.main.kill()
            elif data == "reload".encode('utf-8'):
                self.main.reload()
                self.transport.write("reload_ready".encode('utf-8'))
            else:
                self.main.logger.info("Был выслан неизвестный TCP запрос")
                self.transport.write(data)
        except Exception:
            pass

    def handle_static_calculation(self):
        self.main.logger.info("TCP RECEIVED - calculate")

        calculater = StaticProcessingLogic(
            "calculatron/input/ready_photo.png",
            "calculatron/input/info.json",
            self.main.config
        )

        self.main.if_previous_request_was_static_drape = True

        try:
            self.main.logger.info("Начат расчёт статических коэффициентов")
            calculater.calculate()
            self.main.logger.info("Закончен расчёт статических коэффициентов")

            self.main.logger.info("Начато создание визуализации для статических коэффициентов")
            calculater.create_plots()
            self.transport.write("ready".encode('utf-8'))
            self.main.logger.info("Закончено создание визуализации для статических коэффициентов")

            del calculater

            self.main.logger.info("TCP SENDED - ready")
        except Exception as exp:
            self.main.logger.exception(exp)

    def handle_dynamic_calculation(self):
        self.main.logger.info("TCP RECEIVED - calculate_dynamic")

        calculater = DynamicProcessingLogic([
            "calculatron/input/ready_photo_60rpm.png",
            "calculatron/input/ready_photo_80rpm.png",
            "calculatron/input/ready_photo_100rpm.png",
            "calculatron/input/ready_photo_120rpm.png",
        ],
            "calculatron/input/info.json",
            self.main.config,
            self.main.if_previous_request_was_static_drape
        )

        self.main.if_previous_request_was_static_drape = False

        try:
            self.main.logger.info("Начат расчёт динамических коэффициентов")
            calculater.calculate()
            self.transport.write("dynamic_ready".encode('utf-8'))
            self.main.logger.info("Закончен расчёт динамических коэффициентов")

            del calculater

            self.main.logger.info("TCP SENDED - dynamic_ready")
        except Exception as exp:
            self.main.logger.exception(exp)

    def handle_3d(self):
        self.main.logger.info("TCP RECEIVED - 3d")

        calculater = Model3DLogic(
            "calculatron/input/3D",
            self.main.config
        )

        self.main.if_previous_request_was_static_drape = False

        try:
            self.main.logger.info("Происходит создание 3d модели")
            calculater.create_3d()
            self.transport.write("3d_ready".encode('utf-8'))
            self.main.logger.info("Закончено создание 3d модели")

            del calculater

            self.main.logger.info("TCP SENDED - 3d_ready")
        except Exception as exp:
            self.main.logger.exception(exp)

    def handle_show_model(self):
        self.main.logger.info("TCP RECEIVED - show_model")

        calculater = Model3DLogic(
            "calculatron/input/3D",
            self.main.config
        )

        self.main.if_previous_request_was_static_drape = False

        try:
            self.main.logger.info("Происходит визуализация 3d модели")
            calculater.visualise_3d_model()
            self.transport.write("show_model_ready".encode('utf-8'))
            self.main.logger.info("Визуализация 3d модели закончена")

            del calculater

            self.main.logger.info("TCP SENDED - show_model_ready")
        except Exception as exp:
            self.main.logger.exception(exp)


class Main:
    def __init__(self):
        self.logger = None
        self.config = None
        self.endpoint = None
        self.if_previous_request_was_static_drape = False

        self._get_config()
        self._setup_app()
        #self._check_out_process()

    def _get_config(self):
        try:
            with open("calculatron/config.yaml", "r") as file:
                self.config = yaml.safe_load(file)
        except FileNotFoundError as error:
            self.config = {"server": {"host": "localhost", "port": 8000},
                           "logger": {"level": "INFO"},
                           "image_processing": {"cm_in_pixels": 0.1}}
        except Exception as error:
            raise error

    def _check_out_process_old(self):
        # Завершает процесс, использующий заданный порт, в зависимости от ОС
        os_name = platform.system()
        port = self.config["server"]["port"]

        if os_name == "Linux" or os_name == "Darwin":  # Для Unix-подобных систем (Linux, macOS)
            try:
                # Получение PID’а на UNIX системах.
                pid = subprocess.check_output(["lsof", "-i", f":{port}", "-t"]).decode().strip()

                if pid:
                    self.logger.info(f"Найден процесс на порту {port} с PID {pid}. Попытка его завершения…")
                    # Завершение процесса.
                    subprocess.check_output(["kill", "-9", pid])
                    self.logger.info("Процесс успешно завершен.")
            except subprocess.CalledProcessError as e:
                self.logger.info(f"Не удалось завершить процесс на порту {port}: {e}")

        elif os_name == "Windows":  # Для Windows
            try:
                # Находим PID процесса, использующего порт, на Windows.
                lines = subprocess.check_output(["netstat", "-aon", "|", "findstr", f":{port}"]).decode().strip().splitlines()
                pids = set(line.rstrip().split()[-1] for line in lines if "LISTENING" in line)
                for pid in pids:
                    self.logger.info(f"Найден процесс на порту {port} с PID {pid}. Попытка его завершения…")
                    # Завершение процесса.
                    subprocess.check_output(["taskkill", "/F", "/PID", pid])
                    self.logger.info("Процесс успешно завершен.")
            except subprocess.CalledProcessError as e:
                self.logger.info(f"Не удалось завершить процесс на порту {port}: {e}")
        else:
            pass

    def _check_out_process(self):
        os_name = platform.system()
        port = self.config["server"]["port"]

        try:
            if os_name == "Linux" or os_name == "Darwin":  # Unix-подобные
                pid = subprocess.check_output(f"lsof -t -i:{port}", shell=True).decode().strip()
                if pid:
                    subprocess.check_output(f"kill -9 {pid}", shell=True)
                    print("Процесс успешно завершен.")
                elif os_name == "Windows":  # Windows
                    # Запуск netstat и поиск PID
                    output = subprocess.check_output(f"netstat -aon", shell=True).decode()
                    pattern = re.compile(f".:{port}.", re.MULTILINE)
                    matches = pattern.findall(output)
                    for match in matches:
                        pid = match.strip().split()[-1]  # Предполагаем, что PID - это последний столбец
                        # Завершение процесса
                        subprocess.check_output(f"taskkill /F /PID {pid}", shell=True)
                        print("Процесс успешно завершен.")
        except subprocess.CalledProcessError as e:
            print(f"Не удалось завершить процесс на порту {port}: {e}")

    def _setup_app(self):
        try:
            os.mkdir(os.path.join("calculatron", "src", "logs"))
        except OSError as error:
            pass
        except Exception as error:
            raise error
        try:
            os.mkdir(os.path.join("calculatron", "input"))
        except OSError as error:
            pass
        try:
            os.mkdir(os.path.join("calculatron", "input", "3D"))
        except OSError as error:
            pass
        except Exception as error:
            raise error
        try:
            os.mkdir(os.path.join("calculatron", "output"))
        except OSError as error:
            pass
        except Exception as error:
            raise error
        try:
            os.mkdir(os.path.join("calculatron", "cache"))
        except OSError as error:
            pass
        except Exception as error:
            raise error
        try:
            os.mkdir(os.path.join("calculatron", "cache", "static_photos"))
        except OSError as error:
            pass
        except Exception as error:
            raise error
        try:
            os.mkdir(os.path.join("calculatron", "cache", "dynamic_photos"))
        except OSError as error:
            pass
        except Exception as error:
            raise error

        logging.basicConfig(level=self.config["logger"]["level"])

        self.logger = logging.getLogger("server")
        self.logger.handlers.clear()
        formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")

        console_handler = logging.StreamHandler()
        console_handler.setFormatter(formatter)

        file_handler = logging.FileHandler(os.path.join("calculatron", "src", "logs", "server.log"), encoding="utf-8")
        file_handler.setFormatter(formatter)

        self.logger.addHandler(console_handler)
        self.logger.addHandler(file_handler)

    def run(self):