telegram-channel-dataset / clean_dataset.py
GCStream's picture
Add DataView tool: dataset visualizer with gallery, table, compare, and drawer views
11ce4a7 verified
Raw
History Blame Contribute Delete
12.7 kB
"""
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()