aboutsummaryrefslogtreecommitdiff
path: root/src/test_export.py
blob: 8f5ff38ec951d6db73484d0bfe5716417888c33f (plain) (blame)
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
import re
import pathlib


def check_duplicate_names(kml_file: str, quiet: bool = False) -> dict:
    """Check for duplicate names in the exported KML file.

    Args:
        kml_file (str): Path to the KML file exported from Google My Maps.
        quiet (bool, optional): If True, suppress output. Defaults to False.
    Returns:
        dict: A dictionary with names as keys and their counts as values.
    """
    if not quiet:
        print("\nChecking for duplicate names in the exported KML file...")

    with open(kml_file, "r", encoding="utf-8") as f:
        content = f.read()

    regex = r"<name>(<!\[CDATA\[)?(.*?)(\]\]>)?</name>"
    matches = re.findall(regex, content)

    names = {}
    for match in matches:
        name = match[1]
        if name in names:
            names[name] += 1
        else:
            names[name] = 1

    if not quiet:
        if any(count > 1 for count in names.values()):
            print("Duplicate names found in the exported KML file:")
            for name, count in names.items():
                if count > 1:
                    print(f" - {name}: {count} times")
        else:
            print("No duplicate names found in the exported KML file.")

    return names


def check_missing_names(kml_file: str, kml_glob: str, quiet: bool = False) -> dict:
    """Check for missing names in the exported KML file compared to other KML files.

    Args:
        kml_file (str): Path to the KML file exported from Google My Maps.
        kml_glob (str): Glob pattern to match KML files to check against the exported KML file.
        quiet (bool, optional): If True, suppress output. Defaults to False.
    Returns:
        { 'file_name': { 'missing': [list of missing names], 'total': total number of names in the file } }
    """
    if not quiet:
        print("\nChecking for missing names in the exported KML file compared to other KML files...")

    names = check_duplicate_names(kml_file, quiet=True)

    missing_files = {}

    for file in pathlib.Path().glob(kml_glob):
        with open(file, "r", encoding="utf-8") as f:
            content = f.read()

        regex = r"<name>(<!\[CDATA\[)?(.*?)(\]\]>)?</name>"
        matches = re.findall(regex, content)

        current_names = set(match[1] for match in matches)

        for name in current_names:
            if not name in names:
                if file.name not in missing_files:
                    missing_files[file.name] = {'missing': [], 'total': len(
                        current_names)-1}  # because of the name of the document
                missing_files[file.name]['missing'].append(name)

    if not quiet:
        if not missing_files:
            print("All names in the KML files matching the glob pattern were found in the exported KML file.")
        else:
            print("Files with names not found in the exported KML file:")
            for file, count in missing_files.items():
                print(f" - {file}: missing {len(count['missing'])}/{count['total']}")
                for name in count['missing']:
                    print(f"   - {name}")

    return missing_files


if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(
        description="Check for duplicate or missing names in the KML file exported from Google My Maps.")
    parser.add_argument("kml_file", type=str, help="Path to the KML file exported from Google My Maps.")
    parser.add_argument("kml_glob", type=str,
                        help="Glob pattern to match KML files to check against the exported KML file.")
    args = parser.parse_args()

    check_duplicate_names(args.kml_file)
    check_missing_names(args.kml_file, args.kml_glob)