Download load_data.py from Alicericci/astronomy-data: direct link, hf CLI and curl.
- Browser
- Download file 5.78 kB
-
https://huggingface.co/datasets/Alicericci/astronomy-data/resolve/main/load_data.py
- Command line
-
hf download hf://datasets/Alicericci/astronomy-data/load_data.py
-
curl -L -o load_data.py https://huggingface.co/datasets/Alicericci/astronomy-data/resolve/main/load_data.py
5.78 kB
| import json, os, hashlib, logging | |
| from pathlib import Path | |
| log = logging.getLogger(__name__) | |
| # --- real data source: astronomy --- | |
| TV_DATASET = None | |
| HF_CANDIDATES = [] | |
| IMAGE_FIELD = 'image' | |
| TEXT_FIELD = None | |
| LABEL_FIELD = 'label' | |
| PROMPT_TEMPLATE = 'an astronomical image of {label}' | |
| DATASET_URL = 'https://www.kaggle.com/c/galaxy-zoo-the-galaxy-challenge' | |
| 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 | |
| if IMAGE_FIELD not in ex or ex[IMAGE_FIELD] is None: | |
| continue | |
| p = os.path.join(img_dir, str(i) + '.jpg') | |
| try: | |
| ex[IMAGE_FIELD].convert('RGB').save(p) | |
| except Exception: | |
| continue | |
| out.append({'image': p, '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 load(data_dir): | |
| files = list(Path(data_dir).glob('*.jsonl')) | |
| if not files: | |
| files = list(Path(data_dir).glob('*.json')) | |
| samples = [] | |
| for f in files: | |
| with open(f, encoding="utf-8") as fp: | |
| if f.suffix == '.json': | |
| d = json.load(fp) | |
| samples.extend(d if isinstance(d, list) else [d]) | |
| else: | |
| samples.extend(json.loads(l) for l in fp if l.strip()) | |
| return samples | |
| def filter_quality(samples, min_score=0.5): | |
| results = [] | |
| for s in samples: | |
| text = s.get('astronomy', s.get('text', '')) | |
| if len(text.split()) >= 3: | |
| results.append(s) | |
| return results | |
| def dedup(samples): | |
| seen = set() | |
| out = [] | |
| 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 in seen: | |
| continue | |
| seen.add(h) | |
| out.append(s) | |
| return out | |
| def preprocess(samples, out_dir, img_size=224): | |
| os.makedirs(out_dir, exist_ok=True) | |
| processed = [] | |
| for s in samples: | |
| item = {} | |
| if 'image' in s: | |
| try: | |
| from PIL import Image as IM | |
| img = IM.open(s['image']).convert('RGB') | |
| img = img.resize((img_size, img_size)) | |
| p = os.path.join(out_dir, os.path.basename(s['image'])) | |
| img.save(p, 'JPEG', quality=95) | |
| item['image'] = p | |
| except Exception: | |
| continue | |
| text = s.get('astronomy', s.get('text', '')) | |
| item['text'] = text | |
| item['domain'] = 'astronomy' | |
| processed.append(item) | |
| return processed | |
| def save_jsonl(data, path): | |
| with open(path, 'w', encoding="utf-8") as f: | |
| for d in data: | |
| f.write(json.dumps(d, ensure_ascii=False) + '\n') | |
| def main(): | |
| import sys | |
| data_dir = sys.argv[1] if len(sys.argv) > 1 else './data' | |
| out = sys.argv[2] if len(sys.argv) > 2 else './output' | |
| samples = load(data_dir) or fetch_real_samples() | |
| samples = filter_quality(samples) | |
| samples = dedup(samples) | |
| result = preprocess(samples, out) | |
| save_jsonl(result, os.path.join(out, 'dataset.jsonl')) | |
| print(f'Done: {len(result)} samples') | |
| if __name__ == '__main__': | |
| main() | |