Download apple_store/script/app_collect.py from Jl-wei/PhoneWatchUI: direct link, hf CLI and curl.
- Browser
- Download file 44.4 kB
-
https://huggingface.co/datasets/Jl-wei/PhoneWatchUI/resolve/main/apple_store/script/app_collect.py
- Command line
-
hf download hf://datasets/Jl-wei/PhoneWatchUI/apple_store/script/app_collect.py
-
curl -L -o app_collect.py https://huggingface.co/datasets/Jl-wei/PhoneWatchUI/resolve/main/apple_store/script/app_collect.py
44.4 kB
| """Collect PhoneWatchUI Apple app metadata from a supplied App-ID list. | |
| Includes the Apple Watch and iPhone page parsers. No network requests are made | |
| when this file is imported; run the CLI to collect public metadata, not IPA files. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| from datetime import datetime, timezone | |
| import gzip | |
| import hashlib | |
| from html.parser import HTMLParser | |
| import json | |
| import math | |
| from pathlib import Path | |
| import re | |
| import time | |
| from typing import Any | |
| from urllib.parse import urlsplit | |
| from urllib.request import Request, urlopen | |
| def write_json(path, value): | |
| path = Path(path) | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| temporary = path.with_name(path.name + '.tmp') | |
| temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2) + '\n') | |
| temporary.replace(path) | |
| def jsonl(path): | |
| with Path(path).open() as stream: | |
| for line in stream: | |
| if line.strip(): | |
| yield json.loads(line) | |
| def dump_line(stream, value): | |
| stream.write(json.dumps(value, ensure_ascii=False, separators=(',', ':')) + '\n') | |
| # Apple Watch product parser. | |
| class _Document(HTMLParser): | |
| def __init__(self) -> None: | |
| super().__init__(convert_charrefs=True) | |
| self.scripts: list[tuple[dict[str, str | None], str]] = [] | |
| self.links: list[str] = [] | |
| self.canonical: str | None = None | |
| self.language: str | None = None | |
| self._script: dict[str, str | None] | None = None | |
| self._parts: list[str] = [] | |
| def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: | |
| values = dict(attrs) | |
| if tag == "script": | |
| self._script, self._parts = values, [] | |
| elif tag == "html": | |
| self.language = values.get("lang") | |
| elif tag == "link" and "canonical" in (values.get("rel") or "").split(): | |
| self.canonical = values.get("href") | |
| elif tag == "a" and values.get("href"): | |
| self.links.append(values["href"]) | |
| def handle_data(self, data: str) -> None: | |
| if self._script is not None: | |
| self._parts.append(data) | |
| def handle_endtag(self, tag: str) -> None: | |
| if tag == "script" and self._script is not None: | |
| self.scripts.append((self._script, "".join(self._parts))) | |
| self._script, self._parts = None, [] | |
| def _dict(value: Any) -> dict: | |
| return value if isinstance(value, dict) else {} | |
| def _list(value: Any) -> list: | |
| return value if isinstance(value, list) else [] | |
| def _text(value: Any) -> str | None: | |
| return value.strip() if isinstance(value, str) and value.strip() else None | |
| def _id(value: Any) -> str | None: | |
| if isinstance(value, bool): | |
| return None | |
| text = str(value) if isinstance(value, (str, int)) else "" | |
| return text if text.isdigit() else None | |
| def _app_url(value: Any) -> tuple[str, str] | None: | |
| if not isinstance(value, str): | |
| return None | |
| try: | |
| parts = urlsplit(value) | |
| if parts.scheme != "https" or parts.hostname != "apps.apple.com" or parts.username: | |
| return None | |
| match = re.fullmatch(r"/([a-z]{2})/app/(?:[^/]+/)?id(\d+)/?", parts.path) | |
| if match: | |
| return match.group(2), value | |
| except ValueError: | |
| pass | |
| return None | |
| def _walk(value: Any): | |
| """Walk public content without collecting metrics, tokens, or review bodies.""" | |
| pending = [value] | |
| while pending: | |
| current = pending.pop() | |
| if isinstance(current, dict): | |
| yield current | |
| pending.extend( | |
| child for key, child in reversed(list(current.items())) | |
| if key not in {"userTokenHash", "actionMetrics", "impressionMetrics", | |
| "pageMetrics", "pageRenderMetrics", "allProductReviews", | |
| "editorsChoiceProductReviews"} | |
| ) | |
| elif isinstance(current, list): | |
| pending.extend(reversed(current)) | |
| def _product_nodes(root: Any) -> list[dict]: | |
| """Support array, data-array, numeric dictionary, and direct wrappers.""" | |
| nodes = [] | |
| pending = [root] | |
| while pending: | |
| node = pending.pop() | |
| if isinstance(node, list): | |
| pending.extend(reversed(node)) | |
| elif isinstance(node, dict): | |
| inner = _dict(node.get("data")) | |
| if (isinstance(inner.get("shelfMapping"), dict) | |
| or isinstance(inner.get("appPlatforms"), list)): | |
| nodes.append(node) | |
| # Do not confuse embedded related products with the main product. | |
| continue | |
| for key, child in reversed(list(node.items())): | |
| if key == "data" or key.isdigit(): | |
| pending.append(child) | |
| return nodes | |
| def _identity(node: dict) -> set[str]: | |
| data = _dict(node.get("data")) | |
| values = { | |
| _id(_dict(node.get("intent")).get("id")), | |
| _id(_dict(data.get("lockup")).get("adamId")), | |
| } | |
| canonical = _app_url(data.get("canonicalURL")) | |
| if canonical: | |
| values.add(canonical[0]) | |
| return values - {None} | |
| def _artwork(shot: Any, rank: int) -> dict | None: | |
| shot = _dict(shot) | |
| template = _text(shot.get("template")) | |
| width, height = shot.get("width"), shot.get("height") | |
| if (not template or isinstance(width, bool) or isinstance(height, bool) | |
| or not isinstance(width, int) or not isinstance(height, int) | |
| or width <= 0 or height <= 0): | |
| return None | |
| crop = shot.get("crop") or "bb" | |
| if not isinstance(crop, str) or not re.fullmatch(r"[A-Za-z0-9-]+", crop): | |
| return None | |
| url = template | |
| for key, value in {"w": width, "h": height, "c": crop, "f": "png"}.items(): | |
| url = url.replace("{" + key + "}", str(value)) | |
| if "{" in url or "}" in url: | |
| return None | |
| try: | |
| parts = urlsplit(url) | |
| host = parts.hostname or "" | |
| if (parts.scheme != "https" or parts.username | |
| or not (host == "mzstatic.com" or host.endswith(".mzstatic.com"))): | |
| return None | |
| except ValueError: | |
| return None | |
| return {"rank": rank, "url": url, "width": width, "height": height, | |
| "platform": "watch", "source_template": template} | |
| def _http_url(value: Any) -> str | None: | |
| value = _text(value) | |
| if value: | |
| try: | |
| parts = urlsplit(value) | |
| if parts.scheme in {"http", "https"} and parts.hostname and not parts.username: | |
| return value | |
| except ValueError: | |
| pass | |
| return None | |
| def _number(value: Any, *, integer: bool = False) -> int | float | None: | |
| if isinstance(value, bool) or not isinstance(value, (str, int, float)): | |
| return None | |
| if isinstance(value, str) and not re.fullmatch(r"\d+(?:\.\d+)?", value): | |
| return None # Do not estimate exact counts from labels such as "87K". | |
| try: | |
| number = float(value) | |
| if not math.isfinite(number) or number < 0 or (integer and not number.is_integer()): | |
| return None | |
| return int(number) if number.is_integer() else number | |
| except (ValueError, OverflowError): | |
| return None | |
| def _date(value: Any) -> str | None: | |
| """Normalize explicit dates; never resolve relative dates or invent a timezone.""" | |
| value = _text(value) | |
| if not value: | |
| return None | |
| try: | |
| if re.fullmatch(r"\d{4}-\d{2}-\d{2}", value): | |
| return datetime.strptime(value, "%Y-%m-%d").date().isoformat() | |
| parsed = datetime.fromisoformat(value.replace("Z", "+00:00")) | |
| except ValueError: | |
| try: | |
| parsed = datetime.strptime(value.split(" (")[0], "%a %b %d %Y %H:%M:%S GMT%z") | |
| except ValueError: | |
| return None | |
| return parsed.isoformat() if parsed.tzinfo is not None else None | |
| def _extra_metadata(data: dict, products: list[dict], requested_id: str) -> dict: | |
| """Select scalar public fields from the identified product, not related apps.""" | |
| fields = { | |
| key: None for key in ( | |
| "developer_name", "developer_id", "developer_url", "seller_name", | |
| "app_version", "app_version_updated_at", "app_version_updated_at_raw", | |
| "app_version_release_notes", "app_release_date", "price", "currency", | |
| "is_free", "has_in_app_purchases", "age_rating", "content_rating_code", | |
| "rating_average", "rating_count", "supported_languages", "website_url", | |
| "support_url", "privacy_policy_url", "copyright", | |
| ) | |
| } | |
| sources: dict[str, str] = {} | |
| def put(key: str, value: Any, source: str) -> None: | |
| if fields[key] is None and value is not None: | |
| fields[key] = value | |
| sources[key] = source | |
| shelves = _dict(data.get("shelfMapping")) | |
| developer = _dict(data.get("developerAction")) | |
| put("developer_name", _text(developer.get("title")), "data.developerAction.title") | |
| put("developer_url", _http_url(developer.get("pageUrl")), "data.developerAction.pageUrl") | |
| destination = _dict(developer.get("destination")) | |
| if destination.get("$kind") == "DeveloperPageIntent": | |
| put("developer_id", _id(destination.get("id")), "data.developerAction.destination.id") | |
| version_items = _list(_dict(shelves.get("mostRecentVersion")).get("items")) | |
| for index, item in enumerate(version_items): | |
| item = _dict(item) | |
| version = _text(item.get("primarySubtitle")) | |
| if not version: | |
| continue | |
| version = re.sub(r"^Version\s+", "", version) | |
| base = f"data.shelfMapping.mostRecentVersion.items[{index}]" | |
| put("app_version", version, base + ".primarySubtitle") | |
| raw_date = _text(item.get("secondarySubtitle")) | |
| put("app_version_updated_at_raw", raw_date, base + ".secondarySubtitle") | |
| put("app_version_updated_at", _date(raw_date), base + ".secondarySubtitle") | |
| put("app_version_release_notes", _text(item.get("text")), base + ".text") | |
| break # Do not mix a different version's date or notes with the current one. | |
| offer = _dict(data.get("titleOfferDisplayProperties")) | |
| for source, target in [("isFree", "is_free"), ("hasInAppPurchases", "has_in_app_purchases")]: | |
| value = offer.get(source) | |
| if isinstance(value, bool): | |
| put(target, value, "data.titleOfferDisplayProperties." + source) | |
| put("content_rating_code", _number(offer.get("contentRating"), integer=True), | |
| "data.titleOfferDisplayProperties.contentRating") | |
| for index, item in enumerate(_list(_dict(shelves.get("productRatings")).get("items"))): | |
| item = _dict(item) | |
| if _id(item.get("productId")) not in {None, requested_id}: | |
| continue | |
| base = f"data.shelfMapping.productRatings.items[{index}]" | |
| average = _number(item.get("ratingAverage")) | |
| if average is not None and average <= 5: | |
| put("rating_average", average, base + ".ratingAverage") | |
| put("rating_count", _number(item.get("totalNumberOfRatings"), integer=True), | |
| base + ".totalNumberOfRatings") | |
| for index, item in enumerate(_list(_dict(shelves.get("information")).get("items"))): | |
| item = _dict(item) | |
| title = (_text(item.get("title")) or "").lower() | |
| texts = [_text(_dict(entry).get("text")) for entry in _list(item.get("items"))] | |
| texts = [text for text in texts if text] | |
| base = f"data.shelfMapping.information.items[{index}]" | |
| if title in {"seller", "copyright"} and texts: | |
| put("seller_name" if title == "seller" else "copyright", texts[0], base + ".items[0].text") | |
| elif title == "age rating": | |
| put("age_rating", _text(item.get("summary")) or (texts[0] if texts else None), base) | |
| elif title == "languages" and texts: | |
| languages = list(dict.fromkeys(language.strip() for text in texts | |
| for language in text.split(",") if language.strip())) | |
| put("supported_languages", languages or None, base + ".items[*].text") | |
| for index, item in enumerate(_list(_dict(shelves.get("description")).get("items"))): | |
| for link_index, link in enumerate(_list(_dict(item).get("developerLinks"))): | |
| link = _dict(link) | |
| label = (_text(link.get("text")) or "").lower() | |
| target = {"website": "website_url", "support": "support_url", | |
| "privacy policy": "privacy_policy_url"}.get(label) | |
| if target: | |
| put(target, _http_url(_dict(link.get("clickAction")).get("url")), | |
| f"data.shelfMapping.description.items[{index}].developerLinks[{link_index}].clickAction.url") | |
| for index, item in enumerate(_list(_dict(shelves.get("privacyHeader")).get("items"))): | |
| links = _dict(_dict(_dict(item).get("bodyText")).get("linkedSubstrings")) | |
| for label, action in links.items(): | |
| if "privacy" in label.lower(): | |
| put("privacy_policy_url", _http_url(_dict(action).get("url")), | |
| f"data.shelfMapping.privacyHeader.items[{index}].bodyText.linkedSubstrings.{label}.url") | |
| for product in products: | |
| product_url = _app_url(product.get("url")) | |
| if product_url and product_url[0] != requested_id: | |
| continue | |
| author = _dict(product.get("author")) | |
| put("developer_name", _text(author.get("name")), "jsonld.SoftwareApplication.author.name") | |
| put("developer_url", _http_url(author.get("url")), "jsonld.SoftwareApplication.author.url") | |
| structured_offer = _dict(product.get("offers")) | |
| put("price", _number(structured_offer.get("price")), "jsonld.SoftwareApplication.offers.price") | |
| currency = _text(structured_offer.get("priceCurrency")) | |
| if currency and re.fullmatch(r"[A-Z]{3}", currency): | |
| put("currency", currency, "jsonld.SoftwareApplication.offers.priceCurrency") | |
| rating = _dict(product.get("aggregateRating")) | |
| average = _number(rating.get("ratingValue")) | |
| if average is not None and average <= 5: | |
| put("rating_average", average, "jsonld.SoftwareApplication.aggregateRating.ratingValue") | |
| for count_key in ("ratingCount", "reviewCount"): | |
| put("rating_count", _number(rating.get(count_key), integer=True), | |
| "jsonld.SoftwareApplication.aggregateRating." + count_key) | |
| put("app_release_date", _date(product.get("datePublished")), "jsonld.SoftwareApplication.datePublished") | |
| put("app_version", _text(product.get("softwareVersion")), "jsonld.SoftwareApplication.softwareVersion") | |
| if fields["developer_id"] is None and fields["developer_url"]: | |
| parts = urlsplit(fields["developer_url"]) | |
| match = re.fullmatch(r"/[a-z]{2}/developer/(?:[^/]+/)?id(\d+)/?", parts.path) | |
| if parts.hostname == "apps.apple.com" and match: | |
| put("developer_id", match.group(1), sources["developer_url"]) | |
| fields["field_sources"] = sources | |
| return fields | |
| def parse_product(html: str, requested_id: str) -> dict: | |
| """Return public metadata, watch evidence, and original-size screenshot URLs. | |
| ``watch_supported`` is True for explicit positive evidence, False only for a | |
| complete identified product with explicit non-watch platform compatibility, | |
| and None otherwise. ``metadata.parse_status`` reports parsing separately. | |
| Screenshot ranks are zero-based across all accepted watch shelves. The | |
| requested ID remains the output ID; an identity mismatch yields no artwork. | |
| """ | |
| requested_id = str(requested_id) | |
| result = {"app_id": requested_id, "name": None, "description": None, | |
| "genres": [], "watch_supported": None, "evidence": [], | |
| "screenshots": [], "related_apps": [], "metadata": {}} | |
| meta = result["metadata"] | |
| evidence = result["evidence"] | |
| warnings: list[str] = [] | |
| document = _Document() | |
| try: | |
| document.feed(html) | |
| document.close() | |
| except (ValueError, AssertionError): | |
| warnings.append("html_parse_error") | |
| meta["html_language"] = document.language | |
| meta["canonical_url"] = document.canonical | |
| nodes: list[dict] = [] | |
| ld_products: list[dict] = [] | |
| serialized_count, malformed_count = 0, 0 | |
| for attrs, content in document.scripts: | |
| is_server = attrs.get("id") == "serialized-server-data" | |
| is_ld = (attrs.get("type") or "").lower() == "application/ld+json" | |
| if not is_server and not is_ld: | |
| continue | |
| if is_server: | |
| serialized_count += 1 | |
| try: | |
| payload = json.loads(content) | |
| except (ValueError, RecursionError): | |
| if is_server: | |
| malformed_count += 1 | |
| warnings.append("invalid_server_json" if is_server else "invalid_ld_json") | |
| continue | |
| if is_server: | |
| nodes.extend(_product_nodes(payload)) | |
| else: | |
| ld_products.extend(x for x in _walk(payload) | |
| if x.get("@type") == "SoftwareApplication") | |
| canonical = _app_url(document.canonical) | |
| canonical_id = canonical[0] if canonical else None | |
| candidates = [node for node in nodes if _identity(node) == {requested_id}] | |
| if not candidates: | |
| candidates = [node for node in nodes if not _identity(node)] | |
| identity_mismatch = bool( | |
| (canonical_id is not None and canonical_id != requested_id) | |
| or (nodes and not candidates) | |
| ) | |
| selected = candidates[0] if candidates and not identity_mismatch else {} | |
| data = _dict(selected.get("data")) | |
| intent = _dict(selected.get("intent")) | |
| lockup = _dict(data.get("lockup")) | |
| identity_evidence = _identity(selected) | |
| if canonical_id: | |
| identity_evidence.add(canonical_id) | |
| identified = bool(selected) and identity_evidence == {requested_id} | |
| incomplete = data.get("isIncomplete") is True | |
| meta["parse_status"] = ( | |
| "app_id_mismatch" if identity_mismatch | |
| else "identity_unknown" if selected and not identified else "ok" if selected | |
| else "malformed_json" if malformed_count | |
| else "unknown_structure" if serialized_count else "missing_script" | |
| ) | |
| meta["identity_verified"] = identified | |
| meta["is_incomplete"] = incomplete if selected else None | |
| meta["storefront"] = _text(intent.get("storefront")) | |
| meta["language"] = _text(intent.get("language")) | |
| meta["requested_platform"] = _text(intent.get("platform")) | |
| meta["bundle_id"] = _text(lockup.get("bundleId")) | |
| meta["subtitle"] = _text(lockup.get("subtitle")) | |
| if _app_url(data.get("canonicalURL")): | |
| meta["canonical_url"] = data["canonicalURL"] | |
| if not meta["storefront"] and _app_url(meta["canonical_url"]): | |
| meta["storefront"] = urlsplit(meta["canonical_url"]).path.split("/")[1] | |
| meta["language"] = meta["language"] or document.language | |
| result["name"] = _text(data.get("title")) or _text(lockup.get("title")) | |
| shelves = _dict(data.get("shelfMapping")) | |
| description = _dict(shelves.get("description")) | |
| paragraphs = [_text(_dict(item.get("paragraph")).get("text")) | |
| for item in _list(description.get("items")) if isinstance(item, dict)] | |
| result["description"] = "\n\n".join(p for p in paragraphs if p) or None | |
| def genre(value: Any) -> None: | |
| value = _text(value) | |
| if value and value not in result["genres"]: | |
| result["genres"].append(value) | |
| compatibility: list[dict] = [] | |
| for item in _list(_dict(shelves.get("information")).get("items")): | |
| item = _dict(item) | |
| title = (_text(item.get("title")) or "").lower() | |
| if title == "category": | |
| for entry in _list(item.get("items")): | |
| genre(_dict(entry).get("text")) | |
| if title == "compatibility": | |
| for entry in _list(item.get("items")): | |
| entry = _dict(entry) | |
| heading, text = _text(entry.get("heading")), _text(entry.get("text")) | |
| if heading or text: | |
| compatibility.append({"platform": heading, "requirement": text}) | |
| for item in _list(_dict(shelves.get("informationRibbon")).get("items")): | |
| item = _dict(item) | |
| if item.get("key") == "category": | |
| genre(item.get("caption")) | |
| meta["compatibility"] = compatibility | |
| # JSON-LD is useful metadata, but its phone-oriented OS summary cannot prove | |
| # the absence of a watch app. A watchOS requirement is positive evidence. | |
| ld_watch = False | |
| for product in ld_products: | |
| product_url = _app_url(product.get("url")) | |
| if identity_mismatch or (product_url and product_url[0] != requested_id): | |
| continue | |
| result["name"] = result["name"] or _text(product.get("name")) | |
| result["description"] = result["description"] or _text(product.get("description")) | |
| if not result["genres"]: | |
| category = product.get("applicationCategory") | |
| for value in category if isinstance(category, list) else [category]: | |
| genre(value) | |
| if re.search(r"\bwatchOS\b", _text(product.get("operatingSystem")) or "", re.I): | |
| ld_watch = True | |
| # Keep rich metadata under the same identity guard as downloadable artwork. | |
| # No raw page, metrics, reviewer identities, or version-history payloads escape. | |
| if identified: | |
| meta.update(_extra_metadata(data, ld_products, requested_id)) | |
| raw_platforms = data.get("appPlatforms") | |
| platforms = [p.lower() for p in raw_platforms if isinstance(p, str)] if isinstance(raw_platforms, list) else [] | |
| meta["platforms"] = platforms | |
| explicit_watch = any(p in {"watch", "watchos", "applewatch"} for p in platforms) | |
| compatibility_watch = any( | |
| "watch" in ((row["platform"] or "") + " " + (row["requirement"] or "")).lower() | |
| for row in compatibility | |
| ) | |
| if explicit_watch: | |
| evidence.append("appPlatforms:watch") | |
| if compatibility_watch: | |
| evidence.append("compatibility:watch") | |
| if ld_watch: | |
| evidence.append("structured_operating_system:watchOS") | |
| watch_shelves: list[str] = [] | |
| # Public content can be decoded without identifying its app. Never turn | |
| # such content into downloadable corpus records or positive Watch labels. | |
| for key, shelf in shelves.items() if identified else []: | |
| if not isinstance(shelf, dict): | |
| continue | |
| platform = _text(_dict(_dict(shelf.get("contentsMetadata")).get("platform")).get("appPlatform")) | |
| platform = platform.lower() if platform else None | |
| key_watch = key.startswith("product_media_watch") | |
| if not key_watch and platform != "watch": | |
| continue | |
| conflicting_key = key.startswith("product_media_") and not key_watch | |
| if (key_watch and platform not in {None, "watch"}) or (platform == "watch" and conflicting_key): | |
| warnings.append("conflicting_platform_shelf:" + key) | |
| continue | |
| watch_shelves.append(key) | |
| evidence.append("watch_media_shelf:" + key) | |
| for shelf_item_index, item in enumerate(_list(shelf.get("items"))): | |
| item = _dict(item) | |
| if not item.get("screenshot"): | |
| continue # Videos and other promotional media are not screenshots. | |
| shot = _artwork(item["screenshot"], len(result["screenshots"])) | |
| if not shot: | |
| warnings.append("invalid_watch_artwork:" + key) | |
| continue | |
| shot.update(shelf_key=key, shelf_item_index=shelf_item_index) | |
| result["screenshots"].append(shot) | |
| meta["watch_shelves"] = watch_shelves | |
| if identified and (explicit_watch or compatibility_watch or ld_watch or watch_shelves): | |
| result["watch_supported"] = True | |
| if platforms and not explicit_watch: | |
| warnings.append("watch_evidence_conflicts_with_appPlatforms") | |
| elif identified and not incomplete: | |
| if platforms: | |
| result["watch_supported"] = False | |
| evidence.append("complete_appPlatforms_without_watch") | |
| elif compatibility and any(row["platform"] for row in compatibility): | |
| result["watch_supported"] = False | |
| evidence.append("complete_compatibility_without_watch") | |
| if identity_mismatch: | |
| evidence.append("product_identity_mismatch") | |
| elif selected and not identified: | |
| evidence.append("product_identity_unverified") | |
| related: dict[str, str] = {} | |
| def add_related(url: Any) -> None: | |
| parsed = _app_url(url) | |
| if parsed and parsed[0] != requested_id: | |
| related.setdefault(*parsed) | |
| for url in document.links: | |
| add_related(url) | |
| for obj in _walk(shelves): | |
| for field in ("pageUrl", "url"): | |
| add_related(obj.get(field)) | |
| if obj.get("$kind") == "ProductPageIntent": | |
| app_id = _id(obj.get("id")) | |
| country = _text(obj.get("storefront")) or meta["storefront"] or "us" | |
| if app_id and re.fullmatch(r"[a-z]{2}", country): | |
| add_related(f"https://apps.apple.com/{country}/app/id{app_id}?platform=watch") | |
| result["related_apps"] = [{"app_id": app_id, "url": url} for app_id, url in related.items()] | |
| meta["warnings"] = list(dict.fromkeys(warnings)) | |
| return result | |
| # iPhone product parser; gallery membership stays separate from Watch. | |
| _PHONE = {"phone", "iphone"} | |
| _OTHER_PLATFORMS = {"pad", "ipad", "watch", "watchos", "applewatch", "mac", "macos", | |
| "tv", "appletv", "vision", "visionos", "reality", "ipod"} | |
| _OTHER_COMPATIBILITY = {"ipad", "ipod touch", "mac", "apple watch", "apple tv", | |
| "apple vision", "apple vision pro"} | |
| _MAX_NODES = 10000 | |
| _MAX_DEPTH = 32 | |
| _MAX_SHELVES = 512 | |
| _MAX_ITEMS = 1000 | |
| class _LimitReached(ValueError): | |
| pass | |
| def _nodes(payload, *, jsonld=False): | |
| """Visit known wrappers only, with a budget and no related-product descent.""" | |
| pending, found, visited = [(payload, 0)], [], 0 | |
| while pending: | |
| node, depth = pending.pop() | |
| visited += 1 | |
| if visited > _MAX_NODES or depth > _MAX_DEPTH: | |
| raise _LimitReached | |
| if isinstance(node, list): | |
| children = node | |
| elif isinstance(node, dict): | |
| if jsonld: | |
| if node.get("@type") == "SoftwareApplication": | |
| found.append(node) | |
| continue | |
| children = [node["@graph"]] if "@graph" in node else [] | |
| else: | |
| data = _dict(node.get("data")) | |
| if isinstance(data.get("shelfMapping"), dict) or isinstance(data.get("appPlatforms"), list): | |
| found.append(node) | |
| continue | |
| children = [value for key, value in node.items() if key == "data" or key.isdigit()] | |
| else: | |
| continue | |
| if len(children) + len(pending) + visited > _MAX_NODES: | |
| raise _LimitReached | |
| pending.extend((child, depth + 1) for child in reversed(children)) | |
| return found | |
| def _compatibility(shelves): | |
| rows = [] | |
| for item in _list(_dict(shelves.get("information")).get("items"))[:_MAX_ITEMS]: | |
| item = _dict(item) | |
| if (_text(item.get("title")) or "").lower() != "compatibility": | |
| continue | |
| for entry in _list(item.get("items"))[:_MAX_ITEMS]: | |
| entry = _dict(entry) | |
| heading, text = _text(entry.get("heading")), _text(entry.get("text")) | |
| # Current public pages encode the same headings as styled Markdown. | |
| raw = _text(_dict(_dict(entry.get("linkableText")).get("styledText")).get("rawText")) | |
| if raw and not (heading or text): | |
| match = re.fullmatch(r"\*\*([^*]+)\*\*\s*(.*)", raw, flags=re.S) | |
| heading, text = (match.group(1), match.group(2)) if match else (None, raw) | |
| if heading or text: | |
| rows.append({"platform": heading, "requirement": text}) | |
| return rows | |
| def _phone_artwork(value, rank): | |
| shot = _artwork(value, rank) | |
| if shot is None: | |
| return None | |
| try: | |
| parts = urlsplit(shot["url"]) | |
| if (parts.username is not None or parts.password is not None or parts.port is not None | |
| or parts.fragment or not parts.path.lower().endswith(".png")): | |
| return None | |
| except ValueError: | |
| return None | |
| return {**shot, "platform": "phone"} | |
| def parse_phone_product(html: str, requested_id: str) -> dict: | |
| """Return identified US-English product data and native-size phone artwork. | |
| ``phone_supported`` is True for positive phone evidence, False only when a | |
| complete page explicitly lists other platforms, and None for uncertainty. | |
| Locale contradictions or missing locale evidence never authorize downloads. | |
| ``metadata.media_parse_complete`` additionally rejects incomplete/malformed | |
| phone media; callers use it before marking a no-images or complete result. | |
| """ | |
| requested_id = str(requested_id) | |
| result = {"app_id": requested_id, "name": None, "description": None, "genres": [], | |
| "phone_supported": None, "evidence": [], "screenshots": [], "related_apps": [], | |
| "page_locale_verified": False, "metadata": {}} | |
| meta, warnings = result["metadata"], [] | |
| document = _Document() | |
| try: | |
| document.feed(html) | |
| document.close() | |
| except (ValueError, AssertionError): | |
| warnings.append("html_parse_error") | |
| nodes, products = [], [] | |
| serialized, malformed, limited = 0, 0, False | |
| for attrs, content in document.scripts: | |
| server = attrs.get("id") == "serialized-server-data" | |
| jsonld = (attrs.get("type") or "").lower() == "application/ld+json" | |
| if not server and not jsonld: | |
| continue | |
| serialized += int(server) | |
| try: | |
| payload = json.loads(content) | |
| (nodes if server else products).extend(_nodes(payload, jsonld=not server)) | |
| except _LimitReached: | |
| limited = True | |
| warnings.append("parser_limit_reached") | |
| except (ValueError, RecursionError): | |
| malformed += int(server) | |
| warnings.append("invalid_server_json" if server else "invalid_ld_json") | |
| canonical = _app_url(document.canonical) | |
| canonical_id = canonical[0] if canonical else None | |
| candidates = [node for node in nodes if _identity(node) == {requested_id}] | |
| if not candidates: | |
| candidates = [node for node in nodes if not _identity(node)] | |
| mismatch = bool((canonical_id is not None and canonical_id != requested_id) or (nodes and not candidates)) | |
| selected = candidates[0] if candidates and not mismatch and not limited else {} | |
| data, intent = _dict(selected.get("data")), _dict(selected.get("intent")) | |
| identity = _identity(selected) | ({canonical_id} if canonical_id else set()) | |
| identified = bool(selected) and identity == {requested_id} | |
| shelves, lockup = _dict(data.get("shelfMapping")), _dict(data.get("lockup")) | |
| status = ("parser_limit_reached" if limited else "app_id_mismatch" if mismatch | |
| else "identity_unknown" if selected and not identified else "ok" if selected | |
| else "malformed_json" if malformed else "unknown_structure" if serialized else "missing_script") | |
| canonical_url = data.get("canonicalURL") if _app_url(data.get("canonicalURL")) else document.canonical | |
| canonical_product = _app_url(canonical_url) | |
| storefront = _text(intent.get("storefront")) | |
| if not storefront and canonical_product: | |
| storefront = urlsplit(canonical_product[1]).path.split("/")[1] | |
| language = _text(intent.get("language")) or document.language | |
| meta.update(html_language=document.language, canonical_url=canonical_url, parse_status=status, | |
| identity_verified=identified, is_incomplete=data.get("isIncomplete") is True if selected else None, | |
| storefront=storefront, language=language, requested_platform=_text(intent.get("platform")), | |
| bundle_id=_text(lockup.get("bundleId")), subtitle=_text(lockup.get("subtitle")), | |
| compatibility=_compatibility(shelves), phone_shelves=[], media_parse_complete=False, | |
| platforms=[p.strip().lower() for p in _list(data.get("appPlatforms")) if isinstance(p, str)], | |
| warnings=warnings) | |
| common_shelves = ("description", "information", "informationRibbon", "mostRecentVersion", | |
| "productRatings", "privacyHeader") | |
| if (len(shelves) > _MAX_SHELVES | |
| or any(len(_list(_dict(shelves.get(key)).get("items"))) > _MAX_ITEMS for key in common_shelves) | |
| or any(len(_list(_dict(item).get("items"))) > _MAX_ITEMS | |
| for item in _list(_dict(shelves.get("information")).get("items"))) | |
| or any(len(_list(_dict(item).get("developerLinks"))) > _MAX_ITEMS | |
| for item in _list(_dict(shelves.get("description")).get("items")))): | |
| meta["parse_status"] = "parser_limit_reached" | |
| warnings.append("parser_limit_reached") | |
| return result | |
| result["name"] = _text(data.get("title")) or _text(lockup.get("title")) | |
| result["description"] = "\n\n".join(text for item in _list(_dict(shelves.get("description")).get("items")) | |
| if (text := _text(_dict(_dict(item).get("paragraph")).get("text")))) or None | |
| for item in _list(_dict(shelves.get("information")).get("items")): | |
| if (_text(_dict(item).get("title")) or "").lower() == "category": | |
| for entry in _list(_dict(item).get("items")): | |
| text = _text(_dict(entry).get("text")) | |
| if text and text not in result["genres"]: | |
| result["genres"].append(text) | |
| for item in _list(_dict(shelves.get("informationRibbon")).get("items")): | |
| if _dict(item).get("key") == "category": | |
| text = _text(item.get("caption")) | |
| if text and text not in result["genres"]: | |
| result["genres"].append(text) | |
| matching_products = [product for product in products | |
| if not _app_url(product.get("url")) or _app_url(product.get("url"))[0] == requested_id] | |
| if identified: | |
| meta.update(_extra_metadata(data, matching_products, requested_id)) | |
| for product in matching_products: | |
| result["name"] = result["name"] or _text(product.get("name")) | |
| result["description"] = result["description"] or _text(product.get("description")) | |
| if not result["genres"]: | |
| categories = product.get("applicationCategory") | |
| result["genres"] = [value for category in (categories if isinstance(categories, list) else [categories]) | |
| if (value := _text(category))] | |
| if not identified: | |
| if mismatch: | |
| result["evidence"].append("product_identity_mismatch") | |
| elif selected: | |
| result["evidence"].append("product_identity_unverified") | |
| return result | |
| languages = [value for value in (document.language, _text(intent.get("language"))) if value] | |
| storefronts = [value for value in (storefront,) if value] | |
| for url in (document.canonical, data.get("canonicalURL")): | |
| if _app_url(url): | |
| storefronts.append(urlsplit(url).path.split("/")[1]) | |
| if any(value.lower() != "us" for value in storefronts): | |
| meta["parse_status"] = "non_us_storefront" | |
| return result | |
| if any(not re.fullmatch(r"en(?:-[a-z0-9]+)*", value, re.I) for value in languages): | |
| meta["parse_status"] = "non_english_locale" | |
| return result | |
| if not storefronts or not languages: | |
| meta["parse_status"] = "locale_unknown" | |
| return result | |
| result["page_locale_verified"] = True | |
| for key, shelf in shelves.items(): | |
| device = re.match(r"^product_media_([^_]+)(?:_|$)", key) | |
| key_phone = bool(device and device.group(1) in _PHONE) | |
| if not isinstance(shelf, dict): | |
| if key_phone: | |
| warnings.append("invalid_phone_shelf:" + key) | |
| continue | |
| platform = _text(_dict(_dict(shelf.get("contentsMetadata")).get("platform")).get("appPlatform")) | |
| platform = platform.lower() if platform else None | |
| if not key_phone and platform not in _PHONE: | |
| continue | |
| if ((key_phone and platform is not None and platform not in _PHONE) | |
| or (platform in _PHONE and device and not key_phone)): | |
| warnings.append("conflicting_platform_shelf:" + key) | |
| continue | |
| meta["phone_shelves"].append(key) | |
| result["evidence"].append("phone_media_shelf:" + key) | |
| items = shelf.get("items") | |
| if not isinstance(items, list) or len(items) > _MAX_ITEMS: | |
| warnings.append("invalid_phone_shelf:" + key) | |
| continue | |
| for shelf_item_index, item in enumerate(items): | |
| if not isinstance(item, dict): | |
| warnings.append("invalid_phone_artwork:" + key) | |
| continue | |
| if "screenshot" not in item: | |
| continue | |
| shot = _phone_artwork(item["screenshot"], len(result["screenshots"])) | |
| if shot is None: | |
| warnings.append("invalid_phone_artwork:" + key) | |
| else: | |
| shot.update(shelf_key=key, shelf_item_index=shelf_item_index) | |
| result["screenshots"].append(shot) | |
| platforms = meta["platforms"] | |
| raw_platforms = _list(data.get("appPlatforms")) | |
| known_nonphone_platforms = bool(platforms and len(platforms) == len(raw_platforms) | |
| and all(p in _OTHER_PLATFORMS for p in platforms)) | |
| compatibility = meta["compatibility"] | |
| phone_platform = any(platform in _PHONE for platform in platforms) | |
| phone_compatibility = any(re.search(r"\biphone\b", row["platform"] or "", re.I) for row in compatibility) | |
| if phone_platform: | |
| result["evidence"].append("appPlatforms:phone") | |
| if phone_compatibility: | |
| result["evidence"].append("iphone_compatibility_without_phone_platform" if known_nonphone_platforms | |
| else "compatibility:phone") | |
| media_errors = any(w.startswith(("invalid_phone_", "conflicting_platform_shelf:", "parser_limit_reached", | |
| "invalid_server_json", "invalid_ld_json", "html_parse_error")) | |
| for w in warnings) | |
| meta["media_parse_complete"] = meta["is_incomplete"] is False and not media_errors | |
| if known_nonphone_platforms and not meta["phone_shelves"] and meta["media_parse_complete"]: | |
| # Watch-only listings can require a paired iPhone without offering an | |
| # iPhone app. The explicit platform list takes precedence over that | |
| # compatibility requirement, but never over real phone media. | |
| result["phone_supported"] = False | |
| result["evidence"].append("complete_appPlatforms_without_phone") | |
| elif known_nonphone_platforms and not result["screenshots"] and not meta["media_parse_complete"]: | |
| # Missing media on an incomplete page, or broken/conflicting phone | |
| # shelves, cannot establish either positive or negative availability. | |
| pass | |
| elif phone_platform or meta["phone_shelves"] or (phone_compatibility and not raw_platforms): | |
| result["phone_supported"] = True | |
| if not meta["phone_shelves"]: | |
| warnings.append("missing_phone_media_shelf") | |
| meta["media_parse_complete"] = False | |
| if platforms and not phone_platform: | |
| warnings.append("phone_evidence_conflicts_with_appPlatforms") | |
| meta["media_parse_complete"] = False | |
| elif meta["media_parse_complete"]: | |
| if not raw_platforms and compatibility and all( | |
| (row["platform"] or "").replace("\u00a0", " ").lower() in _OTHER_COMPATIBILITY for row in compatibility): | |
| result["phone_supported"] = False | |
| result["evidence"].append("complete_compatibility_without_phone") | |
| related = {} | |
| for link in document.links: | |
| app = _app_url(link) | |
| if app and app[0] != requested_id: | |
| related.setdefault(*app) | |
| result["related_apps"] = [{"app_id": app_id, "url": url} for app_id, url in related.items()] | |
| meta["warnings"] = list(dict.fromkeys(warnings)) | |
| return result | |
| # App metadata collection command. | |
| def read_ids(path): | |
| seen = set() | |
| for line in Path(path).read_text().splitlines(): | |
| line = line.strip() | |
| if not line or line.startswith('#'): | |
| continue | |
| if line.startswith('{'): | |
| line = str(json.loads(line)['app_id']) | |
| match = re.fullmatch(r'\d+', line) or re.search(r'/id(\d+)', line) | |
| if not match: | |
| raise ValueError(f'Expected numeric App ID or App Store URL: {line}') | |
| app_id = match.group(1) if match.lastindex else match.group(0) | |
| # Deduplicate app requests only; screenshot positions are never merged. | |
| if app_id not in seen: | |
| seen.add(app_id) | |
| yield app_id | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument('--app-ids', required=True, type=Path, help='Text IDs/URLs, one per line; apps.jsonl is also accepted') | |
| parser.add_argument('--output', required=True, type=Path, help='Candidate metadata JSONL; use a new path for a new acquisition') | |
| parser.add_argument('--cache', type=Path, help='Raw HTML response cache; defaults beside output') | |
| parser.add_argument('--delay', type=float, default=0.3) | |
| parser.add_argument('--timeout', type=float, default=45) | |
| parser.add_argument('--limit', type=int) | |
| args = parser.parse_args() | |
| cache = args.cache or args.output.parent / 'cache' | |
| cache.mkdir(parents=True, exist_ok=True) | |
| args.output.parent.mkdir(parents=True, exist_ok=True) | |
| with args.output.open('x') as output: | |
| for index, app_id in enumerate(read_ids(args.app_ids)): | |
| if args.limit is not None and index >= args.limit: | |
| break | |
| url = f'https://apps.apple.com/us/app/id{app_id}?l=en-US&platform=watch' | |
| fetched_at = datetime.now(timezone.utc).isoformat() | |
| try: | |
| request = Request(url, headers={'User-Agent': 'Mozilla/5.0 PhoneWatchUI/1.0', 'Accept-Language': 'en-US,en;q=0.9'}) | |
| with urlopen(request, timeout=args.timeout) as response: | |
| body = response.read() | |
| metadata = {'requested_url': url, 'final_url': response.url, 'http_status': response.status, | |
| 'content_type': response.headers.get('Content-Type'), 'fetched_at': fetched_at} | |
| key = hashlib.sha256(url.encode()).hexdigest() | |
| (cache / f'{key}.gz').write_bytes(gzip.compress(body)) | |
| write_json(cache / f'{key}.json', metadata) | |
| html = body.decode('utf-8') | |
| watch = parse_product(html, app_id) | |
| phone = parse_phone_product(html, app_id) | |
| for manifest in (watch, phone): | |
| manifest['response'] = metadata | |
| manifest['collected_at'] = fetched_at | |
| manifest['requested_storefront'] = 'us' | |
| manifest['requested_locale'] = 'en-US' | |
| row = {'app_id': app_id, 'store': 'apple_store', 'title': watch.get('name'), 'description': watch.get('description'), | |
| 'source_url': url, 'watch_selection': {'selected': watch.get('watch_supported') is True, | |
| 'evidence': watch.get('evidence', []), 'method': 'explicit_product_page_platform_evidence'}, | |
| 'metadata': {'watch_manifest': watch, 'phone_manifest': phone}, 'metadata_download_status': 'downloaded'} | |
| except Exception as error: | |
| row = {'app_id': app_id, 'store': 'apple_store', 'title': None, 'description': None, 'source_url': url, | |
| 'watch_selection': {'selected': None, 'evidence': [], 'method': 'explicit_product_page_platform_evidence'}, | |
| 'metadata': {}, 'metadata_download_status': 'failed', 'error': type(error).__name__} | |
| dump_line(output, row) | |
| output.flush() | |
| print(json.dumps({'app_id': app_id, 'status': row['metadata_download_status']}), flush=True) | |
| time.sleep(max(args.delay, 0)) | |
| if __name__ == '__main__': | |
| main() | |