|
| 1 | +import argparse |
| 2 | +import csv |
| 3 | +import logging |
| 4 | +import os |
| 5 | +from pathlib import Path |
| 6 | +from typing import Iterable, Set, Dict, Any, Optional |
| 7 | +import requests |
| 8 | +from pymongo import MongoClient |
| 9 | +from concurrent.futures import ThreadPoolExecutor, as_completed |
| 10 | + |
| 11 | +API_URL = os.environ.get("ARC_API_URL") |
| 12 | +API_TOKEN = os.environ.get("ARC_TOKEN") |
| 13 | + |
| 14 | +MONGO_URI = os.environ.get("MONGO_URI") |
| 15 | +MONGO_DB = os.environ.get("MONGO_DB") |
| 16 | +MONGO_COLLECTION = os.environ.get("MONGO_COLLECTION") |
| 17 | + |
| 18 | + |
| 19 | +def load_photo_editor_ids(path: str) -> Set[str]: |
| 20 | + with open(path, newline="") as f: |
| 21 | + return {row[0] for row in csv.reader(f) if row} |
| 22 | + |
| 23 | + |
| 24 | +def fetch_revisions(story_id: str) -> Iterable[Dict[str, Any]]: |
| 25 | + if not API_TOKEN: |
| 26 | + raise RuntimeError("ARC_TOKEN not configured") |
| 27 | + url = f"{API_URL}/stories/{story_id}/revisions" |
| 28 | + headers = {"Authorization": f"Bearer {API_TOKEN}"} |
| 29 | + try: |
| 30 | + response = requests.get(url, headers=headers, timeout=30) |
| 31 | + response.raise_for_status() |
| 32 | + return response.json().get("revisions", []) |
| 33 | + except Exception as exc: |
| 34 | + logging.error("Failed to fetch revisions for %s: %s", story_id, exc) |
| 35 | + return [] |
| 36 | + |
| 37 | + |
| 38 | +def story_has_photo_editor(revisions: Iterable[Dict[str, Any]], editor_ids: Set[str]) -> bool: |
| 39 | + return any(rev.get("user_id") in editor_ids for rev in revisions) |
| 40 | + |
| 41 | +def first_lead_art_revision( |
| 42 | + revisions: Iterable[Dict[str, Any]], |
| 43 | + editors: Optional[Set[str]] = None, |
| 44 | +) -> Optional[Dict[str, Any]]: |
| 45 | + """Return the first revision containing lead art. |
| 46 | +
|
| 47 | + If ``editors`` is provided, only revisions by those users are considered. |
| 48 | + """ |
| 49 | + for rev in sorted(revisions, key=lambda r: r.get("revision_date", "")): |
| 50 | + if editors is not None and rev.get("user_id") not in editors: |
| 51 | + continue |
| 52 | + promo = rev.get("story", {}).get("promo_items", {}) |
| 53 | + if promo.get("lead_art"): |
| 54 | + return rev |
| 55 | + return None |
| 56 | + |
| 57 | + |
| 58 | +def ingest_story(story_id: str) -> Optional[Dict[str, Any]]: |
| 59 | + """Return metadata for a story including a label based on editor.""" |
| 60 | + revisions = list(fetch_revisions(story_id)) |
| 61 | + rev = first_lead_art_revision(revisions, PHOTO_EDITOR_IDS) |
| 62 | + label = 2 |
| 63 | + if not rev: |
| 64 | + rev = first_lead_art_revision(revisions) |
| 65 | + label = 1 |
| 66 | + if not rev: |
| 67 | + return None |
| 68 | + story = rev.get("story", {}) |
| 69 | + image_id = story.get("promo_items", {}).get("lead_art", {}).get("id") |
| 70 | + text = story.get("text", "") |
| 71 | + timestamp = rev.get("revision_date") |
| 72 | + if isinstance(timestamp, str): |
| 73 | + timestamp = timestamp[:19] |
| 74 | + return { |
| 75 | + "story_id": story_id, |
| 76 | + "text": text, |
| 77 | + "image_id": image_id, |
| 78 | + "timestamp": timestamp, |
| 79 | + "label": label, |
| 80 | + } |
| 81 | + |
| 82 | + |
| 83 | +def fetch_image_id_from_mongo(story_id: str) -> str: |
| 84 | + client = MongoClient(MONGO_URI) |
| 85 | + db = client[MONGO_DB] |
| 86 | + collection = db[MONGO_COLLECTION] |
| 87 | + doc = collection.find_one({"_id": story_id}, {"promo_items.lead_art.id": 1}) |
| 88 | + client.close() |
| 89 | + if doc: |
| 90 | + return doc.get("promo_items", {}).get("lead_art", {}).get("id", "") |
| 91 | + return "" |
| 92 | + |
| 93 | + |
| 94 | +def fetch_story_ids_since(since_date: str) -> Iterable[str]: |
| 95 | + client = MongoClient(MONGO_URI) |
| 96 | + db = client[MONGO_DB] |
| 97 | + collection = db[MONGO_COLLECTION] |
| 98 | + query = {"last_updated_date": {"$gte": since_date}} |
| 99 | + projection = {"_id": 1} |
| 100 | + story_ids = [doc["_id"] for doc in collection.find(query, projection)] |
| 101 | + client.close() |
| 102 | + return story_ids |
| 103 | + |
| 104 | + |
| 105 | +def process_story(story_id: str, editor_ids: Set[str]) -> Dict[str, str] | None: |
| 106 | + revisions = list(fetch_revisions(story_id)) |
| 107 | + if story_has_photo_editor(revisions, editor_ids): |
| 108 | + image_id = fetch_image_id_from_mongo(story_id) |
| 109 | + return {"story_id": story_id, "image_id": image_id} |
| 110 | + return None |
| 111 | + |
| 112 | + |
| 113 | +def main(args=None): |
| 114 | + parser = argparse.ArgumentParser() |
| 115 | + parser.add_argument("--since", required=True, help="ISO date to start from (e.g., 2021-01-01)") |
| 116 | + parser.add_argument("--editor-csv", default="editor_ids.csv", help="CSV file of photo editor user IDs") |
| 117 | + parser.add_argument("--workers", type=int, default=8, help="Number of parallel threads") |
| 118 | + ns = parser.parse_args(args) |
| 119 | + |
| 120 | + photo_editor_ids = load_photo_editor_ids(ns.editor_csv) |
| 121 | + story_ids = fetch_story_ids_since(ns.since) |
| 122 | + |
| 123 | + Path("artifacts").mkdir(exist_ok=True) |
| 124 | + matched_path = Path("artifacts/story_image_pairs.csv") |
| 125 | + |
| 126 | + matched_rows = [] |
| 127 | + with ThreadPoolExecutor(max_workers=ns.workers) as executor: |
| 128 | + future_to_story = {executor.submit(process_story, story_id, photo_editor_ids): story_id for story_id in story_ids} |
| 129 | + for future in as_completed(future_to_story): |
| 130 | + result = future.result() |
| 131 | + if result: |
| 132 | + matched_rows.append(result) |
| 133 | + |
| 134 | + with matched_path.open("w", newline="") as f: |
| 135 | + writer = csv.DictWriter(f, fieldnames=["story_id", "image_id"]) |
| 136 | + writer.writeheader() |
| 137 | + writer.writerows(matched_rows) |
| 138 | + |
| 139 | + print(f"Wrote matched story IDs and image IDs to {matched_path}") |
| 140 | + |
| 141 | + |
| 142 | +if __name__ == "__main__": |
| 143 | + main() |
0 commit comments