File size: 12,703 Bytes
11ce4a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
"""
clean_dataset.py — Extract clean prompts from Telegram AI image dataset.
Groups consecutive images by prompt, strips ads/model names/hashtags,
and outputs a VLM-training-ready JSONL file.

Usage:
  python tools/dataview/clean_dataset.py \
    --input telegram-channel-dataset/dataset.parquet \
    --output telegram-channel-dataset/cleaned.jsonl
"""

import argparse
import json
import re
import sys
from pathlib import Path

import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq


# ── Patterns to strip ──────────────────────────────────────────────────
STRIP_PATTERNS = [
    # Hashtags
    r'#[\w\u4e00-\u9fff]+',
    # Bot links / Telegram links
    r'\[.*?\]\(https?://t\.me/[^\)]+\)',
    r'https?://t\.me/\S+',
    r'https?://\S+',
    # Source/author lines
    r'来源:.*',
    r'作者:.*',
    r'Source:.*',
    r'Author:.*',
    # Ad / promo lines
    r'🚀.*',
    r'📚\s*教程目录.*',
    r'━━+',
    r'🤖.*我们的 Bot.*',
    r'🔥.*邪修频道.*',
    r'VPN推荐.*',
    r'NanoGPT.*',
    r'免费赠送.*',
    r'快来体验.*',
    r'Dubis.*',
    r'Bot 机器人.*',
    # Model name prefixes in titles
    r'^(✨|🔥|🧩|🖼️|🎞️|🎬|🏮|🎨|📷|📸|🌟|💡|🎭|🎪|🎬|🌙|🌅|🌸|🎭|🖌️)\s*',
    r'^GPT-?Image[-\s]*2?[||]',
    r'^GPTImage2?[||]',
    # Title lines (Chinese titles with emoji)
    r'^.*?[||].*?(prompt|模板|技巧|构图|写真|人像|海报|封面).*?$',
]

# Fields that contain prompt-relevant information
PROMPT_FIELDS = [
    '任务', '主体', '服装', '场景', '光线', '镜头', '风格', '构图',
    '约束', '画幅', '关键特征', '变体', '重点', '角色感', '妆造',
    '动作', '调色', '反差', '结构', '适用', '示例',
    'Task', 'Subject', 'Style', 'Lighting', 'Camera', 'Composition',
    'Prompt skeleton',
]

# Chinese field labels to English mapping
FIELD_MAP = {
    '任务': 'task',
    '主体': 'subject',
    '服装': 'clothing',
    '场景': 'scene',
    '光线': 'lighting',
    '镜头': 'camera',
    '风格': 'style',
    '构图': 'composition',
    '约束': 'avoid',
    '画幅': 'aspect_ratio',
    '关键特征': 'key_features',
    '变体': 'variants',
    '重点': 'focus',
    '角色感': 'character',
    '妆造': 'makeup',
    '动作': 'pose',
    '调色': 'color_grading',
    '反差': 'contrast',
    '结构': 'layout',
    '适用': 'use_case',
    '示例': 'examples',
    'Task': 'task',
    'Subject': 'subject',
    'Style': 'style',
    'Lighting': 'lighting',
    'Camera': 'camera',
    'Composition': 'composition',
    'Prompt skeleton': 'prompt_skeleton',
}


def clean_text(text: str) -> str:
    """Remove ads, links, hashtags, model names, and other noise."""
    if not text or pd.isna(text):
        return ''
    text = str(text)

    # Apply strip patterns
    for pattern in STRIP_PATTERNS:
        text = re.sub(pattern, '', text, flags=re.MULTILINE | re.IGNORECASE)

    # Remove lines that are just emojis or very short
    lines = text.split('\n')
    cleaned_lines = []
    for line in lines:
        line = line.strip()
        if not line:
            continue
        # Skip very short lines (likely noise)
        if len(line) < 3:
            continue
        # Skip lines that are mostly emojis
        emoji_chars = len(re.findall(r'[\U0001F300-\U0001F9FF]', line))
        if emoji_chars > len(line) * 0.5:
            continue
        cleaned_lines.append(line)

    return '\n'.join(cleaned_lines).strip()


