File size: 11,263 Bytes
2978bba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
"""
scripts/data_setup.py

Utilities to fetch real face images from Unsplash and generate morphed images by averaging.
"""
import os
import uuid
import random
try:
    import requests
except ImportError:
    requests = None
from PIL import Image
import numpy as np

# Base data directory
DATA_DIR = os.path.join(os.getcwd(), 'data')

def fetch_real_faces(count: int, split: str = 'train') -> int:
    """
    Fetch random face images from Unsplash into data/<split>/real/.
    Requires environment variable UNSPLASH_ACCESS_KEY to be set.
    Returns the number of images downloaded.
    """
    if requests is None:
        raise ImportError('requests library is required to fetch images')
    access_key = os.getenv('UNSPLASH_ACCESS_KEY')
    if not access_key:
        raise EnvironmentError('UNSPLASH_ACCESS_KEY environment variable not set')
    save_dir = os.path.join(DATA_DIR, split, 'real')
    os.makedirs(save_dir, exist_ok=True)
    # Unsplash random photo endpoint
    url = 'https://api.unsplash.com/photos/random'
    params = {
        'client_id': access_key,
        'query': 'face portrait',
        'count': count
    }
    resp = requests.get(url, params=params)
    if resp.status_code != 200:
        raise RuntimeError(f'Unsplash API error {resp.status_code}: {resp.text}')
    items = resp.json()
    downloaded = 0
    for item in items:
        img_url = item.get('urls', {}).get('small')
        if not img_url:
            continue
        img_data = requests.get(img_url).content
        fname = os.path.join(save_dir, f"{uuid.uuid4()}.jpg")
        with open(fname, 'wb') as f:
            f.write(img_data)
        downloaded += 1
    return downloaded

def generate_morphs(count: int, split: str = 'train') -> int:
    """
    Generate morphed images by averaging random pairs from data/<split>/real/,
    saving to data/<split>/morph/. Returns number generated.
    """
    real_dir = os.path.join(DATA_DIR, split, 'real')
    morph_dir = os.path.join(DATA_DIR, split, 'morph')
    os.makedirs(morph_dir, exist_ok=True)
    # Collect real image files
    files = [f for f in os.listdir(real_dir)
             if f.lower().endswith(('.png', '.jpg', '.jpeg'))]
    if len(files) < 2:
        raise RuntimeError('Not enough real images to generate morphs')
    generated = 0
    for _ in range(count):
        a, b = random.sample(files, 2)
        path_a = os.path.join(real_dir, a)
        path_b = os.path.join(real_dir, b)
        img_a = Image.open(path_a).convert('RGB').resize((224, 224))
        img_b = Image.open(path_b).convert('RGB').resize((224, 224))
        arr_a = np.array(img_a).astype(np.float32)
        arr_b = np.array(img_b).astype(np.float32)
        arr = ((arr_a + arr_b) / 2.0).astype(np.uint8)
        img_m = Image.fromarray(arr)
        fname = os.path.join(morph_dir, f"{uuid.uuid4()}.jpg")
        img_m.save(fname)
        generated += 1
    return generated
    
try:
    from sklearn.datasets import fetch_lfw_people
except ImportError:
    fetch_lfw_people = None

def fetch_lfw(count: int, split: str = 'train') -> int:
    """
    Download images from the LFW (Labeled Faces in the Wild) dataset.
    Saves up to `count` RGB images into data/<split>/real/.
    Requires scikit-learn to be installed.
    Returns the number of images saved.
    """
    if fetch_lfw_people is None:
        # scikit-learn not installed: report error
        raise ImportError('scikit-learn is required to fetch LFW dataset')
    # fetch grayscale images
    lfw = fetch_lfw_people(min_faces_per_person=1, resize=0.5, color=False)
    images = lfw.images
    num = min(count, len(images))
    save_dir = os.path.join(DATA_DIR, split, 'real')
    os.makedirs(save_dir, exist_ok=True)
    for idx in range(num):
        img_gray = images[idx]
        # convert to RGB by stacking
        arr3 = np.stack([img_gray] * 3, axis=-1)
        pil_img = Image.fromarray((arr3 * 255).astype(np.uint8))
        pil_img = pil_img.resize((224, 224))
        fname = os.path.join(save_dir, f"lfw_{idx}_{uuid.uuid4().hex}.jpg")
        pil_img.save(fname)
    return num

