dataset_132648601_nlp_summarization_multimodal3 / dataset_132648601_nlp_summarization_multimodal3.py
| import json, os, hashlib | |
| from pathlib import Path | |
| # nlp_summarization dataset processor | |
| # modality: multimodal3, preprocessing: domain_specific | |
| # --- real data source: nlp_summarization --- | |
| TV_DATASET = None | |
| HF_CANDIDATES = ['xsum', 'cnn_dailymail', 'multi_news'] | |
| IMAGE_FIELD = None | |
| TEXT_FIELD = 'document' | |
| LABEL_FIELD = 'summary' | |
| PROMPT_TEMPLATE = 'a photo of a {label}' | |
| DATASET_URL = 'https://huggingface.co/datasets/xsum' | |
| def fetch_real_samples(max_samples=5000, cache_dir='./_cache'): | |
| # 本地没有数据时自动下载真实公开数据集: torchvision -> HuggingFace -> 手动说明 | |
| out = [] | |
| if TV_DATASET is not None: | |
| try: | |
| import torchvision | |
| ctor = getattr(torchvision.datasets, TV_DATASET) | |
| try: | |
| ds = ctor(root=cache_dir, split='train', download=True) | |
| except TypeError: | |
| try: | |
| ds = ctor(root=cache_dir, train=True, download=True) | |
| except TypeError: | |
| ds = ctor(root=cache_dir, download=True) | |
| classes = getattr(ds, 'classes', None) | |
| os.makedirs(os.path.join(cache_dir, 'tv'), exist_ok=True) | |
| for i, item in enumerate(ds): | |
| if len(out) >= max_samples: | |
| break | |
| img, label = item[0], item[1] | |
| name = classes[label] if classes else str(label) | |
| p = os.path.join(cache_dir, 'tv', str(i) + '.png') | |
| try: | |
| img.save(p) | |
| except Exception: | |
| continue | |
| out.append({'image': p, 'text': PROMPT_TEMPLATE.format(label=name)}) | |
| if out: | |
| return out | |
| except Exception as e: | |
| print('torchvision load failed:', e) | |
| for repo in HF_CANDIDATES: | |
| try: | |
| from datasets import load_dataset | |
| try: | |
| ds = load_dataset(repo, split='train', streaming=True) | |
| except Exception: | |
| ds = load_dataset(repo, split='train') | |
| img_dir = os.path.join(cache_dir, 'hf_images') | |
| os.makedirs(img_dir, exist_ok=True) | |
| for i, ex in enumerate(ds): | |
| if len(out) >= max_samples: | |
| break | |
| txt = None | |
| if TEXT_FIELD is not None and TEXT_FIELD in ex: | |
| v = ex[TEXT_FIELD] | |
| txt = v if isinstance(v, str) else ' '.join(map(str, v if isinstance(v, (list, tuple)) else [v])) | |
| if txt is None and LABEL_FIELD in ex: | |
| txt = PROMPT_TEMPLATE.format(label=ex[LABEL_FIELD]) | |
| if txt is None: | |
| continue | |
| out.append({'text': txt}) | |
| if out: | |
| return out | |
| except Exception as e: | |
| print('HF load failed for', repo, ':', e) | |
| print('Automatic download failed. Please get the data manually from:') | |
| print(' ' + DATASET_URL) | |
| return out | |
| def build_dataset(src, dst, sz=224): | |
| samples = [] | |
| for f in Path(src).glob('*.jsonl'): | |
| with open(f) as fp: | |
| for line in fp: | |
| if line.strip(): | |
| samples.append(json.loads(line)) | |
| if not samples: | |
| samples = fetch_real_samples() | |
| # dedup | |
| seen = set() | |
| unique = [] | |
| for s in samples: | |
| fp = s.get('image', s.get('audio', '')) | |
| if fp and os.path.exists(fp): | |
| h = hashlib.md5(open(fp, 'rb').read()).hexdigest() | |
| if h not in seen: | |
| seen.add(h) | |
| unique.append(s) | |
| else: | |
| unique.append(s) | |
| os.makedirs(dst, exist_ok=True) | |
| out = [] | |
| for s in unique: | |
| item = {} | |
| if 'image' in s: | |
| from PIL import Image | |
| img = Image.open(s['image']).convert('RGB').resize((sz, sz)) | |
| p = os.path.join(dst, os.path.basename(s['image'])) | |
| img.save(p, 'JPEG', quality=95) | |
| item['image'] = p | |
| item['text'] = s.get('nlp_summarization', s.get('text', '')) | |
| item['domain'] = 'nlp_summarization' | |
| out.append(item) | |
| with open(os.path.join(dst, 'dataset.jsonl'), 'w') as f: | |
| for d in out: | |
| f.write(json.dumps(d, ensure_ascii=False) + '\n') | |
| return out | |
| if __name__ == '__main__': | |
| import sys | |
| result = build_dataset(sys.argv[1], sys.argv[2]) | |
| print(f'Processed {len(result)} samples') | |