diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..7e0b67d
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,27 @@
+name: CI
+
+on:
+ push:
+ branches: [main, Testing]
+ pull_request:
+ branches: [main]
+
+jobs:
+ check:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Set up Python
+ uses: actions/setup-python@v5
+ with:
+ python-version: "3.12"
+
+ - name: Install dependencies
+ run: pip install -r requirements.txt
+
+ - name: Syntax check
+ run: python -m py_compile app.py generator.py
+
+ - name: Import smoke test
+ run: python -c "import app; print('app imports OK')"
diff --git a/.gitignore b/.gitignore
index b056356..5f1f6f2 100644
--- a/.gitignore
+++ b/.gitignore
@@ -15,5 +15,11 @@ data/
Thumbs.db
.vscode/
+# Local database (your drafts library)
+*.db
+
+# Generated logo
+logo.png
+
# Never commit secrets
.env
diff --git a/README.md b/README.md
index 628bc0b..b2c29c9 100644
--- a/README.md
+++ b/README.md
@@ -36,6 +36,9 @@ Set these as environment variables before starting the server:
| `PEXELS_API_KEY` | Better stock images (falls back to Openverse without it) |
| `LLM_MODEL` | Override the Claude model (default: `claude-sonnet-4-5`) |
| `PORT` | Change the web server port (default: 5000) |
+| `LINKEDIN_CLIENT_ID` / `LINKEDIN_CLIENT_SECRET` | From your LinkedIn developer app — enables "Connect LinkedIn" and one-click posting |
+| `BASE_URL` | Public URL of the site (e.g. `https://postpilot-nsks.onrender.com`), used for the OAuth redirect. Default: `http://localhost:5000` |
+| `SECRET_KEY` | Random string for login sessions (generate one; without it, logins reset on every server restart) |
PowerShell example:
diff --git a/app.js b/app.js
index 3ea2c6c..fca511b 100644
--- a/app.js
+++ b/app.js
@@ -20,6 +20,35 @@
})
.catch(() => { $("llm-badge").textContent = "offline"; });
+ // LinkedIn connection state
+ let liConnected = false;
+ const liBtn = $("li-connect");
+
+ function refreshLinkedIn() {
+ fetch("/api/linkedin/status")
+ .then((r) => r.json())
+ .then((s) => {
+ if (!s.configured) { liBtn.style.display = "none"; return; }
+ liBtn.style.display = "";
+ liConnected = s.connected;
+ if (s.connected) {
+ liBtn.textContent = `LinkedIn: ${s.name} ✓ (disconnect)`;
+ liBtn.onclick = () => {
+ fetch("/api/linkedin/logout", { method: "POST" }).then(refreshLinkedIn);
+ };
+ } else {
+ liBtn.textContent = "Connect LinkedIn";
+ liBtn.onclick = () => { window.location.href = "/auth/linkedin"; };
+ }
+ })
+ .catch(() => {});
+ }
+ refreshLinkedIn();
+
+ // Surface OAuth errors passed back as ?li_error=...
+ const liError = new URLSearchParams(window.location.search).get("li_error");
+ if (liError) setError("LinkedIn sign-in failed: " + liError);
+
function setError(msg) {
errorBox.textContent = msg;
errorBox.classList.toggle("visible", !!msg);
@@ -67,7 +96,11 @@
card.innerHTML = `
${imgHtml}
${esc(d.text)}
@@ -85,6 +118,57 @@
});
});
+ const saveBtn = card.querySelector(".save-btn");
+ saveBtn.addEventListener("click", async () => {
+ saveBtn.disabled = true;
+ try {
+ const r = await fetch("/api/library/save", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(d),
+ });
+ if (!r.ok) throw new Error((await r.json()).error || "Save failed");
+ saveBtn.textContent = "Saved ✓";
+ saveBtn.classList.add("copied");
+ } catch (e) {
+ saveBtn.disabled = false;
+ setError(e.message);
+ }
+ });
+
+ const liPostBtn = card.querySelector(".li-post-btn");
+ liPostBtn.addEventListener("click", async () => {
+ if (!liConnected) {
+ if (confirm("You need to connect your LinkedIn account first. Connect now?"))
+ window.location.href = "/auth/linkedin";
+ return;
+ }
+ if (!confirm("Post this draft to your LinkedIn profile? It will be publicly visible."))
+ return;
+ liPostBtn.disabled = true;
+ liPostBtn.textContent = "Posting…";
+ try {
+ const r = await fetch("/api/linkedin/post", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ text: d.text,
+ image_src: d.image ? d.image.src : "",
+ draft_id: d.id || "",
+ }),
+ });
+ const res = await r.json();
+ if (!r.ok) throw new Error(res.error || "Posting failed");
+ liPostBtn.textContent = res.with_image ? "Posted with image ✓" : "Posted ✓";
+ liPostBtn.classList.add("copied");
+ } catch (e) {
+ liPostBtn.disabled = false;
+ liPostBtn.textContent = "Post to LinkedIn";
+ setError(e.message);
+ if (String(e.message).includes("reconnect")) refreshLinkedIn();
+ }
+ });
+
results.appendChild(card);
});
}
diff --git a/app.py b/app.py
index 49642d6..c56701d 100644
--- a/app.py
+++ b/app.py
@@ -9,15 +9,111 @@
PEXELS_API_KEY, LLM_MODEL, PORT.
"""
import os
+import secrets
+import shutil
+import sqlite3
import threading
import uuid
+from datetime import datetime, timezone
-from flask import Flask, jsonify, request, send_from_directory
+import requests
+from flask import (Flask, jsonify, redirect, request, send_from_directory,
+ session)
+
+
+def _load_dotenv(path=".env"):
+ """Load KEY=VALUE lines from a local .env file (no dependency needed).
+ Real environment variables always win over .env values."""
+ try:
+ with open(path, "r", encoding="utf-8") as f:
+ for line in f:
+ line = line.strip()
+ if not line or line.startswith("#") or "=" not in line:
+ continue
+ k, _, v = line.partition("=")
+ k, v = k.strip(), v.strip().strip('"').strip("'")
+ if k and v and k not in os.environ:
+ os.environ[k] = v
+ except OSError:
+ pass
+
+
+_load_dotenv(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".env"))
import generator as g
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
app = Flask(__name__, static_folder=None)
+# Needed for login sessions. Set SECRET_KEY in production so logins
+# survive server restarts.
+app.secret_key = os.getenv("SECRET_KEY") or secrets.token_hex(32)
+# Keep users signed in for ~60 days (matches LinkedIn token lifetime)
+from datetime import timedelta
+app.permanent_session_lifetime = timedelta(days=60)
+
+# --- Drafts library (SQLite) ----------------------------------------------
+DB_PATH = os.path.join(BASE_DIR, "postpilot.db")
+
+
+def _db():
+ conn = sqlite3.connect(DB_PATH)
+ conn.row_factory = sqlite3.Row
+ return conn
+
+
+def _init_db():
+ with _db() as c:
+ c.execute("""CREATE TABLE IF NOT EXISTS posts (
+ id TEXT PRIMARY KEY,
+ created TEXT,
+ text TEXT,
+ source_title TEXT, source_url TEXT, source_date TEXT,
+ image_src TEXT, image_source TEXT, image_license TEXT,
+ image_attribution TEXT, image_page TEXT,
+ status TEXT DEFAULT 'saved',
+ posted_at TEXT)""")
+
+
+_init_db()
+
+
+def _save_draft(draft):
+ img = draft.get("image") or {}
+ with _db() as c:
+ c.execute(
+ "INSERT INTO posts (id, created, text, source_title, source_url, "
+ "source_date, image_src, image_source, image_license, "
+ "image_attribution, image_page, status) "
+ "VALUES (?,?,?,?,?,?,?,?,?,?,?,'saved')",
+ (draft["id"], draft["created"], draft["text"],
+ draft["source"].get("title", ""), draft["source"].get("url", ""),
+ draft["source"].get("date", ""),
+ img.get("src", ""), img.get("source", ""),
+ img.get("license", ""), img.get("attribution", ""),
+ img.get("page", "")))
+
+
+def _row_to_draft(r):
+ d = {"id": r["id"], "created": r["created"], "text": r["text"],
+ "status": r["status"], "posted_at": r["posted_at"],
+ "source": {"title": r["source_title"], "url": r["source_url"],
+ "date": r["source_date"]},
+ "image": None}
+ if r["image_src"]:
+ d["image"] = {"src": r["image_src"], "source": r["image_source"],
+ "license": r["image_license"],
+ "attribution": r["image_attribution"],
+ "page": r["image_page"]}
+ return d
+
+# --- LinkedIn OAuth config (set these env vars to enable posting) ---
+LI_CLIENT_ID = os.getenv("LINKEDIN_CLIENT_ID", "")
+LI_CLIENT_SECRET = os.getenv("LINKEDIN_CLIENT_SECRET", "")
+BASE_URL = os.getenv("BASE_URL", "http://localhost:5000").rstrip("/")
+LI_REDIRECT_URI = BASE_URL + "/auth/callback"
+app.config.update(SESSION_COOKIE_SECURE=BASE_URL.startswith("https"),
+ SESSION_COOKIE_HTTPONLY=True,
+ SESSION_COOKIE_SAMESITE="Lax")
# In-memory job store: jobs run in a thread so the browser can poll progress
# instead of holding one long request open.
@@ -30,8 +126,10 @@ def _job_update(job_id, **kw):
JOBS[job_id].update(kw)
-def _serialize_draft(text, topic, img):
+def _serialize_draft(text, topic, img, draft_id):
d = {
+ "id": draft_id,
+ "created": datetime.now(timezone.utc).isoformat(timespec="seconds"),
"text": text,
"source": {
"title": topic.primary.title,
@@ -55,6 +153,51 @@ def _serialize_draft(text, topic, img):
return d
+def _rank_topics_for_voice(content, voice, transcript_text, n):
+ """Boost the weight of news signals most relevant to the user's
+ themes/opinions so select_topics() favors them over generic top headlines."""
+ primaries = [s for s in content if s.kind in ("ai_news", "arxiv")] or list(content)
+ if len(primaries) <= n:
+ return
+ interests = "; ".join((voice.themes or []) + (voice.opinions or []))
+ if not interests.strip():
+ interests = (transcript_text or "")[:600]
+ if not interests.strip():
+ return
+
+ if g.llm_available():
+ try:
+ lines = "\n".join(f"{i}. {s.title or s.short(80)}"
+ for i, s in enumerate(primaries))
+ raw = g.llm_complete(
+ f"A person cares about these topics and opinions:\n{interests}\n\n"
+ f"Candidate news headlines:\n{lines}\n\n"
+ f"Return ONLY a JSON array with the indices of the {n} headlines "
+ "most relevant to what this person cares about, most relevant "
+ "first. Example: [4, 0, 7]",
+ system="You rank news headlines by relevance to a person's "
+ "interests. Output only the JSON array.",
+ max_tokens=100, temperature=0.1)
+ import json as _json
+ import re as _re
+ cleaned = _re.sub(r"^```[a-zA-Z]*\n?|\n?```$", "", raw.strip())
+ try:
+ idx = [int(x) for x in _json.loads(cleaned)]
+ except Exception:
+ idx = [int(x) for x in _re.findall(r"\d+", cleaned)]
+ for rank, i in enumerate(idx[:n]):
+ if 0 <= i < len(primaries):
+ primaries[i].weight += 100 - rank
+ return
+ except Exception as e:
+ print(f" [warn] LLM topic ranking failed ({e}); using keywords.")
+
+ # Fallback: keyword overlap between interests and each headline
+ key = g._keywords(interests + " " + (transcript_text or ""))
+ for s in primaries:
+ s.weight += 1.5 * len(key & g._keywords(s.title + " " + s.text))
+
+
def _run_job(job_id, settings, transcript_text):
try:
_job_update(job_id, progress="Gathering live AI news...")
@@ -68,23 +211,40 @@ def _run_job(job_id, settings, transcript_text):
_job_update(job_id, progress="Building your voice profile...")
voice = g.build_voice_profile(voice_signals)
- _job_update(job_id, progress="Selecting topics...")
+ _job_update(job_id, progress="Matching news to your topics...")
+ try:
+ _rank_topics_for_voice(content, voice, transcript_text,
+ settings.variants)
+ except Exception as e:
+ print(f" [warn] topic ranking failed ({e}).")
topics = g.select_topics(content, settings.variants)
drafts = []
+ used_images = set()
for i, topic in enumerate(topics, 1):
_job_update(job_id, progress=f"Writing variant {i} of {len(topics)}...")
text = g.format_post(g.generate_post(topic, voice, settings),
max_chars=getattr(settings, "max_chars", 2900))
+ draft_id = uuid.uuid4().hex[:12]
img = None
if settings.images:
try:
_job_update(job_id, progress=f"Finding image for variant {i}...")
- q, _alt = g.build_image_query(topic)
- img = g.find_image(q, i)
+ q, _alt = g.build_image_query(topic, post_text=text)
+ img = g.find_image(q, i, context=text,
+ exclude=used_images)
+ if img and img.get("url"):
+ used_images.add(img["url"])
+ # Give the image a unique name so library drafts keep
+ # their picture after later runs overwrite variant-N.jpg
+ if img and img.get("local_path"):
+ unique = os.path.join(BASE_DIR, g.IMAGE_DIR,
+ f"{draft_id}.jpg")
+ shutil.copyfile(img["local_path"], unique)
+ img["local_path"] = unique
except Exception as e:
print(f" [warn] image step failed ({e}).")
- drafts.append(_serialize_draft(text, topic, img))
+ drafts.append(_serialize_draft(text, topic, img, draft_id))
result = {
"drafts": drafts,
@@ -152,6 +312,7 @@ def _wc(key, default):
transcript = g.SAMPLE_TRANSCRIPT
settings = g.Settings(tone=tone, length=length_key, variants=variants,
news_lookback_hours=lookback,
+ max_news_items=12,
images=bool(data.get("images", True)))
# Extra attrs consumed by _run_job / generator.generate_post
settings.max_tokens = min(8000, max(700, int(word_max * 2.2) + 300))
@@ -175,6 +336,43 @@ def api_status(job_id):
return jsonify(job)
+@app.post("/api/library/save")
+def api_library_save():
+ d = request.get_json(silent=True) or {}
+ if not d.get("id") or not (d.get("text") or "").strip():
+ return jsonify({"error": "Invalid draft."}), 400
+ d.setdefault("source", {})
+ d.setdefault("created",
+ datetime.now(timezone.utc).isoformat(timespec="seconds"))
+ try:
+ _save_draft(d)
+ except sqlite3.IntegrityError:
+ return jsonify({"ok": True, "already_saved": True})
+ return jsonify({"ok": True})
+
+
+@app.get("/api/library")
+def api_library():
+ with _db() as c:
+ rows = c.execute("SELECT * FROM posts ORDER BY created DESC").fetchall()
+ return jsonify({"drafts": [_row_to_draft(r) for r in rows]})
+
+
+@app.post("/api/library//delete")
+def api_library_delete(pid):
+ with _db() as c:
+ row = c.execute("SELECT image_src FROM posts WHERE id=?", (pid,)).fetchone()
+ c.execute("DELETE FROM posts WHERE id=?", (pid,))
+ # Clean up the image file if it was a locally stored one
+ if row and (row["image_src"] or "").startswith("/images/"):
+ p = os.path.join(BASE_DIR, g.IMAGE_DIR, os.path.basename(row["image_src"]))
+ try:
+ os.remove(p)
+ except OSError:
+ pass
+ return jsonify({"ok": True})
+
+
@app.get("/api/health")
def api_health():
return jsonify({"ok": True, "llm": g.llm_available(),
@@ -182,6 +380,173 @@ def api_health():
"tavily": bool(g.TAVILY_API_KEY)})
+# --------------------------- LinkedIn ------------------------------------
+
+@app.get("/auth/linkedin")
+def auth_linkedin():
+ if not LI_CLIENT_ID:
+ return ("LinkedIn is not configured on this server "
+ "(missing LINKEDIN_CLIENT_ID).", 503)
+ state = secrets.token_urlsafe(16)
+ session["li_state"] = state
+ from urllib.parse import urlencode
+ params = urlencode({
+ "response_type": "code",
+ "client_id": LI_CLIENT_ID,
+ "redirect_uri": LI_REDIRECT_URI,
+ "state": state,
+ "scope": "openid profile w_member_social",
+ })
+ return redirect("https://www.linkedin.com/oauth/v2/authorization?" + params)
+
+
+@app.get("/auth/callback")
+def auth_callback():
+ err = request.args.get("error_description") or request.args.get("error")
+ if err:
+ return redirect("/app?li_error=" + err[:200])
+ if request.args.get("state") != session.pop("li_state", None):
+ return redirect("/app?li_error=state_mismatch")
+ code = request.args.get("code", "")
+ try:
+ r = requests.post("https://www.linkedin.com/oauth/v2/accessToken",
+ data={"grant_type": "authorization_code",
+ "code": code,
+ "redirect_uri": LI_REDIRECT_URI,
+ "client_id": LI_CLIENT_ID,
+ "client_secret": LI_CLIENT_SECRET},
+ timeout=20)
+ r.raise_for_status()
+ token = r.json()["access_token"]
+ u = requests.get("https://api.linkedin.com/v2/userinfo",
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=20)
+ u.raise_for_status()
+ info = u.json()
+ session.permanent = True
+ session["li_token"] = token
+ session["li_sub"] = info.get("sub", "")
+ session["li_name"] = info.get("name", "LinkedIn user")
+ return redirect("/app")
+ except Exception as e:
+ return redirect("/app?li_error=" + str(e)[:200])
+
+
+@app.get("/api/linkedin/status")
+def linkedin_status():
+ return jsonify({
+ "configured": bool(LI_CLIENT_ID),
+ "connected": bool(session.get("li_token")),
+ "name": session.get("li_name", ""),
+ })
+
+
+@app.post("/api/linkedin/logout")
+def linkedin_logout():
+ for k in ("li_token", "li_sub", "li_name"):
+ session.pop(k, None)
+ return jsonify({"ok": True})
+
+
+def _li_upload_image(token, author_urn, local_path):
+ """Register + upload an image asset. Returns the asset URN."""
+ reg = requests.post(
+ "https://api.linkedin.com/v2/assets?action=registerUpload",
+ headers={"Authorization": f"Bearer {token}",
+ "X-Restli-Protocol-Version": "2.0.0"},
+ json={"registerUploadRequest": {
+ "recipes": ["urn:li:digitalmediaRecipe:feedshare-image"],
+ "owner": author_urn,
+ "serviceRelationships": [{
+ "relationshipType": "OWNER",
+ "identifier": "urn:li:userGeneratedContent"}]}},
+ timeout=20)
+ reg.raise_for_status()
+ v = reg.json()["value"]
+ upload_url = v["uploadMechanism"][
+ "com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest"]["uploadUrl"]
+ asset = v["asset"]
+ with open(local_path, "rb") as f:
+ up = requests.put(upload_url, data=f.read(),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=60)
+ up.raise_for_status()
+ return asset
+
+
+@app.post("/api/linkedin/post")
+def linkedin_post():
+ token = session.get("li_token")
+ sub = session.get("li_sub")
+ if not token or not sub:
+ return jsonify({"error": "Not connected to LinkedIn."}), 401
+ data = request.get_json(silent=True) or {}
+ text = (data.get("text") or "").strip()
+ if not text:
+ return jsonify({"error": "Post text is empty."}), 400
+ author = f"urn:li:person:{sub}"
+
+ media = []
+ category = "NONE"
+ image_src = data.get("image_src") or ""
+ if image_src.startswith("/images/"):
+ local = os.path.join(BASE_DIR, g.IMAGE_DIR,
+ os.path.basename(image_src))
+ if os.path.exists(local):
+ try:
+ asset = _li_upload_image(token, author, local)
+ media = [{"status": "READY", "media": asset}]
+ category = "IMAGE"
+ except Exception as e:
+ print(f" [warn] LinkedIn image upload failed ({e}); "
+ f"posting text only.")
+
+ body = {
+ "author": author,
+ "lifecycleState": "PUBLISHED",
+ "specificContent": {"com.linkedin.ugc.ShareContent": {
+ "shareCommentary": {"text": text},
+ "shareMediaCategory": category,
+ **({"media": media} if media else {}),
+ }},
+ "visibility": {"com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC"},
+ }
+ try:
+ r = requests.post("https://api.linkedin.com/v2/ugcPosts",
+ headers={"Authorization": f"Bearer {token}",
+ "X-Restli-Protocol-Version": "2.0.0"},
+ json=body, timeout=30)
+ if r.status_code == 401:
+ for k in ("li_token", "li_sub", "li_name"):
+ session.pop(k, None)
+ return jsonify({"error": "LinkedIn session expired - "
+ "please reconnect."}), 401
+ r.raise_for_status()
+ post_id = r.headers.get("x-restli-id") or r.json().get("id", "")
+ # Mark the library draft as posted
+ draft_id = data.get("draft_id")
+ if draft_id:
+ try:
+ with _db() as c:
+ c.execute("UPDATE posts SET status='posted', posted_at=? "
+ "WHERE id=?",
+ (datetime.now(timezone.utc).isoformat(
+ timespec="seconds"), draft_id))
+ except Exception as e:
+ print(f" [warn] could not mark draft posted ({e}).")
+ return jsonify({"ok": True, "post_id": post_id,
+ "with_image": category == "IMAGE"})
+ except requests.HTTPError as e:
+ detail = ""
+ try:
+ detail = e.response.json().get("message", "")[:300]
+ except Exception:
+ pass
+ return jsonify({"error": f"LinkedIn rejected the post. {detail}"}), 502
+ except Exception as e:
+ return jsonify({"error": str(e)[:300]}), 502
+
+
# --------------------------- Static pages ---------------------------------
@app.get("/")
@@ -194,6 +559,11 @@ def generator_page():
return send_from_directory(BASE_DIR, "generator.html")
+@app.get("/library")
+def library_page():
+ return send_from_directory(BASE_DIR, "library.html")
+
+
@app.get("/styles.css")
def styles():
return send_from_directory(BASE_DIR, "styles.css")
diff --git a/generator.html b/generator.html
index 4b519a0..b870606 100644
--- a/generator.html
+++ b/generator.html
@@ -14,7 +14,9 @@
Features
How it works
Generator
+ Library
checking…
+
diff --git a/generator.py b/generator.py
index 3e8396d..742fb4e 100644
--- a/generator.py
+++ b/generator.py
@@ -176,7 +176,9 @@ def build_voice_profile(voice_signals):
raw = llm_complete("Read the material and return ONLY a JSON object with keys "
"`summary` (2-3 sentences), `themes` (array), `opinions` (array of stances "
"they actually expressed), `style_notes` (array about sentence length, tone, "
- "hooks, hashtag habits).\n\n" + corpus,
+ "hooks, hashtag habits). In style_notes, capture voice as vocabulary, rhythm "
+ "and attitude - IGNORE mechanical sloppiness like lowercase typing or missing "
+ "apostrophes; that comes from quick note-taking, not their published style.\n\n" + corpus,
system="You profile how a person thinks and writes so someone could draft in "
"their voice. Be specific. Don't invent beliefs.", max_tokens=1200, temperature=0.3)
d = _loads_lenient(raw)
@@ -228,15 +230,18 @@ def _keywords(text):
# ---------------------------------------------------------------------------
# IMAGE SOURCING (license-safe: Openverse free / Pexels optional)
# ---------------------------------------------------------------------------
-def build_image_query(topic):
+def build_image_query(topic, post_text=""):
seed = topic.primary.title or topic.primary.short(80)
+ ctx = f"HEADLINE: {seed}"
+ if post_text:
+ ctx += f"\n\nTHE POST THE IMAGE WILL ACCOMPANY:\n{post_text[:500]}"
if llm_available():
try:
raw = llm_complete(
"Give a SHORT stock-photo search query (3-6 words, generic and "
"conceptual - NO named people, companies, or logos, so it's "
- "license-safe) that visually fits this news, plus one line of alt "
- 'text. Return ONLY JSON {"query":..., "alt":...}.\n\nHEADLINE: ' + seed,
+ "license-safe) that visually fits the post below, plus one line "
+ 'of alt text. Return ONLY JSON {"query":..., "alt":...}.\n\n' + ctx,
system="You choose safe, relevant stock-photo search terms.",
max_tokens=200, temperature=0.3)
d = _loads_lenient(raw)
@@ -245,46 +250,69 @@ def build_image_query(topic):
except Exception as e:
print(f" [warn] image query via LLM failed ({e}); using keywords.")
return (" ".join(list(_keywords(seed))[:4]) or "technology"), seed
-def _search_pexels(query):
- if requests is None or not PEXELS_API_KEY: return None
+def _search_pexels(query, count=1):
+ if requests is None or not PEXELS_API_KEY: return []
try:
r = requests.get("https://api.pexels.com/v1/search",
headers={"Authorization": PEXELS_API_KEY},
- params={"query": query, "per_page": 1, "orientation": "landscape"}, timeout=20)
+ params={"query": query, "per_page": count, "orientation": "landscape"}, timeout=20)
r.raise_for_status()
- photos = r.json().get("photos", [])
- if not photos: return None
- p = photos[0]
- return {"url": p["src"]["large"], "source": "Pexels",
+ return [{"url": p["src"]["large"], "source": "Pexels",
"license": "Pexels License (free commercial use; attribution optional)",
"attribution": f"Photo by {p.get('photographer','')} on Pexels",
- "page": p.get("url", "")}
+ "page": p.get("url", ""), "alt": p.get("alt", "")}
+ for p in r.json().get("photos", [])]
except Exception as e:
print(f" [warn] Pexels search failed ({e}).")
- return None
-def _search_openverse(query):
- if requests is None: return None
+ return []
+def _search_openverse(query, count=1):
+ if requests is None: return []
try:
r = requests.get("https://api.openverse.org/v1/images/",
- params={"q": query, "page_size": 1, "license_type": "commercial"},
+ params={"q": query, "page_size": count, "license_type": "commercial"},
headers={"User-Agent": "linkedin-post-generator"}, timeout=20)
r.raise_for_status()
- results = r.json().get("results", [])
- if not results: return None
- it = results[0]
- lic = f"{it.get('license','')} {it.get('license_version','')}".strip().upper()
- return {"url": it.get("url", ""), "source": it.get("source", "Openverse"),
- "license": f"CC {lic}".strip() + " (verify credit requirement)",
- "attribution": it.get("attribution") or
- f"{it.get('creator','Unknown')} via {it.get('source','Openverse')}",
- "page": it.get("foreign_landing_url", "")}
+ out = []
+ for it in r.json().get("results", []):
+ lic = f"{it.get('license','')} {it.get('license_version','')}".strip().upper()
+ out.append({"url": it.get("url", ""), "source": it.get("source", "Openverse"),
+ "license": f"CC {lic}".strip() + " (verify credit requirement)",
+ "attribution": it.get("attribution") or
+ f"{it.get('creator','Unknown')} via {it.get('source','Openverse')}",
+ "page": it.get("foreign_landing_url", ""),
+ "alt": it.get("title", "")})
+ return out
except Exception as e:
print(f" [warn] Openverse search failed ({e}).")
- return None
-def find_image(query, index):
- """Return dict {local_path, source, license, attribution, page, url, query} or None."""
- info = _search_pexels(query) or _search_openverse(query)
- if not info: return None
+ return []
+def _pick_best_image(candidates, context):
+ """Ask the LLM which candidate's description best matches the post."""
+ if len(candidates) < 2 or not context or not llm_available():
+ return candidates[0]
+ try:
+ lines = "\n".join(f"{i}. {c.get('alt') or c.get('page') or c.get('url')}"
+ for i, c in enumerate(candidates))
+ raw = llm_complete(
+ f"THE POST:\n{context[:400]}\n\nCANDIDATE IMAGES (descriptions):\n"
+ f"{lines}\n\nReply with ONLY the number of the image that best "
+ "matches the post's topic and tone.",
+ system="You pick the most relevant stock photo. Output one number.",
+ max_tokens=10, temperature=0.0)
+ m = re.search(r"\d+", raw)
+ i = int(m.group(0)) if m else 0
+ return candidates[i] if 0 <= i < len(candidates) else candidates[0]
+ except Exception as e:
+ print(f" [warn] image ranking failed ({e}); using first result.")
+ return candidates[0]
+def find_image(query, index, context="", exclude=None):
+ """Return dict {local_path, source, license, attribution, page, url, query} or None.
+ `exclude` is a set of image URLs already used by other variants."""
+ candidates = _search_pexels(query, 15) or _search_openverse(query, 15)
+ if exclude:
+ fresh = [c for c in candidates if c.get("url") not in exclude]
+ if fresh: candidates = fresh
+ if not candidates: return None
+ info = _pick_best_image(candidates, context)
info["query"] = query
info["local_path"] = ""
if requests is not None and info.get("url"):
@@ -324,11 +352,26 @@ def generate_post(topic, voice, s: Settings):
- {TONE_GUIDE.get(s.tone, TONE_GUIDE['insightful'])}
- Length: {LENGTH_GUIDE.get(s.length, LENGTH_GUIDE['medium'])}
- Tie the news to one of their themes or opinions explicitly.
-- Short paragraphs, blank line between them. Plain text only - NO markdown.
+- Flawless grammar, spelling, and punctuation. Complete sentences only -
+ no fragments unless used deliberately once for punch.
+- CRITICAL: their "voice" means their ideas, opinions, and vocabulary - NOT
+ their typing habits. Even if their source material is lowercase, missing
+ apostrophes, or sloppily punctuated, YOU always write with standard
+ capitalization (every sentence starts with a capital letter) and correct
+ apostrophes (don't, isn't, they're). No exceptions.
+- Structure: paragraphs of 1-3 sentences each, with a blank line between
+ EVERY paragraph. Never write a wall of text. One idea per paragraph, in
+ logical order: hook, context, insight, takeaway, question.
+- Plain text only - NO markdown, NO bullet characters, NO emoji spam.
- End with a genuine question. Finish with 3-5 hashtags on the last line.
+- Before finishing, re-read the post and fix any grammatical or flow issues.
- Output ONLY the post text."""
return llm_complete(prompt, system="You are a ghostwriter who writes authentic, "
- "human LinkedIn posts. You never sound like an AI.",
+ "human LinkedIn posts. You never sound like an AI. You ALWAYS use standard "
+ "capitalization and punctuation: every sentence starts with a capital letter, "
+ "contractions have apostrophes (don't, isn't, they're), proper nouns are "
+ "capitalized (Microsoft, ChatGPT, AI). A person's voice is their ideas and "
+ "word choice, never sloppy mechanics.",
max_tokens=getattr(s, "max_tokens", 700), temperature=0.8)
except Exception as e:
print(f" [warn] LLM generation failed ({e}); using template.")
@@ -347,6 +390,11 @@ def format_post(text, max_chars=2900):
text = re.sub(r"\[([^\]]+)\]\(([^)]+)\)", r"\1 (\2)", text)
text = text.replace("`", "")
text = re.sub(r"\n{3,}", "\n\n", text).strip()
+ # Safety net: capitalize the first letter of every sentence/paragraph
+ # and fix standalone "i", even if the model mimicked lowercase notes.
+ text = re.sub(r"(^|[.!?]\s+|\n\s*)([a-z])",
+ lambda m: m.group(1) + m.group(2).upper(), text)
+ text = re.sub(r"\bi\b", "I", text)
if len(text) > max_chars: text = text[:max_chars].rsplit("\n", 1)[0].rstrip()
return text
def save_run(drafts, s: Settings):
diff --git a/index.html b/index.html
index a9c02bd..dc5f48f 100644
--- a/index.html
+++ b/index.html
@@ -14,6 +14,7 @@
Features
How it works
Examples
+ Library
Open generator
diff --git a/library.html b/library.html
new file mode 100644
index 0000000..b645303
--- /dev/null
+++ b/library.html
@@ -0,0 +1,157 @@
+
+
+
+
+
+ Library — PostPilot
+
+
+
+
+
+
+
+
Your drafts
+
Drafts you save from the generator live here. Post the keepers, delete the rest.
+
+
+
+
+ Nothing saved yet.
Generate some posts and hit "Save to library" on the ones worth keeping.
+
+
+
+
+
+
+
+
+
diff --git a/make_logo.py b/make_logo.py
new file mode 100644
index 0000000..cc7101d
--- /dev/null
+++ b/make_logo.py
@@ -0,0 +1,13 @@
+"""Generate a simple square PostPilot logo (logo.png). Run: py make_logo.py"""
+from PIL import Image, ImageDraw, ImageFont
+
+img = Image.new("RGB", (400, 400), "#0f1117")
+d = ImageDraw.Draw(img)
+d.rounded_rectangle([20, 20, 380, 380], radius=70, fill="#4f8ff7")
+try:
+ font = ImageFont.truetype("arialbd.ttf", 220)
+except Exception:
+ font = ImageFont.load_default()
+d.text((200, 185), "P", font=font, anchor="mm", fill="white")
+img.save("logo.png")
+print("Saved logo.png - upload this on the LinkedIn app form.")