def extract_structured_fields(text: str) -> dict:
    """Extract structured prompt fields from Chinese text."""
    if not text:
        return {}

    fields = {}
    # Match patterns like "字段名:值" or "字段名: value"
    field_names = '|'.join(re.escape(f) for f in PROMPT_FIELDS)
    field_pattern = re.compile(
        rf'^(?:[-•]\s*)?({field_names})[::]\s*(.+?)(?:\n|$)',
        re.MULTILINE
    )

    for match in field_pattern.finditer(text):
        field_name = match.group(1).strip()
        value = match.group(2).strip()
        if value and len(value) > 2:
            eng_name = FIELD_MAP.get(field_name, field_name)
            fields[eng_name] = value

    return fields


def extract_prompt_skeleton(text: str) -> str:
    """Extract 'Prompt skeleton' section if present."""
    if not text:
        return ''
    match = re.search(r'Prompt skeleton[:\s]*\n(.+?)(?:\n\n|\n备注|\Z)', text, re.DOTALL)
    if match:
        return match.group(1).strip()
    return ''


def build_prompt(text: str) -> str:
    """Build a clean prompt from the structured fields."""
    if not text:
        return ''

    # Try to get prompt skeleton first (most direct)
    skeleton = extract_prompt_skeleton(text)
    if skeleton and len(skeleton) > 20:
        return skeleton

    # Extract structured fields
    fields = extract_structured_fields(text)

    if not fields:
        # Fallback: try to extract any English prompt-like content
        lines = text.split('\n')
        prompt_parts = []
        for line in lines:
            line = line.strip()
            # Skip Chinese-only lines
            chinese_chars = len(re.findall(r'[\u4e00-\u9fff]', line))
            if chinese_chars > len(line) * 0.3:
                continue
            # Skip very short lines
            if len(line) < 10:
                continue
            # Skip known noise
            if any(skip in line.lower() for skip in ['bot', 'http', '#', '来源', '作者', 'source', 'author']):
                continue
            prompt_parts.append(line)
        if prompt_parts:
            return '; '.join(prompt_parts)
        return ''

    # Build prompt from fields in logical order
    order = ['task', 'subject', 'character', 'makeup', 'clothing', 'pose',
             'scene', 'lighting', 'camera', 'composition', 'aspect_ratio',
             'key_features', 'style', 'color_grading', 'contrast', 'layout',
             'avoid', 'use_case', 'prompt_skeleton']

    parts = []
    for key in order:
        if key in fields:
            parts.append(fields[key])

    # Add any remaining fields not in order
    for key, val in fields.items():
        if key not in order and val:
            parts.append(val)

    return '; '.join(parts) if parts else ''


def group_images(df: pd.DataFrame) -> list:
    """Group consecutive images by prompt (same dimensions = same generation)."""
    groups = []
    current_group = None

    for idx, row in df.iterrows():
        has_text = row['text'] and str(row['text']).strip()
        has_image = row['image'] is not None and isinstance(row['image'], bytes) and len(row['image']) > 100

        if has_text and has_image:
            # Start new group
            if current_group:
                groups.append(current_group)
            current_group = {
                'message_id': row['message_id'],
                'datetime': row['datetime'],
                'raw_text': row['text'],
                'images': [{
                    'row_idx': idx,
                    'message_id': row['message_id'],
                    'width': row['width'],
                    'height': row['height'],
                    'image_bytes': row['image'],
                }]
            }
        elif current_group and has_image:
            # Check if dimensions match (same generation batch)
            last_img = current_group['images'][-1]
            if row['width'] == last_img['width'] and row['height'] == last_img['height']:
                current_group['images'].append({
                    'row_idx': idx,
                    'message_id': row['message_id'],
                    'width': row['width'],
                    'height': row['height'],
                    'image_bytes': row['image'],
                })

    if current_group:
        groups.append(current_group)

    return groups


