File size: 8,528 Bytes
41f037f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Build Hugging Face–ready Parquet files from the raw VK CSV exports.

Input  (raw/<category>_posts.csv): one row per post plus one row per comment;
       comment rows repeat all fields of their parent post.
Output (data/<category>_<posts|comments>/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"(?<![\d\w])(?:\+7|8)[\s\-(]*\d{3}[\s\-)]*\d{3}[\s\-]*\d{2}[\s\-]*\d{2}(?![\d\w])"
    r"|(?<![\d\w+])9\d{2}[\s\-]?\d{3}[\s\-]?\d{2}[\s\-]?\d{2}(?![\d\w])"
)


def mask(text: str) -> str:
    text = USER_MENTION.sub("@user", text)
    text = GROUP_MENTION.sub(r"\1", text)
    text = USER_LINK.sub("<vk_user>", text)
    text = EMAIL.sub("<email>", text)
    text = PHONE.sub("<phone>", 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()