File size: 5,639 Bytes
f9b0dca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import json
import glob
import re
from collections import Counter

CHUNKS_DIR = "d:/NLP_KMH/Chatbot_NIHE_v2/data/chunks"

# Keywords for topic definition
# Keywords for topic definition
TOPIC_KEYWORDS = {
    "Tiêm chủng & Vắc xin": ["tiêm chủng", "vắc xin", "vaccine", "lịch tiêm", "tiêm phòng", "phản ứng sau tiêm", "an toàn tiêm chủng"],
    "Bệnh truyền nhiễm": ["sốt xuất huyết", "tay chân miệng", "sởi", "cúm", "bệnh dại", "covid", "hiv", "aids", "viêm gan", "lao", "bạch hầu", "ho gà", "uốn ván", "vi rút", "vi khuẩn", "truyền nhiễm", "dịch bệnh", "h5n1", "ev71"],
    "Bệnh không lây nhiễm": ["bệnh không lây nhiễm", "tiểu đường", "đái tháo đường", "ung thư", "tim mạch", "huyết áp", "tâm thần", "trầm cảm", "béo phì", "dinh dưỡng", "rối loạn chuyển hóa"],
    "Sức khỏe cộng đồng": ["sức khỏe cộng đồng", "vệ sinh môi trường", "nước sạch", "hút thuốc", "rượu bia", "vận động", "người cao tuổi", "trường học", "y tế công cộng", "phòng chống tai nạn"],
    "Xét nghiệm & Chẩn đoán": ["xét nghiệm", "chẩn đoán", "lấy mẫu", "sinh học phân tử", "quy trình xét nghiệm", "kết quả xét nghiệm", "giám sát phòng thí nghiệm"],
    "Nghiên cứu & Đào tạo": ["nghiên cứu khoa học", "đào tạo", "tuyển sinh", "luận án", "tiến sĩ", "thạc sĩ", "nghiên cứu sinh", "thử nghiệm lâm sàng", "hội nghị khoa học", "tạp chí"],
    "Hợp tác quốc tế": ["hợp tác quốc tế", "dự án", "who", "cdc", "đối tác", "viện trợ", "đoàn công tác"],
    "Phòng chống dịch": ["phòng chống dịch", "kiểm soát dịch", "khai báo y tế", "cách ly", "giãn cách", "truy vết", "ổ dịch", "đáp ứng khẩn cấp"],
    "Giới thiệu & Tổ chức": ["giới thiệu viện", "lịch sử", "cơ cấu tổ chức", "lãnh đạo viện", "ban giám đốc", "chức năng nhiệm vụ", "đảng bộ", "công đoàn"],
    "Tin tức & Sự kiện": ["tin tức", "sự kiện", "hoạt động", "thông báo", "chúc mừng", "gặp mặt", "tiếp đón"]
}

def is_garbage(doc):
    """Check if a chunk is garbage/navigation noise."""
    text = doc.get("text", "")
    url = doc.get("url", "")
    title = doc.get("title", "")
    
    # 1. Check URL patterns for Categories/Tags which are usually list pages
    if "Category:" in url or "danh-muc" in url:
        return True
    
    # 2. Check for navigation loops
    if text.count("Trang chủ") > 2 or text.count("Giới thiệu") > 3:
        return True
        
    # 3. Check for specific noise phrases and commercial content
    text_lower = text.lower()
    garbage_keywords = [
        "mời báo giá", "yêu cầu báo giá", "chào giá", "đấu thầu", "gói thầu", "mua sắm hàng hóa",
        "kết quả lựa chọn nhà thầu", "catalogue", "sitemap", "404 not found", "access denied",
        "file đính kèm", "danh sách", "kết quả thẩm định", "thông báo mời"
    ]
    
    if any(k in text_lower for k in garbage_keywords) or any(k in title.lower() for k in garbage_keywords):
        return True

    noise_phrases = ["Chào mừng bạn đến với NIHE"]
    for phrase in noise_phrases:
        if text.count(phrase) > 2:
            return True
            
    # 4. Too short
    if len(text.strip()) < 150:
        return True
        
    return False

def assign_topic_advanced(text, title=""):
    """Assign topic based on keyword density."""
    text_lower = (title + " " + text).lower()
    scores = {topic: 0 for topic in TOPIC_KEYWORDS}
    
    for topic, keywords in TOPIC_KEYWORDS.items():
        for kw in keywords:
            # Weight deeper/longer matches or title matches?
            # Simple count for now
            scores[topic] += text_lower.count(kw)
            
    # Get topic with max score
    best_topic = max(scores, key=scores.get)
    
    if scores[best_topic] > 0:
        return best_topic
    return "Tin tức chung"

def main():
    print(f"Scanning chunks in {CHUNKS_DIR}...")
    files = glob.glob(os.path.join(CHUNKS_DIR, "*.json"))
    
    deleted_count = 0
    updated_count = 0
    
    for filepath in files:
        with open(filepath, 'r', encoding='utf-8') as f:
            try:
                doc = json.load(f)
            except json.JSONDecodeError:
                print(f"Error reading {filepath}, deleting.")
                os.remove(filepath)
                continue
                
        # 1. Filter Garbage
        if is_garbage(doc):
            print(f"Deleting garbage chunk: {doc.get('id')} ({doc.get('title')})")
            f.close() # Ensure closed before remove
            os.remove(filepath)
            deleted_count += 1
            continue
            
        # 2. Refine Topic
        # User asked to fix topics, so let's force update based on better logic.
        new_topic = assign_topic_advanced(doc.get('text', ''), doc.get('title', ''))
        
        if new_topic != doc.get('topic'):
            doc['topic'] = new_topic
            doc['language'] = 'vi' # Ensure lang is set
            
            with open(filepath, 'w', encoding='utf-8') as f:
                json.dump(doc, f, ensure_ascii=False, indent=2)
            updated_count += 1
            
    print(f"Refinement Complete.")
    print(f"- Deleted {deleted_count} garbage files.")
    print(f"- Updated topic for {updated_count} files.")

if __name__ == "__main__":
    main()