File size: 6,029 Bytes
dbfcf0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
import json, os, hashlib, logging
from typing import List, Dict, Optional

log = logging.getLogger(__name__)

# --- real data source: code ---
TV_DATASET = None
HF_CANDIDATES = ['code_search_net', 'codeparrot/github-code']
IMAGE_FIELD = None
TEXT_FIELD = 'func_code_string'
LABEL_FIELD = 'func_documentation_string'
PROMPT_TEMPLATE = 'a photo of a {label}'
DATASET_URL = 'https://huggingface.co/datasets/code_search_net'

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


class CodeDataset:
    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) 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('code', 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('code', s.get('text', ''))
            item['domain'] = 'code'
            self.processed.append(item)
        return self.processed

    def save(self):
        path = os.path.join(self.output_dir, 'dataset.jsonl')
        with open(path, 'w') 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 = CodeDataset(sys.argv[1] if len(sys.argv) > 1 else './data',
                  sys.argv[2] if len(sys.argv) > 2 else './output')
    ds.run()