MagiciteBabel / loggings.py
iarcanar's picture
Upload 23 files
3bb13c3 verified
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)