| import time
|
| import re
|
| import json
|
| import os
|
| from enum import Enum
|
| import logging
|
|
|
|
|
|
|
| class DialogueType(Enum):
|
| NORMAL = "normal"
|
| CHARACTER = "character"
|
| CHOICE = "choice"
|
| SYSTEM = "system"
|
|
|
|
|
| class NameConfidence:
|
| def __init__(self, name):
|
| self.name = name
|
| self.confidence = 0.8
|
| self.last_update = time.time()
|
|
|
| def add_appearance(self):
|
| """อัพเดทเวลาล่าสุดที่พบชื่อนี้"""
|
| self.last_update = time.time()
|
|
|
| def should_confirm(self):
|
| """ตรวจสอบว่าควรยืนยันชื่อนี้หรือไม่"""
|
| return (
|
| self.confidence >= 0.7
|
| and len(self.appearances) >= 2
|
| and time.time() - self.appearances[0]["time"] < 600
|
| )
|
|
|
|
|
| class TextCorrector:
|
| def __init__(self):
|
| self.load_npc_data()
|
|
|
|
|
| initial_data = {"npcs": [], "last_updated": time.time(), "version": "1.0"}
|
| if not os.path.exists("new_friends.json"):
|
| try:
|
| with open("new_friends.json", "w", encoding="utf-8") as f:
|
| json.dump(initial_data, f, indent=4, ensure_ascii=False)
|
| logging.info("Created new new_friends.json file")
|
| except Exception as e:
|
| logging.error(f"Failed to create new_friends.json: {e}")
|
|
|
|
|
| self.load_new_friends()
|
|
|
|
|
| self.temp_names_cache = []
|
| self.confirmed_names = set()
|
| self.max_cached_names = 10
|
|
|
| def load_new_friends(self):
|
| """โหลดชื่อที่ยืนยันแล้วจาก new_friends.json"""
|
| try:
|
| if os.path.exists("new_friends.json"):
|
| with open("new_friends.json", "r", encoding="utf-8") as f:
|
| data = json.load(f)
|
| for npc in data.get("npcs", []):
|
| self.confirmed_names.add(npc["name"])
|
| except Exception as e:
|
| logging.error(f"Error loading new_friends.json: {e}")
|
|
|
| def save_new_friend(self, name, role="Unknown", description="Found in dialogue"):
|
| try:
|
|
|
| initial_data = {"npcs": [], "last_updated": time.time(), "version": "1.0"}
|
|
|
|
|
| if os.path.exists("new_friends.json"):
|
| with open("new_friends.json", "r", encoding="utf-8") as f:
|
| data = json.load(f)
|
| else:
|
| data = initial_data
|
| logging.info("Creating new new_friends.json file")
|
|
|
|
|
| if not any(npc["name"] == name for npc in data["npcs"]):
|
|
|
| npc_data = {
|
| "name": name,
|
| "role": role,
|
| "description": description,
|
| "added_timestamp": time.time(),
|
| "confidence": 1.0,
|
| }
|
| data["npcs"].append(npc_data)
|
| data["last_updated"] = time.time()
|
|
|
|
|
| with open("new_friends.json", "w", encoding="utf-8") as f:
|
| json.dump(data, f, indent=4, ensure_ascii=False)
|
|
|
| self.confirmed_names.add(name)
|
| logging.info(f"New friend saved: {name}")
|
|
|
| except Exception as e:
|
| logging.error(f"Error saving new friend: {e}")
|
|
|
| if not os.path.exists("new_friends.json"):
|
| try:
|
| with open("new_friends.json", "w", encoding="utf-8") as f:
|
| json.dump(initial_data, f, indent=4, ensure_ascii=False)
|
| logging.info("Created new new_friends.json file after error")
|
| except Exception as e2:
|
| logging.error(f"Failed to create new_friends.json: {e2}")
|
|
|
| def cache_new_name(self, name):
|
| """เพิ่มชื่อใหม่เข้าแคชแบบวงกลม"""
|
|
|
| for cached in self.temp_names_cache:
|
| if cached.name == name:
|
| cached.add_appearance()
|
| return cached.name
|
|
|
|
|
| new_name = NameConfidence(name)
|
| self.temp_names_cache.append(new_name)
|
|
|
|
|
| if len(self.temp_names_cache) > self.max_cached_names:
|
| self.temp_names_cache.pop(0)
|
|
|
| return name
|
|
|
| def find_similar_cached_name(self, name):
|
| """ค้นหาชื่อที่คล้ายกันในแคช"""
|
| highest_similarity = 0
|
| best_match = None
|
|
|
| for cached in self.temp_names_cache:
|
| similarity = self.calculate_name_similarity(name, cached.name)
|
| if (
|
| similarity > highest_similarity and similarity > 0.7
|
| ):
|
| highest_similarity = similarity
|
| best_match = cached.name
|
|
|
| return best_match
|
|
|
| def is_likely_character_name(self, text):
|
| """ตรวจสอบว่าข้อความน่าจะเป็นชื่อคนหรือไม่"""
|
| words = text.split()
|
| first_word = words[0] if words else ""
|
|
|
|
|
| if not first_word or not first_word[0].isupper():
|
| return False
|
|
|
|
|
| special_chars = sum(1 for c in text if not c.isalnum() and c not in "' -")
|
| if special_chars > 1:
|
| return False
|
|
|
|
|
| if len(text) < 2 or len(text) > 50:
|
| return False
|
|
|
|
|
| common_words = {
|
| "the",
|
| "a",
|
| "an",
|
| "this",
|
| "that",
|
| "these",
|
| "those",
|
| "here",
|
| "there",
|
| }
|
| first_word_lower = first_word.lower()
|
|
|
|
|
| if first_word_lower in common_words:
|
| return False
|
|
|
|
|
| connecting_words = {"van", "von", "de", "del", "of", "the"}
|
| for word in words[1:]:
|
| if not word[0].isupper() and word.lower() not in connecting_words:
|
| return False
|
|
|
| return True
|
|
|
| def load_npc_data(self):
|
| try:
|
| with open("NPC.json", "r", encoding="utf-8") as file:
|
| npc_data = json.load(file)
|
| self.word_corrections = npc_data["word_fixes"]
|
| self.names = set()
|
|
|
|
|
| self.names.add("???")
|
|
|
|
|
| for char in npc_data["main_characters"]:
|
| self.names.add(char["firstName"])
|
| if char["lastName"]:
|
| self.names.add(f"{char['firstName']} {char['lastName']}")
|
|
|
|
|
| for npc in npc_data["npcs"]:
|
| self.names.add(npc["name"])
|
|
|
| print("TextCorrector: Loaded names:", self.names)
|
|
|
| except FileNotFoundError:
|
| raise FileNotFoundError("NPC.json file not found")
|
| except json.JSONDecodeError:
|
| raise ValueError("Invalid JSON in NPC.json")
|
|
|
| def correct_text(self, text):
|
|
|
| if text.strip() in ["22", "22?", "222", "222?", "???"]:
|
| return "???"
|
|
|
|
|
| text = re.sub(r"^(22|222)\s*", "??? ", text)
|
|
|
| speaker, content, dialogue_type = self.split_speaker_and_content(text)
|
|
|
| if speaker and speaker != "???":
|
| speaker = re.sub(r"[^\w\s\u0E00-\u0E7F]", "", speaker)
|
|
|
| words = content.split() if content else []
|
| corrected_words = []
|
| for word in words:
|
| if not re.search(r"[\u0E00-\u0E7F]", word):
|
| word = self.word_corrections.get(word, word)
|
| corrected_words.append(word)
|
|
|
| content = (
|
| self.clean_content(" ".join(corrected_words)) if corrected_words else ""
|
| )
|
|
|
| if speaker:
|
| return f"{speaker}: {content}" if content else speaker
|
| return content
|
|
|
| def _clean_name(self, name):
|
| """ทำความสะอาดชื่อเพื่อเปรียบเทียบ"""
|
| if not name:
|
| return ""
|
| name = name.lower().strip()
|
| replacements = {
|
| "'": "",
|
| "`": "",
|
| " ": "",
|
| "z": "2",
|
| "$": "s",
|
| "0": "o",
|
| "1": "l",
|
| }
|
| for old, new in replacements.items():
|
| name = name.replace(old, new)
|
| return name
|
|
|
| def calculate_name_similarity(self, name1, name2):
|
| """คำนวณความคล้ายคลึงของชื่อ"""
|
| if not name1 or not name2:
|
| return 0
|
|
|
| clean_name1 = self._clean_name(name1)
|
| clean_name2 = self._clean_name(name2)
|
|
|
| if clean_name1 == clean_name2:
|
| return 1.0
|
|
|
| len1, len2 = len(clean_name1), len(clean_name2)
|
| if len1 == 0 or len2 == 0:
|
| return 0
|
|
|
| matrix = [[0] * (len2 + 1) for _ in range(len1 + 1)]
|
|
|
| for i in range(len1 + 1):
|
| matrix[i][0] = i
|
| for j in range(len2 + 1):
|
| matrix[0][j] = j
|
|
|
| for i in range(1, len1 + 1):
|
| for j in range(1, len2 + 1):
|
| if clean_name1[i - 1] == clean_name2[j - 1]:
|
| matrix[i][j] = matrix[i - 1][j - 1]
|
| else:
|
| matrix[i][j] = min(
|
| matrix[i - 1][j] + 1,
|
| matrix[i][j - 1] + 1,
|
| matrix[i - 1][j - 1] + 1,
|
| )
|
|
|
| distance = matrix[len1][len2]
|
| max_length = max(len1, len2)
|
| similarity = 1 - (distance / max_length)
|
|
|
| return similarity
|
|
|
| def is_numeric_name(self, name: str) -> bool:
|
| """
|
| ตรวจสอบว่าชื่อเป็นตัวเลขหรือไม่
|
| Args:
|
| name: ชื่อที่ต้องการตรวจสอบ
|
| Returns:
|
| bool: True ถ้าชื่อเป็นตัวเลข, False ถ้าไม่ใช่
|
| """
|
|
|
| cleaned_name = re.sub(r"[^a-zA-Z0-9]", "", name)
|
|
|
| return cleaned_name.isdigit()
|
|
|
| def split_speaker_and_content(self, text):
|
| """แยกชื่อผู้พูดและเนื้อหา"""
|
|
|
| if text.startswith(("???", "??", "22", "222")):
|
| for separator in [": ", " - ", " – "]:
|
| if separator in text:
|
| content = text.split(separator, 1)[1].strip()
|
| return "???", content, DialogueType.CHARACTER
|
| return None, text, DialogueType.NORMAL
|
|
|
|
|
| text = text.replace("_", "")
|
|
|
|
|
| content_separators = [": ", " - ", " – "]
|
| speaker = None
|
| content = None
|
|
|
| for separator in content_separators:
|
| if separator in text:
|
| parts = text.split(separator, 1)
|
| if len(parts) == 2:
|
| speaker = parts[0].strip()
|
| content = parts[1].strip()
|
|
|
|
|
| if self.is_numeric_name(speaker):
|
| return None, text, DialogueType.NORMAL
|
|
|
|
|
| if speaker.startswith("?"):
|
| speaker = "???"
|
| return speaker, content.strip(), DialogueType.CHARACTER
|
|
|
|
|
| if speaker in self.names or speaker in self.confirmed_names:
|
| return speaker, content.strip(), DialogueType.CHARACTER
|
| else:
|
|
|
| return None, text, DialogueType.NORMAL
|
|
|
|
|
| return None, text, DialogueType.NORMAL
|
|
|
| def clean_content(self, content):
|
|
|
|
|
|
|
| content = re.sub(
|
| r"[^\w\s\u0E00-\u0E7F\u3130-\u318F\uAC00-\uD7AF.!...—]",
|
| "",
|
| content
|
| )
|
|
|
|
|
| content = content.replace("|", "I")
|
|
|
|
|
| content = re.sub(r'(^|(?<=\s))!(?![\s"\'.])', "I", content)
|
|
|
|
|
| content = re.sub(r"[_\-]{2,}", "...", content)
|
|
|
|
|
| content = re.sub(r"\s+", " ", content)
|
|
|
|
|
| if not content.endswith(("...", "!", "—")):
|
| content = re.sub(r"\.{1,2}$", "...", content)
|
|
|
|
|
| content = content.replace(" - ", " — ")
|
|
|
| return content.strip()
|
|
|
| def reload_data(self):
|
| """โหลดข้อมูลใหม่"""
|
| print("TextCorrector: Reloading NPC data...")
|
| self.load_npc_data()
|
|
|
| self.temp_names_cache.clear()
|
| self.load_new_friends()
|
| print("TextCorrector: Data reloaded successfully")
|
|
|