#!/usr/bin/env python3 """Build Hugging Face–ready Parquet files from the raw VK CSV exports. Input (raw/_posts.csv): one row per post plus one row per comment; comment rows repeat all fields of their parent post. Output (data/_/train.parquet): six configs, posts and comments split into separate tables linked by (group, post_id). Processing: * posts and comments are separated, exact duplicates by ID are dropped; * rows with empty text (media-only posts, sticker comments) are dropped; * float-looking IDs/counters from the comment rows are cast to integers; * dates are rebuilt from the Unix timestamps in UTC (the *_date columns in the raw CSV are in the collector's local time); * personal data in text is masked: user mentions, links to user profiles, phone numbers, e-mail addresses; * a heuristic language label is added (same rules as tuvan_detector.py in the tuvan-lang-in-vk-posts project). Usage: python scripts/prepare.py (from the repository root) """ from __future__ import annotations import csv import json import re import sys from pathlib import Path import pandas as pd import pyarrow as pa import pyarrow.parquet as pq ROOT = Path(__file__).resolve().parent.parent RAW_DIR = ROOT / "raw" DATA_DIR = ROOT / "data" SOURCES = { "official_media": "official_media_posts.csv", "gov_institutions": "gov_institutions_posts.csv", "community_media": "community_media_posts.csv", } csv.field_size_limit(sys.maxsize) # --------------------------------------------------------------------------- # # Personal-data masking # --------------------------------------------------------------------------- # USER_MENTION = re.compile(r"\[id\d+\|[^\]]*\]") # [id123|Имя] GROUP_MENTION = re.compile(r"\[(?:club|public|event)\d+\|([^\]]*)\]") # [club1|Минздрав] -> Минздрав USER_LINK = re.compile(r"(?:https?://)?(?:m\.)?vk\.com/id\d+\b") EMAIL = re.compile(r"\b[\w.+-]+@[\w-]+(?:\.[\w-]+)+\b") PHONE = re.compile( r"(? str: text = USER_MENTION.sub("@user", text) text = GROUP_MENTION.sub(r"\1", text) text = USER_LINK.sub("", text) text = EMAIL.sub("", text) text = PHONE.sub("", text) return text # --------------------------------------------------------------------------- # # Heuristic language label (rules copied from tuvan_detector.py) # --------------------------------------------------------------------------- # TUVAN_CHARS = set("ңөүҢӨҮ") TUVAN_RU_LAYOUT = re.compile("|".join([ r"\bмен\b", r"\bсен\b", r"\bбис\b", r"\bсилер\b", r"\bчуве\b", r"\bчок\b", r"\bбар\b", r"\bтур\b", r"\bболур\b", r"\bдээш\b", r"\bкылыр\b", r"\bбистин\b", r"\bмээн\b", r"\bсилернин\b", r"\bачамнын\b", r"\bавамнын\b", r"\bачазы\b", r"\bавазы\b", r"\bооренир\b", r"\bооренип\b", r"\bооредилге\b", r"\bоршээ\b", r"\bог-буле\b", r"\bтыванын\b", r"\bог-буленин\b", r"\bог-булезинге\b", r"\bог-булелиг\b", r"\bменээ\b", r"\bортек\b", r"\bортээ\b", r"\bкожууннун\b", r"\bторуттунген\b", r"\bчуректиг\b", r"\bчуректеривиске\b", r"\bчурек\b", r"\bчуректер\b", r"\bмонгеде\b", r"\bсоолгу\b", r"\bулегер\b", r"\bбригадазынын\b", r"\bоглувустун\b", r"\bсумузунун\b", r"\bозуп\b", r"\w+нын\b", r"\w+зы\b", r"\w+ынын\b", r"\w+устун\b", r"\w+узунун\b", r"\w+ээ\b", r"\w+иг\b", r"\w+иске\b", r"\w+илге\b", r"\bоо\w+\b", ])) def lang_heuristic(text: str) -> str: if any(ch in TUVAN_CHARS for ch in text): return "tyv" # Tuvan written with ң/ө/ү if TUVAN_RU_LAYOUT.search(text.lower()): return "tyv_ru_layout" # probably Tuvan typed on a Russian keyboard (noisy) return "ru" # Russian or other # --------------------------------------------------------------------------- # # Reading # --------------------------------------------------------------------------- # def as_int(value: str) -> int | None: value = value.strip() return int(float(value)) if value else None def read_raw(path: Path, category: str) -> tuple[pd.DataFrame, pd.DataFrame, dict]: posts, comments = [], [] with path.open(encoding="utf-8-sig", newline="") as f: for row in csv.DictReader(f): if row["type"] == "post": posts.append({ "post_id": as_int(row["post_id"]), "group": row["group"], "category": category, "text": row["post_text"], "likes": as_int(row["post_likes"]), "comments_count": as_int(row["post_comments_count"]), "date_unix": as_int(row["post_date_unix"]), }) elif row["type"] == "comment": comments.append({ "comment_id": as_int(row["comment_id"]), "post_id": as_int(row["post_id"]), "group": row["group"], "category": category, "text": row["comment_text"], "likes": as_int(row["comment_likes"]), "date_unix": as_int(row["comment_date_unix"]), }) else: raise ValueError(f"{path.name}: unknown row type {row['type']!r}") stats = {"raw_posts": len(posts), "raw_comments": len(comments)} return pd.DataFrame(posts), pd.DataFrame(comments), stats def finalize(df: pd.DataFrame, id_col: str, stats: dict, kind: str) -> pd.DataFrame: n = len(df) df = df.drop_duplicates(["group", id_col], keep="last") stats[f"{kind}_duplicates_dropped"] = n - len(df) n = len(df) df = df[df["text"].str.strip() != ""] stats[f"{kind}_empty_dropped"] = n - len(df) df = df.copy() df["text"] = df["text"].map(mask) df["lang_heuristic"] = df["text"].map(lang_heuristic) df["date"] = pd.to_datetime(df["date_unix"], unit="s", utc=True) df["year"] = df["date"].dt.year.astype("int16") df = df.drop(columns="date_unix").sort_values(["date", id_col], ascending=False) stats[kind] = len(df) stats[f"{kind}_lang"] = df["lang_heuristic"].value_counts().to_dict() return df.reset_index(drop=True) POST_SCHEMA = pa.schema([ ("post_id", pa.int64()), ("group", pa.string()), ("category", pa.string()), ("text", pa.string()), ("lang_heuristic", pa.string()), ("likes", pa.int64()), ("comments_count", pa.int64()), ("date", pa.timestamp("s", tz="UTC")), ("year", pa.int16()), ]) COMMENT_SCHEMA = pa.schema([ ("comment_id", pa.int64()), ("post_id", pa.int64()), ("group", pa.string()), ("category", pa.string()), ("text", pa.string()), ("lang_heuristic", pa.string()), ("likes", pa.int64()), ("date", pa.timestamp("s", tz="UTC")), ("year", pa.int16()), ]) def write(df: pd.DataFrame, schema: pa.Schema, config: str) -> Path: out = DATA_DIR / config / "train.parquet" out.parent.mkdir(parents=True, exist_ok=True) table = pa.Table.from_pandas(df[schema.names], schema=schema, preserve_index=False) pq.write_table(table, out, row_group_size=10_000) return out def main() -> None: all_stats = {} for category, filename in SOURCES.items(): print(f"→ {filename}") posts, comments, stats = read_raw(RAW_DIR / filename, category) posts = finalize(posts, "post_id", stats, "posts") comments = finalize(comments, "comment_id", stats, "comments") for df, schema, kind in ((posts, POST_SCHEMA, "posts"), (comments, COMMENT_SCHEMA, "comments")): path = write(df, schema, f"{category}_{kind}") print(f" {path.relative_to(ROOT)}: {len(df):,} rows, {path.stat().st_size / 1e6:.1f} MB") all_stats[category] = stats (ROOT / "scripts" / "stats.json").write_text(json.dumps(all_stats, indent=2, ensure_ascii=False)) print(json.dumps(all_stats, indent=2, ensure_ascii=False)) if __name__ == "__main__": main()