summaryrefslogtreecommitdiffstats
path: root/workers/translation_worker.py
blob: e4caa3595b91f28505570c7be4f9e0b5e8f14f20 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
from __future__ import annotations
from PyQt6.QtCore import QObject, QProcess, pyqtSignal
from pathlib import Path

class TranslationWorker(QObject):
    log_line = pyqtSignal(str)
    finished = pyqtSignal(bool, str)  # success, output_path
    error = pyqtSignal(str)

    def __init__(self, transart_script: Path, article_path: Path, direction: str, parent=None):
        super().__init__(parent)
        self._script = transart_script
        self._article_path = article_path
        self._direction = direction  # e.g. "it-en" or "en-it"
        self._process = QProcess(self)
        self._process.readyReadStandardOutput.connect(self._on_stdout)
        self._process.readyReadStandardError.connect(self._on_stderr)
        self._process.finished.connect(self._on_finished)

    def start(self):
        self._process.start("python3", [
            str(self._script),
            "--direction", self._direction,
            str(self._article_path),
        ])

    def _on_stdout(self):
        data = self._process.readAllStandardOutput().data().decode("utf-8", errors="replace")
        for line in data.splitlines():
            self.log_line.emit(line)

    def _on_stderr(self):
        data = self._process.readAllStandardError().data().decode("utf-8", errors="replace")
        for line in data.splitlines():
            self.log_line.emit(f"[stderr] {line}")

    def _on_finished(self, exit_code: int, _):
        success = exit_code == 0
        path_str = str(self._article_path)
        if "/it/" in path_str:
            out = path_str.replace("/it/", "/en/", 1)
        elif "/en/" in path_str:
            out = path_str.replace("/en/", "/it/", 1)
        else:
            out = ""
        if not success:
            self.error.emit(f"transart.py exited with code {exit_code}")
        self.finished.emit(success, out)