File size: 8,303 Bytes
f6d6600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58c86aa
f6d6600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58c86aa
f6d6600
 
 
 
 
 
58c86aa
f6d6600
 
 
58c86aa
 
f6d6600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58c86aa
f6d6600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58c86aa
f6d6600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
278
279
from __future__ import annotations

import json
import math
import re
from pathlib import Path

import pandas as pd
from rich.console import Console
from rich.progress import BarColumn, Progress, TaskProgressColumn, TextColumn, TimeElapsedColumn
from rich.table import Table


INPUT_DIR = Path("data/posts")
OUTPUT_DIR = Path("data/filtered")
BAN_TAGS_FILE = Path("ban_tags.json")
OUTPUT_FILE_COUNT = 10
ALLOWED_FILE_EXTENSIONS = {"jpg", "jpeg", "png", "webp"}
MIN_IMAGE_WIDTH = 512
MIN_IMAGE_HEIGHT = 512
MIN_TAG_COUNT = 5

# フィルタリングに必要なカラム
NEED_COLUMNS = [
    "id",
    "created_at",
    "md5",
    "score",
    "rating",
    "image_width",
    "image_height",
    "file_ext",
    "tag_count",
    "is_deleted",
    "is_banned",
    "is_pending",
    "is_flagged",
    "tag_string_general",
    "tag_string_character",
    "tag_string_copyright",
    "tag_string_artist",
    "file_url",
]

TAG_COLUMNS = [
    "tag_string_general",
    "tag_string_character",
    "tag_string_copyright",
    "tag_string_artist",
]

# 出力時に必要なカラム
OUTPUT_COLUMNS = [
    "id",
    "created_at",
    "score",
    "rating",
    "tag_count",
    "tag_string_general",
    "tag_string_character",
    "tag_string_copyright",
    "tag_string_artist",
    "file_url",
]

INTERNAL_COLUMNS = ["md5", *OUTPUT_COLUMNS]

console = Console()


def list_post_files() -> list[Path]:
    return sorted(INPUT_DIR.glob("*.parquet"))


def load_ban_tags() -> set[str]:
    with BAN_TAGS_FILE.open(mode="r", encoding="utf-8") as file:
        grouped_tags: dict[str, list[str]] = json.load(file)

    return {
        tag
        for tags in grouped_tags.values()
        for tag in tags
        if tag
    }


def build_tag_pattern(ban_tags: set[str]) -> re.Pattern[str] | None:
    if not ban_tags:
        return None

    escaped_tags = [re.escape(tag) for tag in sorted(ban_tags, key=len, reverse=True)]
    return re.compile(r"(?<!\S)(?:" + "|".join(escaped_tags) + r")(?!\S)")


def load_post_file(path: Path) -> pd.DataFrame:
    return pd.read_parquet(path, columns=NEED_COLUMNS)


def build_filter_mask(data: pd.DataFrame, ban_tag_pattern: re.Pattern[str] | None) -> pd.Series:
    mask = (
        data["score"].ge(0)
        & data["is_deleted"].eq(False)
        & data["is_banned"].eq(False)
        & data["is_pending"].eq(False)
        & data["is_flagged"].eq(False)
        & data["file_ext"].fillna("").str.lower().isin(ALLOWED_FILE_EXTENSIONS)
        & data["image_width"].ge(MIN_IMAGE_WIDTH)
        & data["image_height"].ge(MIN_IMAGE_HEIGHT)
        & data["tag_count"].ge(MIN_TAG_COUNT)
        & data["file_url"].notna()
        & data["file_url"].str.len().gt(0)
    )

    if ban_tag_pattern is None:
        return mask

    has_banned_tag = pd.Series(False, index=data.index)
    for column in TAG_COLUMNS:
        has_banned_tag |= data[column].fillna("").str.contains(ban_tag_pattern, regex=True)

    return mask & ~has_banned_tag


def filter_posts(data: pd.DataFrame, ban_tag_pattern: re.Pattern[str] | None) -> pd.DataFrame:
    mask = build_filter_mask(data, ban_tag_pattern)
    return data.loc[mask, INTERNAL_COLUMNS].reset_index(drop=True)


def filter_post_file(path: Path, ban_tag_pattern: re.Pattern[str] | None) -> tuple[pd.DataFrame, int, int]:
    data = load_post_file(path)
    filtered = filter_posts(data, ban_tag_pattern)
    return filtered, len(data), len(filtered)


def split_ranges(total_rows: int, part_count: int) -> list[tuple[int, int]]:
    if total_rows == 0:
        return [(0, 0) for _ in range(part_count)]

    base_size = total_rows // part_count
    remainder = total_rows % part_count
    ranges: list[tuple[int, int]] = []
    start = 0

    for index in range(part_count):
        size = base_size + (1 if index < remainder else 0)
        end = start + size
        ranges.append((start, end))
        start = end

    return ranges


