|
| 1 | +import asyncio |
| 2 | +import datetime |
| 3 | +import os |
| 4 | +from typing import List, Optional |
| 5 | +import aiohttp |
| 6 | +import click |
| 7 | +import structlog |
| 8 | +from html2text import HTML2Text |
| 9 | + |
| 10 | +from data_types import Post |
| 11 | +from clients import supabase_client |
| 12 | +import tqdm |
| 13 | +# Set up logging |
| 14 | +logger = structlog.get_logger() |
| 15 | + |
| 16 | +# Initialize HTML to text converter |
| 17 | +h = HTML2Text() |
| 18 | +h.ignore_links = True |
| 19 | + |
| 20 | +async def fetch_item(session: aiohttp.ClientSession, item_id: int) -> Optional[Post]: |
| 21 | + """Fetch a single HN item and convert it to a Post.""" |
| 22 | + async with session.get(f"https://hacker-news.firebaseio.com/v0/item/{item_id}.json") as response: |
| 23 | + if response.status != 200: |
| 24 | + logger.error("Failed to fetch item %d: %s", item_id, await response.text()) |
| 25 | + return None |
| 26 | + |
| 27 | + item = await response.json() |
| 28 | + if not item or item.get("dead") or item.get("deleted"): |
| 29 | + return None |
| 30 | + |
| 31 | + return { |
| 32 | + "url": item.get("url", f"https://news.ycombinator.com/item?id={item_id}"), |
| 33 | + "time_added": item["time"], |
| 34 | + "source": "hackernews", |
| 35 | + "tags": ["hackernews:top"], |
| 36 | + "title": item["title"], |
| 37 | + "abstract": h.handle(item.get("text", "")), |
| 38 | + "attrs": { |
| 39 | + "hn_id": item_id, |
| 40 | + "score": item.get("score", 0), |
| 41 | + "by": item.get("by", ""), |
| 42 | + "descendants": item.get("descendants", 0), |
| 43 | + }, |
| 44 | + "links": {}, |
| 45 | + } |
| 46 | + |
| 47 | + |
| 48 | + |
| 49 | +async def fetch_top_stories(limit: int) -> List[Post]: |
| 50 | + """Fetch top stories from HN API.""" |
| 51 | + async with aiohttp.ClientSession() as session: |
| 52 | + # First get the list of top story IDs |
| 53 | + async with session.get("https://hacker-news.firebaseio.com/v0/topstories.json") as response: |
| 54 | + if response.status != 200: |
| 55 | + logger.error("Failed to fetch top stories: %s", await response.text()) |
| 56 | + return [] |
| 57 | + |
| 58 | + story_ids = await response.json() |
| 59 | + story_ids = story_ids[:limit] |
| 60 | + |
| 61 | + # Fetch each story concurrently |
| 62 | + tasks = [fetch_item(session, story_id) for story_id in story_ids] |
| 63 | + posts = await asyncio.gather(*tasks) |
| 64 | + |
| 65 | + # Filter out None values |
| 66 | + return [post for post in posts if post is not None] |
| 67 | + |
| 68 | +async def fetch_stories_by_date(date_str: str) -> List[Post]: |
| 69 | + """Fetch stories from HN Algolia API for a specific date. |
| 70 | + |
| 71 | + Args: |
| 72 | + date_str: Date in YYYY-MM-DD format |
| 73 | + """ |
| 74 | + # Convert date string to timestamp |
| 75 | + from datetime import datetime |
| 76 | + date = datetime.strptime(date_str, "%Y-%m-%d") |
| 77 | + start_timestamp = int(date.timestamp()) |
| 78 | + end_timestamp = start_timestamp + 86400 # Add 24 hours in seconds |
| 79 | + |
| 80 | + # Construct Algolia API URL |
| 81 | + url = f"https://hn.algolia.com/api/v1/search_by_date" |
| 82 | + params = { |
| 83 | + "tags": "story", |
| 84 | + "numericFilters": f"created_at_i>={start_timestamp},created_at_i<{end_timestamp}", |
| 85 | + "hitsPerPage": 100 |
| 86 | + } |
| 87 | + |
| 88 | + async with aiohttp.ClientSession() as session: |
| 89 | + async with session.get(url, params=params) as response: |
| 90 | + if response.status != 200: |
| 91 | + logger.error("Failed to fetch stories: %s", await response.text()) |
| 92 | + return [] |
| 93 | + |
| 94 | + data = await response.json() |
| 95 | + hits = data.get("hits", []) |
| 96 | + |
| 97 | + posts = [] |
| 98 | + for hit in hits: |
| 99 | + if hit.get("dead") or hit.get("deleted"): |
| 100 | + continue |
| 101 | + |
| 102 | + posts.append({ |
| 103 | + "url": hit.get("url", f"https://news.ycombinator.com/item?id={hit['objectID']}"), |
| 104 | + "time_added": hit["created_at_i"], |
| 105 | + "source": "hackernews", |
| 106 | + "tags": ["hackernews:top"], |
| 107 | + "title": hit["title"], |
| 108 | + "abstract": h.handle(hit.get("story_text", "")), |
| 109 | + "attrs": { |
| 110 | + "hn_id": int(hit["objectID"]), |
| 111 | + "score": hit.get("points", 0), |
| 112 | + "by": hit.get("author", ""), |
| 113 | + "descendants": hit.get("num_comments", 0), |
| 114 | + }, |
| 115 | + "links": {}, |
| 116 | + }) |
| 117 | + |
| 118 | + return posts |
| 119 | + |
| 120 | +@click.command() |
| 121 | +@click.argument('limit', type=int) |
| 122 | +def crawl_hn(limit: int): |
| 123 | + """Crawl top stories from Hacker News.""" |
| 124 | + logger.info("Starting HN crawl with limit %d", limit) |
| 125 | + |
| 126 | + # Run the async function |
| 127 | + posts = asyncio.run(fetch_top_stories(limit)) |
| 128 | + logger.info("Fetched %d posts from HN", len(posts)) |
| 129 | + |
| 130 | + # Save to database |
| 131 | + if posts: |
| 132 | + supabase_client.table("Post").upsert(posts, on_conflict="source,url").execute() |
| 133 | + logger.info("Successfully saved %d posts to database", len(posts)) |
| 134 | + |
| 135 | +@click.command() |
| 136 | +@click.option('--date_start', type=str) |
| 137 | +@click.option('--date_end', type=str) |
| 138 | +def crawl_hn_by_date(date_start: str, date_end: str): |
| 139 | + """Crawl stories from Hacker News for a specific date.""" |
| 140 | + logger.info("Starting HN crawl for date %s to %s", date_start, date_end) |
| 141 | + |
| 142 | + date_start = datetime.datetime.strptime(date_start, "%Y-%m-%d") |
| 143 | + date_end = datetime.datetime.strptime(date_end, "%Y-%m-%d") |
| 144 | + |
| 145 | + def date_range(start: datetime.datetime, end: datetime.datetime): |
| 146 | + for n in range(int((end - start).days)): |
| 147 | + yield (start + datetime.timedelta(n)).strftime("%Y-%m-%d") |
| 148 | + |
| 149 | + for date in tqdm.tqdm(date_range(date_start, date_end)): |
| 150 | + # Run the async function |
| 151 | + import time |
| 152 | + time.sleep(5) |
| 153 | + posts = asyncio.run(fetch_stories_by_date(date)) |
| 154 | + logger.info("Fetched %d posts from HN", len(posts)) |
| 155 | + |
| 156 | + # Save to database |
| 157 | + if posts: |
| 158 | + supabase_client.table("Post").upsert(posts, on_conflict="source,url").execute() |
| 159 | + logger.info("Successfully saved %d posts to database", len(posts)) |
| 160 | + |
| 161 | +if __name__ == "__main__": |
| 162 | + crawl_hn_by_date() |
0 commit comments