def fetch_pexels(count: int, split: str = 'train') -> int:
    """
    Fetch random face images from Pexels API into data/<split>/real/.
    Requires environment variable PEXELS_API_KEY to be set.
    Returns the number of images downloaded.
    """
    try:
        import requests
    except ImportError:
        raise ImportError('requests library is required to fetch Pexels images')
    api_key = os.getenv('PEXELS_API_KEY')
    if not api_key:
        raise EnvironmentError('PEXELS_API_KEY environment variable not set')
    save_dir = os.path.join(DATA_DIR, split, 'real')
    os.makedirs(save_dir, exist_ok=True)
    url = 'https://api.pexels.com/v1/search'
    headers = {'Authorization': api_key}
    params = {'query': 'face', 'per_page': count}
    resp = requests.get(url, headers=headers, params=params)
    if resp.status_code != 200:
        raise RuntimeError(f'Pexels API error {resp.status_code}: {resp.text}')
    data = resp.json()
    photos = data.get('photos', [])
    downloaded = 0
    for photo in photos:
        img_url = photo.get('src', {}).get('medium')
        if not img_url:
            continue
        img_data = requests.get(img_url).content
        fname = os.path.join(save_dir, f"{uuid.uuid4()}.jpg")
        with open(fname, 'wb') as f:
            f.write(img_data)
        downloaded += 1
    return downloaded

def fetch_pixabay(count: int, split: str = 'train') -> int:
    """
    Fetch random face images from Pixabay API into data/<split>/real/.
    Requires environment variable PIXABAY_API_KEY to be set.
    Returns the number of images downloaded.
    """
    try:
        import requests
    except ImportError:
        raise ImportError('requests library is required to fetch Pixabay images')
    api_key = os.getenv('PIXABAY_API_KEY')
    if not api_key:
        raise EnvironmentError('PIXABAY_API_KEY environment variable not set')
    save_dir = os.path.join(DATA_DIR, split, 'real')
    os.makedirs(save_dir, exist_ok=True)
    url = 'https://pixabay.com/api/'
    params = {'key': api_key, 'q': 'face', 'image_type': 'photo', 'per_page': count}
    resp = requests.get(url, params=params)
    if resp.status_code != 200:
        raise RuntimeError(f'Pixabay API error {resp.status_code}: {resp.text}')
    data = resp.json()
    hits = data.get('hits', [])
    downloaded = 0
    for hit in hits:
        img_url = hit.get('webformatURL')
        if not img_url:
            continue
        img_data = requests.get(img_url).content
        fname = os.path.join(save_dir, f"{uuid.uuid4()}.jpg")
        with open(fname, 'wb') as f:
            f.write(img_data)
        downloaded += 1
    return downloaded
    
