Add preprocess.py, README.md, dataset_infos.json, metadata_sample.jsonl
Browse filesFiles changed (4)
- README.mdAdded+55
- dataset_infos.jsonAdded+26
- metadata_sample.jsonlAdded+24
- preprocess.pyAdded+167
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455---
license: apache-2.0
tags:
- dataset
- comics
- image-audio
---
# Comics Image Audio Data Notes
## Dataset summary
A documented **Comics** data-preparation workflow for **Image Audio** records. The bundled rows demonstrate the schema and validation path rather than pretending to be a full training corpus.
## Included material
- `preprocess.py` — loading, cleaning, and split preparation code.
- `dataset_infos.json` — schema and split metadata.
- `metadata_sample.jsonl` — small, human-readable records for checking the schema.
- `README.md` — data card and usage notes.
## Processing choices
| Stage | Setting |
|---|---|
| Storage format | tfrecord |
| Preprocessing | aggressive |
| Augmentation | autoaugment |
| Split strategy | temporal |
| Sampling | contrastive |
| Quality checks | moderate |
| Labeling | semi auto |
## Validation checklist
Before using the prepared data, verify source licenses, duplicates across splits, missing values, label balance, and modality-specific corruption. Record the source version and every filtering rule so a later run can reproduce the same rows.
## Intended use
The repository is suitable for testing the data pipeline, adapting it to a documented source, and preparing controlled research splits. Release status: **metadata sample; full source data not bundled**. The sample is for schema inspection only and should not be reported as a full training corpus.
## Risks and limitations
The loader cannot guarantee that an external source is representative, correctly licensed, or free of sensitive information. Users remain responsible for source review, privacy checks, and bias analysis before training or redistribution.
## Files
- `preprocess.py` — primary artifact
- `README.md` — this documentation
- `dataset_infos.json` — schema metadata
- `metadata_sample.jsonl` — schema sample
## License
Released under **apache-2.0**. Review the source-data terms separately when this repository is used with external datasets.1234567891011121314151617181920212223242526{
"description": "Metadata sample and preparation pipeline for comics / image_audio data",
"features": {
"id": {
"dtype": "string"
},
"description": {
"dtype": "string"
},
"label": {
"dtype": "int64"
},
"domain": {
"dtype": "string"
},
"modality": {
"dtype": "string"
}
},
"splits": {
"sample": {
"num_examples": 24
}
},
"release_status": "metadata sample; full source data not bundled"
}123456789101112131415161718192021222324{"id": "sample-001", "description": "schema validation example", "label": 0, "domain": "comics", "modality": "image_audio"}
{"id": "sample-002", "description": "quality-control example", "label": 1, "domain": "comics", "modality": "image_audio"}
{"id": "sample-003", "description": "split inspection example", "label": 2, "domain": "comics", "modality": "image_audio"}
{"id": "sample-004", "description": "label review example", "label": 3, "domain": "comics", "modality": "image_audio"}
{"id": "sample-005", "description": "deduplication example", "label": 0, "domain": "comics", "modality": "image_audio"}
{"id": "sample-006", "description": "format conversion example", "label": 1, "domain": "comics", "modality": "image_audio"}
{"id": "sample-007", "description": "schema validation example", "label": 2, "domain": "comics", "modality": "image_audio"}
{"id": "sample-008", "description": "quality-control example", "label": 3, "domain": "comics", "modality": "image_audio"}
{"id": "sample-009", "description": "split inspection example", "label": 0, "domain": "comics", "modality": "image_audio"}
{"id": "sample-010", "description": "label review example", "label": 1, "domain": "comics", "modality": "image_audio"}
{"id": "sample-011", "description": "deduplication example", "label": 2, "domain": "comics", "modality": "image_audio"}
{"id": "sample-012", "description": "format conversion example", "label": 3, "domain": "comics", "modality": "image_audio"}
{"id": "sample-013", "description": "schema validation example", "label": 0, "domain": "comics", "modality": "image_audio"}
{"id": "sample-014", "description": "quality-control example", "label": 1, "domain": "comics", "modality": "image_audio"}
{"id": "sample-015", "description": "split inspection example", "label": 2, "domain": "comics", "modality": "image_audio"}
{"id": "sample-016", "description": "label review example", "label": 3, "domain": "comics", "modality": "image_audio"}
{"id": "sample-017", "description": "deduplication example", "label": 0, "domain": "comics", "modality": "image_audio"}
{"id": "sample-018", "description": "format conversion example", "label": 1, "domain": "comics", "modality": "image_audio"}
{"id": "sample-019", "description": "schema validation example", "label": 2, "domain": "comics", "modality": "image_audio"}
{"id": "sample-020", "description": "quality-control example", "label": 3, "domain": "comics", "modality": "image_audio"}
{"id": "sample-021", "description": "split inspection example", "label": 0, "domain": "comics", "modality": "image_audio"}
{"id": "sample-022", "description": "label review example", "label": 1, "domain": "comics", "modality": "image_audio"}
{"id": "sample-023", "description": "deduplication example", "label": 2, "domain": "comics", "modality": "image_audio"}
{"id": "sample-024", "description": "format conversion example", "label": 3, "domain": "comics", "modality": "image_audio"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167import json, os, hashlib, logging
from typing import List, Dict, Optional
log = logging.getLogger(__name__)
# --- real data source: comics ---
TV_DATASET = None
HF_CANDIDATES = []
IMAGE_FIELD = 'image'
TEXT_FIELD = None
LABEL_FIELD = 'label'
PROMPT_TEMPLATE = 'a manga panel of {label}'
DATASET_URL = 'http://www.manga109.org/en/'
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
class ComicsDataset:
def __init__(self, data_dir: str, output_dir: str, img_size: int = 224):
self.data_dir = data_dir
self.output_dir = output_dir
self.img_size = img_size
self.samples = []
self.processed = []
def load(self) -> List[Dict]:
from pathlib import Path
for f in Path(self.data_dir).glob('*.jsonl'):
with open(f, encoding="utf-8") as fp:
for line in fp:
if line.strip():
self.samples.append(json.loads(line))
log.info(f'Loaded {len(self.samples)} samples')
return self.samples
def filter(self) -> List[Dict]:
filtered = []
for s in self.samples:
text = s.get('comics', s.get('text', ''))
if len(text.split()) >= 3:
filtered.append(s)
self.samples = filtered
return filtered
def deduplicate(self) -> List[Dict]:
seen = set()
result = []
for s in self.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)
result.append(s)
self.samples = result
return result
def process(self) -> List[Dict]:
os.makedirs(self.output_dir, exist_ok=True)
for s in self.samples:
item = {}
if 'image' in s:
try:
from PIL import Image
img = Image.open(s['image']).convert('RGB')
img = img.resize((self.img_size, self.img_size))
p = os.path.join(self.output_dir, os.path.basename(s['image']))
img.save(p, 'JPEG', quality=95)
item['image'] = p
except Exception as e:
log.warning(f'Failed: {e}')
continue
item['text'] = s.get('comics', s.get('text', ''))
item['domain'] = 'comics'
self.processed.append(item)
return self.processed
def save(self):
path = os.path.join(self.output_dir, 'dataset.jsonl')
with open(path, 'w', encoding="utf-8") as f:
for d in self.processed:
f.write(json.dumps(d, ensure_ascii=False) + '\n')
log.info(f'Saved {len(self.processed)} samples to {path}')
def run(self):
self.load()
if not self.samples:
self.samples = fetch_real_samples()
self.filter()
self.deduplicate()
self.process()
self.save()
if __name__ == '__main__':
import sys
ds = ComicsDataset(sys.argv[1] if len(sys.argv) > 1 else './data',
sys.argv[2] if len(sys.argv) > 2 else './output')
ds.run()README.mdAdded+55
dataset_infos.jsonAdded+26
metadata_sample.jsonlAdded+24
preprocess.pyAdded+167