williamsmichael21 commited on
Commit
fe8f2eb
·
verified ·
1 Parent(s): 7186a13

Upload 2 files

Browse files
README.md ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ tags:
4
+ - ecommerce
5
+ - hdf5
6
+ - image-text
7
+ - lenient
8
+ - minimal
9
+ - mixup-cutmix
10
+ - pseudo-label
11
+ - random
12
+ - temporal
13
+ ---
14
+
15
+ # dataset_015484619_ecommerce_image_text.py
16
+
17
+ ## Dataset Summary
18
+
19
+ A **ecommerce** dataset with **image text** modality, stored in **hdf5** format.
20
+
21
+ ## Preprocessing & Augmentation
22
+
23
+ - **Preprocessing**: minimal
24
+ - **Augmentation**: mixup cutmix
25
+
26
+ ## Splits & Sampling
27
+
28
+ - **Split strategy**: temporal
29
+ - **Sampling**: random
30
+
31
+ ## Quality & Labeling
32
+
33
+ - **Quality filtering**: lenient
34
+ - **Labeling**: pseudo label
35
+
36
+ ## Files
37
+
38
+ - `dataset_015484619_ecommerce_image_text.py` — main artifact of this repository
39
+
40
+ ## License
41
+
42
+ See the license field above.
dataset_015484619_ecommerce_image_text.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json, os, hashlib, logging
2
+ from typing import List, Dict, Optional
3
+
4
+ log = logging.getLogger(__name__)
5
+
6
+ # --- real data source: ecommerce ---
7
+ TV_DATASET = None
8
+ HF_CANDIDATES = ['ashraq/fashion-product-images-small']
9
+ IMAGE_FIELD = 'image'
10
+ TEXT_FIELD = None
11
+ LABEL_FIELD = 'articleType'
12
+ PROMPT_TEMPLATE = 'a product catalog photo of {label}'
13
+ DATASET_URL = 'https://www.kaggle.com/datasets/paramaggarwal/fashion-product-images-dataset'
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
+ class EcommerceDataset:
84
+ def __init__(self, data_dir: str, output_dir: str, img_size: int = 224):
85
+ self.data_dir = data_dir
86
+ self.output_dir = output_dir
87
+ self.img_size = img_size
88
+ self.samples = []
89
+ self.processed = []
90
+
91
+ def load(self) -> List[Dict]:
92
+ # 加载
93
+ from pathlib import Path
94
+ for f in Path(self.data_dir).glob('*.jsonl'):
95
+ with open(f) as fp:
96
+ for line in fp:
97
+ if line.strip():
98
+ self.samples.append(json.loads(line))
99
+ log.info(f'Loaded {len(self.samples)} samples')
100
+ return self.samples
101
+
102
+ def filter(self) -> List[Dict]:
103
+
104
+ filtered = []
105
+ for s in self.samples:
106
+ text = s.get('ecommerce', s.get('text', ''))
107
+ if len(text.split()) >= 3:
108
+ filtered.append(s)
109
+ self.samples = filtered
110
+ return filtered
111
+
112
+ def deduplicate(self) -> List[Dict]:
113
+ seen = set()
114
+ result = []
115
+ for s in self.samples:
116
+ fp = s.get('image', s.get('audio', ''))
117
+ if fp and os.path.exists(fp):
118
+ h = hashlib.md5(open(fp, 'rb').read()).hexdigest()
119
+ if h in seen:
120
+ continue
121
+ seen.add(h)
122
+ result.append(s)
123
+ self.samples = result
124
+ return result
125
+
126
+ def process(self) -> List[Dict]:
127
+ os.makedirs(self.output_dir, exist_ok=True)
128
+ for s in self.samples:
129
+ item = {}
130
+ if 'image' in s:
131
+ try:
132
+ from PIL import Image
133
+ img = Image.open(s['image']).convert('RGB')
134
+ img = img.resize((self.img_size, self.img_size))
135
+ p = os.path.join(self.output_dir, os.path.basename(s['image']))
136
+ img.save(p, 'JPEG', quality=95)
137
+ item['image'] = p
138
+ except Exception as e:
139
+ log.warning(f'Failed: {e}')
140
+ continue
141
+ item['text'] = s.get('ecommerce', s.get('text', ''))
142
+ item['domain'] = 'ecommerce'
143
+ self.processed.append(item)
144
+ return self.processed
145
+
146
+ def save(self):
147
+ path = os.path.join(self.output_dir, 'dataset.jsonl')
148
+ with open(path, 'w') as f:
149
+ for d in self.processed:
150
+ f.write(json.dumps(d, ensure_ascii=False) + '\n')
151
+ log.info(f'Saved {len(self.processed)} samples to {path}')
152
+
153
+ def run(self):
154
+ self.load()
155
+ if not self.samples:
156
+ self.samples = fetch_real_samples()
157
+ self.filter()
158
+ self.deduplicate()
159
+ self.process()
160
+ self.save()
161
+
162
+
163
+ if __name__ == '__main__':
164
+ import sys
165
+ ds = EcommerceDataset(sys.argv[1] if len(sys.argv) > 1 else './data',
166
+ sys.argv[2] if len(sys.argv) > 2 else './output')
167
+ ds.run()