def save_split_files(data: pd.DataFrame, part_count: int) -> list[tuple[Path, int]]:
    digits = max(2, int(math.log10(part_count - 1)) + 1 if part_count > 1 else 1)
    outputs: list[tuple[Path, int]] = []

    for index, (start, end) in enumerate(split_ranges(len(data), part_count)):
        output_path = OUTPUT_DIR / f"filtered_posts_{index:0{digits}d}.parquet"
        part = data.iloc[start:end].loc[:, OUTPUT_COLUMNS].reset_index(drop=True)
        part.to_parquet(output_path, index=False)
        outputs.append((output_path, len(part)))

    return outputs


def drop_duplicate_posts(data: pd.DataFrame) -> tuple[pd.DataFrame, dict[str, int]]:
    id_deduplicated = data.drop_duplicates(subset="id", keep="first")
    id_duplicate_count = len(data) - len(id_deduplicated)

    md5_values = id_deduplicated["md5"].fillna("")
    has_md5 = md5_values.str.len().gt(0)
    duplicated_md5 = has_md5 & id_deduplicated["md5"].duplicated()
    md5_duplicate_count = int(duplicated_md5.sum())
    deduplicated = id_deduplicated.loc[~duplicated_md5].reset_index(drop=True)

    return deduplicated, {
        "id": id_duplicate_count,
        "md5": md5_duplicate_count,
        "total": len(data) - len(deduplicated),
    }


def print_filter_summary(results: list[tuple[Path, int, int]]) -> None:
    table = Table(title="Filtering Summary")
    table.add_column("file")
    table.add_column("input", justify="right")
    table.add_column("output", justify="right")
    table.add_column("removed", justify="right")

    total_input = 0
    total_output = 0
    for input_path, input_count, output_count in results:
        total_input += input_count
        total_output += output_count
        table.add_row(
            input_path.name,
            f"{input_count:,}",
            f"{output_count:,}",
            f"{input_count - output_count:,}",
        )

    table.add_section()
    table.add_row(
        "total",
        f"{total_input:,}",
        f"{total_output:,}",
        f"{total_input - total_output:,}",
    )
    console.print(table)


def print_output_summary(outputs: list[tuple[Path, int]]) -> None:
    table = Table(title="Output Summary")
    table.add_column("file")
    table.add_column("rows", justify="right")

    for output_path, row_count in outputs:
        table.add_row(output_path.name, f"{row_count:,}")

    console.print(table)


def main() -> None:
    post_files = list_post_files()
    if not post_files:
        raise FileNotFoundError(f"No parquet files found in {INPUT_DIR}")

    OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
    ban_tags = load_ban_tags()
    ban_tag_pattern = build_tag_pattern(ban_tags)
    filtered_frames: list[pd.DataFrame] = []
    results: list[tuple[Path, int, int]] = []

    console.print(f"[bold]Input:[/] {INPUT_DIR}")
    console.print(f"[bold]Output:[/] {OUTPUT_DIR}")
    console.print(f"[bold]Ban tags:[/] {len(ban_tags)}")
    console.print(
        "[bold]Filters:[/] "
        f"ext={sorted(ALLOWED_FILE_EXTENSIONS)}, "
        f"min_size={MIN_IMAGE_WIDTH}x{MIN_IMAGE_HEIGHT}, "
        f"min_tag_count={MIN_TAG_COUNT}"
    )

    with Progress(
        TextColumn("[progress.description]{task.description}"),
        BarColumn(),
        TaskProgressColumn(),
        TimeElapsedColumn(),
        console=console,
    ) as progress:
        task = progress.add_task("filtering parquet files", total=len(post_files))

        for path in post_files:
            progress.update(task, description=path.name)
            filtered, input_count, output_count = filter_post_file(path, ban_tag_pattern)
            filtered_frames.append(filtered)
            results.append((path, input_count, output_count))
            progress.advance(task)

    print_filter_summary(results)

    console.print("[bold]Concatenating filtered posts...[/]")
    filtered_posts = pd.concat(filtered_frames, ignore_index=True)
    filtered_posts, duplicate_counts = drop_duplicate_posts(filtered_posts)
    console.print(
        "[bold]Duplicates removed:[/] "
        f"id={duplicate_counts['id']:,}, "
        f"md5={duplicate_counts['md5']:,}, "
        f"total={duplicate_counts['total']:,}"
    )

    console.print(f"[bold]Saving:[/] {OUTPUT_FILE_COUNT} parquet files")
    outputs = save_split_files(filtered_posts, OUTPUT_FILE_COUNT)
    print_output_summary(outputs)


if __name__ == "__main__":
    main()