def fetch_utkface(count: int, split: str = 'train') -> int:
    """
    Fetch the UTKFace dataset (faces only) from an S3 archive.
    Downloads and extracts up to `count` JPEGs into data/<split>/real/.
    No API key required.
    Returns the number of images extracted.
    """
    import requests, tarfile, tempfile
    url = 'https://s3-us-west-1.amazonaws.com/utkface/UTKFace.tar.gz'
    save_dir = os.path.join(DATA_DIR, split, 'real')
    os.makedirs(save_dir, exist_ok=True)
    # Download UTKFace archive (follow redirects automatically)
    resp = requests.get(url, stream=True)
    # Handle moved-permanently redirect for outdated S3 endpoint
    if resp.status_code == 301:
        raise RuntimeError(
            'UTKFace download URL has moved (HTTP 301). '
            'Please download the UTKFace dataset manually from https://susanqq.github.io/UTKFace/ '
            f'and extract {count} images into data/{split}/real/'
        )
    if resp.status_code != 200:
        raise RuntimeError(f'UTKFace download error {resp.status_code}')
    tmp = tempfile.NamedTemporaryFile(delete=False, suffix='.tar.gz')
    for chunk in resp.iter_content(chunk_size=1024*1024):
        if chunk:
            tmp.write(chunk)
    tmp.close()
    # Extract JPEGs
    extracted = 0
    with tarfile.open(tmp.name, 'r:gz') as tar:
        for member in tar.getmembers():
            if extracted >= count:
                break
            if member.isfile() and member.name.lower().endswith('.jpg'):
                f = tar.extractfile(member)
                if f:
                    outpath = os.path.join(save_dir, os.path.basename(member.name))
                    with open(outpath, 'wb') as out:
                        out.write(f.read())
                    extracted += 1
    return extracted

def fetch_tpdne(count: int, split: str = 'train') -> int:
    """
    Fetch GAN-generated faces from thispersondoesnotexist.com
    into data/<split>/real/. No API key required.
    Returns the number of images downloaded.
    """
    try:
        import requests
    except ImportError:
        raise ImportError('requests library is required to fetch GAN images')
    save_dir = os.path.join(DATA_DIR, split, 'real')
    os.makedirs(save_dir, exist_ok=True)
    downloaded = 0
    for i in range(count):
        resp = requests.get('https://thispersondoesnotexist.com/image', timeout=5)
        if resp.status_code != 200:
            continue
        fname = os.path.join(save_dir, f"tpdne_{uuid.uuid4().hex}.jpg")
        with open(fname, 'wb') as f:
            f.write(resp.content)
        downloaded += 1
    return downloaded
    
def fetch_celeba(count: int, split: str = 'train') -> int:
    """
    Fetch a sample of the CelebA dataset via Kaggle CLI.
    Requires Kaggle CLI installed and KAGGLE_USERNAME/KAGGLE_KEY set.
    Downloads and unzips full CelebA into data/raw/celeba/, then copies up to `count` images into data/<split>/real/.
    """
    import subprocess, glob, random, shutil
    raw_dir = os.path.join(DATA_DIR, 'raw', 'celeba')
    save_dir = os.path.join(DATA_DIR, split, 'real')
    os.makedirs(save_dir, exist_ok=True)
    # Download and unzip if not already present
    if not os.path.isdir(raw_dir):
        os.makedirs(raw_dir, exist_ok=True)
        cmd = [
            'kaggle', 'datasets', 'download', '-d', 'jessicali9530/celeba-dataset',
            '-p', raw_dir, '--unzip'
        ]
        subprocess.run(cmd, check=True)
    # Collect all images
    img_paths = glob.glob(os.path.join(raw_dir, '**', '*.jpg'), recursive=True)
    if not img_paths:
        raise RuntimeError('No CelebA images found in raw directory')
    # Randomly sample up to count
    chosen = random.sample(img_paths, min(count, len(img_paths)))
    copied = 0
    for src in chosen:
        dst = os.path.join(save_dir, os.path.basename(src))
        if not os.path.exists(dst):
            shutil.copy2(src, dst)
            copied += 1
    return copied

def fetch_vggface2(count: int, split: str = 'train') -> int:
    """
    Stub for VGGFace2 dataset: manual download required.
    Download from https://www.robots.ox.ac.uk/~vgg/data/vgg_face2/ and extract into data/<split>/real/vggface2/.
    This function does not automate download.
    """
    raise EnvironmentError(
        'VGGFace2 requires manual download: fetch from https://www.robots.ox.ac.uk/~vgg/data/vgg_face2/ '
        'and extract images into data/{}/real/vggface2/'.format(split)
    )