# main.py
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
import asyncio
from typing import AsyncGenerator
from hn_scraper import start_scraper
from database import get_stories, init_db
templates = Jinja2Templates(directory="templates")
async def lifespan(app: FastAPI) -> AsyncGenerator:
await init_db()
app.state.scraper_task = asyncio.create_task(start_scraper())
yield
app.state.scraper_task.cancel()
app = FastAPI(lifespan=lifespan)
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.get("/", response_class=HTMLResponse)
async def read_root(request: Request):
stories = await get_stories()
def get_trend_symbol(trend: str) -> str:
symbols = {
'up': '↑',
'down': '↓',
'same': '→',
'new': '✱',
'removed': '✖',
}
return symbols.get(trend, '')
return templates.TemplateResponse(
"index.html",
{
"request": request,
"stories": stories,
"get_trend_symbol": get_trend_symbol,
},
)
# hn_scraper.py
import asyncio
import aiohttp
from typing import List, Dict, Any
from datetime import datetime
from metadata import fetch_metadata
from database import update_stories
HACKER_NEWS_TOP_STORIES_URL = "https://hacker-news.firebaseio.com/v0/topstories.json"
HACKER_NEWS_ITEM_URL = "https://hacker-news.firebaseio.com/v0/item/{}.json"
async def fetch_json(session: aiohttp.ClientSession, url: str) -> Any:
async with session.get(url) as response:
return await response.json()
async def fetch_top_stories() -> List[Dict[str, Any]]:
async with aiohttp.ClientSession() as session:
top_story_ids = await fetch_json(session, HACKER_NEWS_TOP_STORIES_URL)
tasks = [
fetch_json(session, HACKER_NEWS_ITEM_URL.format(story_id))
for story_id in top_story_ids[:30]
]
stories = await asyncio.gather(*tasks)
return stories
async def start_scraper() -> None:
while True:
try:
stories = await fetch_top_stories()
stories_with_metadata = []
for index, story in enumerate(stories, start=1):
if 'url' in story:
metadata = await fetch_metadata(story['url'])
story.update(metadata)
else:
story['description'] = ''
story['image_url'] = ''
story['current_position'] = index
story['hn_url'] = f"https://news.ycombinator.com/item?id={story['id']}"
story['time_posted'] = datetime.fromtimestamp(story['time'])
story['comments_count'] = story.get('descendants', 0)
story['poster'] = story.get('by', '')
stories_with_metadata.append(story)
await update_stories(stories_with_metadata)
except Exception as e:
print(f"Error fetching stories: {e}")
await asyncio.sleep(180) # Sleep for 3 minutes
# metadata.py
import aiohttp
from bs4 import BeautifulSoup
from typing import Dict, Any
from PIL import Image
from io import BytesIO
import os
import hashlib
metadata_cache: Dict[str, Dict[str, Any]] = {}
IMAGE_DIR = "static/images"
if not os.path.exists(IMAGE_DIR):
os.makedirs(IMAGE_DIR)
async def fetch_metadata(url: str) -> Dict[str, Any]:
if url in metadata_cache:
return metadata_cache[url]
try:
async with aiohttp.ClientSession() as session:
async with session.get(url, timeout=10) as response:
html = await response.text()
soup = BeautifulSoup(html, 'html.parser')
og_image = soup.find('meta', property='og:image')
og_description = soup.find('meta', property='og:description')
favicon = soup.find('link', rel='icon')
image_url = og_image['content'] if og_image else (favicon['href'] if favicon else None)
description = og_description['content'] if og_description else ''
if image_url:
image_filename = await download_and_resize_image(image_url)
else:
image_filename = None # Placeholder or default image
metadata = {
'image_url': f"/static/images/{image_filename}" if image_filename else None,
'description': description,
}
metadata_cache[url] = metadata
return metadata
except Exception as e:
print(f"Error fetching metadata for {url}: {e}")
return {'image_url': None, 'description': ''}
async def download_and_resize_image(image_url: str) -> str:
try:
async with aiohttp.ClientSession() as session:
async with session.get(image_url, timeout=10) as response:
if response.status == 200:
image_data = await response.read()
image = Image.open(BytesIO(image_data))
image = image.convert('RGB')
max_width = 640
if image.width > max_width:
ratio = max_width / float(image.width)
height = int((float(image.height) * float(ratio)))
image = image.resize((max_width, height), Image.ANTIALIAS)
image_hash = hashlib.md5(image_url.encode('utf-8')).hexdigest()
image_filename = f"{image_hash}.jpg"
image_path = os.path.join(IMAGE_DIR, image_filename)
image.save(image_path, "JPEG")
return image_filename
except Exception as e:
print(f"Error downloading image {image_url}: {e}")
return None
# database.py
from typing import List, Dict, Any
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy import select
from sqlalchemy.orm import sessionmaker
from models import Base, Story
from sqlalchemy.engine import URL
DATABASE_URL = URL.create(
"sqlite+aiosqlite",
database="hn-clone.db",
)
engine = create_async_engine(
DATABASE_URL, echo=False,
)
async_session = sessionmaker(
engine, expire_on_commit=False, class_=AsyncSession
)
async def init_db() -> None:
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
async def get_stories() -> List[Story]:
async with async_session() as session:
result = await session.execute(
select(Story).where(Story.trend != 'removed').order_by(Story.current_position)
)
stories = result.scalars().all()
return stories
async def update_stories(new_stories: List[Dict[str, Any]]) -> None:
async with async_session() as session:
existing_stories = (await session.execute(select(Story))).scalars().all()
existing_ids = {story.id for story in existing_stories}
new_ids = {story['id'] for story in new_stories}
# Handle removed stories
removed_ids = existing_ids - new_ids
for story_id in removed_ids:
story = await session.get(Story, story_id)
if story:
story.last_position = story.current_position
story.current_position = None
story.trend = 'removed'
session.add(story)
for new_story in new_stories:
existing_story = await session.get(Story, new_story['id'])
if existing_story:
new_story['last_position'] = existing_story.current_position
new_story['trend'] = determine_trend(
existing_story.current_position, new_story['current_position']
)
for key, value in new_story.items():
if hasattr(existing_story, key):
setattr(existing_story, key, value)
session.add(existing_story)
else:
new_story['last_position'] = None
new_story['trend'] = 'new'
story = Story(**new_story)
session.add(story)
await session.commit()
def determine_trend(last_pos: int, current_pos: int) -> str:
if last_pos is None:
return 'new'
elif last_pos > current_pos:
return 'up'
elif last_pos < current_pos:
return 'down'
else:
return 'same'
# models.py
from sqlalchemy.orm import declarative_base
from sqlalchemy import Column, Integer, String, DateTime, Text
Base = declarative_base()
class Story(Base):
__tablename__ = 'stories'
id = Column(Integer, primary_key=True)
title = Column(String)
url = Column(String)
hn_url = Column(String)
score = Column(Integer)
poster = Column(String)
comments_count = Column(Integer)
time_posted = Column(DateTime)
description = Column(Text)
image_url = Column(String)
last_position = Column(Integer)
current_position = Column(Integer)
trend = Column(String)
<!-- templates/index.html -->
<!DOCTYPE html>
<html>
<head>
<title>Hacker News Top Stories</title>
<link rel="stylesheet" href="/static/css/styles.css">
</head>
<body>
<h1>Hacker News Top Stories</h1>
<table>
<thead>
<tr>
<th>Trend</th>
<th>#</th>
<th>Title</th>
<th>Image</th>
<th>Score</th>
<th>Comments</th>
<th>Poster</th>
<th>Time Posted</th>
<th>Description</th>
</tr>
</thead>
<tbody>
{% for story in stories %}
<tr>
<td>{{ get_trend_symbol(story.trend) }}</td>
<td>{{ story.current_position if story.current_position else '' }}</td>
<td><a href="{{ story.url }}">{{ story.title }}</a></td>
<td>
{% if story.image_url %}
<img src="{{ story.image_url }}" alt="Image" width="100">
{% endif %}
</td>
<td>{{ story.score }}</td>
<td>{{ story.comments_count }}</td>
<td>{{ story.poster }}</td>
<td>{{ story.time_posted.strftime('%Y-%m-%d %H:%M:%S') }}</td>
<td>{{ story.description }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<p>Last updated: {{ stories[0].time_posted.strftime('%Y-%m-%d %H:%M:%S') if stories else 'N/A' }}</p>
<script>
setTimeout(function(){
window.location.reload(1);
}, 180000); // Refresh every 3 minutes
</script>
</body>
</html>
/* static/css/styles.css */
body {
font-family: Arial, sans-serif;
margin: 20px;
}
h1 {
text-align: center;
}
table {
width: 100%;
border-collapse: collapse;
table-layout: fixed;
word-wrap: break-word;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
vertical-align: top;
text-align: left;
}
th {
background-color: #f2f2f2;
}
img {
max-width: 100px;
height: auto;
}
@media screen and (max-width: 768px) {
table, thead, tbody, th, td, tr {
display: block;
}
tr {
margin-bottom: 15px;
}
th, td {
text-align: right;
}
th::before, td::before {
float: left;
font-weight: bold;
}
}
Note: Make sure to install the required dependencies:
pip install fastapi uvicorn aiohttp sqlalchemy[asyncio] aiosqlite Jinja2 beautifulsoup4 Pillow
Start the application using:
uvicorn main:app --reload