BonusLockSMith commited on
Commit
c5d0aa5
·
verified ·
1 Parent(s): 512f4e6

Deploy text summarizer (30-in-15 #2)

Browse files
Files changed (6) hide show
  1. .env.example +7 -0
  2. Dockerfile +9 -0
  3. README.md +40 -4
  4. app.py +198 -0
  5. demo.png +0 -0
  6. requirements.txt +4 -0
.env.example ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Pick ONE backend. For a public deploy, use a cloud API (not local Ollama).
2
+ # Option A — Claude API (recommended):
3
+ ANTHROPIC_API_KEY=sk-ant-...
4
+ ANTHROPIC_MODEL=claude-haiku-4-5
5
+ # Option B — local Ollama (dev only; needs the fleet up):
6
+ # OLLAMA_URL=http://192.168.12.223:11434
7
+ # OLLAMA_MODEL=qwen2.5:7b
Dockerfile ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Text Summarizer — runs on Hugging Face Spaces, Render, Railway, Fly.io, etc.
2
+ FROM python:3.11-slim
3
+ WORKDIR /app
4
+ COPY requirements.txt .
5
+ RUN pip install --no-cache-dir -r requirements.txt
6
+ COPY . .
7
+ ENV PORT=7860
8
+ EXPOSE 7860
9
+ CMD ["python", "app.py"]
README.md CHANGED
@@ -1,10 +1,46 @@
1
  ---
2
  title: Text Summarizer
3
- emoji: 🦀
4
- colorFrom: pink
5
- colorTo: yellow
6
  sdk: docker
 
7
  pinned: false
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  title: Text Summarizer
3
+ emoji: 📝
4
+ colorFrom: indigo
5
+ colorTo: blue
6
  sdk: docker
7
+ app_port: 7860
8
  pinned: false
9
  ---
10
 
11
+ # Text Summarizer 📝
12
+
13
+ Paste an article, email, or notes — **or drop in a URL** — and get a faithful TL;DR
14
+ plus key points, streamed live. Pick the depth: **Brief**, **Standard**, or **Detailed**.
15
+
16
+ > Project **#2** of my *"30 AI Projects in 15 Days"* build-in-public challenge.
17
+
18
+ ![demo](demo.png)
19
+
20
+ ## What it does
21
+ - **Summarize text or a link** — paste raw text, or give it a URL and it fetches +
22
+ extracts the article for you.
23
+ - **Three depths** — a 2–3 sentence TL;DR, a paragraph + key bullets, or a detailed
24
+ breakdown that preserves names/numbers/dates.
25
+ - **Faithful** — instructed to never add facts or opinions not in the source.
26
+ - **Live streaming** output with a one-click **Copy**.
27
+
28
+ ## What it demonstrates
29
+ - **Prompt engineering** — length/format control via a parameterized system prompt.
30
+ - **Retrieval from the web** — server-side fetch + HTML→text extraction (BeautifulSoup).
31
+ - **Streaming UX** (Server-Sent Events) and a clean, responsive single-file UI.
32
+ - **Backend-agnostic** — Claude API in the cloud, or a local Ollama model. Same code.
33
+
34
+ ## Run locally
35
+ ```bash
36
+ pip install -r requirements.txt
37
+ export ANTHROPIC_API_KEY=sk-ant-... # or set OLLAMA_URL / OLLAMA_MODEL
38
+ python app.py # http://127.0.0.1:8500
39
+ ```
40
+
41
+ ## Deploy (always-on)
42
+ Ships with a `Dockerfile` — works on **Hugging Face Spaces**, Render, Railway, or Fly.io.
43
+ Set `ANTHROPIC_API_KEY` (+ optional `ANTHROPIC_MODEL=claude-haiku-4-5`) as a secret.
44
+
45
+ ---
46
+ Built by **Robert Lucyk** · [GritAI Solutions](https://gritai.solutions) · part of the 30-in-15 challenge.
app.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Text Summarizer — paste text or a URL, get a clean TL;DR + key points.
3
+ Streams the summary live. Backend auto-selects: Anthropic Claude API if
4
+ ANTHROPIC_API_KEY is set, otherwise a local Ollama model.
5
+
6
+ pip install flask requests anthropic beautifulsoup4
7
+ python app.py # http://127.0.0.1:8500
8
+
9
+ Project #2 of the "30 Projects in 15 Days" challenge — GritAI.
10
+ """
11
+ import os, json, html
12
+ from flask import Flask, request, Response
13
+
14
+ PORT = int(os.environ.get("PORT", "8500"))
15
+ ANTHROPIC_KEY = os.environ.get("ANTHROPIC_API_KEY")
16
+ ANTHROPIC_MODEL = os.environ.get("ANTHROPIC_MODEL", "claude-sonnet-5")
17
+ OLLAMA_URL = os.environ.get("OLLAMA_URL", "http://127.0.0.1:11434")
18
+ OLLAMA_MODEL = os.environ.get("OLLAMA_MODEL", "qwen2.5:7b")
19
+ MAX_CHARS = 24000 # cap input to control tokens/cost
20
+
21
+ LENGTHS = {
22
+ "brief": "a 2-3 sentence TL;DR only. No bullet points.",
23
+ "standard": "a one-paragraph TL;DR, then a blank line, then 3-5 key points each on its own line starting with '- '.",
24
+ "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).",
25
+ }
26
+
27
+ def system_prompt(length):
28
+ return ("You are an expert summarizer. Produce " + LENGTHS.get(length, LENGTHS["standard"]) + " "
29
+ "Be faithful to the source — never add facts, opinions, or details that aren't present. "
30
+ "Write in plain text: no markdown bold/headers/symbols like ** or #. Bullets start with '- '.")
31
+
32
+ def fetch_url_text(url):
33
+ import requests
34
+ from bs4 import BeautifulSoup
35
+ r = requests.get(url, timeout=20, headers={"User-Agent": "Mozilla/5.0 (compatible; GritAI-Summarizer/1.0)"})
36
+ r.raise_for_status()
37
+ soup = BeautifulSoup(r.text, "html.parser")
38
+ for tag in soup(["script", "style", "nav", "header", "footer", "aside", "noscript", "form"]):
39
+ tag.decompose()
40
+ lines = [l.strip() for l in soup.get_text("\n").splitlines() if l.strip()]
41
+ text = "\n".join(lines)
42
+ if len(text) < 200:
43
+ raise ValueError("Couldn't extract readable text from that page (it may be JavaScript-only or blocked).")
44
+ return text
45
+
46
+ def summarize_stream(text, length):
47
+ sys = system_prompt(length)
48
+ user = "Summarize the following:\n\n" + text[:MAX_CHARS]
49
+ if ANTHROPIC_KEY:
50
+ import anthropic
51
+ client = anthropic.Anthropic(api_key=ANTHROPIC_KEY)
52
+ with client.messages.stream(model=ANTHROPIC_MODEL, max_tokens=800, system=sys,
53
+ messages=[{"role": "user", "content": user}]) as s:
54
+ for t in s.text_stream:
55
+ yield t
56
+ return
57
+ import requests
58
+ with requests.post(f"{OLLAMA_URL}/api/chat", stream=True, timeout=120, json={
59
+ "model": OLLAMA_MODEL, "stream": True,
60
+ "messages": [{"role": "system", "content": sys}, {"role": "user", "content": user}],
61
+ "options": {"temperature": 0.2}}) as r:
62
+ r.raise_for_status()
63
+ for line in r.iter_lines():
64
+ if not line:
65
+ continue
66
+ d = json.loads(line)
67
+ if d.get("message", {}).get("content"):
68
+ yield d["message"]["content"]
69
+ if d.get("done"):
70
+ break
71
+
72
+ app = Flask(__name__)
73
+
74
+ @app.route("/")
75
+ def home():
76
+ return Response(PAGE, mimetype="text/html")
77
+
78
+ @app.route("/api/summarize", methods=["POST"])
79
+ def api_summarize():
80
+ body = request.get_json(force=True)
81
+ text = (body.get("text") or "").strip()
82
+ url = (body.get("url") or "").strip()
83
+ length = body.get("length", "standard")
84
+
85
+ def gen():
86
+ import sys as _sys
87
+ try:
88
+ src = text
89
+ if url:
90
+ yield "data: " + json.dumps({"t": "Fetching the page…\n\n"}) + "\n\n"
91
+ src = fetch_url_text(url)
92
+ if not src:
93
+ yield "data: " + json.dumps({"t": "Please paste some text or a URL to summarize."}) + "\n\n"
94
+ yield "data: [DONE]\n\n"
95
+ return
96
+ if url:
97
+ yield "data: " + json.dumps({"reset": True}) + "\n\n" # clear the "fetching" note
98
+ for chunk in summarize_stream(src, length):
99
+ yield "data: " + json.dumps({"t": chunk}) + "\n\n"
100
+ except Exception as e:
101
+ print("summarize error:", repr(e), file=_sys.stderr, flush=True)
102
+ yield "data: " + json.dumps({"t": f"Sorry — {str(e)[:160]}"}) + "\n\n"
103
+ yield "data: [DONE]\n\n"
104
+
105
+ return Response(gen(), mimetype="text/event-stream",
106
+ headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
107
+
108
+ PAGE = """<!doctype html><html lang="en"><head><meta charset="utf-8">
109
+ <title>Summarizer — paste text or a link</title>
110
+ <meta name="viewport" content="width=device-width,initial-scale=1">
111
+ <style>
112
+ :root{--primary:#4f46e5;--accent:#6366f1;--ink:#1e2230;--bg:#f5f6fb;--card:#ffffff;--muted:#8990a5;--line:#e6e8f2}
113
+ *{box-sizing:border-box}html,body{height:100%}
114
+ body{margin:0;font-family:'Segoe UI',system-ui,-apple-system,sans-serif;color:var(--ink);
115
+ background:radial-gradient(140% 90% at 50% 0%,#fff,var(--bg) 60%);display:flex;justify-content:center}
116
+ .app{width:100%;max-width:720px;min-height:100dvh;display:flex;flex-direction:column;padding:0 16px}
117
+ header{padding:26px 4px 14px}
118
+ header h1{margin:0;font-size:26px;letter-spacing:-.3px;display:flex;align-items:center;gap:10px}
119
+ header p{margin:6px 0 0;color:var(--muted);font-size:14px}
120
+ .card{background:var(--card);border:1px solid var(--line);border-radius:16px;padding:16px;box-shadow:0 6px 24px rgba(30,34,48,.06)}
121
+ 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}
122
+ .divide{display:flex;align-items:center;gap:10px;color:var(--muted);font-size:12px;margin:10px 2px}
123
+ .divide::before,.divide::after{content:"";flex:1;height:1px;background:var(--line)}
124
+ .urlrow{display:flex;align-items:center;gap:8px;border:1px solid var(--line);border-radius:12px;padding:2px 6px 2px 12px;background:#fbfbfe}
125
+ .urlrow svg{width:16px;height:16px;color:var(--muted);flex:none}
126
+ .urlrow input{flex:1;border:0;outline:none;padding:11px 4px;font-size:14px;background:transparent;color:var(--ink)}
127
+ .controls{display:flex;flex-wrap:wrap;gap:12px;align-items:center;justify-content:space-between;margin-top:14px}
128
+ .seg{display:inline-flex;background:#eef0f9;border-radius:11px;padding:3px}
129
+ .seg button{border:0;background:transparent;padding:8px 14px;border-radius:9px;font-size:13px;cursor:pointer;color:var(--muted);transition:.15s}
130
+ .seg button.on{background:#fff;color:var(--primary);box-shadow:0 1px 3px rgba(0,0,0,.10);font-weight:600}
131
+ .go{border:0;border-radius:12px;padding:12px 22px;font-size:15px;font-weight:600;cursor:pointer;color:#fff;
132
+ background:linear-gradient(135deg,var(--primary),var(--accent));transition:.15s}
133
+ .go:hover{filter:brightness(1.08)}.go:disabled{opacity:.5;cursor:default}
134
+ .out{margin:18px 0 8px;display:none}
135
+ .out.show{display:block}
136
+ .out .bar{display:flex;align-items:center;justify-content:space-between;margin-bottom:8px}
137
+ .out .bar h2{margin:0;font-size:14px;color:var(--muted);font-weight:600;letter-spacing:.4px;text-transform:uppercase}
138
+ .copy{border:1px solid var(--line);background:#fff;border-radius:9px;padding:6px 12px;font-size:12.5px;cursor:pointer;color:var(--primary)}
139
+ .copy:hover{border-color:var(--accent)}
140
+ #result{white-space:pre-wrap;line-height:1.6;font-size:15px;min-height:24px}
141
+ .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}
142
+ .typing span:nth-child(2){animation-delay:.2s}.typing span:nth-child(3){animation-delay:.4s}
143
+ @keyframes bd{0%,60%,100%{transform:translateY(0);opacity:.35}30%{transform:translateY(-5px);opacity:1}}
144
+ .foot{text-align:center;color:var(--muted);font-size:11px;padding:16px 0 22px}.foot b{color:#6b7290}
145
+ </style></head>
146
+ <body><div class="app">
147
+ <header><h1>📝 Summarizer</h1><p>Paste an article, email, or notes — or drop in a link — and get the gist in seconds.</p></header>
148
+ <div class="card">
149
+ <textarea id="src" placeholder="Paste text here…"></textarea>
150
+ <div class="divide">or summarize a link</div>
151
+ <div class="urlrow">
152
+ <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>
153
+ <input id="url" placeholder="https://…" autocomplete="off">
154
+ </div>
155
+ <div class="controls">
156
+ <div class="seg" id="seg">
157
+ <button data-v="brief">Brief</button>
158
+ <button data-v="standard" class="on">Standard</button>
159
+ <button data-v="detailed">Detailed</button>
160
+ </div>
161
+ <button class="go" id="go" onclick="run()">Summarize</button>
162
+ </div>
163
+ </div>
164
+ <div class="out" id="out">
165
+ <div class="bar"><h2>Summary</h2><button class="copy" id="copy" onclick="copyOut()" style="display:none">Copy</button></div>
166
+ <div class="card"><div id="result"></div></div>
167
+ </div>
168
+ <div class="foot">Faithful summaries · your text isn't stored · <b>GritAI</b></div>
169
+ </div><script>
170
+ let length="standard",busy=false;
171
+ const src=document.getElementById('src'),url=document.getElementById('url'),go=document.getElementById('go'),
172
+ out=document.getElementById('out'),result=document.getElementById('result'),copy=document.getElementById('copy');
173
+ document.getElementById('seg').addEventListener('click',e=>{const b=e.target.closest('button');if(!b)return;
174
+ length=b.dataset.v;[...seg.children].forEach(x=>x.classList.toggle('on',x===b));});
175
+ function copyOut(){navigator.clipboard.writeText(result.textContent);copy.textContent='Copied!';setTimeout(()=>copy.textContent='Copy',1400);}
176
+ async function run(){if(busy)return;const text=src.value.trim(),u=url.value.trim();
177
+ if(!text&&!u){src.focus();return;}
178
+ busy=true;go.disabled=true;go.textContent='Summarizing…';out.classList.add('show');copy.style.display='none';
179
+ result.innerHTML='<span class="typing"><span></span><span></span><span></span></span>';
180
+ let full='';
181
+ try{
182
+ const r=await fetch('/api/summarize',{method:'POST',headers:{'Content-Type':'application/json'},
183
+ body:JSON.stringify({text,url:u,length})});
184
+ const rd=r.body.getReader(),dec=new TextDecoder();let buf='';
185
+ while(true){const {value,done}=await rd.read();if(done)break;buf+=dec.decode(value,{stream:true});
186
+ let i;while((i=buf.indexOf('\\n\\n'))>=0){const line=buf.slice(0,i).trim();buf=buf.slice(i+2);
187
+ if(!line.startsWith('data:'))continue;const p=line.slice(5).trim();if(p==='[DONE]')continue;
188
+ try{const o=JSON.parse(p);if(o.reset){full='';result.textContent='';}
189
+ else if(o.t){full+=o.t;result.textContent=full;}}catch(e){}}}
190
+ if(full.trim())copy.style.display='inline-block';else result.textContent='No summary produced — try again.';
191
+ }catch(e){result.textContent='Sorry — something went wrong. Please try again.';}
192
+ busy=false;go.disabled=false;go.textContent='Summarize';}
193
+ </script></body></html>"""
194
+
195
+ if __name__ == "__main__":
196
+ backend = "Claude API" if ANTHROPIC_KEY else f"Ollama ({OLLAMA_MODEL} @ {OLLAMA_URL})"
197
+ print(f"Text Summarizer on http://127.0.0.1:{PORT} [backend: {backend}]", flush=True)
198
+ app.run(host="0.0.0.0", port=PORT, threaded=True)
demo.png ADDED
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ flask>=3.0
2
+ requests>=2.31
3
+ anthropic>=0.40
4
+ beautifulsoup4>=4.12