A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.
feat: add Hacker News Newsletter Agent using Gemma 4
Tiioluwanib801fda51389
diff --git a/ai_agents/hacker_news_newsletter_agent/.env.example b/ai_agents/hacker_news_newsletter_agent/.env.examplenew file mode 100644index 0000000..9b098db--- /dev/null+++ b/ai_agents/hacker_news_newsletter_agent/.env.example@@ -0,0 +1,11 @@+# ── Google AI Studio API ──────────────────────────────────────────────────────+# Get your free key at https://aistudio.google.com/apikey+GOOGLE_API_KEY=your_google_api_key_here++# ── Gmail SMTP ────────────────────────────────────────────────────────────────+# The Gmail address the newsletter is sent FROM++# 16-character App Password from https://myaccount.google.com/apppasswords+# Requires 2-Step Verification. Remove the spaces from the generated password.+GMAIL_APP_PASSWORD=your16charapppassworddiff --git a/ai_agents/hacker_news_newsletter_agent/README.md b/ai_agents/hacker_news_newsletter_agent/README.mdnew file mode 100644index 0000000..eab1cc6--- /dev/null+++ b/ai_agents/hacker_news_newsletter_agent/README.md@@ -0,0 +1,113 @@+# Hacker News Newsletter Agent++> Fetch the latest tech stories from Hacker News, summarise them with Gemma 4, and deliver a polished HTML newsletter straight to your inbox.++## Overview++Hacker News Newsletter Agent is a Streamlit app that automates the full newsletter pipeline: it pulls the 10 most recent tech stories from Hacker News, scrapes the full article content, generates a clean structured HTML newsletter using Gemma 4 via Google AI Studio, lets you preview it in the browser, and sends it to any email address via Gmail SMTP — all in one click.++## Demo++++## Features++- Fetches the 10 latest tech stories from Hacker News via the Algolia Search API (no API key required)+- Scrapes full article content with Trafilatura for richer summarisation+- Generates a structured HTML newsletter with story summaries and key insights using Gemma 4+- Live newsletter preview rendered in the Streamlit UI before sending+- Delivers the newsletter via Gmail SMTP with SSL encryption+- Single-page Streamlit UI — enter your email and click generate++## Tech Stack++| Layer | Technology |+|---|---|+| LLM | Gemma 4 (`gemma-4-31b-it`) via Google AI Studio (`google-genai`) |+| News Fetching | Hacker News Algolia API — free, no API key needed |+| Content Extraction | `trafilatura` |+| Email Delivery | `smtplib` — Gmail SMTP on port 465 (SSL) |+| UI | Streamlit |++## Prerequisites++- Python 3.10 or higher+- A [Google AI Studio](https://aistudio.google.com/apikey) account (free tier works)+- A Gmail account with [2-Step Verification](https://myaccount.google.com/security) enabled++## Installation++**1. Clone the repository**++```bash+git clone https://github.com/Sumanth077/Hands-On-AI-Engineering.git+cd Hands-On-AI-Engineering/ai_agents/hacker_news_newsletter_agentc+```++**2. Create and activate a virtual environment**++Windows:+```bash+python -m venv .venv+.venv\Scripts\activate+```++macOS / Linux:+```bash+python -m venv .venv+source .venv/bin/activate+```++**3. Install dependencies**++```bash+pip install -r requirements.txt+```++**4. Configure environment variables**++```bash+cp .env.example .env+```++Open `.env` and fill in your credentials (see [Environment Variables](#environment-variables) below).++## Usage++```bash+streamlit run app.py+```++1. Enter your email address in the input field+2. Click **Generate Newsletter**+3. Wait while the app fetches stories, scrapes content, and generates the newsletter (~30–60 seconds)+4. Review the rendered HTML preview+5. Click **Send Newsletter** to deliver it to your inbox++## Environment Variables++| Variable | Description |+|---|---|+| `GOOGLE_API_KEY` | API key from [aistudio.google.com](https://aistudio.google.com/apikey) |+| `GMAIL_ADDRESS` | The Gmail address the newsletter is sent from |+| `GMAIL_APP_PASSWORD` | 16-character App Password from [myaccount.google.com/apppasswords](https://myaccount.google.com/apppasswords) — remove spaces |++> **Note:** Gmail App Passwords require 2-Step Verification to be enabled. Do not use your regular Gmail password.++```env+GOOGLE_API_KEY=your_google_api_key_here+GMAIL_APP_PASSWORD=your16charapppassword+```++## Project Structure++```text+hacker-news-newsletter-agent/+├── app.py # Streamlit UI and pipeline orchestration+├── tools.py # Core functions: fetch, scrape, generate, send+├── requirements.txt # Python dependencies+├── .env.example # Environment variable template+└── assets/+ └── demo.png # Demo screenshot+```diff --git a/ai_agents/hacker_news_newsletter_agent/app.py b/ai_agents/hacker_news_newsletter_agent/app.pynew file mode 100644index 0000000..6faa2f6--- /dev/null+++ b/ai_agents/hacker_news_newsletter_agent/app.py@@ -0,0 +1,177 @@+import os+import re++import streamlit as st+from dotenv import load_dotenv++load_dotenv()++# ── Page config ───────────────────────────────────────────────────────────────+st.set_page_config(+ page_title="HN Newsletter Agent",+ page_icon="📰",+ layout="centered",+ initial_sidebar_state="collapsed",+)++st.markdown(+ """+ <style>+ .block-container { padding-top: 2rem; }+ div[data-testid="stForm"] { border: none; padding: 0; }+ </style>+ """,+ unsafe_allow_html=True,+)++# ── Header ────────────────────────────────────────────────────────────────────+st.title("📰 Hacker News Newsletter Agent")+st.markdown(+ "Fetch today's top HN stories, summarise them with AI, and deliver a "+ "polished newsletter straight to your inbox — powered by **Gemma 4 via Google AI Studio**."+)+st.divider()++# ── Env-var health check ──────────────────────────────────────────────────────+missing = [v for v in ("GOOGLE_API_KEY", "GMAIL_ADDRESS", "GMAIL_APP_PASSWORD") if not os.getenv(v)]+if missing:+ st.warning(+ f"⚠️ Missing environment variables: `{'`, `'.join(missing)}`. "+ "Copy `.env.example` to `.env` and fill in the values before running."+ )++# ── Session state ─────────────────────────────────────────────────────────────+for key, val in {+ "newsletter_html": None,+ "recipient_email": "",+ "send_result": None,+}.items():+ if key not in st.session_state:+ st.session_state[key] = val+++def extract_html(raw: str) -> str:+ cleaned = re.sub(r"<think>.*?</think>", "", raw, flags=re.DOTALL)+ m = re.search(r"<!DOCTYPE html>.*?</html>", cleaned, re.DOTALL | re.IGNORECASE)+ if m:+ return m.group(0).strip()+ m = re.search(r"<html.*?</html>", cleaned, re.DOTALL | re.IGNORECASE)+ if m:+ return m.group(0).strip()+ return cleaned.strip()+++# ══════════════════════════════════════════════════════════════════════════════+# STEP 1: Generate+# ══════════════════════════════════════════════════════════════════════════════+with st.form("newsletter_form"):+ email_input = st.text_input(+ "📧 Your Email Address",+ placeholder="[email protected]",+ help="The newsletter will be delivered here.",+ )++ submitted = st.form_submit_button(+ "🚀 Generate Newsletter",+ type="primary",+ use_container_width=True,+ )++if submitted:+ if not email_input or "@" not in email_input:+ st.error("❌ Please enter a valid email address.")+ st.stop()+ if missing:+ st.error(f"❌ Configure missing env vars first: `{'`, `'.join(missing)}`")+ st.stop()++ from tools import fetch_top_stories, extract_content, generate_newsletter++ # Clear any previous generation+ st.session_state.newsletter_html = None+ st.session_state.send_result = None+ st.session_state.topic_note = None++ progress = st.progress(0)+ status = st.empty()++ try:+ status.info("🔍 Fetching top Hacker News stories…")+ progress.progress(10)+ stories = fetch_top_stories(count=10)++ status.info(f"📄 Scraping content from {len(stories)} articles…")+ for i, story in enumerate(stories):+ story["content"] = extract_content(story["url"])+ progress.progress(10 + int(60 * (i + 1) / len(stories)))++ status.info("✍️ Generating newsletter with Gemma 4…")+ progress.progress(75)+ raw_output = generate_newsletter(stories)++ progress.progress(100)+ status.empty()+ progress.empty()++ newsletter_html = extract_html(raw_output)+ st.session_state.newsletter_html = newsletter_html+ st.session_state.recipient_email = email_input+ st.rerun()++ except Exception as exc:+ progress.empty()+ status.empty()+ st.error(f"❌ Pipeline error: {exc}")+ with st.expander("Full traceback"):+ st.exception(exc)+ st.info("Check your API keys and Gmail credentials in `.env`.")+++# ══════════════════════════════════════════════════════════════════════════════+# STEP 2: Edit & Send (shown only after a newsletter has been generated)+# ══════════════════════════════════════════════════════════════════════════════+if st.session_state.newsletter_html is not None:+ st.divider()+ st.subheader("📄 Newsletter HTML")+ st.caption(+ f"Recipient: **{st.session_state.recipient_email}**"+ + " | Edit the HTML below before sending."+ )++ import streamlit.components.v1 as components+ components.html(st.session_state.newsletter_html, height=620, scrolling=True)++ already_sent = bool(+ st.session_state.send_result+ and "successfully" in st.session_state.send_result.lower()+ )++ col_send, col_back = st.columns([2, 1])++ with col_send:+ if st.button(+ "📬 Send Newsletter",+ type="primary",+ use_container_width=True,+ disabled=already_sent,+ ):+ from tools import send_email++ with st.spinner("Sending via Gmail SMTP…"):+ result_msg = send_email(+ newsletter=st.session_state.newsletter_html,+ recipient=st.session_state.recipient_email,+ )+ st.session_state.send_result = result_msg+ st.rerun()++ with col_back:+ if st.button("↩ Start Over", use_container_width=True):+ st.session_state.clear()+ st.rerun()++ if st.session_state.send_result:+ if already_sent:+ st.success(f"🎉 {st.session_state.send_result}")+ else:+ st.error(f"Delivery failed: {st.session_state.send_result}")diff --git a/ai_agents/hacker_news_newsletter_agent/assets/demo.png b/ai_agents/hacker_news_newsletter_agent/assets/demo.pngnew file mode 100644index 0000000..cfe641cBinary files /dev/null and b/ai_agents/hacker_news_newsletter_agent/assets/demo.png differdiff --git a/ai_agents/hacker_news_newsletter_agent/requirements.txt b/ai_agents/hacker_news_newsletter_agent/requirements.txtnew file mode 100644index 0000000..5d5715c--- /dev/null+++ b/ai_agents/hacker_news_newsletter_agent/requirements.txt@@ -0,0 +1,5 @@+streamlit>=1.35.0+trafilatura>=1.9.0+google-genai>=1.0.0+python-dotenv>=1.0.0+requests>=2.31.0diff --git a/ai_agents/hacker_news_newsletter_agent/tools.py b/ai_agents/hacker_news_newsletter_agent/tools.pynew file mode 100644index 0000000..6dd2c60--- /dev/null+++ b/ai_agents/hacker_news_newsletter_agent/tools.py@@ -0,0 +1,188 @@+import os+import re+import smtplib+from datetime import datetime, timedelta+from email.mime.multipart import MIMEMultipart+from email.mime.text import MIMEText++import requests+import trafilatura+from google import genai+from google.genai import types+++def fetch_top_stories(count: int = 10) -> list[dict]:+ url = "https://hn.algolia.com/api/v1/search_by_date?query=tech&tags=story&hitsPerPage=10"+ response = requests.get(+ url,+ headers={"Cache-Control": "no-cache"},+ timeout=15,+ )+ response.raise_for_status()++ stories = []+ for hit in response.json().get("hits", []):+ url = hit.get("url") or f"https://news.ycombinator.com/item?id={hit['objectID']}"+ stories.append({+ "id": hit["objectID"],+ "title": hit.get("title", "No title"),+ "url": url,+ "score": hit.get("points", 0),+ "author": hit.get("author", "Unknown"),+ "comments": hit.get("num_comments", 0),+ })++ print(f"[fetch_top_stories] Algolia returned {len(stories)} stories")+ return stories+++def extract_content(url: str) -> str:+ if not url or "news.ycombinator.com" in url:+ return f"[Full content unavailable — read at: {url}]"+ try:+ downloaded = trafilatura.fetch_url(url)+ if downloaded:+ extracted = trafilatura.extract(+ downloaded,+ include_comments=False,+ include_tables=False,+ no_fallback=False,+ )+ if extracted:+ return extracted[:1800]+ except Exception:+ pass+ return f"[Full content unavailable — read at: {url}]"+++def generate_newsletter(stories: list[dict]) -> str:+ date_str = datetime.now().strftime("%B %d, %Y")++ stories_text = ""+ for i, story in enumerate(stories, 1):+ stories_text += (+ f"\nStory {i}:\n"+ f"Title: {story['title']}\n"+ f"URL: {story['url']}\n"+ f"Score: {story['score']} points | Author: {story['author']} | Comments: {story['comments']}\n"+ f"Content:\n{story.get('content', '[No content available]')}\n"+ f"---\n"+ )++ prompt = f"""You are a seasoned tech newsletter editor. Write a complete HTML newsletter covering the top Hacker News stories below.++Today's date is {date_str}. You have been given {len(stories)} top Hacker News stories.++EDITORIAL RULES:+- Summarise each story clearly and accurately in 2-3 sentences. No forced angle — just report what the story is about.+- The "Key insight" callout should highlight the single most interesting or actionable takeaway from the story.+- Write in a clear, confident voice — informative but not dry, no hype, no filler.+- If any article's content appears clearly outdated relative to today, note that briefly.++OUTPUT RULES — follow exactly:+- Output ONLY a raw HTML document. Do NOT wrap it in markdown code fences.+- Do NOT include any text, explanation, or preamble before <!DOCTYPE html>.+- Start the output with <!DOCTYPE html> and end with </html>.++Use this exact HTML structure and inline styles:++<!DOCTYPE html>+<html lang="en">+<head>+<meta charset="UTF-8">+<meta name="viewport" content="width=device-width,initial-scale=1">+<title>Hacker News Tech Digest</title>+</head>+<body style="margin:0;padding:0;background:#f4f4f4;font-family:-apple-system,Arial,sans-serif;">+<div style="max-width:680px;margin:0 auto;background:#ffffff;">++ <div style="background:#ff6600;padding:32px 40px;text-align:center;">+ <h1 style="margin:0;color:#ffffff;font-size:26px;letter-spacing:-0.5px;">Hacker News Tech Digest</h1>+ <p style="margin:8px 0 0;color:rgba(255,255,255,0.9);font-size:14px;">{date_str}</p>+ </div>++ <div style="padding:24px 40px 0;">+ <p style="color:#555;font-size:15px;line-height:1.6;margin:0;">+ Your curated summary of today's top stories from the Hacker News community.+ </p>+ </div>++ <div style="padding:16px 40px 32px;">++ <div style="margin-bottom:28px;padding-bottom:28px;border-bottom:1px solid #eeeeee;">+ <span style="font-size:11px;font-weight:700;text-transform:uppercase;color:#ff6600;letter-spacing:0.5px;">Story #N</span>+ <h2 style="margin:6px 0 4px;font-size:18px;line-height:1.3;">+ <a href="ARTICLE_URL" style="color:#1a1a1a;text-decoration:none;">ARTICLE_TITLE</a>+ </h2>+ <p style="margin:0 0 10px;font-size:13px;color:#999;">+ ⬆ SCORE points · by AUTHOR · COMMENTS comments+ </p>+ <p style="margin:0 0 12px;font-size:15px;color:#444;line-height:1.65;">+ 2-3 sentence summary of the story.+ </p>+ <div style="background:#fff8f0;border-left:3px solid #ff6600;padding:10px 14px;font-size:14px;color:#555;line-height:1.5;">+ <strong style="color:#ff6600;">Key insight:</strong> The most interesting or actionable takeaway from this story.+ </div>+ </div>++ </div>++ <div style="background:#f9f9f9;padding:20px 40px;text-align:center;border-top:1px solid #eeeeee;">+ <p style="margin:0;color:#aaa;font-size:12px;">Generated by HN Newsletter Agent on {date_str}</p>+ <p style="margin:4px 0 0;color:#aaa;font-size:12px;">Powered by Gemini via Google AI Studio</p>+ </div>++</div>+</body>+</html>++Fill in all {len(stories)} stories using the article block pattern above. Ensure every link is the real article URL.++STORIES DATA:+{stories_text}"""++ client = genai.Client(api_key=os.getenv("GOOGLE_API_KEY"))+ response = client.models.generate_content(+ model="gemma-4-31b-it",+ contents=prompt,+ config=types.GenerateContentConfig(+ temperature=0.3,+ max_output_tokens=8192,+ ),+ )+ return response.text+++def send_email(newsletter: str, recipient: str) -> str:+ gmail_address = os.getenv("GMAIL_ADDRESS")+ gmail_password = os.getenv("GMAIL_APP_PASSWORD")++ if not gmail_address or not gmail_password:+ return "Error: GMAIL_ADDRESS or GMAIL_APP_PASSWORD not set in environment."++ html_content = re.sub(r"<think>.*?</think>", "", newsletter, flags=re.DOTALL).strip()+ date_str = datetime.now().strftime("%B %d, %Y")+ subject = f"Hacker News Daily Digest — {date_str}"++ try:+ msg = MIMEMultipart("alternative")+ msg["Subject"] = subject+ msg["From"] = f"HN Newsletter Agent <{gmail_address}>"+ msg["To"] = recipient+ msg.attach(MIMEText(html_content, "html", "utf-8"))++ with smtplib.SMTP_SSL("smtp.gmail.com", 465) as server:+ server.login(gmail_address, gmail_password)+ server.sendmail(gmail_address, recipient, msg.as_string())++ return f"Newsletter successfully sent to {recipient}."++ except smtplib.SMTPAuthenticationError:+ return (+ "Authentication failed. Verify GMAIL_ADDRESS and GMAIL_APP_PASSWORD in .env. "+ "Use a Gmail App Password, not your regular account password."+ )+ except smtplib.SMTPException as exc:+ return f"SMTP error while sending: {exc}"+ except Exception as exc:+ return f"Unexpected error: {exc}"