kaizhangana commited on
Commit
61ceba6
·
verified ·
1 Parent(s): e361b21

Upload 2 files

Browse files
Files changed (2) hide show
  1. README.md +42 -0
  2. loader.py +159 -0
README.md ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: cc-by-4.0
3
+ tags:
4
+ - active
5
+ - huggingface
6
+ - image-depth
7
+ - manual
8
+ - minimal
9
+ - movie-posters
10
+ - none
11
+ - strict
12
+ - temporal
13
+ ---
14
+
15
+ # loader.py
16
+
17
+ ## Dataset Summary
18
+
19
+ A **movie posters** dataset with **image depth** modality, stored in **huggingface** format.
20
+
21
+ ## Preprocessing & Augmentation
22
+
23
+ - **Preprocessing**: minimal
24
+ - **Augmentation**: none
25
+
26
+ ## Splits & Sampling
27
+
28
+ - **Split strategy**: temporal
29
+ - **Sampling**: active
30
+
31
+ ## Quality & Labeling
32
+
33
+ - **Quality filtering**: strict
34
+ - **Labeling**: manual
35
+
36
+ ## Files
37
+
38
+ - `loader.py` — main artifact of this repository
39
+
40
+ ## License
41
+
42
+ See the license field above.
loader.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json, os, hashlib, logging
2
+ from pathlib import Path
3
+
4
+ log = logging.getLogger(__name__)
5
+
6
+ # --- real data source: movie_posters ---
7
+ TV_DATASET = None
8
+ HF_CANDIDATES = []
9
+ IMAGE_FIELD = 'image'
10
+ TEXT_FIELD = None
11
+ LABEL_FIELD = 'label'
12
+ PROMPT_TEMPLATE = 'a movie poster for a {label} film'
13
+ DATASET_URL = 'https://www.kaggle.com/datasets/neha1703/movie-genre-from-its-poster'
14
+
15
+ def fetch_real_samples(max_samples=5000, cache_dir='./_cache'):
16
+ # 本地???有数据时自动下载真实公开数据集: torchvision -> HuggingFace -> 手动说明
17
+ out = []
18
+ if TV_DATASET is not None:
19
+ try:
20
+ import torchvision
21
+ ctor = getattr(torchvision.datasets, TV_DATASET)
22
+ try:
23
+ ds = ctor(root=cache_dir, split='train', download=True)
24
+ except TypeError:
25
+ try:
26
+ ds = ctor(root=cache_dir, train=True, download=True)
27
+ except TypeError:
28
+ ds = ctor(root=cache_dir, download=True)
29
+ classes = getattr(ds, 'classes', None)
30
+ os.makedirs(os.path.join(cache_dir, 'tv'), exist_ok=True)
31
+ for i, item in enumerate(ds):
32
+ if len(out) >= max_samples:
33
+ break
34
+ img, label = item[0], item[1]
35
+ name = classes[label] if classes else str(label)
36
+ p = os.path.join(cache_dir, 'tv', str(i) + '.png')
37
+ try:
38
+ img.save(p)
39
+ except Exception:
40
+ continue
41
+ out.append({'image': p, 'text': PROMPT_TEMPLATE.format(label=name)})
42
+ if out:
43
+ return out
44
+ except Exception as e:
45
+ print('torchvision load failed:', e)
46
+ for repo in HF_CANDIDATES:
47
+ try:
48
+ from datasets import load_dataset
49
+ try:
50
+ ds = load_dataset(repo, split='train', streaming=True)
51
+ except Exception:
52
+ ds = load_dataset(repo, split='train')
53
+ img_dir = os.path.join(cache_dir, 'hf_images')
54
+ os.makedirs(img_dir, exist_ok=True)
55
+ for i, ex in enumerate(ds):
56
+ if len(out) >= max_samples:
57
+ break
58
+ txt = None
59
+ if TEXT_FIELD is not None and TEXT_FIELD in ex:
60
+ v = ex[TEXT_FIELD]
61
+ txt = v if isinstance(v, str) else ' '.join(map(str, v if isinstance(v, (list, tuple)) else [v]))
62
+ if txt is None and LABEL_FIELD in ex:
63
+ txt = PROMPT_TEMPLATE.format(label=ex[LABEL_FIELD])
64
+ if txt is None:
65
+ continue
66
+ if IMAGE_FIELD not in ex or ex[IMAGE_FIELD] is None:
67
+ continue
68
+ p = os.path.join(img_dir, str(i) + '.jpg')
69
+ try:
70
+ ex[IMAGE_FIELD].convert('RGB').save(p)
71
+ except Exception:
72
+ continue
73
+ out.append({'image': p, 'text': txt})
74
+ if out:
75
+ return out
76
+ except Exception as e:
77
+ print('HF load failed for', repo, ':', e)
78
+ print('Automatic download failed. Please get the data manually from:')
79
+ print(' ' + DATASET_URL)
80
+ return out
81
+
82
+
83
+ def load(data_dir):
84
+
85
+ files = list(Path(data_dir).glob('*.jsonl'))
86
+ if not files:
87
+ files = list(Path(data_dir).glob('*.json'))
88
+ samples = []
89
+ for f in files:
90
+ with open(f) as fp:
91
+ if f.suffix == '.json':
92
+ d = json.load(fp)
93
+ samples.extend(d if isinstance(d, list) else [d])
94
+ else:
95
+ samples.extend(json.loads(l) for l in fp if l.strip())
96
+ return samples
97
+
98
+ def filter_quality(samples, min_score=0.5):
99
+
100
+ results = []
101
+ for s in samples:
102
+ text = s.get("movie_posters", s.get("text", ""))
103
+ if len(text.split()) >= 3:
104
+ results.append(s)
105
+ return results
106
+
107
+ def dedup(samples):
108
+ seen = set()
109
+ out = []
110
+ for s in samples:
111
+ fp = s.get("image", s.get("audio", ""))
112
+ if fp and os.path.exists(fp):
113
+ h = hashlib.md5(open(fp, 'rb').read()).hexdigest()
114
+ if h in seen:
115
+ continue
116
+ seen.add(h)
117
+ out.append(s)
118
+ return out
119
+
120
+ def preprocess(samples, out_dir, img_size=224):
121
+
122
+ os.makedirs(out_dir, exist_ok=True)
123
+ processed = []
124
+ for s in samples:
125
+ item = {}
126
+ if "image" in s:
127
+ try:
128
+ from PIL import Image as IM
129
+ img = IM.open(s["image"]).convert("RGB")
130
+ img = img.resize((img_size, img_size))
131
+ p = os.path.join(out_dir, os.path.basename(s["image"]))
132
+ img.save(p, "JPEG", quality=95)
133
+ item["image"] = p
134
+ except Exception:
135
+ continue
136
+ text = s.get("movie_posters", s.get("text", ""))
137
+ item["text"] = text
138
+ item["domain"] = "movie_posters"
139
+ processed.append(item)
140
+ return processed
141
+
142
+ def save_jsonl(data, path):
143
+ with open(path, 'w') as f:
144
+ for d in data:
145
+ f.write(json.dumps(d, ensure_ascii=False) + '\n')
146
+
147
+ def main():
148
+ import sys
149
+ data_dir = sys.argv[1] if len(sys.argv) > 1 else './data'
150
+ out = sys.argv[2] if len(sys.argv) > 2 else './output'
151
+ samples = load(data_dir) or fetch_real_samples()
152
+ samples = filter_quality(samples)
153
+ samples = dedup(samples)
154
+ result = preprocess(samples, out)
155
+ save_jsonl(result, os.path.join(out, 'dataset.jsonl'))
156
+ print(f'Done: {len(result)} samples')
157
+
158
+ if __name__ == '__main__':
159
+ main()