File size: 6,771 Bytes
0d25dbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Download original Google Play gallery positions without assigning devices.

Repeated URLs and bytes receive separate files. Run device_filter.py on the
resulting images.jsonl to add the public device labels after downloading.
"""
import argparse
import hashlib
import io
import json
from pathlib import Path
import time
from urllib.parse import urlsplit, urlunsplit

from PIL import Image
import requests

from app_collect import clean_app, read_jsonl, write_line


EXTENSIONS = {"PNG":"png", "JPEG":"jpg", "WEBP":"webp", "GIF":"gif", "MPO":"mpo"}
MAX_BYTES = 40 * 1024 * 1024


def native_url(url):
    parts = urlsplit(url)
    if parts.scheme != "https" or parts.hostname not in {"play-lh.googleusercontent.com", "lh3.googleusercontent.com"}:
        raise ValueError("Unsupported screenshot CDN URL")
    return urlunsplit((parts.scheme, parts.netloc, parts.path.split("=", 1)[0] + "=s0", "", ""))


def inspect_bytes(data):
    if len(data) > MAX_BYTES:
        raise ValueError("Image byte limit")
    with Image.open(io.BytesIO(data)) as image:
        width, height = image.size
        fmt = image.format
        frames = getattr(image, "n_frames", 1)
        if fmt not in EXTENSIONS or not 1 <= frames <= 16 or min(width, height) <= 0 or width * height > 40_000_000:
            raise ValueError("Image format, dimensions, or frame limit")
        image.verify()
    pixels = 0
    with Image.open(io.BytesIO(data)) as image:
        for frame in range(frames):
            image.seek(frame)
            pixels += image.width * image.height
            if image.width * image.height > 40_000_000 or pixels > 80_000_000:
                raise ValueError("Image pixel limit")
            image.load()
    return {"width":width, "height":height, "format":fmt, "sha256":hashlib.sha256(data).hexdigest(), "size_bytes":len(data)}


def fetch_bytes(session, url):
    data = bytearray()
    with session.get(url, timeout=(15, 60), stream=True) as response:
        response.raise_for_status()
        for chunk in response.iter_content(128 * 1024):
            data.extend(chunk)
            if len(data) > MAX_BYTES:
                raise ValueError("Image byte limit")
    return bytes(data)


def app_folder(app_id):
    # Always add a suffix for fresh downloads; avoids case-fold collisions.
    return app_id + "__" + hashlib.sha256(app_id.encode()).hexdigest()[:10]

def screenshot_positions(metadata):
    """Accept the frozen scraper schema and the bundled live parser schema."""
    for ordinal, value in enumerate(metadata.get("screenshots", [])):
        if isinstance(value, str):
            yield ordinal, value
        elif isinstance(value, dict):
            for position in value.get("source_gallery_indices", [value.get("index", ordinal)]):
                yield position, value["url"]


def image_row(app_id, position, *, width=None, height=None, image_path=None,
              source_url=None, sha256=None):
    """Build one unclassified gallery-position record for device_filter.py."""
    return {
        "image_id": f"google_play:{app_id}:screenshots:{position}",
        "app_id": app_id, "store": "google_play", "gallery": "screenshots",
        "position": position, "image_path": image_path,
        "width": width, "height": height,
        "aspect_ratio": width / height if width and height else None,
        "source_url": source_url, "sha256": sha256,
    }


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--apps", type=Path, required=True)
    parser.add_argument("--output", type=Path, required=True, help="A fresh dataset directory.")
    parser.add_argument("--interval", type=float, default=0.2)
    parser.add_argument("--attempts", type=int, default=3)
    parser.add_argument("--limit", type=int, help="Download only this many positions; retain remaining positions without files.")
    args = parser.parse_args()
    if args.attempts < 1 or (args.limit is not None and args.limit < 0):
        parser.error("Invalid attempts or limit")
    if (args.output / "images.jsonl").exists() or (args.output / "images").exists():
        parser.error("Choose a fresh output directory to preserve existing data.")
    args.output.mkdir(parents=True, exist_ok=True)
    app_output = args.output / "apps.jsonl"
    if args.apps.resolve() != app_output.resolve():
        if app_output.exists():
            parser.error("apps.jsonl already exists and differs from --apps")
    (args.output / "images").mkdir()
    session = requests.Session()
    attempted = 0
    with (args.output / "images.jsonl").open("x", encoding="utf-8") as output:
        for app in read_jsonl(args.apps):
            app_id = app["app_id"]
            for position, source_url in screenshot_positions(app.get("metadata", app)):
                record = image_row(app_id, position, source_url=source_url)
                if args.limit is None or attempted < args.limit:
                    attempted += 1
                    for attempt in range(args.attempts):
                        try:
                            url = native_url(source_url)
                            data = fetch_bytes(session, url)
                            info = inspect_bytes(data)
                            relative = f"images/{app_folder(app_id)}/{position:04d}.{EXTENSIONS[info['format']]}"
                            path = args.output / relative
                            path.parent.mkdir(parents=True, exist_ok=True)
                            with path.open("xb") as image_file:
                                image_file.write(data)
                            record = image_row(app_id, position,
                                width=info["width"], height=info["height"], source_url=source_url,
                                image_path=relative, sha256=info["sha256"])
                            break
                        except (requests.RequestException, OSError, ValueError, SyntaxError):
                            if attempt + 1 < args.attempts:
                                time.sleep(2 ** attempt)
                    time.sleep(max(0, args.interval))
                write_line(output, record)
                output.flush()
    # Sanitize only after reading the selected records: --apps is allowed to
    # name output/apps.jsonl itself. Keep all apps in limited image runs.
    temporary_apps = args.output / "apps.jsonl.public.tmp"
    with temporary_apps.open("x", encoding="utf-8") as output:
        for app in read_jsonl(args.apps):
            write_line(output, clean_app(app))
    temporary_apps.replace(app_output)
    print(json.dumps({"attempted_positions":attempted, "manifest":str(args.output / "images.jsonl")}))


if __name__ == "__main__":
    main()