File size: 10,877 Bytes
3bb13c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
import os
import csv
import json
import logging
from datetime import datetime
import time
import psutil  # type: ignore
import GPUtil  # type: ignore
import traceback


class LoggingManager:
    def __init__(self, settings):
        self.settings = settings
        self.log_dir = "logs"
        self.feedback_dir = "feedback"
        self.ensure_directories()
        self.setup_logging()
        self.benchmark_file = None
        self.feedback_file = None
        self.error_file = None
        self.last_api_params = None
        self.last_status_message = ""
        self.loading_symbols = ["|", "/", "-", "\\"]
        self.loading_index = 0

    def log_npc_manager(self, message):
        """บันทึกข้อความสำหรับ NPC Manager แบบกรองแล้ว"""
        # ข้อความสำคัญที่ต้องการแสดง
        important_messages = [
            "NPC Manager started",
            "Data loaded successfully",
            "Font system ready",
            "Error:",
            "Warning:",
        ]

        # แสดงเฉพาะข้อความสำคัญ
        if any(msg in message for msg in important_messages):
            print(message)

    def log_startup_info(self):
        """บันทึกข้อมูลสำคัญตอนเริ่มต้นระบบ"""
        current_model = self.settings.get_displayed_model()
        screen_size = self.settings.get("screen_size", "2560x1440")
        use_gpu = self.settings.get("use_gpu_for_ocr", False)

        startup_info = [
            "=== MagicBabel System Started ===",
            f"Model: {current_model}",
            f"Screen Size: {screen_size}",
            f"OCR Processing: {'GPU' if use_gpu else 'CPU'}",
            "===============================",
        ]

        for line in startup_info:
            logging.info(line)
            print(line)

    def log_model_change(self, old_model, new_model, parameters):
        """บันทึกการเปลี่ยนแปลง model"""
        log_lines = [
            "=== Model Change ===",
            f"From: {old_model}",
            f"To: {new_model}",
            "Parameters:",
            f"- Max Tokens: {parameters.get('max_tokens', 'N/A')}",
            f"- Temperature: {parameters.get('temperature', 'N/A')}",
            "===================",
        ]

        for line in log_lines:
            logging.info(line)
            print(line)

    def log_system_status(self):
        """บันทึกสถานะระบบ"""
        memory_usage = psutil.Process().memory_info().rss / 1024 / 1024  # MB
        gpu_usage = (
            self.get_gpu_usage() if self.settings.get("use_gpu_for_ocr") else "N/A"
        )

        status_lines = [
            "=== System Status ===",
            f"Memory Usage: {memory_usage:.2f} MB",
            f"GPU Usage: {gpu_usage}",
            "====================",
        ]

        for line in status_lines:
            logging.info(line)
            print(line)

    def ensure_directories(self):
        for directory in [self.log_dir, self.feedback_dir]:
            if not os.path.exists(directory):
                os.makedirs(directory)

    def setup_logging(self):
        logging.basicConfig(
            filename=os.path.join(self.log_dir, "app.log"),
            level=logging.INFO,
            format="%(asctime)s - %(levelname)s - %(message)s",
        )
        logging.info("Logging initialized")

    def init_benchmark_logging(self):
        self.benchmark_file = os.path.join(
            self.log_dir, f"benchmark_{datetime.now().strftime('%Y%m%d')}.csv"
        )
        file_exists = os.path.isfile(self.benchmark_file)

        with open(self.benchmark_file, "a", newline="") as file:
            writer = csv.writer(file)
            if not file_exists:
                writer.writerow(
                    ["Timestamp", "Action", "Duration", "Memory Usage", "GPU Usage"]
                )
        logging.info(f"Benchmark logging initialized: {self.benchmark_file}")

    def log_benchmark(self, action, duration):
        if not self.benchmark_file or not os.path.isfile(self.benchmark_file):
            self.init_benchmark_logging()

        memory_usage = psutil.Process().memory_info().rss / 1024 / 1024  # MB
        gpu_usage = (
            self.get_gpu_usage() if self.settings.get("use_gpu_for_ocr") else "N/A"
        )

        with open(self.benchmark_file, "a", newline="") as file:
            writer = csv.writer(file)
            writer.writerow([datetime.now(), action, duration, memory_usage, gpu_usage])

        # เปลี่ยนจาก logging.info เป็น self.update_status
        self.update_status(f"Benchmark: {action}, Duration: {duration:.4f}s")

    def get_gpu_usage(self):
        try:
            gpus = GPUtil.getGPUs()
            if gpus:
                return f"{gpus[0].load * 100:.2f}%"
        except Exception as e:
            logging.error(f"Error getting GPU usage: {e}")
        return "N/A"

    def log_api_params_change(self):
        current_api_params = self.settings.get_api_parameters()
        if current_api_params != self.last_api_params:
            today = datetime.now().strftime("%Y%m%d")
            self.feedback_file = os.path.join(
                self.feedback_dir, f"feedback_{today}.json"
            )

            api_change_data = {
                "timestamp": datetime.now().isoformat(),
                "new_params": current_api_params,
            }

            if os.path.isfile(self.feedback_file):
                with open(self.feedback_file, "r+", encoding="utf-8") as file:
                    data = json.load(file)
                    if "api_params_changes" not in data:
                        data["api_params_changes"] = []
                    data["api_params_changes"].append(api_change_data)
                    data["api_parameters"] = current_api_params
                    file.seek(0)
                    file.truncate()
                    json.dump(data, file, indent=2, ensure_ascii=False)
            else:
                with open(self.feedback_file, "w", encoding="utf-8") as file:
                    initial_data = {
                        "api_parameters": current_api_params,
                        "api_params_changes": [api_change_data],
                        "feedbacks": [],
                    }
                    json.dump(initial_data, file, indent=2, ensure_ascii=False)

            self.last_api_params = current_api_params
            logging.info("API parameters updated and logged")

    def log_error(self, error_message):
        logging.error(error_message)
        self.write_error_to_file(error_message)

    def write_error_to_file(self, error_message):
        today = datetime.now().strftime("%Y%m%d")
        self.error_file = os.path.join(self.log_dir, f"error_{today}.log")

        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        formatted_error = f"[{timestamp}] {error_message}\n"
        formatted_error += f"Traceback:\n{traceback.format_exc()}\n\n"

        with open(self.error_file, "a", encoding="utf-8") as file:
            file.write(formatted_error)

    def log_info(self, info_message):
        """

        บันทึก log ข้อมูลโดยไม่แสดงซ้ำ

        """
        # ข้อความที่ไม่ต้องบันทึกซ้ำ
        skip_logging_messages = {
            "OCR scanning...",
            "OCR completed",
            "Waiting for text...",
            "Translating...",
        }

        if info_message not in skip_logging_messages:
            logging.info(info_message)

    def log_warning(self, warning_message):
        logging.warning(warning_message)
        self.write_error_to_file(f"WARNING: {warning_message}")

    def log_critical(self, critical_message):
        logging.critical(critical_message)
        self.write_error_to_file(f"CRITICAL: {critical_message}")

    def update_status(self, message):
        """

        อัพเดทและแสดงสถานะแบบต่อเนื่องในบรรทัดเดียว

        Args:

            message: ข้อความที่ต้องการแสดง

        """
        current_time = time.time()

        # สถานะการทำงานต่อเนื่อง
        continuous_states = {
            "OCR scanning": {
                "icon": "🔍",
                "variants": ["scanning.", "scanning..", "scanning..."],
            },
            "Waiting for text": {
                "icon": "⌛",
                "variants": ["waiting.", "waiting..", "waiting..."],
            },
        }

        # ตรวจสอบว่าเป็นสถานะต่อเนื่องหรือไม่
        for state, config in continuous_states.items():
            if state in message:
                if not hasattr(self, "_animation_state"):
                    self._animation_state = 0
                    self._last_animation_time = 0

                # อัพเดทแอนิเมชันทุก 0.3 วินาที
                if current_time - self._last_animation_time > 0.3:
                    self._animation_state = (self._animation_state + 1) % len(
                        config["variants"]
                    )
                    self._last_animation_time = current_time

                display_message = f"{config['icon']} {state}{config['variants'][self._animation_state]}"
                print(f"\r{display_message:<60}", end="", flush=True)
                return

        # ข้อความที่ไม่ต้องแสดงซ้ำ
        skip_messages = {"OCR completed", "Processing image"}

        if message in skip_messages:
            if hasattr(self, "_last_message") and self._last_message == message:
                return

        # เก็บข้อความล่าสุด
        self._last_message = message

        # แสดงข้อความสำคัญเท่านั้น
        important_messages = {
            "Translation updated": "✅ Translation updated",
            "Error": "❌ Error detected",
        }

        if message in important_messages:
            display_message = important_messages[message]
            print(f"\r{display_message:<60}", end="", flush=True)
            logging.info(message)