Spaces:
Running
Running
Deploy text summarizer (30-in-15 #2)
Browse filesFiles changed (6)
- .env.exampleAdded+7
- DockerfileAdded+9
- README.md+40-4
- app.pyAdded+198
- demo.pngAdded
- requirements.txtAdded+4
1234567# Pick ONE backend. For a public deploy, use a cloud API (not local Ollama).# Option A — Claude API (recommended):ANTHROPIC_API_KEY=sk-ant-...ANTHROPIC_MODEL=claude-haiku-4-5# Option B — local Ollama (dev only; needs the fleet up):# OLLAMA_URL=http://192.168.12.223:11434# OLLAMA_MODEL=qwen2.5:7b123456789# Text Summarizer — runs on Hugging Face Spaces, Render, Railway, Fly.io, etc.FROM python:3.11-slimWORKDIR /appCOPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txtCOPY . .ENV PORT=7860EXPOSE 7860CMD ["python", "app.py"]12345678910---title: Text Summarizeremoji: 🦀colorFrom: pinkcolorTo: yellowsdk: dockerpinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference12345678910111213141516171819202122232425262728293031323334353637383940414243444546---title: Text Summarizeremoji: 📝colorFrom: indigocolorTo: bluesdk: dockerapp_port: 7860pinned: false---# Text Summarizer 📝Paste an article, email, or notes — **or drop in a URL** — and get a faithful TL;DRplus key points, streamed live. Pick the depth: **Brief**, **Standard**, or **Detailed**.> Project **#2** of my *"30 AI Projects in 15 Days"* build-in-public challenge.## What it does- **Summarize text or a link** — paste raw text, or give it a URL and it fetches +extracts the article for you.- **Three depths** — a 2–3 sentence TL;DR, a paragraph + key bullets, or a detailedbreakdown that preserves names/numbers/dates.- **Faithful** — instructed to never add facts or opinions not in the source.- **Live streaming** output with a one-click **Copy**.## What it demonstrates- **Prompt engineering** — length/format control via a parameterized system prompt.- **Retrieval from the web** — server-side fetch + HTML→text extraction (BeautifulSoup).- **Streaming UX** (Server-Sent Events) and a clean, responsive single-file UI.- **Backend-agnostic** — Claude API in the cloud, or a local Ollama model. Same code.## Run locally```bashpip install -r requirements.txtexport ANTHROPIC_API_KEY=sk-ant-... # or set OLLAMA_URL / OLLAMA_MODELpython app.py # http://127.0.0.1:8500```## Deploy (always-on)Ships with a `Dockerfile` — works on **Hugging Face Spaces**, Render, Railway, or Fly.io.Set `ANTHROPIC_API_KEY` (+ optional `ANTHROPIC_MODEL=claude-haiku-4-5`) as a secret.---Built by **Robert Lucyk** · [GritAI Solutions](https://gritai.solutions) · part of the 30-in-15 challenge.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198#!/usr/bin/env python"""Text Summarizer — paste text or a URL, get a clean TL;DR + key points.Streams the summary live. Backend auto-selects: Anthropic Claude API ifANTHROPIC_API_KEY is set, otherwise a local Ollama model.
pip install flask requests anthropic beautifulsoup4 python app.py # http://127.0.0.1:8500
Project #2 of the "30 Projects in 15 Days" challenge — GritAI."""import os, json, htmlfrom flask import Flask, request, Response
PORT = int(os.environ.get("PORT", "8500"))ANTHROPIC_KEY = os.environ.get("ANTHROPIC_API_KEY")ANTHROPIC_MODEL = os.environ.get("ANTHROPIC_MODEL", "claude-sonnet-5")OLLAMA_URL = os.environ.get("OLLAMA_URL", "http://127.0.0.1:11434")OLLAMA_MODEL = os.environ.get("OLLAMA_MODEL", "qwen2.5:7b")MAX_CHARS = 24000 # cap input to control tokens/cost
LENGTHS = { "brief": "a 2-3 sentence TL;DR only. No bullet points.", "standard": "a one-paragraph TL;DR, then a blank line, then 3-5 key points each on its own line starting with '- '.", "detailed": "a short summary paragraph, then a blank line, then 6-10 key points each on its own line starting with '- ', preserving important specifics (names, numbers, dates).",}
def system_prompt(length): return ("You are an expert summarizer. Produce " + LENGTHS.get(length, LENGTHS["standard"]) + " " "Be faithful to the source — never add facts, opinions, or details that aren't present. " "Write in plain text: no markdown bold/headers/symbols like ** or #. Bullets start with '- '.")
def fetch_url_text(url): import requests from bs4 import BeautifulSoup r = requests.get(url, timeout=20, headers={"User-Agent": "Mozilla/5.0 (compatible; GritAI-Summarizer/1.0)"}) r.raise_for_status() soup = BeautifulSoup(r.text, "html.parser") for tag in soup(["script", "style", "nav", "header", "footer", "aside", "noscript", "form"]): tag.decompose() lines = [l.strip() for l in soup.get_text("\n").splitlines() if l.strip()] text = "\n".join(lines) if len(text) < 200: raise ValueError("Couldn't extract readable text from that page (it may be JavaScript-only or blocked).") return text
def summarize_stream(text, length): sys = system_prompt(length) user = "Summarize the following:\n\n" + text[:MAX_CHARS] if ANTHROPIC_KEY: import anthropic client = anthropic.Anthropic(api_key=ANTHROPIC_KEY) with client.messages.stream(model=ANTHROPIC_MODEL, max_tokens=800, system=sys, messages=[{"role": "user", "content": user}]) as s: for t in s.text_stream: yield t return import requests with requests.post(f"{OLLAMA_URL}/api/chat", stream=True, timeout=120, json={ "model": OLLAMA_MODEL, "stream": True, "messages": [{"role": "system", "content": sys}, {"role": "user", "content": user}], "options": {"temperature": 0.2}}) as r: r.raise_for_status() for line in r.iter_lines(): if not line: continue d = json.loads(line) if d.get("message", {}).get("content"): yield d["message"]["content"] if d.get("done"): break
app = Flask(__name__)
@app.route("/")def home(): return Response(PAGE, mimetype="text/html")
@app.route("/api/summarize", methods=["POST"])def api_summarize(): body = request.get_json(force=True) text = (body.get("text") or "").strip() url = (body.get("url") or "").strip() length = body.get("length", "standard")
def gen(): import sys as _sys try: src = text if url: yield "data: " + json.dumps({"t": "Fetching the page…\n\n"}) + "\n\n" src = fetch_url_text(url) if not src: yield "data: " + json.dumps({"t": "Please paste some text or a URL to summarize."}) + "\n\n" yield "data: [DONE]\n\n" return if url: yield "data: " + json.dumps({"reset": True}) + "\n\n" # clear the "fetching" note for chunk in summarize_stream(src, length): yield "data: " + json.dumps({"t": chunk}) + "\n\n" except Exception as e: print("summarize error:", repr(e), file=_sys.stderr, flush=True) yield "data: " + json.dumps({"t": f"Sorry — {str(e)[:160]}"}) + "\n\n" yield "data: [DONE]\n\n"
return Response(gen(), mimetype="text/event-stream", headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
PAGE = """<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Summarizer — paste text or a link</title><meta name="viewport" content="width=device-width,initial-scale=1"><style>:root{--primary:#4f46e5;--accent:#6366f1;--ink:#1e2230;--bg:#f5f6fb;--card:#ffffff;--muted:#8990a5;--line:#e6e8f2}*{box-sizing:border-box}html,body{height:100%}body{margin:0;font-family:'Segoe UI',system-ui,-apple-system,sans-serif;color:var(--ink); background:radial-gradient(140% 90% at 50% 0%,#fff,var(--bg) 60%);display:flex;justify-content:center}.app{width:100%;max-width:720px;min-height:100dvh;display:flex;flex-direction:column;padding:0 16px}header{padding:26px 4px 14px}header h1{margin:0;font-size:26px;letter-spacing:-.3px;display:flex;align-items:center;gap:10px}header p{margin:6px 0 0;color:var(--muted);font-size:14px}.card{background:var(--card);border:1px solid var(--line);border-radius:16px;padding:16px;box-shadow:0 6px 24px rgba(30,34,48,.06)}textarea{width:100%;min-height:150px;border:0;outline:none;resize:vertical;font-size:15px;line-height:1.5;color:var(--ink);font-family:inherit;background:transparent}.divide{display:flex;align-items:center;gap:10px;color:var(--muted);font-size:12px;margin:10px 2px}.divide::before,.divide::after{content:"";flex:1;height:1px;background:var(--line)}.urlrow{display:flex;align-items:center;gap:8px;border:1px solid var(--line);border-radius:12px;padding:2px 6px 2px 12px;background:#fbfbfe}.urlrow svg{width:16px;height:16px;color:var(--muted);flex:none}.urlrow input{flex:1;border:0;outline:none;padding:11px 4px;font-size:14px;background:transparent;color:var(--ink)}.controls{display:flex;flex-wrap:wrap;gap:12px;align-items:center;justify-content:space-between;margin-top:14px}.seg{display:inline-flex;background:#eef0f9;border-radius:11px;padding:3px}.seg button{border:0;background:transparent;padding:8px 14px;border-radius:9px;font-size:13px;cursor:pointer;color:var(--muted);transition:.15s}.seg button.on{background:#fff;color:var(--primary);box-shadow:0 1px 3px rgba(0,0,0,.10);font-weight:600}.go{border:0;border-radius:12px;padding:12px 22px;font-size:15px;font-weight:600;cursor:pointer;color:#fff; background:linear-gradient(135deg,var(--primary),var(--accent));transition:.15s}.go:hover{filter:brightness(1.08)}.go:disabled{opacity:.5;cursor:default}.out{margin:18px 0 8px;display:none}.out.show{display:block}.out .bar{display:flex;align-items:center;justify-content:space-between;margin-bottom:8px}.out .bar h2{margin:0;font-size:14px;color:var(--muted);font-weight:600;letter-spacing:.4px;text-transform:uppercase}.copy{border:1px solid var(--line);background:#fff;border-radius:9px;padding:6px 12px;font-size:12.5px;cursor:pointer;color:var(--primary)}.copy:hover{border-color:var(--accent)}#result{white-space:pre-wrap;line-height:1.6;font-size:15px;min-height:24px}.typing{display:inline-flex;gap:5px}.typing span{width:8px;height:8px;border-radius:50%;background:var(--accent);opacity:.5;animation:bd 1.2s infinite ease-in-out}.typing span:nth-child(2){animation-delay:.2s}.typing span:nth-child(3){animation-delay:.4s}@keyframes bd{0%,60%,100%{transform:translateY(0);opacity:.35}30%{transform:translateY(-5px);opacity:1}}.foot{text-align:center;color:var(--muted);font-size:11px;padding:16px 0 22px}.foot b{color:#6b7290}</style></head><body><div class="app"><header><h1>📝 Summarizer</h1><p>Paste an article, email, or notes — or drop in a link — and get the gist in seconds.</p></header><div class="card"> <textarea id="src" placeholder="Paste text here…"></textarea> <div class="divide">or summarize a link</div> <div class="urlrow"> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M10 13a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-1 1"/><path d="M14 11a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l1-1"/></svg> <input id="url" placeholder="https://…" autocomplete="off"> </div> <div class="controls"> <div class="seg" id="seg"> <button data-v="brief">Brief</button> <button data-v="standard" class="on">Standard</button> <button data-v="detailed">Detailed</button> </div> <button class="go" id="go" onclick="run()">Summarize</button> </div></div><div class="out" id="out"> <div class="bar"><h2>Summary</h2><button class="copy" id="copy" onclick="copyOut()" style="display:none">Copy</button></div> <div class="card"><div id="result"></div></div></div><div class="foot">Faithful summaries · your text isn't stored · <b>GritAI</b></div></div><script>let length="standard",busy=false;const src=document.getElementById('src'),url=document.getElementById('url'),go=document.getElementById('go'), out=document.getElementById('out'),result=document.getElementById('result'),copy=document.getElementById('copy');document.getElementById('seg').addEventListener('click',e=>{const b=e.target.closest('button');if(!b)return; length=b.dataset.v;[...seg.children].forEach(x=>x.classList.toggle('on',x===b));});function copyOut(){navigator.clipboard.writeText(result.textContent);copy.textContent='Copied!';setTimeout(()=>copy.textContent='Copy',1400);}async function run(){if(busy)return;const text=src.value.trim(),u=url.value.trim(); if(!text&&!u){src.focus();return;} busy=true;go.disabled=true;go.textContent='Summarizing…';out.classList.add('show');copy.style.display='none'; result.innerHTML='<span class="typing"><span></span><span></span><span></span></span>'; let full=''; try{ const r=await fetch('/api/summarize',{method:'POST',headers:{'Content-Type':'application/json'}, body:JSON.stringify({text,url:u,length})}); const rd=r.body.getReader(),dec=new TextDecoder();let buf=''; while(true){const {value,done}=await rd.read();if(done)break;buf+=dec.decode(value,{stream:true}); let i;while((i=buf.indexOf('\\n\\n'))>=0){const line=buf.slice(0,i).trim();buf=buf.slice(i+2); if(!line.startsWith('data:'))continue;const p=line.slice(5).trim();if(p==='[DONE]')continue; try{const o=JSON.parse(p);if(o.reset){full='';result.textContent='';} else if(o.t){full+=o.t;result.textContent=full;}}catch(e){}}} if(full.trim())copy.style.display='inline-block';else result.textContent='No summary produced — try again.'; }catch(e){result.textContent='Sorry — something went wrong. Please try again.';} busy=false;go.disabled=false;go.textContent='Summarize';}</script></body></html>"""
if __name__ == "__main__": backend = "Claude API" if ANTHROPIC_KEY else f"Ollama ({OLLAMA_MODEL} @ {OLLAMA_URL})" print(f"Text Summarizer on http://127.0.0.1:{PORT} [backend: {backend}]", flush=True) app.run(host="0.0.0.0", port=PORT, threaded=True)1234flask>=3.0requests>=2.31anthropic>=0.40beautifulsoup4>=4.12.env.exampleAdded+7
DockerfileAdded+9
README.md+40-4
app.pyAdded+198
demo.pngAdded

requirements.txtAdded+4