Download filtering_posts.py from jupo-ai/filtered-danbooru-posts: direct link, hf CLI and curl.
- Browser
- Download file 8.3 kB
-
https://huggingface.co/datasets/jupo-ai/filtered-danbooru-posts/resolve/main/filtering_posts.py
- Command line
-
hf download hf://datasets/jupo-ai/filtered-danbooru-posts/filtering_posts.py
-
curl -L -o filtering_posts.py https://huggingface.co/datasets/jupo-ai/filtered-danbooru-posts/resolve/main/filtering_posts.py
8.3 kB
| 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() | |