def main():
    parser = argparse.ArgumentParser(description='Clean Telegram AI image dataset')
    parser.add_argument('--input', '-i', required=True, help='Input parquet file')
    parser.add_argument('--output', '-o', default=None, help='Output JSONL file')
    parser.add_argument('--parquet', default=None, help='Output cleaned parquet (with only useful columns)')
    parser.add_argument('--min-images', type=int, default=1, help='Min images per group')
    parser.add_argument('--min-prompt-len', type=int, default=10, help='Min prompt length')
    parser.add_argument('--stats', action='store_true', help='Print stats only')
    args = parser.parse_args()

    # Read parquet
    print(f"Reading {args.input}...")
    df = pq.read_table(args.input).to_pandas()
    print(f"  Total rows: {len(df)}")

    # Optionally output cleaned parquet (strip noise columns)
    if args.parquet:
        KEEP = ['message_id', 'datetime', 'media_type', 'text', 'width', 'height', 'image']
        available = [c for c in KEEP if c in df.columns]
        clean = df[available].copy()
        if 'media_type' in clean.columns:
            clean = clean[clean['media_type'] == 'photo'].copy()
        clean.reset_index(drop=True, inplace=True)
        pq.write_table(pa.Table.from_pandas(clean), args.parquet)
        print(f"  Cleaned parquet: {len(clean)} rows, {len(clean.columns)} cols -> {args.parquet}")

    # Group images
    groups = group_images(df)
    print(f"  Prompt groups: {len(groups)}")

    # Clean and filter
    cleaned = []
    for group in groups:
        prompt = build_prompt(group['raw_text'])
        if len(prompt) < args.min_prompt_len:
            continue
        if len(group['images']) < args.min_images:
            continue

        cleaned.append({
            'prompt': prompt,
            'raw_text': group['raw_text'],
            'num_images': len(group['images']),
            'message_id': group['message_id'],
            'datetime': group['datetime'],
            'images': group['images'],
        })

    print(f"  Cleaned groups: {len(cleaned)}")
    print(f"  Total images: {sum(g['num_images'] for g in cleaned)}")

    if args.stats:
        # Print distribution
        from collections import Counter
        sizes = Counter(g['num_images'] for g in cleaned)
        print("\n  Group size distribution:")
        for size, count in sorted(sizes.items()):
            print(f"    {size} images: {count} groups")

        # Show sample prompts
        print("\n  Sample prompts:")
        for g in cleaned[:5]:
            print(f"    [{g['num_images']} imgs] {g['prompt'][:120]}...")
        return

    # Output
    if args.output:
        output_path = Path(args.output)
        output_path.parent.mkdir(parents=True, exist_ok=True)

        with open(output_path, 'w', encoding='utf-8') as f:
            for group in cleaned:
                record = {
                    'prompt': group['prompt'],
                    'num_images': group['num_images'],
                    'message_id': group['message_id'],
                    'datetime': group['datetime'],
                    'image_paths': [
                        f"images/msg_{img['message_id']}_row_{img['row_idx']}.webp"
                        for img in group['images']
                    ],
                }
                f.write(json.dumps(record, ensure_ascii=False) + '\n')

        print(f"\n  Written to {output_path}")

        # Also save images
        img_dir = output_path.parent / 'images'
        img_dir.mkdir(exist_ok=True)

        from PIL import Image
        import io

        print("  Extracting images...")
        saved = 0
        for group in cleaned:
            for img_data in group['images']:
                try:
                    img = Image.open(io.BytesIO(img_data['image_bytes']))
                    img_path = img_dir / f"msg_{img_data['message_id']}_row_{img_data['row_idx']}.webp"
                    img.save(img_path, format='WEBP', quality=90)
                    saved += 1
                except Exception as e:
                    print(f"    Warning: Failed to save image {img_data['message_id']}: {e}")

        print(f"  Saved {saved} images to {img_dir}")
    else:
        # Just print stats
        from collections import Counter
        sizes = Counter(g['num_images'] for g in cleaned)
        print("\n  Group size distribution:")
        for size, count in sorted(sizes.items()):
            print(f"    {size} images: {count} groups")

        print("\n  Sample prompts:")
        for g in cleaned[:10]:
            print(f"    [{g['num_images']} imgs] {g['prompt'][:150]}...")


if __name__ == '__main__':
    main()