GCStream commited on
Commit
fa18f9a
·
verified ·
1 Parent(s): 38857ff

Add clean_dataset.py

Browse files
Files changed (1) hide show
  1. tools/dataview/clean_dataset.py +376 -0
tools/dataview/clean_dataset.py ADDED
@@ -0,0 +1,376 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ clean_dataset.py — Extract clean prompts from Telegram AI image dataset.
3
+ Groups consecutive images by prompt, strips ads/model names/hashtags,
4
+ and outputs a VLM-training-ready JSONL file.
5
+
6
+ Usage:
7
+ python tools/dataview/clean_dataset.py \
8
+ --input telegram-channel-dataset/dataset.parquet \
9
+ --output telegram-channel-dataset/cleaned.jsonl
10
+ """
11
+
12
+ import argparse
13
+ import json
14
+ import re
15
+ import sys
16
+ from pathlib import Path
17
+
18
+ import pandas as pd
19
+ import pyarrow as pa
20
+ import pyarrow.parquet as pq
21
+
22
+
23
+ # ── Patterns to strip ──────────────────────────────────────────────────
24
+ STRIP_PATTERNS = [
25
+ # Hashtags
26
+ r'#[\w\u4e00-\u9fff]+',
27
+ # Bot links / Telegram links
28
+ r'\[.*?\]\(https?://t\.me/[^\)]+\)',
29
+ r'https?://t\.me/\S+',
30
+ r'https?://\S+',
31
+ # Source/author lines
32
+ r'来源:.*',
33
+ r'作者:.*',
34
+ r'Source:.*',
35
+ r'Author:.*',
36
+ # Ad / promo lines
37
+ r'🚀.*',
38
+ r'📚\s*教程目录.*',
39
+ r'━━+',
40
+ r'🤖.*我们的 Bot.*',
41
+ r'🔥.*邪修频道.*',
42
+ r'VPN推荐.*',
43
+ r'NanoGPT.*',
44
+ r'免费赠送.*',
45
+ r'快来体验.*',
46
+ r'Dubis.*',
47
+ r'Bot 机器人.*',
48
+ # Model name prefixes in titles
49
+ r'^(✨|🔥|🧩|🖼️|🎞️|🎬|🏮|🎨|📷|📸|🌟|💡|🎭|🎪|🎬|🌙|🌅|🌸|🎭|🖌️)\s*',
50
+ r'^GPT-?Image[-\s]*2?[||]',
51
+ r'^GPTImage2?[||]',
52
+ # Title lines (Chinese titles with emoji)
53
+ r'^.*?[||].*?(prompt|模板|技巧|构图|写真|人像|海报|封面).*?$',
54
+ ]
55
+
56
+ # Fields that contain prompt-relevant information
57
+ PROMPT_FIELDS = [
58
+ '任务', '主体', '服装', '场景', '光线', '镜头', '风格', '构图',
59
+ '约束', '画幅', '关键特征', '变体', '重点', '角色感', '妆造',
60
+ '动作', '调色', '反差', '结构', '适用', '示例',
61
+ 'Task', 'Subject', 'Style', 'Lighting', 'Camera', 'Composition',
62
+ 'Prompt skeleton',
63
+ ]
64
+
65
+ # Chinese field labels to English mapping
66
+ FIELD_MAP = {
67
+ '任务': 'task',
68
+ '主体': 'subject',
69
+ '服装': 'clothing',
70
+ '场景': 'scene',
71
+ '光线': 'lighting',
72
+ '镜头': 'camera',
73
+ '风格': 'style',
74
+ '构图': 'composition',
75
+ '约束': 'avoid',
76
+ '画幅': 'aspect_ratio',
77
+ '关键特征': 'key_features',
78
+ '变体': 'variants',
79
+ '重点': 'focus',
80
+ '角色感': 'character',
81
+ '妆造': 'makeup',
82
+ '动作': 'pose',
83
+ '调色': 'color_grading',
84
+ '反差': 'contrast',
85
+ '结构': 'layout',
86
+ '适用': 'use_case',
87
+ '示例': 'examples',
88
+ 'Task': 'task',
89
+ 'Subject': 'subject',
90
+ 'Style': 'style',
91
+ 'Lighting': 'lighting',
92
+ 'Camera': 'camera',
93
+ 'Composition': 'composition',
94
+ 'Prompt skeleton': 'prompt_skeleton',
95
+ }
96
+
97
+
98
+ def clean_text(text: str) -> str:
99
+ """Remove ads, links, hashtags, model names, and other noise."""
100
+ if not text or pd.isna(text):
101
+ return ''
102
+ text = str(text)
103
+
104
+ # Apply strip patterns
105
+ for pattern in STRIP_PATTERNS:
106
+ text = re.sub(pattern, '', text, flags=re.MULTILINE | re.IGNORECASE)
107
+
108
+ # Remove lines that are just emojis or very short
109
+ lines = text.split('\n')
110
+ cleaned_lines = []
111
+ for line in lines:
112
+ line = line.strip()
113
+ if not line:
114
+ continue
115
+ # Skip very short lines (likely noise)
116
+ if len(line) < 3:
117
+ continue
118
+ # Skip lines that are mostly emojis
119
+ emoji_chars = len(re.findall(r'[\U0001F300-\U0001F9FF]', line))
120
+ if emoji_chars > len(line) * 0.5:
121
+ continue
122
+ cleaned_lines.append(line)
123
+
124
+ return '\n'.join(cleaned_lines).strip()
125
+
126
+
127
+ def extract_structured_fields(text: str) -> dict:
128
+ """Extract structured prompt fields from Chinese text."""
129
+ if not text:
130
+ return {}
131
+
132
+ fields = {}
133
+ # Match patterns like "字段名:值" or "字段名: value"
134
+ field_names = '|'.join(re.escape(f) for f in PROMPT_FIELDS)
135
+ field_pattern = re.compile(
136
+ rf'^(?:[-•]\s*)?({field_names})[::]\s*(.+?)(?:\n|$)',
137
+ re.MULTILINE
138
+ )
139
+
140
+ for match in field_pattern.finditer(text):
141
+ field_name = match.group(1).strip()
142
+ value = match.group(2).strip()
143
+ if value and len(value) > 2:
144
+ eng_name = FIELD_MAP.get(field_name, field_name)
145
+ fields[eng_name] = value
146
+
147
+ return fields
148
+
149
+
150
+ def extract_prompt_skeleton(text: str) -> str:
151
+ """Extract 'Prompt skeleton' section if present."""
152
+ if not text:
153
+ return ''
154
+ match = re.search(r'Prompt skeleton[:\s]*\n(.+?)(?:\n\n|\n备注|\Z)', text, re.DOTALL)
155
+ if match:
156
+ return match.group(1).strip()
157
+ return ''
158
+
159
+
160
+ def build_prompt(text: str) -> str:
161
+ """Build a clean prompt from the structured fields."""
162
+ if not text:
163
+ return ''
164
+
165
+ # Try to get prompt skeleton first (most direct)
166
+ skeleton = extract_prompt_skeleton(text)
167
+ if skeleton and len(skeleton) > 20:
168
+ return skeleton
169
+
170
+ # Extract structured fields
171
+ fields = extract_structured_fields(text)
172
+
173
+ if not fields:
174
+ # Fallback: try to extract any English prompt-like content
175
+ lines = text.split('\n')
176
+ prompt_parts = []
177
+ for line in lines:
178
+ line = line.strip()
179
+ # Skip Chinese-only lines
180
+ chinese_chars = len(re.findall(r'[\u4e00-\u9fff]', line))
181
+ if chinese_chars > len(line) * 0.3:
182
+ continue
183
+ # Skip very short lines
184
+ if len(line) < 10:
185
+ continue
186
+ # Skip known noise
187
+ if any(skip in line.lower() for skip in ['bot', 'http', '#', '来源', '作者', 'source', 'author']):
188
+ continue
189
+ prompt_parts.append(line)
190
+ if prompt_parts:
191
+ return '; '.join(prompt_parts)
192
+ return ''
193
+
194
+ # Build prompt from fields in logical order
195
+ order = ['task', 'subject', 'character', 'makeup', 'clothing', 'pose',
196
+ 'scene', 'lighting', 'camera', 'composition', 'aspect_ratio',
197
+ 'key_features', 'style', 'color_grading', 'contrast', 'layout',
198
+ 'avoid', 'use_case', 'prompt_skeleton']
199
+
200
+ parts = []
201
+ for key in order:
202
+ if key in fields:
203
+ parts.append(fields[key])
204
+
205
+ # Add any remaining fields not in order
206
+ for key, val in fields.items():
207
+ if key not in order and val:
208
+ parts.append(val)
209
+
210
+ return '; '.join(parts) if parts else ''
211
+
212
+
213
+ def group_images(df: pd.DataFrame) -> list:
214
+ """Group consecutive images by prompt (same dimensions = same generation)."""
215
+ groups = []
216
+ current_group = None
217
+
218
+ for idx, row in df.iterrows():
219
+ has_text = row['text'] and str(row['text']).strip()
220
+ has_image = row['image'] is not None and isinstance(row['image'], bytes) and len(row['image']) > 100
221
+
222
+ if has_text and has_image:
223
+ # Start new group
224
+ if current_group:
225
+ groups.append(current_group)
226
+ current_group = {
227
+ 'message_id': row['message_id'],
228
+ 'datetime': row['datetime'],
229
+ 'raw_text': row['text'],
230
+ 'images': [{
231
+ 'row_idx': idx,
232
+ 'message_id': row['message_id'],
233
+ 'width': row['width'],
234
+ 'height': row['height'],
235
+ 'image_bytes': row['image'],
236
+ }]
237
+ }
238
+ elif current_group and has_image:
239
+ # Check if dimensions match (same generation batch)
240
+ last_img = current_group['images'][-1]
241
+ if row['width'] == last_img['width'] and row['height'] == last_img['height']:
242
+ current_group['images'].append({
243
+ 'row_idx': idx,
244
+ 'message_id': row['message_id'],
245
+ 'width': row['width'],
246
+ 'height': row['height'],
247
+ 'image_bytes': row['image'],
248
+ })
249
+
250
+ if current_group:
251
+ groups.append(current_group)
252
+
253
+ return groups
254
+
255
+
256
+ def main():
257
+ parser = argparse.ArgumentParser(description='Clean Telegram AI image dataset')
258
+ parser.add_argument('--input', '-i', required=True, help='Input parquet file')
259
+ parser.add_argument('--output', '-o', default=None, help='Output JSONL file')
260
+ parser.add_argument('--parquet', default=None, help='Output cleaned parquet (with only useful columns)')
261
+ parser.add_argument('--min-images', type=int, default=1, help='Min images per group')
262
+ parser.add_argument('--min-prompt-len', type=int, default=10, help='Min prompt length')
263
+ parser.add_argument('--stats', action='store_true', help='Print stats only')
264
+ args = parser.parse_args()
265
+
266
+ # Read parquet
267
+ print(f"Reading {args.input}...")
268
+ df = pq.read_table(args.input).to_pandas()
269
+ print(f" Total rows: {len(df)}")
270
+
271
+ # Optionally output cleaned parquet (strip noise columns)
272
+ if args.parquet:
273
+ KEEP = ['message_id', 'datetime', 'media_type', 'text', 'width', 'height', 'image']
274
+ available = [c for c in KEEP if c in df.columns]
275
+ clean = df[available].copy()
276
+ if 'media_type' in clean.columns:
277
+ clean = clean[clean['media_type'] == 'photo'].copy()
278
+ clean.reset_index(drop=True, inplace=True)
279
+ pq.write_table(pa.Table.from_pandas(clean), args.parquet)
280
+ print(f" Cleaned parquet: {len(clean)} rows, {len(clean.columns)} cols -> {args.parquet}")
281
+
282
+ # Group images
283
+ groups = group_images(df)
284
+ print(f" Prompt groups: {len(groups)}")
285
+
286
+ # Clean and filter
287
+ cleaned = []
288
+ for group in groups:
289
+ prompt = build_prompt(group['raw_text'])
290
+ if len(prompt) < args.min_prompt_len:
291
+ continue
292
+ if len(group['images']) < args.min_images:
293
+ continue
294
+
295
+ cleaned.append({
296
+ 'prompt': prompt,
297
+ 'raw_text': group['raw_text'],
298
+ 'num_images': len(group['images']),
299
+ 'message_id': group['message_id'],
300
+ 'datetime': group['datetime'],
301
+ 'images': group['images'],
302
+ })
303
+
304
+ print(f" Cleaned groups: {len(cleaned)}")
305
+ print(f" Total images: {sum(g['num_images'] for g in cleaned)}")
306
+
307
+ if args.stats:
308
+ # Print distribution
309
+ from collections import Counter
310
+ sizes = Counter(g['num_images'] for g in cleaned)
311
+ print("\n Group size distribution:")
312
+ for size, count in sorted(sizes.items()):
313
+ print(f" {size} images: {count} groups")
314
+
315
+ # Show sample prompts
316
+ print("\n Sample prompts:")
317
+ for g in cleaned[:5]:
318
+ print(f" [{g['num_images']} imgs] {g['prompt'][:120]}...")
319
+ return
320
+
321
+ # Output
322
+ if args.output:
323
+ output_path = Path(args.output)
324
+ output_path.parent.mkdir(parents=True, exist_ok=True)
325
+
326
+ with open(output_path, 'w', encoding='utf-8') as f:
327
+ for group in cleaned:
328
+ record = {
329
+ 'prompt': group['prompt'],
330
+ 'num_images': group['num_images'],
331
+ 'message_id': group['message_id'],
332
+ 'datetime': group['datetime'],
333
+ 'image_paths': [
334
+ f"images/msg_{img['message_id']}_row_{img['row_idx']}.webp"
335
+ for img in group['images']
336
+ ],
337
+ }
338
+ f.write(json.dumps(record, ensure_ascii=False) + '\n')
339
+
340
+ print(f"\n Written to {output_path}")
341
+
342
+ # Also save images
343
+ img_dir = output_path.parent / 'images'
344
+ img_dir.mkdir(exist_ok=True)
345
+
346
+ from PIL import Image
347
+ import io
348
+
349
+ print(" Extracting images...")
350
+ saved = 0
351
+ for group in cleaned:
352
+ for img_data in group['images']:
353
+ try:
354
+ img = Image.open(io.BytesIO(img_data['image_bytes']))
355
+ img_path = img_dir / f"msg_{img_data['message_id']}_row_{img_data['row_idx']}.webp"
356
+ img.save(img_path, format='WEBP', quality=90)
357
+ saved += 1
358
+ except Exception as e:
359
+ print(f" Warning: Failed to save image {img_data['message_id']}: {e}")
360
+
361
+ print(f" Saved {saved} images to {img_dir}")
362
+ else:
363
+ # Just print stats
364
+ from collections import Counter
365
+ sizes = Counter(g['num_images'] for g in cleaned)
366
+ print("\n Group size distribution:")
367
+ for size, count in sorted(sizes.items()):
368
+ print(f" {size} images: {count} groups")
369
+
370
+ print("\n Sample prompts:")
371
+ for g in cleaned[:10]:
372
+ print(f" [{g['num_images']} imgs] {g['prompt'][:150]}...")
373
+
374
+
375
+ if __name__ == '__main__':
376
+ main()