-
leadhound
+
leadhound

Sign in

diff --git a/leadhound/dashboard/logo.svg b/leadhound/dashboard/logo.svg new file mode 100644 index 0000000..668fdd0 --- /dev/null +++ b/leadhound/dashboard/logo.svg @@ -0,0 +1 @@ + diff --git a/leadhound/dashboard/plan.js b/leadhound/dashboard/plan.js index 7efde57..c94f34e 100644 --- a/leadhound/dashboard/plan.js +++ b/leadhound/dashboard/plan.js @@ -63,8 +63,8 @@ export function openPlan() { el('div', { class: 'sheet-h' }, el('div', { class: 'ai' }, icon('check')), el('div', {}, el('h3', {}, t('plan.title')), el('p', {}, status)), el('button', { class: 'x', 'aria-label': t('sheet.close'), onclick: () => d.close() }, icon('x'))), p.need_signup && el('div', { class: 'buy' }, signup, serr, el('p', { class: 'sd' }, t('plan.signup_note'))), - el('ul', { class: 'perks' }, ['plan.f1', 'plan.f2', 'plan.f3', 'plan.f4', 'plan.f5'].map(k => el('li', {}, icon('check'), t(k)))), - el('p', { class: 'sd' }, t('plan.free_note', { n: p.free_searches, m: p.free_max_leads })), + el('ul', { class: 'perks' }, ['plan.f1', 'plan.f2', 'plan.f3', 'plan.f4'].map(k => el('li', {}, icon('check'), t(k)))), + el('p', { class: 'sd' }, t('plan.free_note')), p.configured && p.plan !== 'pro' && el('div', { class: 'buy' }, el('div', { class: 'price' }, t('plan.price', { month: p.price_month, year: p.price_year })), buy ? el('a', { class: 'cta sm', href: buy, target: '_blank', rel: 'noopener noreferrer' }, t('plan.get'), icon('arrow')) : el('span', { class: 'sd' }, t('plan.not_for_sale')), diff --git a/leadhound/dashboard/server.py b/leadhound/dashboard/server.py index 5206c2d..4b616c8 100644 --- a/leadhound/dashboard/server.py +++ b/leadhound/dashboard/server.py @@ -7,6 +7,7 @@ from __future__ import annotations import csv +import hashlib import io import json import os @@ -21,23 +22,24 @@ from pathlib import Path from urllib.parse import parse_qs, urlparse -from .. import __version__, accounts as accts, config, i18n, licensing, paths, profiles, sending, updates -from ..draft import make_draft +from .. import __version__, accounts as accts, alerts, config, i18n, licensing, paths, profiles, replies, sending, updates +from ..draft import make_draft, make_followup from ..jobs import AutoScanner, JobBusy, JobManager from ..langs import LANGUAGES -from ..models import KINDS, STATUSES +from ..models import KINDS, STATUSES, Lead +from ..score import score from ..money import CURRENCIES from ..net import Fetcher from ..send import SendError from ..sources import SOURCES, osm from ..store import Store -from ..textutil import csv_cell +from ..textutil import csv_cell, find_emails from .auth import Auth, TooManyAttempts, cookie_value STATIC = Path(__file__).parent -STATIC_FILES = {name: ("text/css" if name.endswith(".css") else "text/javascript") +STATIC_FILES = {name: ("text/css" if name.endswith(".css") else "image/svg+xml" if name.endswith(".svg") else "text/javascript") for name in ("app.css", "app.js", "util.js", "i18n.js", "icons.js", "today.js", "compose.js", "accounts.js", "plan.js", - "leads.js", "find.js", "settings.js", "login.js")} + "leads.js", "find.js", "settings.js", "login.js", "theme.js", "logo.svg")} FONT_RX = re.compile(r"fonts/([a-z-]+)\.woff2") LOCALE_RX = re.compile(r"locales/([a-z]{2})\.json") CSP = ("default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; " @@ -53,8 +55,8 @@ def __init__(self, code: int, msg: str): class Ctx: """Everything a request needs; one per server.""" - def __init__(self, store, config_path, token, port, jobs, auth=None, fetcher_factory=Fetcher): - self.store, self.config_path, self.token, self.port = store, config_path, token, port + def __init__(self, store, config_path, token, port, jobs, auth=None, fetcher_factory=Fetcher, demo=False): + self.store, self.config_path, self.token, self.port, self.demo = store, config_path, token, port, demo self.jobs, self.auth, self.fetcher_factory = jobs, auth, fetcher_factory self.lock = threading.Lock() self.license = licensing.License(os.path.join(os.path.dirname(os.path.abspath(config_path)), "license.json")) @@ -76,7 +78,7 @@ def meta(m, q, b): "sources": list(SOURCES), "statuses": list(STATUSES), "kinds": list(KINDS), "languages": LANGUAGES, "currencies": sorted(CURRENCIES), "professions": profiles.summary(), "llm_ready": cfg.llm_provider != "none", "hosted_ai": bool(licensing.SERVER), "profession": cfg.profession, - "config_path": c.config_path, "db_path": store_path(store)} + "config_path": c.config_path, "db_path": store_path(store), "demo": c.demo} def pro(feature: str): try: @@ -87,7 +89,7 @@ def pro(feature: str): def leads_list(m, q, b): leads = store.query(status=q.get("status") or None, kind=q.get("kind") or None, source=q.get("source") or None, min_score=int(q.get("min", 0) or 0), - search=q.get("q", ""), limit=max(1, min(int(q.get("limit", 300)), 1000, c.license.max_leads())), + search=q.get("q", ""), limit=max(1, min(int(q.get("limit", 300)), 1000)), sort=q.get("sort", "score")) return 200, [asdict(l) for l in leads] @@ -95,7 +97,26 @@ def lead_get(m, q, b): lead = store.get(int(m.group(1))) if not lead: raise HttpError(404, "lead not found") - return 200, asdict(lead) + return 200, {**asdict(lead), "outreach": store.outreach(lead.id)} + + def followups(m, q, b): + cfg = c.cfg() + due = store.followups_due(cfg.follow_up_days, cfg.follow_up_max) + return 200, [{**asdict(l), "outreach": {**info, "max": cfg.follow_up_max}} for l, info in due] + + def lead_followup(m, q, b): + lead = need_lead(int(m.group(1))) + action, cfg = b.get("action"), c.cfg() + if action == "draft": + n = store.outreach(lead.id)["followups"] + 1 + return 200, {"draft": make_followup(lead, cfg, n), "n": n} + if action == "sent": + store.log(lead.id, "followup", str(b.get("via", "manual"))) + elif action == "stop": + store.log(lead.id, "nofollow") + else: + raise HttpError(400, "unknown action") + return 200, store.outreach(lead.id) def lead_update(m, q, b): lid = int(m.group(1)) @@ -107,10 +128,7 @@ def lead_update(m, q, b): for k in ("notes", "draft"): if k in fields and (not isinstance(fields[k], str) or len(fields[k]) > 20000): raise HttpError(400, f"{k} must be text under 20000 characters") - was = store.get(lid).status store.update(lid, **fields) - if fields.get("status") == "contacted" and was != "contacted": - c.license.count_use() return 200, asdict(store.get(lid)) def lead_draft(m, q, b): # runs unlocked: an LLM call can take a minute and must not freeze the app @@ -118,17 +136,33 @@ def lead_draft(m, q, b): # runs unlocked: an LLM call can take a minute and mus lead = store.get(int(m.group(1))) if not lead: raise HttpError(404, "lead not found") - if b.get("llm"): - pro("ai") cfg = c.cfg() - token = c.license.ai_token() if cfg.llm_provider == "leadhound" else None + hosted = bool(b.get("llm")) and cfg.llm_provider == "leadhound" + if hosted: # your own AI key or a local model is free; the hosted AI costs the seller money + pro("ai") + token = c.license.ai_token() if hosted else None text, engine = make_draft(lead, cfg, use_llm=bool(b.get("llm")), ai_token=token) - if b.get("llm"): + if hosted: c.license.count_use() with c.lock: store.update(lead.id, draft=text) return 200, {"draft": text, "engine": engine} + def lead_add(m, q, b): + """A post or page you found yourself (or sent from the browser extension). Scored like any other lead.""" + url = str(b.get("url", "")).strip() + if not re.match(r"^https?://[^\s/]+\.[^\s]+$", url) or len(url) > 500: + raise HttpError(400, "Enter the full link, starting with https://") + host = urlparse(url).netloc.removeprefix("www.") + title = " ".join(str(b.get("title") or host).split())[:200] + body, contact = str(b.get("body") or "")[:6000], " ".join(str(b.get("contact") or "").split())[:300] + contact = contact or ", ".join(find_emails(body)[:2]) # an address in the pasted post + lead = Lead(source="added", external_id=hashlib.sha1(url.encode(), usedforsecurity=False).hexdigest()[:16], + kind="post", title=title, url=url, body=body, contact=contact, created_at=time.time(), + signals=[f"added by you from {host}"]) + lead_id, is_new = store.upsert(score(lead, c.cfg(), time.time())) + return 200, {"id": lead_id, "new": is_new} + def bulk(m, q, b): ids = b.get("ids") if not isinstance(ids, list) or not all(isinstance(i, int) for i in ids): @@ -157,27 +191,18 @@ def config_set(m, q, b): new = config.from_dict(base, b) except (ValueError, TypeError) as e: raise HttpError(400, str(e)) - if new.auto_scan_hours and not base.auto_scan_hours: + if (new.auto_scan_hours and not base.auto_scan_hours) or (new.alert_email and not base.alert_email): pro("autosearch") config.save(new, c.config_path) return 200, config.to_dict(new) def job_start(m, q, b): - kind = str(b.get("kind", "")) - if kind in ("local", "audit"): - pro("business") try: job = c.jobs.start(str(b.get("kind", "")), b.get("params") or {}) except JobBusy as e: raise HttpError(409, str(e)) except (ValueError, TypeError) as e: raise HttpError(400, str(e)) - if kind == "scan": - try: - c.license.use_search() - except licensing.ProRequired: - c.jobs.cancel(job.id) - raise HttpError(402, "You used today's free searches. Upgrade for unlimited searches.") return 200, job.to_dict() def job_get(m, q, b): @@ -210,8 +235,12 @@ def need_lead(lid: int): def lead_channels(m, q, b): return 200, sending.channels_for(need_lead(int(m.group(1))), c.accounts.public()) + def no_demo(): + if c.demo: + raise HttpError(400, "Sending is turned off in the demo. Your own leadhound sends from your own accounts.") + def lead_send(m, q, b): # network call: unlocked, store access is locked by hand - pro("send") + no_demo() with c.lock: lead = need_lead(int(m.group(1))) try: @@ -220,8 +249,19 @@ def lead_send(m, q, b): # network call: unlocked, store access is locked by han except SendError as e: raise HttpError(e.code, str(e)) with c.lock: - store.update(lead.id, status="contacted", draft=b["body"], via=res["via"]) - c.license.count_use() + if b.get("followup"): # a nudge to someone you already wrote to: keep the first message as the draft + store.log(lead.id, "followup", res["via"]) + else: + store.update(lead.id, status="contacted", draft=b["body"], via=res["via"]) + return 200, res + + def replies_check(m, q, b): # talks to your mail server: unlocked, the store is locked by hand + pro("replies") + try: + res = replies.check(c.accounts, store, c.lock, bool(c.auth)) + except SendError as e: + raise HttpError(e.code, str(e)) + c.license.count_use() return 200, res def accounts_get(m, q, b): @@ -233,7 +273,7 @@ def account_post(m, q, b): # a connect check talks to the service: unlocked if not spec: raise HttpError(404, "unknown platform") if action == "connect": - pro("send") + no_demo() try: who = sending.connect(c.accounts, pid, b.get("fields") or {}, bool(c.auth)) except SendError as e: @@ -271,12 +311,14 @@ def i18n_catalog(m, q, b): return [ ("GET", r"/api/meta", meta), ("GET", r"/api/stats", lambda m, q, b: (200, store.stats())), + ("GET", r"/api/insights", lambda m, q, b: (200, store.insights())), ("GET", r"/api/leads", leads_list), ("GET", r"/api/leads/(\d+)", lead_get), ("POST", r"/api/leads/(\d+)", lead_update), ("POST", r"/api/leads/(\d+)/draft", lead_draft, False), + ("GET", r"/api/followups", followups), ("POST", r"/api/replies", replies_check, False), ("POST", r"/api/leads/(\d+)/followup", lead_followup), ("GET", r"/api/leads/(\d+)/channels", lead_channels), ("POST", r"/api/leads/(\d+)/send", lead_send, False), ("GET", r"/api/plan", plan_get, False), ("POST", r"/api/plan", plan_post, False), ("GET", r"/api/accounts", accounts_get), ("POST", r"/api/accounts/([a-z]+)", account_post, False), - ("POST", r"/api/leads/bulk", bulk), ("GET", r"/api/export", export), + ("POST", r"/api/leads/bulk", bulk), ("POST", r"/api/leads", lead_add), ("GET", r"/api/export", export), ("GET", r"/api/config", lambda m, q, b: (200, config.to_dict(c.cfg()))), ("POST", r"/api/config", config_set), ("POST", r"/api/jobs", job_start), ("GET", r"/api/jobs/current", lambda m, q, b: (200, c.jobs.current.to_dict() if c.jobs.current else None)), @@ -390,7 +432,7 @@ def _handle(self, method: str): c.auth.logout(self._session()) return self._send(200, {"ok": True}, headers={"Set-Cookie": "lh_session=; Path=/; Max-Age=0"}) if method == "GET" and u.path == "/api/ping": # lets a second launch find this one; reveals only the version - return self._send(200, {"leadhound": __version__, "cloud": bool(c.auth)}) + return self._send(200, {"leadhound": __version__, "cloud": bool(c.auth), "demo": c.demo}) if not self._authed(): return self._send(401, {"error": "please sign in"}) if not secrets.compare_digest(self.headers.get("X-Leadhound-Token", ""), c.token): @@ -440,7 +482,7 @@ def store_path(store: Store) -> str: def make_server(db_path: str, config_path: str, port: int = 8787, fetcher_factory=None, - host: str = "127.0.0.1", password: str | None = None): + host: str = "127.0.0.1", password: str | None = None, demo: bool = False): store = Store(db_path) token = secrets.token_urlsafe(24) auth = Auth(password) if password else None @@ -448,23 +490,25 @@ def make_server(db_path: str, config_path: str, port: int = 8787, fetcher_factor jm = JobManager(db_path, config_path, fetcher_factory=factory, cloud=bool(auth)) httpd = ThreadingHTTPServer((host, port), BaseHTTPRequestHandler) # build the handler after binding so the Host allow-list uses the real port (port 0 = any free port) - ctx = Ctx(store, config_path, token, httpd.server_address[1], jm, auth, factory) + ctx = Ctx(store, config_path, token, httpd.server_address[1], jm, auth, factory, demo) ctx.stop = httpd.shutdown + jm.on_done.append(lambda job: alerts.after_auto_search(ctx, job)) httpd.RequestHandlerClass = make_handler(ctx) httpd.jobs = jm httpd.ctx = ctx - httpd.auto = AutoScanner(jm, os.path.join(os.path.dirname(os.path.abspath(config_path)), "state.json")) + httpd.auto = AutoScanner(jm, os.path.join(os.path.dirname(os.path.abspath(config_path)), "state.json"), + allowed=ctx.license.is_pro) return httpd, token -def find_running(port: int = 8787, tries: int = 20) -> int | None: - """Port of a leadhound already running on this computer, if any.""" +def find_running(port: int = 8787, tries: int = 20, demo: bool = False) -> int | None: + """Port of a leadhound already running on this computer, if any (the demo and your real one are told apart).""" import urllib.request for p in range(port, port + tries): try: with urllib.request.urlopen(f"http://127.0.0.1:{p}/api/ping", timeout=0.4) as r: info = json.loads(r.read(500)) - if info.get("leadhound") and not info.get("cloud"): + if info.get("leadhound") and not info.get("cloud") and bool(info.get("demo")) == demo: return p except Exception: continue @@ -481,7 +525,8 @@ def bind(db_path: str, config_path: str, port: int, tries: int = 20, **kw): raise OSError(f"no free port in {port}-{port + tries - 1}") -def serve(db_path: str, config_path: str, port: int = 8787, open_browser: bool = True, cloud: bool = False) -> None: +def serve(db_path: str, config_path: str, port: int = 8787, open_browser: bool = True, cloud: bool = False, + demo: bool = False) -> None: if cloud: password = os.environ.get("LEADHOUND_PASSWORD", "") if len(password) < 8: @@ -490,12 +535,12 @@ def serve(db_path: str, config_path: str, port: int = 8787, open_browser: bool = print(f"leadhound (cloud mode) listening on port {httpd.server_address[1]}", flush=True) open_browser = False else: - running = find_running(port) if open_browser else None + running = find_running(port, demo=demo) if open_browser else None if running: # double-clicked twice: just show the window that is already there print(f"leadhound is already running at http://127.0.0.1:{running}/, opening it.", flush=True) webbrowser.open(f"http://127.0.0.1:{running}/") return - httpd, _ = bind(db_path, config_path, port) + httpd, _ = bind(db_path, config_path, port, demo=demo) url = f"http://127.0.0.1:{httpd.server_address[1]}/" print(f"leadhound is running at {url} (close this window or press Ctrl+C to stop)", flush=True) if open_browser: diff --git a/leadhound/dashboard/settings.js b/leadhound/dashboard/settings.js index 1f6fc11..b1c2211 100644 --- a/leadhound/dashboard/settings.js +++ b/leadhound/dashboard/settings.js @@ -2,6 +2,7 @@ import { $, api, el, emit, state, toast, openModal, closeModal } from './util.js'; import { t, LANG, setLang, catName } from './i18n.js'; import { runQueue, rememberPlace, startJob, defaultSources } from './find.js'; +import { proTag } from './plan.js'; const root = $('#view-settings'); const list = v => (v || []).join(', '); @@ -31,6 +32,9 @@ function draw() { el('p', { class: 'mut sm' }, t('set.profession_hint')), el('div', { class: 'two' }, field(t('set.name'), '', i('name')), field(t('set.signature'), t('set.signature_hint'), i('signature'))), field(t('set.daily_goal'), t('set.daily_goal_hint'), i('daily_goal', 'number', { min: 1, max: 50 })), + el('div', { class: 'two' }, + field(t('set.fu_days'), t('set.fu_days_hint'), el('select', { id: 's-follow_up_days' }, options([2, 3, 5, 7, 14].map(d => [d, t('set.days', { n: d })]), cfg.follow_up_days))), + field(t('set.fu_max'), t('set.fu_max_hint'), el('select', { id: 's-follow_up_max' }, options([[0, t('set.fu_off')], [1, '1'], [2, '2'], [3, '3']], cfg.follow_up_max)))), field(t('set.pitch'), t('set.pitch_hint'), i('pitch')), field(t('set.skills'), t('set.skills_hint'), i('skills', 'text', { value: list(cfg.skills) })), field(t('set.avoid'), t('set.avoid_hint'), i('avoid', 'text', { value: list(cfg.avoid) })), @@ -38,7 +42,8 @@ function draw() { field(t('set.currency'), '', el('select', { id: 's-currency' }, options(state.meta.currencies.map(c => [c, c]), cfg.currency))), field(t('set.min_budget'), t('set.zero_hint'), i('min_budget', 'number', { min: 0 })), field(t('set.min_rate'), t('set.zero_hint'), i('min_rate', 'number', { min: 0 }))), - field(t('set.portfolio'), t('set.portfolio_hint'), i('portfolio'))), + field(t('set.portfolio'), t('set.portfolio_hint'), i('portfolio')), + field(t('set.proof'), t('set.proof_hint'), el('textarea', { id: 's-proof', rows: 3, placeholder: t('set.proof_ph'), value: (cfg.proof || []).join('\n') }))), el('div', { class: 'card' }, el('h2', {}, t('set.where')), check('freelancer', 'Freelancer.com', t('set.freelancer_hint')), field(t('set.freelancer_cats'), t('set.freelancer_cats_hint'), i('freelancer_categories', 'text', { value: list(cfg.freelancer_categories) })), @@ -46,19 +51,24 @@ function draw() { check('hn', 'Hacker News', ''), check('github', 'GitHub', t('set.github_hint')), el('div', { class: 'two' }, field(t('set.gh_labels'), '', i('github_labels', 'text', { value: list(cfg.github_labels) })), field(t('set.gh_langs'), t('set.gh_langs_hint'), i('github_languages', 'text', { value: list(cfg.github_languages) }))), + check('himalayas', 'Himalayas', t('set.himalayas_hint')), check('mastodon', 'Mastodon', t('set.mastodon_hint')), el('div', { class: 'two' }, field(t('set.mastodon_servers'), '', i('mastodon_instances', 'text', { value: list(cfg.mastodon_instances) })), field(t('set.mastodon_tags'), '', i('mastodon_tags', 'text', { value: list(cfg.mastodon_tags) }))), field(t('set.rss'), t('set.rss_hint'), el('textarea', { id: 's-rss_feeds', rows: 3, value: (cfg.rss_feeds || []).join('\n') })), el('div', { class: 'two' }, field(t('set.max_age'), '', el('select', { id: 's-max_age_days' }, options([7, 14, 21, 30, 60].map(d => [d, t('set.days', { n: d })]), cfg.max_age_days))), - field(t('set.auto'), t('set.auto_hint'), el('select', { id: 's-auto_scan_hours' }, options([[0, t('set.auto_off')], [6, t('set.auto_every', { n: 6 })], [12, t('set.auto_every', { n: 12 })], [24, t('set.auto_daily')]], cfg.auto_scan_hours)))), + field([t('set.auto'), ' ', proTag()], t('set.auto_hint'), el('select', { id: 's-auto_scan_hours' }, options([[0, t('set.auto_off')], [6, t('set.auto_every', { n: 6 })], [12, t('set.auto_every', { n: 12 })], [24, t('set.auto_daily')]], cfg.auto_scan_hours)))), el('p', { class: 'mut' }, key('GitHub', cfg.keys.github), ' · ', t('set.gh_token_hint'))), el('div', { class: 'card' }, el('h2', {}, t('set.ai')), el('p', {}, t('set.ai_desc')), field(t('set.provider'), '', el('select', { id: 's-llm_provider' }, options([['none', t('prov.none')], ...(state.meta.hosted_ai ? [['leadhound', t('prov.leadhound')]] : []), ['anthropic', t('prov.anthropic')], ['openai', t('prov.openai')]], cfg.llm_provider))), state.meta.hosted_ai && el('p', { class: 'mut sm' }, t('set.hosted_note')), el('div', { class: 'two' }, field(t('set.model'), t('set.model_hint'), i('llm_model')), field(t('set.server'), t('set.server_hint'), i('llm_base_url'))), el('p', { class: 'mut' }, key('Anthropic', cfg.keys.anthropic), ' · ', key('OpenAI', cfg.keys.openai), ' · ', t('set.keys_hint'))), + el('div', { class: 'card' }, el('h2', {}, t('set.alerts')), el('p', {}, t('set.alerts_desc')), + check('alert_email', [t('set.alert_email'), ' ', proTag()], t('set.alert_email_hint')), + field(t('set.alert_min'), '', el('select', { id: 's-alert_min_score', style: 'max-width:220px' }, options([50, 60, 70, 80].map(n => [n, String(n)]), cfg.alert_min_score))), + notifyRow()), el('div', { class: 'card' }, el('h2', {}, t('set.local')), el('div', { class: 'two' }, field(t('set.max_biz'), '', i('max_businesses', 'number', { min: 1, max: 300 })), field(t('set.radius'), '', i('radius_m', 'number', { min: 100, max: 20000 })))), updateCard(), @@ -67,16 +77,30 @@ function draw() { el('span', { class: 'mut' }, t('set.stored_at'), ' ', state.meta.config_path))))); } +// Desktop notifications live in this browser only: a search that finds new matches while the tab is hidden shows one. +function notifyRow() { + const row = el('div', { class: 'row', style: 'margin-top:12px' }); + const paint = () => { + const p = typeof Notification === 'undefined' ? 'denied' : Notification.permission; + row.replaceChildren(p === 'granted' ? el('span', { class: 'mut sm' }, t('set.notify_on')) + : p === 'denied' ? el('span', { class: 'mut sm' }, t('set.notify_blocked')) + : el('button', { class: 'btn sm', type: 'button', onclick: () => Notification.requestPermission().then(paint) }, t('set.notify_btn'))); + }; + paint(); + return row; +} + function collect() { const v = id => $('#s-' + id).value; const c = id => $('#s-' + id).checked; return { name: v('name'), signature: v('signature'), pitch: v('pitch'), skills: v('skills'), avoid: v('avoid'), profession: v('profession'), - currency: v('currency'), min_budget: v('min_budget'), min_rate: v('min_rate'), portfolio: v('portfolio'), draft_language: v('draft_language'), + currency: v('currency'), min_budget: v('min_budget'), min_rate: v('min_rate'), portfolio: v('portfolio'), proof: v('proof'), draft_language: v('draft_language'), freelancer: c('freelancer'), freelancer_categories: v('freelancer_categories'), reddit_subreddits: v('reddit_subreddits'), hn: c('hn'), github: c('github'), github_labels: v('github_labels'), github_languages: v('github_languages'), - mastodon: c('mastodon'), mastodon_instances: v('mastodon_instances'), mastodon_tags: v('mastodon_tags'), rss_feeds: v('rss_feeds'), - daily_goal: +v('daily_goal') || 5, max_age_days: +v('max_age_days'), auto_scan_hours: +v('auto_scan_hours'), llm_provider: v('llm_provider'), llm_model: v('llm_model'), + himalayas: c('himalayas'), mastodon: c('mastodon'), mastodon_instances: v('mastodon_instances'), mastodon_tags: v('mastodon_tags'), rss_feeds: v('rss_feeds'), + alert_email: c('alert_email'), alert_min_score: +v('alert_min_score'), + daily_goal: +v('daily_goal') || 5, follow_up_days: +v('follow_up_days'), follow_up_max: +v('follow_up_max'), max_age_days: +v('max_age_days'), auto_scan_hours: +v('auto_scan_hours'), llm_provider: v('llm_provider'), llm_model: v('llm_model'), llm_base_url: v('llm_base_url'), max_businesses: +v('max_businesses'), radius_m: +v('radius_m'), }; } diff --git a/leadhound/dashboard/theme.js b/leadhound/dashboard/theme.js new file mode 100644 index 0000000..a1abd0b --- /dev/null +++ b/leadhound/dashboard/theme.js @@ -0,0 +1,2 @@ +// Runs before the page draws so a chosen light or dark theme never flashes. "auto" follows the computer. +try { const t = localStorage.getItem('lh-theme'); if (t === 'light' || t === 'dark') document.documentElement.dataset.theme = t; } catch { /* storage blocked */ } diff --git a/leadhound/dashboard/today.js b/leadhound/dashboard/today.js index f0d2067..a7d6f5d 100644 --- a/leadhound/dashboard/today.js +++ b/leadhound/dashboard/today.js @@ -2,14 +2,13 @@ import { $, $$, api, el, emit, on, state, store, toast } from './util.js'; import { t, LANG } from './i18n.js'; import { icon } from './icons.js'; -import { runQueue, defaultSources } from './find.js'; -import { srcName, ageText, reasonLine, isNew } from './leads.js'; +import { runQueue, defaultSources, progressChips } from './find.js'; +import { srcName, ageText, reasonLine, isNew, checkReplies } from './leads.js'; import { renderCompose } from './compose.js'; import { SEND, LINK, TOTAL, acct, platIcon, platName, readyCount, sendCount } from './accounts.js'; -import { isPro, loadPlan, openPlan, plan } from './plan.js'; const root = $('#view-today'); -let leads = [], stats = {}, job = null, step = 0, pick = null, found = null, busy = false, wasRunning = false; +let leads = [], stats = {}, fups = [], ins = null, job = null, step = 0, pick = null, pickFu = false, found = null, busy = false, wasRunning = false; const running = () => job && job.status === 'running'; const goal = () => state.cfg.daily_goal || 5; const rate = n => [1, 2, 3, 4, 5].map(i => el('i', { class: i <= n ? 'on' : '' })); @@ -30,12 +29,12 @@ export function initToday() { on('job-done', j => { const added = Object.values(j.result?.new || {}).reduce((a, b) => a + b, 0); if (j.status === 'done' && j.kind !== 'update') found = { added }; - loadPlan().then(paintHero); // the free search counter moved refresh(); }); on('profile-changed', refresh); on('plan-changed', refresh); on('accounts-changed', paintConnect); + on('replies-checked', refresh); window.addEventListener('resize', () => slide()); draw(); refresh(); @@ -58,7 +57,7 @@ function draw() { [0, 1, 2].map(i => el('button', { class: 'step', onclick: () => stepClick(i) }, el('span', { class: 'badge' }, i + 1), el('span', {}, el('b', {}, [t('today.step1'), t('today.step2'), t('today.step3')][i]), el('small', { id: 's' + i }))))), el('div', { class: 'stage' }, - el('section', { class: 'panel', id: 'p0' }, hero(), tiles(), el('div', { id: 'cityask' }), connectBar()), + el('section', { class: 'panel', id: 'p0' }, hero(), el('div', { id: 'fups' }), tiles(), el('div', { id: 'cityask' }), connectBar()), el('section', { class: 'panel', id: 'p1' }, el('div', { class: 'grid', id: 'grid' })), el('section', { class: 'panel', id: 'p2' })))); show(0, false); @@ -75,7 +74,7 @@ function show(i, animate = true) { step = i; $$('.panel').forEach((p, k) => { p.classList.toggle('show', k === i); if (k === i && animate) { p.style.animation = 'none'; void p.offsetWidth; p.style.animation = ''; } }); if (i === 1) paintGrid(); - if (i === 2 && pick) renderCompose($('#p2'), pick, { onBack: () => show(1), onSent }); + if (i === 2 && pick) renderCompose($('#p2'), pick, { onBack: () => show(pickFu ? 0 : 1), onSent }, { followup: pickFu }); paintSteps(); slide(); } @@ -98,8 +97,9 @@ function slide() { } async function refresh() { - try { [leads, stats] = await Promise.all([api('/api/leads?status=new&sort=score&limit=60'), api('/api/stats')]); } catch (e) { return toast(e.message, 'err'); } - paintSteps(); paintHero(); paintGoal(); paintBest(); paintWeek(); paintSources(); paintConnect(); paintCity(); + try { [leads, stats, fups] = await Promise.all([api('/api/leads?status=new&sort=score&limit=60'), api('/api/stats'), api('/api/followups')]); + ins = await api('/api/insights').catch(() => null); } catch (e) { return toast(e.message, 'err'); } + paintSteps(); paintHero(); paintFollowups(); paintGoal(); paintBest(); paintWeek(); paintSources(); paintInsights(); paintConnect(); paintCity(); if (step === 1) paintGrid(); } @@ -112,10 +112,9 @@ function hero() { } function findNow() { - if (!isPro() && plan().searches_left === 0) return openPlan(); // today's free searches are used const jobs = [{ kind: 'scan', params: { sources: defaultSources() } }]; const place = store.get('lh-place'); - if (isPro() && place && state.cfg.categories.length) jobs.push({ kind: 'local', params: { place, categories: state.cfg.categories, website: 'no', audit: false, limit: 40 } }); + if (place && state.cfg.categories.length) jobs.push({ kind: 'local', params: { place, categories: state.cfg.categories, website: 'no', audit: false, limit: 40 } }); runQueue(jobs, true); } @@ -127,13 +126,29 @@ function paintHero() { const empty = !stats.total && !busy_; $('#h0').textContent = found ? (found.added ? t('today.found', { new: found.added, total: n }) : t('today.found0')) : empty ? t('today.empty_title') : t('today.hero_title'); $('#h0p').textContent = found ? (found.added && leads[0] ? t('today.found_text', { score: leads[0].score }) : t('today.found_text0')) : empty ? t('today.empty_text') : t('today.hero_text'); - const left = plan().searches_left; - $('#prog').textContent = busy_ ? (job.log[job.log.length - 1] || '') : !isPro() && left != null ? t('plan.searches_left', { n: left }) : ''; + $('#prog').replaceChildren(...(busy_ ? [progressChips(job) || job.log[job.log.length - 1] || ''] : [])); acts.replaceChildren(...[el('button', { class: 'cta', disabled: busy_, onclick: findNow }, busy_ ? el('span', { class: 'spin' }) : icon('search'), busy_ ? t('today.finding') : t('today.find_btn')), busy_ && el('button', { class: 'cta ghost', onclick: () => api(`/api/jobs/${job.id}/cancel`, {}) }, t('stop')), !busy_ && n > 0 && found && el('button', { class: 'cta ghost', onclick: () => show(1) }, t('today.see'), icon('arrow'))].filter(Boolean)); } +// People you wrote to who have not answered yet: a short nudge often gets the reply. +function paintFollowups() { + const box = $('#fups'); + if (!box) return; + if (!fups.length) return box.replaceChildren(); + box.replaceChildren(el('div', { class: 'tile fups' }, + el('div', { class: 'fuh' }, el('h4', {}, t('fup.title'), el('span', { class: 'cnt' }, fups.length)), + el('button', { class: 'btn ghost sm', onclick: e => checkReplies(e.currentTarget) }, t('rep.check'))), + el('p', { class: 'sd' }, t('fup.text')), + el('div', { class: 'furows' }, fups.slice(0, 5).map(l => el('div', { class: 'furow' }, + el('div', { class: 'fut' }, el('b', {}, l.title), el('small', {}, srcName(l.source), ' · ', t('fup.row', { days: l.outreach.days, n: l.outreach.followups + 1, max: l.outreach.max }))), + el('button', { class: 'btn primary sm', onclick: () => { pick = l; pickFu = true; show(2); } }, icon('pen'), t('fup.write')), + el('button', { class: 'btn ghost sm', onclick: async () => { + try { await api(`/api/leads/${l.id}/followup`, { action: 'stop' }); toast(t('fup.stopped')); refresh(); } catch (e) { toast(e.message, 'err'); } + } }, t('fup.stop'))))))); +} + function tiles() { return el('div', { class: 'tiles' }, el('div', { class: 'tile t-goal' }, el('h4', {}, t('today.goal')), @@ -142,7 +157,8 @@ function tiles() { el('p', { id: 'goalp' })), el('div', { class: 'tile t-best', id: 'best' }), el('div', { class: 'tile t-week' }, el('h4', {}, t('today.week')), el('div', { class: 'wk' }, el('b', { class: 'num', id: 'weekn' }), el('span', {}, t('today.week_sent'))), el('div', { class: 'bars', id: 'bars' })), - el('div', { class: 'tile t-src' }, el('h4', {}, t('today.sources')), el('div', { class: 'srcs', id: 'srcs' }), el('p', {}, t('today.sources_text')))); + el('div', { class: 'tile t-src' }, el('h4', {}, t('today.sources')), el('div', { class: 'srcs', id: 'srcs' }), el('p', {}, t('today.sources_text'))), + el('div', { class: 'tile t-ins', id: 'ins', hidden: true })); } const C = 2 * Math.PI * 44; @@ -185,11 +201,27 @@ function paintWeek() { function paintSources() { const c = state.cfg, place = store.get('lh-place'); - const all = [['Freelancer.com', c.freelancer], ['Reddit', c.reddit_subreddits.length > 0], ['Hacker News', c.hn], ['GitHub', c.github], ['Mastodon', c.mastodon], [t('src.osm'), !!place]]; + const all = [['Freelancer.com', c.freelancer], ['Reddit', c.reddit_subreddits.length > 0], ['Hacker News', c.hn], ['GitHub', c.github], ['Himalayas', c.himalayas], ['Mastodon', c.mastodon], [t('src.osm'), !!place]]; $('#srcs').replaceChildren(...all.map(([n, on_]) => el('button', { class: 'srcchip' + (on_ ? '' : ' off'), onclick: () => emit('open-settings') }, el('i'), n)), el('button', { class: 'srcchip add', onclick: () => emit('open-settings') }, t('today.add_feed'))); } +// What works: reply rate per source, and tips that say the numbers behind them. Shown after 3 messages. +function paintInsights() { + const box = $('#ins'); + if (!box) return; + box.hidden = !ins || ins.contacted < 3; + if (box.hidden) return; + const tip = ([key, a]) => el('li', {}, icon('check'), t('ins.' + key, { ...a, src: a.src ? srcName(a.src) : '' })); + box.replaceChildren(el('h4', {}, t('ins.title')), + el('div', { class: 'insrows' }, ins.sources.slice(0, 6).map(s => { + const bar = el('i', {}); bar.style.setProperty('--w', Math.max(2, s.rate) + '%'); + return el('div', { class: 'insrow' }, el('b', {}, srcName(s.source)), el('span', { class: 'insbar' }, bar), + el('span', { class: 'num' }, s.rate + '%'), el('small', {}, t('ins.row', { replied: s.replied, contacted: s.contacted }), s.won ? ' · ' + t('ins.won', { n: s.won }) : '')); + })), + ins.tips.length > 0 && el('ul', { class: 'instips' }, ins.tips.map(tip))); +} + function connectBar() { return el('div', { class: 'connectbar', id: 'cbar' }, el('div', { class: 'cb-t' }, el('b', {}, t('today.cb_title')), el('span', { id: 'cbs' })), el('div', { class: 'cb-i', id: 'cbi' }), el('button', { class: 'btn primary', id: 'cbgo', onclick: () => emit('goto', 'accounts') })); } @@ -220,7 +252,6 @@ function paintGrid() { return; } grid.replaceChildren(...[...leads.slice(0, 40).map((l, i) => post(l, i)), - !isPro() && (stats.by_status || {}).new > leads.length && el('div', { class: 'more rise', style: '--i:2' }, el('b', {}, t('plan.badge')), el('p', {}, t('plan.upgrade_matches', { n: leads.length, total: stats.by_status.new })), el('button', { class: 'btn primary', onclick: openPlan }, t('plan.upgrade_btn'))), leads.length % 2 === 1 && el('div', { class: 'more rise', style: '--i:3' }, el('b', {}, t('today.more_title')), el('p', {}, t('today.more_text')), el('button', { class: 'btn', onclick: () => { show(0); findNow(); } }, icon('search'), t('today.search_again')))].filter(Boolean)); } @@ -234,7 +265,7 @@ function post(l, i) { return card; } -function write(l) { pick = l; show(2); } +function write(l) { pick = l; pickFu = false; show(2); } async function skip(l, card) { card.classList.add('leaving'); @@ -258,10 +289,11 @@ async function onSent(info) { if (busy) return; busy = true; await celebrate(); - pick = null; + const wasFu = pickFu; + pick = null; pickFu = false; await refresh(); - show(1); + show(wasFu ? 0 : 1); busy = false; const g = (stats.sent_today || 0) >= goal(); - toast(g ? t('today.goal_done') : info && info.via ? t('compose.sent_toast', { name: info.via, as: info.as }) : t('today.nice')); + toast(g ? t('today.goal_done') : info && info.via ? t('compose.sent_toast', { name: info.via, as: info.as }) : wasFu ? t('fup.sent') : t('today.nice')); } diff --git a/leadhound/dashboard/util.js b/leadhound/dashboard/util.js index 405d20c..76ab4a2 100644 --- a/leadhound/dashboard/util.js +++ b/leadhound/dashboard/util.js @@ -74,7 +74,7 @@ export async function copyText(text) { export const scoreClass = s => (s >= 60 ? 'hi' : s >= 35 ? 'mid' : 'lo'); export const safeUrl = u => (/^https?:\/\//i.test(u || '') ? u : null); -export const BRANDS = { reddit: 'Reddit', hn: 'Hacker News', github: 'GitHub', freelancer: 'Freelancer.com', mastodon: 'Mastodon' }; +export const BRANDS = { reddit: 'Reddit', hn: 'Hacker News', github: 'GitHub', freelancer: 'Freelancer.com', mastodon: 'Mastodon', himalayas: 'Himalayas' }; export function openModal(content) { const m = $('#modal'); diff --git a/leadhound/demo.py b/leadhound/demo.py new file mode 100644 index 0000000..4a03f60 --- /dev/null +++ b/leadhound/demo.py @@ -0,0 +1,136 @@ +"""Demo mode: `leadhound demo` opens the app with sample leads, so you can try everything in ten seconds. + +The demo keeps its own folder (~/.leadhound/demo), never touches your real leads, and turns off sending +from connected accounts. Every lead here is made up: the names, links and addresses use example domains. +Searching still works for real, so you can see fresh results next to the samples. +""" +from __future__ import annotations + +import os +import time + +from . import config, paths +from .audit import AuditResult, Finding +from .i18n import msg +from .models import Lead +from .score import score +from .store import Store + +DAY = 86400 + + +def folder() -> str: + return os.path.join(paths.data_dir(), "demo") + + +def _finding(code: str, severity: int, **args) -> Finding: + return Finding(code=code, severity=severity, title=msg("en", f"t.{code}", **args), detail="", + pitch=msg("en", f"f.{code}", **args), args=args) + + +def _business(eid, name, category, city, country, website="", lang="", findings=(), contact="", booking=False, tech=()): + extra = {"website": website, "category": category, "booking_relevant": booking, "country": country, "city": city} + parts = [c.strip() for c in contact.split(",") if c.strip()] + extra.update({k: v for k, v in (("email", next((c for c in parts if "@" in c), "")), + ("phone", next((c for c in parts if "@" not in c), ""))) if v}) # as OpenStreetMap lists them + if website: + extra["audit"] = AuditResult(url=website, final_url=website, status=200, seconds=1.4, findings=list(findings), + tech=list(tech), lang=lang).to_dict() + return Lead(source="osm", external_id=eid, kind="business", title=name, url=f"https://www.openstreetmap.example/node/{eid}", + contact=contact, location=city, signals=[f.title for f in findings], extra=extra) + + +def sample_leads(now: float) -> list[Lead]: + h = 3600 + return [ + Lead(source="freelancer", external_id="demo-1", kind="post", title="WordPress booking site for a physiotherapy clinic", + url="https://www.freelancer.example/projects/demo-1", created_at=now - 2 * h, budget="$750 USD", + body="We need a clean WordPress site with online booking for 3 therapists, plus a simple blog. " + "Please share similar work. Deadline in 3 weeks.", + contact="bid on Freelancer.com", signals=["client project post"], + extra={"skills": ["WordPress", "PHP", "Website Design"], "category": "WordPress"}), + Lead(source="reddit", external_id="demo-2", kind="post", title="[Hiring] Shopify store is slow, need a fix this week", + url="https://www.reddit.example/r/forhire/comments/demo2/", author="u/beanroaster", created_at=now - 5 * h, + budget="$400", body="Paid gig for our small coffee roastery. Looking to hire a developer to speed up the Shopify " + "theme and fix the checkout on phones. Email hello@roaster.example with similar work.", + contact="hello@roaster.example, reddit DM: u/beanroaster"), + Lead(source="reddit", external_id="demo-3", kind="post", title="[Hiring] Python script to clean 40k rows of CSV data", + url="https://www.reddit.example/r/forhire/comments/demo3/", author="u/opsdata", created_at=now - 26 * h, + budget="$250", body="Need someone this week. Messy supplier CSVs, dedupe and normalise addresses.", + contact="reddit DM: u/opsdata"), + Lead(source="hn", external_id="demo-4", kind="post", title="SEEKING FREELANCER | Data engineer | 3-month contract | Remote", + url="https://news.ycombinator.example/item?id=demo4", author="northwind", created_at=now - 50 * h, + body="Seeking freelancer: Python + Postgres pipelines, part-time contract. Email jobs@northwind.example", + contact="jobs@northwind.example, HN: northwind", signals=["seeking freelancer thread"]), + Lead(source="github", external_id="demo-5", kind="issue", title="[acme/exporter] CSV export breaks on non-ASCII names", + url="https://github.example/acme/exporter/issues/1", author="acme", created_at=now - 30 * h, budget="$200", + body="Bounty: $200 paid on merge. Python 3.12.", signals=["paid bounty"], extra={"language": "Python"}), + Lead(source="himalayas", external_id="demo-6", kind="post", title="Shopify developer (contract) · Northwind Goods", + url="https://himalayas.example/companies/northwind/jobs/demo-6", author="Northwind Goods", created_at=now - 8 * h, + budget="$50-$80/hr", body="Remote contract. Theme fixes, faster checkout, app integrations.", + contact="apply via himalayas.app", signals=["remote contract role"], extra={"skills": ["Shopify", "JavaScript"]}), + Lead(source="mastodon", external_id="demo-7", kind="post", title="Busco diseñador web para la página de mi panadería", + url="https://mastodon.example/@panaderia/demo7", author="panaderia", created_at=now - 20 * h, + body="¿Alguien recomienda un diseñador? Pagamos, presupuesto 300 €.", contact="Mastodon: @panaderia@mastodon.example", + extra={"language": "es"}), + Lead(source="rss", external_id="demo-8", kind="post", title="Freelance copywriter for a SaaS landing page", + url="https://weworkremotely.example/jobs/demo-8", created_at=now - 3 * DAY, + body="Contract, 2 weeks. Rewrite our landing page and onboarding emails.", contact="apply via weworkremotely.example"), + _business("demo-9", "Smile Dental Vake", "dentist", "Tbilisi", "ge", website="http://smile-dental.example", lang="ka", + booking=True, contact="info@smile-dental.example, +995 32 200 00 00", tech=["WordPress 5.4"], + findings=[_finding("no_https", 3), _finding("no_booking", 2), _finding("stale", 2, year=2021)]), + _business("demo-10", "Café Lisboa", "cafe", "Lisbon", "pt", contact="+351 21 000 0000"), + _business("demo-11", "Hotel Mar Azul", "hotel", "Valencia", "es", website="https://hotelmarazul.example", lang="es", + booking=True, contact="reservas@hotelmarazul.example", + findings=[_finding("no_mobile", 3), _finding("slow", 2, secs=6.2), _finding("no_description", 1)]), + Lead(source="freelancer", external_id="demo-12", kind="post", title="Translate a restaurant menu from English to Spanish", + url="https://www.freelancer.example/projects/demo-12", created_at=now - 4 * h, budget="€120 EUR", + body="Two-page menu, needs a native Spanish speaker.", contact="bid on Freelancer.com", + signals=["client project post"], extra={"skills": ["Translation", "Spanish"], "category": "Translation"}), + ] + + +DEMO_CONFIG = dict(name="Alex", signature="Alex · alex.example", profession="developer", + skills=["wordpress", "python", "shopify", "csv"], portfolio="https://alex.example", + proof=["wordpress, booking: Rebuilt a clinic's WordPress site with online booking: https://alex.example/clinic", + "csv, python: Cleaned and merged 120k supplier rows for a wholesaler: https://alex.example/data", + "shopify, checkout: Cut a Shopify store's mobile load time from 7 s to 2 s: https://alex.example/shop"], + min_budget=150, min_rate=25, mastodon=True, categories=["dentist", "cafe", "hotel"]) + + +def seed(config_path: str, db_path: str, now: float | None = None) -> int: + """Write the demo profile and sample leads (only into an empty demo database). Returns how many leads it added.""" + now = now or time.time() + if not os.path.exists(config_path): + config.save(config.from_dict(config.Config(), DEMO_CONFIG), config_path) + cfg = config.load(config_path) + store = Store(db_path) + try: + if store.stats()["total"]: + return 0 + ids = {} + for lead in sample_leads(now): + ids[lead.external_id], _ = store.upsert(score(lead, cfg, now)) + # some history, so follow-ups, reply rates and the week chart have something to show + for eid, status, days in (("demo-3", "contacted", 4), ("demo-8", "contacted", 5), ("demo-4", "contacted", 6), + ("demo-12", "contacted", 2)): + store.update(ids[eid], status=status, draft="(sent in the demo)") + store.db.execute("UPDATE activity SET at = ? WHERE lead_id = ?", (now - days * DAY, ids[eid])) + store.update(ids["demo-4"], status="replied") + store.log(ids["demo-4"], "replied", "email") + store.update(ids["demo-12"], status="won") + store.db.commit() + return len(ids) + finally: + store.close() + + +def paths_for_demo(reset: bool = False) -> tuple[str, str]: + d = folder() + os.makedirs(d, exist_ok=True) + cfg, db = os.path.join(d, "config.ini"), os.path.join(d, "leadhound.db") + if reset: + for p in (cfg, db, db + "-wal", db + "-shm"): + if os.path.exists(p): + os.remove(p) + return cfg, db diff --git a/leadhound/draft.py b/leadhound/draft.py index cec952c..ff4c0b0 100644 --- a/leadhound/draft.py +++ b/leadhound/draft.py @@ -1,6 +1,8 @@ """First-message drafts built from the lead's own evidence, in the lead's language. You send them yourself. Language: your setting, or "auto" = the business website's language, then its country, else English. +Proof of work: Settings holds lines like "wordpress, booking: Rebuilt a clinic site with online booking: https://...". +The line whose keywords best match the lead goes into English drafts (and into the AI prompt in any language). In English drafts your own pitch is used; in other languages a translated sentence for your profession replaces it, so a message never mixes two languages. """ @@ -17,7 +19,7 @@ from .textutil import word_hit SOURCE_LABEL = {"reddit": "Reddit", "hn": "Hacker News", "github": "GitHub", "rss": "the job board", - "freelancer": "Freelancer.com", "mastodon": "Mastodon"} + "freelancer": "Freelancer.com", "mastodon": "Mastodon", "himalayas": "Himalayas"} WEB_WORK = {"", "developer", "designer", "marketer", "writer"} # professions that fix websites DEADLINE_RX = re.compile(r"\b(deadline|by (monday|tuesday|wednesday|thursday|friday|the end)|asap|urgent|weeks?|days?)\b|" r"urgente|plazo|prazo|délai|frist|срочно|срок", re.I) @@ -54,6 +56,21 @@ def _name(author: str) -> str: return "" if a.lower() in ("", "[deleted]", "deleted") else a +def pick_proof(lead: Lead, cfg) -> str: + """The proof-of-work line whose keywords best match the lead ("wordpress, booking: Rebuilt a clinic site: https://..."). + Empty when nothing matches: a proof that has nothing to do with the request reads like spam.""" + text = f"{lead.text} {' '.join(lead.extra.get('skills', []))} {lead.extra.get('category', '')}".lower() + best, best_hits = "", 0 + for line in getattr(cfg, "proof", []) or []: + keys, sep, sentence = line.partition(": ") + if not sep or not sentence.strip(): + continue + hits = sum(1 for k in keys.split(",") if k.strip() and word_hit(k.strip(), text)) + if hits > best_hits: + best, best_hits = sentence.strip(), hits + return best if not best or re.search(r"https?://\S+$", best) else _sentence(best) # no full stop glued to a link + + def template_post(lead: Lead, cfg, lang: str = "en") -> str: skills = [s for s in cfg.skills if word_hit(s, lead.text.lower())][:3] skill_line = msg(lang, "p.skills", skills=", ".join(skills)) if skills else msg(lang, "p.generic") @@ -63,8 +80,11 @@ def template_post(lead: Lead, cfg, lang: str = "en") -> str: if lead.source == "github": lines.append(f"{msg(lang, 'p.github', title=title)} {skill_line}") else: - where = SOURCE_LABEL.get(lead.source, lead.source) + where = SOURCE_LABEL.get(lead.source) or urlparse(lead.url).netloc.removeprefix("www.") or lead.source lines.append(f"{msg(lang, 'p.saw', where=where, title=title)} {skill_line} {_offer(cfg, lang)}") + proof = pick_proof(lead, cfg) if lang == "en" else "" # your own words: only in English drafts, like your pitch + if proof: + lines.append(proof) if cfg.portfolio: lines.append(msg(lang, "p.recent", portfolio=cfg.portfolio)) if not lead.budget: @@ -101,6 +121,9 @@ def template_business(lead: Lead, cfg, lang: str = "en") -> str: body = [subject("b.subj_site", domain=domain), "", hello, "", msg(lang, "b.site_intro", domain=domain), "\n".join(_finding_line(f, lang) for f in findings), "", f"{_offer(cfg, lang)} {msg(lang, 'b.quick_fixes')}", msg(lang, "b.ask_report")] + proof = pick_proof(lead, cfg) if lang == "en" else "" + if proof: + body[-1:-1] = [proof] else: # healthy site, blocked check, or work that is not about websites: no invented problems intro = msg(lang, "b.healthy_intro", domain=domain) if website else msg(lang, "b.generic_intro", name=name) extra = f" {msg(lang, 'b.healthy_offer')}" if web else "" @@ -110,13 +133,29 @@ def template_business(lead: Lead, cfg, lang: str = "en") -> str: return "\n".join(body) +def make_followup(lead: Lead, cfg, n: int) -> str: + """The n-th follow-up (1 or more) to a lead that has not answered, in the lead's language. Short and easy to ignore.""" + lang = draft_language(lead, cfg) + title = re.sub(r"^\[[^\]]*\]\s*", "", lead.title).strip()[:90] + lines = [] + if lead.kind == "business": + lines += [f"{msg(lang, 'b.subject')}: {msg(lang, 'fu.subject', name=lead.title)}", "", msg(lang, "b.hello", name=lead.title)] + else: + name = _name(lead.author) + lines.append(msg(lang, "p.hi", name=name) if name else msg(lang, "p.hi_anon")) + lines += ["", msg(lang, "fu.line", title=title), msg(lang, "fu.last" if n >= max(1, cfg.follow_up_max) else "fu.ask"), + "", cfg.signature or cfg.name] + return "\n".join(lines) + + def llm_prompt(lead: Lead, cfg, lang: str) -> str: evidence = lead.body[:2500] if lead.kind == "business": findings = (lead.extra.get("audit") or {}).get("findings", []) evidence = "\n".join(f"- {f['title']}: {f['pitch']}" for f in findings) or "No website listed." return (f"About me: {cfg.name}. {cfg.pitch}. Skills: {', '.join(cfg.skills)}. " - f"Portfolio: {cfg.portfolio or 'none'}. Sign as: {cfg.signature or cfg.name}.\n\n" + f"Portfolio: {cfg.portfolio or 'none'}. Sign as: {cfg.signature or cfg.name}.\n" + f"Relevant past work (use it only if it fits, never invent more): {pick_proof(lead, cfg) or 'none'}\n\n" f"Lead type: {lead.kind} from {lead.source}\nName/author: {lead.author or lead.title}\n" f"Title: {lead.title}\nCategory: {lead.extra.get('category', '')}\n" f"Budget: {lead.budget or 'not stated'}\nEvidence:\n{evidence}\n\n" diff --git a/leadhound/i18n/ar.py b/leadhound/i18n/ar.py index 211764e..6d29657 100644 --- a/leadhound/i18n/ar.py +++ b/leadhound/i18n/ar.py @@ -70,4 +70,15 @@ "why.site_issues": "{n} مشكلة في الموقع، الخطورة {sev}", "why.critical": "وُجدت مشكلات حرجة", "why.site_healthy": "الموقع يبدو سليمًا", "why.not_audited": "لديه موقع (لم يُفحص بعد)", "why.public_email": "بريد عام", "why.public_phone": "هاتف عام", "why.no_contact": "لا توجد وسيلة تواصل عامة", + # follow-ups to a lead that has not answered + "fu.subject": "متابعة: {name}", + "fu.line": "أتابع رسالتي بخصوص \"{title}\". ما زلت متاحًا ويسعدني المساعدة.", + "fu.ask": "هل يكون من الأسهل تبادل بعض الأسئلة القصيرة برسالة أو مكالمة قصيرة؟", + "fu.last": "إن لم يكن التوقيت مناسبًا فلا مشكلة. أخبرني ولن أراسلك مجددًا.", + # the email you get after an automatic search (Pro) + "al.subject": "leadhound: {n} نتائج جديدة لك", + "al.intro": "وجد leadhound {n} نتائج جديدة بدرجة {min} أو أكثر:", + "al.footer": "افتح leadhound لمراسلتهم. تصلك هذه الرسالة لأن التنبيهات مفعّلة في الإعدادات.", + # score reason for Himalayas contract roles + "why.contract_role": "عمل بعقد عن بُعد", } diff --git a/leadhound/i18n/de.py b/leadhound/i18n/de.py index c02357e..977f6c4 100644 --- a/leadhound/i18n/de.py +++ b/leadhound/i18n/de.py @@ -70,4 +70,15 @@ "why.site_issues": "{n} Website-Problem(e), Schwere {sev}", "why.critical": "kritische Probleme gefunden", "why.site_healthy": "Website wirkt in Ordnung", "why.not_audited": "hat eine Website (noch nicht geprüft)", "why.public_email": "öffentliche E-Mail", "why.public_phone": "öffentliche Telefonnummer", "why.no_contact": "kein öffentlicher Kontakt", + # follow-ups to a lead that has not answered + "fu.subject": "Kurze Nachfrage: {name}", + "fu.line": "Ich melde mich noch einmal wegen meiner Nachricht zu „{title}“. Ich bin weiterhin verfügbar und helfe gern.", + "fu.ask": "Wären ein paar kurze Fragen per Nachricht oder ein kurzer Anruf einfacher?", + "fu.last": "Wenn es gerade nicht passt, kein Problem. Sag einfach Bescheid, dann schreibe ich nicht mehr.", + # the email you get after an automatic search (Pro) + "al.subject": "leadhound: {n} neue Treffer für dich", + "al.intro": "leadhound hat {n} neue Treffer mit {min} Punkten oder mehr gefunden:", + "al.footer": "Öffne leadhound, um ihnen zu schreiben. Du bekommst diese E-Mail, weil Benachrichtigungen in den Einstellungen an sind.", + # score reason for Himalayas contract roles + "why.contract_role": "Remote-Auftrag", } diff --git a/leadhound/i18n/en.py b/leadhound/i18n/en.py index d5a7e3d..9ae1898 100644 --- a/leadhound/i18n/en.py +++ b/leadhound/i18n/en.py @@ -75,4 +75,15 @@ "why.site_issues": "{n} website issue(s), severity {sev}", "why.critical": "critical problems found", "why.site_healthy": "website looks healthy", "why.not_audited": "has a website (not checked yet)", "why.public_email": "public email", "why.public_phone": "public phone", "why.no_contact": "no public contact found", + # follow-ups to a lead that has not answered + "fu.subject": "Following up: {name}", + "fu.line": "Just following up on my message about \"{title}\". I'm still available and happy to help.", + "fu.ask": "Would a few quick questions by message or a short call be easier?", + "fu.last": "If the timing isn't right, no problem. Just let me know and I won't write again.", + # the email you get after an automatic search (Pro) + "al.subject": "leadhound: {n} new matches for you", + "al.intro": "leadhound found {n} new matches scoring {min} or more:", + "al.footer": "Open leadhound to write to them. You get this email because alerts are on in Settings.", + # score reason for Himalayas contract roles + "why.contract_role": "remote contract role", } diff --git a/leadhound/i18n/es.py b/leadhound/i18n/es.py index 0487d27..c803193 100644 --- a/leadhound/i18n/es.py +++ b/leadhound/i18n/es.py @@ -70,4 +70,15 @@ "why.site_issues": "{n} problema(s) en la web, gravedad {sev}", "why.critical": "problemas críticos encontrados", "why.site_healthy": "la web parece estar bien", "why.not_audited": "tiene web (aún sin revisar)", "why.public_email": "correo público", "why.public_phone": "teléfono público", "why.no_contact": "sin contacto público", + # follow-ups to a lead that has not answered + "fu.subject": "Seguimiento: {name}", + "fu.line": "Te escribo de nuevo por mi mensaje sobre \"{title}\". Sigo disponible y con ganas de ayudar.", + "fu.ask": "¿Te resultaría más fácil responder unas preguntas por mensaje o una llamada corta?", + "fu.last": "Si no es buen momento, no pasa nada. Avísame y no volveré a escribir.", + # the email you get after an automatic search (Pro) + "al.subject": "leadhound: {n} coincidencias nuevas para ti", + "al.intro": "leadhound encontró {n} coincidencias nuevas con {min} puntos o más:", + "al.footer": "Abre leadhound para escribirles. Recibes este correo porque las alertas están activadas en Ajustes.", + # score reason for Himalayas contract roles + "why.contract_role": "trabajo remoto por contrato", } diff --git a/leadhound/i18n/fr.py b/leadhound/i18n/fr.py index f59af6f..971f6a6 100644 --- a/leadhound/i18n/fr.py +++ b/leadhound/i18n/fr.py @@ -70,4 +70,15 @@ "why.site_issues": "{n} problème(s) sur le site, gravité {sev}", "why.critical": "problèmes critiques trouvés", "why.site_healthy": "le site semble en bon état", "why.not_audited": "a un site (pas encore vérifié)", "why.public_email": "e-mail public", "why.public_phone": "téléphone public", "why.no_contact": "aucun contact public", + # follow-ups to a lead that has not answered + "fu.subject": "Suite à mon message : {name}", + "fu.line": "Je reviens vers vous au sujet de mon message sur « {title} ». Je suis toujours disponible et ravi d'aider.", + "fu.ask": "Serait-il plus simple d'échanger quelques questions par message ou de faire un court appel ?", + "fu.last": "Si ce n'est pas le bon moment, aucun souci. Dites-le-moi et je ne vous relancerai plus.", + # the email you get after an automatic search (Pro) + "al.subject": "leadhound : {n} nouvelles pistes pour vous", + "al.intro": "leadhound a trouvé {n} nouvelles pistes notées {min} ou plus :", + "al.footer": "Ouvrez leadhound pour leur écrire. Vous recevez cet e-mail car les alertes sont activées dans les Réglages.", + # score reason for Himalayas contract roles + "why.contract_role": "mission freelance à distance", } diff --git a/leadhound/i18n/hi.py b/leadhound/i18n/hi.py index 236dd5a..e114a6a 100644 --- a/leadhound/i18n/hi.py +++ b/leadhound/i18n/hi.py @@ -70,4 +70,15 @@ "why.site_issues": "वेबसाइट में {n} समस्या, गंभीरता {sev}", "why.critical": "गंभीर समस्याएँ मिलीं", "why.site_healthy": "वेबसाइट ठीक लगती है", "why.not_audited": "वेबसाइट है (अभी जाँची नहीं गई)", "why.public_email": "सार्वजनिक ईमेल", "why.public_phone": "सार्वजनिक फ़ोन", "why.no_contact": "कोई सार्वजनिक संपर्क नहीं", + # follow-ups to a lead that has not answered + "fu.subject": "फ़ॉलो-अप: {name}", + "fu.line": "\"{title}\" के बारे में अपने संदेश पर फ़ॉलो-अप कर रहा हूँ। मैं अब भी उपलब्ध हूँ और मदद करके खुशी होगी।", + "fu.ask": "क्या संदेश में कुछ छोटे सवाल या एक छोटी कॉल आसान रहेगी?", + "fu.last": "अगर अभी सही समय नहीं है तो कोई बात नहीं। बस बता दें, मैं फिर नहीं लिखूँगा।", + # the email you get after an automatic search (Pro) + "al.subject": "leadhound: आपके लिए {n} नए मैच", + "al.intro": "leadhound को {min} या ज़्यादा स्कोर वाले {n} नए मैच मिले:", + "al.footer": "उन्हें लिखने के लिए leadhound खोलें। यह ईमेल इसलिए आया क्योंकि सेटिंग्स में अलर्ट चालू हैं।", + # score reason for Himalayas contract roles + "why.contract_role": "रिमोट कॉन्ट्रैक्ट काम", } diff --git a/leadhound/i18n/ka.py b/leadhound/i18n/ka.py index ab832c3..d3d318d 100644 --- a/leadhound/i18n/ka.py +++ b/leadhound/i18n/ka.py @@ -70,4 +70,15 @@ "why.site_issues": "საიტზე {n} პრობლემა, სიმძიმე {sev}", "why.critical": "ნაპოვნია კრიტიკული პრობლემები", "why.site_healthy": "საიტი კარგ მდგომარეობაშია", "why.not_audited": "აქვს საიტი (ჯერ არ შემოწმებულა)", "why.public_email": "საჯარო ელფოსტა", "why.public_phone": "საჯარო ტელეფონი", "why.no_contact": "საჯარო კონტაქტი არ არის", + # follow-ups to a lead that has not answered + "fu.subject": "შეხსენება: {name}", + "fu.line": "გწერთ ჩემი შეტყობინების გამო „{title}“-თან დაკავშირებით. ისევ თავისუფალი ვარ და სიამოვნებით დაგეხმარებით.", + "fu.ask": "იქნებ უფრო მარტივი იყოს რამდენიმე კითხვა შეტყობინებით ან მოკლე ზარი?", + "fu.last": "თუ ახლა შესაფერისი დრო არ არის, არაუშავს. მითხარით და აღარ მოგწერთ.", + # the email you get after an automatic search (Pro) + "al.subject": "leadhound: {n} ახალი შესატყვისი", + "al.intro": "leadhound-მა იპოვა {n} ახალი შესატყვისი, {min} ან მეტი ქულით:", + "al.footer": "გახსენით leadhound, რომ მისწეროთ. ამ წერილს იღებთ, რადგან შეტყობინებები ჩართულია პარამეტრებში.", + # score reason for Himalayas contract roles + "why.contract_role": "დისტანციური კონტრაქტი", } diff --git a/leadhound/i18n/pt.py b/leadhound/i18n/pt.py index 94ea9a5..935a45f 100644 --- a/leadhound/i18n/pt.py +++ b/leadhound/i18n/pt.py @@ -70,4 +70,15 @@ "why.site_issues": "{n} problema(s) no site, gravidade {sev}", "why.critical": "problemas críticos encontrados", "why.site_healthy": "o site parece bem", "why.not_audited": "tem site (ainda não verificado)", "why.public_email": "e-mail público", "why.public_phone": "telefone público", "why.no_contact": "sem contato público", + # follow-ups to a lead that has not answered + "fu.subject": "Retomando contato: {name}", + "fu.line": "Só retomando minha mensagem sobre \"{title}\". Continuo disponível e feliz em ajudar.", + "fu.ask": "Seria mais fácil responder algumas perguntas por mensagem ou fazer uma ligação rápida?", + "fu.last": "Se não for o momento certo, sem problema. É só me avisar e não escrevo de novo.", + # the email you get after an automatic search (Pro) + "al.subject": "leadhound: {n} novas oportunidades para você", + "al.intro": "O leadhound encontrou {n} novas oportunidades com nota {min} ou mais:", + "al.footer": "Abra o leadhound para escrever para eles. Você recebe este e-mail porque os alertas estão ligados nas Configurações.", + # score reason for Himalayas contract roles + "why.contract_role": "vaga remota por contrato", } diff --git a/leadhound/i18n/ru.py b/leadhound/i18n/ru.py index e599986..5098424 100644 --- a/leadhound/i18n/ru.py +++ b/leadhound/i18n/ru.py @@ -70,4 +70,15 @@ "why.site_issues": "{n} проблем(ы) на сайте, тяжесть {sev}", "why.critical": "найдены критические проблемы", "why.site_healthy": "сайт выглядит нормально", "why.not_audited": "есть сайт (ещё не проверен)", "why.public_email": "публичный email", "why.public_phone": "публичный телефон", "why.no_contact": "нет публичных контактов", + # follow-ups to a lead that has not answered + "fu.subject": "Напоминание: {name}", + "fu.line": "Напоминаю о своём сообщении насчёт «{title}». Я всё ещё свободен и с радостью помогу.", + "fu.ask": "Может, удобнее обсудить пару вопросов в переписке или коротко созвониться?", + "fu.last": "Если сейчас неудобно, ничего страшного. Просто дайте знать, и я больше не буду писать.", + # the email you get after an automatic search (Pro) + "al.subject": "leadhound: новых совпадений — {n}", + "al.intro": "leadhound нашёл новых совпадений с оценкой от {min}: {n}", + "al.footer": "Откройте leadhound, чтобы написать им. Вы получили это письмо, потому что оповещения включены в настройках.", + # score reason for Himalayas contract roles + "why.contract_role": "удалённый контракт", } diff --git a/leadhound/i18n/tr.py b/leadhound/i18n/tr.py index 54d9f1e..9122e70 100644 --- a/leadhound/i18n/tr.py +++ b/leadhound/i18n/tr.py @@ -70,4 +70,15 @@ "why.site_issues": "sitede {n} sorun, önem {sev}", "why.critical": "kritik sorunlar bulundu", "why.site_healthy": "site sağlıklı görünüyor", "why.not_audited": "web sitesi var (henüz kontrol edilmedi)", "why.public_email": "herkese açık e-posta", "why.public_phone": "herkese açık telefon", "why.no_contact": "herkese açık iletişim yok", + # follow-ups to a lead that has not answered + "fu.subject": "Hatırlatma: {name}", + "fu.line": "\"{title}\" hakkındaki mesajımı hatırlatmak istedim. Hâlâ müsaitim ve yardımcı olmaktan memnuniyet duyarım.", + "fu.ask": "Mesajla birkaç kısa soru ya da kısa bir görüşme daha kolay olur mu?", + "fu.last": "Zamanlama uygun değilse sorun değil. Haber verin, bir daha yazmam.", + # the email you get after an automatic search (Pro) + "al.subject": "leadhound: sizin için {n} yeni eşleşme", + "al.intro": "leadhound, {min} ve üzeri puanlı {n} yeni eşleşme buldu:", + "al.footer": "Onlara yazmak için leadhound'u açın. Bu e-postayı Ayarlar'da uyarılar açık olduğu için alıyorsunuz.", + # score reason for Himalayas contract roles + "why.contract_role": "uzaktan sözleşmeli iş", } diff --git a/leadhound/i18n/zh.py b/leadhound/i18n/zh.py index 2b55d50..c384293 100644 --- a/leadhound/i18n/zh.py +++ b/leadhound/i18n/zh.py @@ -70,4 +70,15 @@ "why.site_issues": "网站有 {n} 个问题,严重度 {sev}", "why.critical": "发现严重问题", "why.site_healthy": "网站看起来没问题", "why.not_audited": "有网站(尚未检查)", "why.public_email": "公开邮箱", "why.public_phone": "公开电话", "why.no_contact": "没有公开联系方式", + # follow-ups to a lead that has not answered + "fu.subject": "跟进:{name}", + "fu.line": "跟进一下我关于“{title}”的消息。我仍然有空,很乐意帮忙。", + "fu.ask": "用消息问几个简单问题,或者简短通个电话,会不会更方便?", + "fu.last": "如果现在时机不合适也没关系。告诉我一声,我就不再打扰。", + # the email you get after an automatic search (Pro) + "al.subject": "leadhound:为你找到 {n} 个新匹配", + "al.intro": "leadhound 找到 {n} 个得分不低于 {min} 的新匹配:", + "al.footer": "打开 leadhound 给他们写信。你收到这封邮件是因为在设置中开启了提醒。", + # score reason for Himalayas contract roles + "why.contract_role": "远程合同岗位", } diff --git a/leadhound/jobs.py b/leadhound/jobs.py index 2672848..9c0818e 100644 --- a/leadhound/jobs.py +++ b/leadhound/jobs.py @@ -24,9 +24,9 @@ class JobBusy(Exception): class Job: - def __init__(self, kind: str, params: dict): + def __init__(self, kind: str, params: dict, auto: bool = False): self.id = uuid.uuid4().hex[:10] - self.kind, self.params = kind, params + self.kind, self.params, self.auto = kind, params, auto # auto: started by the scheduler, not by a click self.status = "running" # running | done | error | cancelled self.log: list[str] = [] self.result: dict = {} @@ -39,7 +39,7 @@ def add(self, line: str) -> None: del self.log[:-MAX_LOG] def to_dict(self) -> dict: - return {"id": self.id, "kind": self.kind, "params": self.params, "status": self.status, + return {"id": self.id, "kind": self.kind, "params": self.params, "status": self.status, "auto": self.auto, "log": list(self.log), "result": self.result, "started": self.started, "finished": self.finished} @@ -97,13 +97,14 @@ def __init__(self, db_path: str, config_path: str, fetcher_factory=Fetcher, clou self.current: Job | None = None self._lock = threading.Lock() self._threads: list[threading.Thread] = [] + self.on_done: list = [] # fn(job), called in the job's thread after it ends (alerts after automatic searches) - def start(self, kind: str, params: dict) -> Job: + def start(self, kind: str, params: dict, auto: bool = False) -> Job: params = clean_params(kind, params, self.cloud) with self._lock: if self.current and self.current.status == "running": raise JobBusy("another search is still running") - job = Job(kind, params) + job = Job(kind, params, auto) self.jobs[job.id] = job self.current = job for old in sorted(self.jobs.values(), key=lambda j: j.started)[:-20]: @@ -162,6 +163,11 @@ def _run(self, job: Job) -> None: finally: if store: store.close() + for fn in self.on_done: + try: + fn(job) + except Exception as e: # an alert must never break searching + job.add(f"after search: {e}") job.finished = time.time() def _audit_one(self, store, cfg, fetcher, job): @@ -185,8 +191,9 @@ def _audit_one(self, store, cfg, fetcher, job): class AutoScanner: """Runs a full search every N hours (Settings > auto search) while leadhound is running.""" - def __init__(self, jobs: JobManager, state_path: str, interval: float = 60): + def __init__(self, jobs: JobManager, state_path: str, interval: float = 60, allowed=lambda: True): self.jobs, self.state_path, self.interval = jobs, state_path, interval + self.allowed = allowed # automatic search is a Pro feature: stops by itself when Pro or the trial ends self._stop = threading.Event() def _last(self) -> float: @@ -207,10 +214,10 @@ def tick(self, now: float | None = None) -> bool: """Start a scan if one is due. Returns True if it started one.""" now = now or time.time() hours = config.load(self.jobs.config_path).auto_scan_hours - if not hours or now - self._last() < hours * 3600: + if not hours or now - self._last() < hours * 3600 or not self.allowed(): return False try: - job = self.jobs.start("scan", {}) + job = self.jobs.start("scan", {}, auto=True) except JobBusy: return False job.add("automatic search (Settings > search automatically)") diff --git a/leadhound/licensing.py b/leadhound/licensing.py index 89f4f26..9ed5de4 100644 --- a/leadhound/licensing.py +++ b/leadhound/licensing.py @@ -1,17 +1,20 @@ """Plans: a free taste, a 7-day trial after sign-up, Free, and Pro by license key. How a copy of leadhound moves through them: - taste full Pro for the first TASTE_USES uses (a search, a sent message, an AI draft). + taste Pro features for the first TASTE_USES uses (an AI draft, a reply check, an automatic search). sign-up then it asks for an email. The license server (licenseserver.py) gives one signed 7-day trial per email and per device, so deleting files or reinstalling does not start a new one. trial 7 days of Pro. Ends for good; asking the server again returns the same, already ended, trial. - free 3 searches a day, your top 10 matches, and "open Gmail / WhatsApp with the message ready". + free everything you do yourself, with no limits: searching every source, all your matches, local businesses, + website checks, drafts, follow-ups and sending from your own connected accounts. No account needed. pro a license key (`LH1..`) signed by the seller's private key, checked offline. + Pro adds the things that run for you or cost the seller money: hosted AI drafts, automatic search with + an email digest of new matches, and reply detection. Where the lock is real: the AI drafts run on the seller's server and need a valid key or trial, so they cannot be -unlocked by editing this app. Searching and sending run on the user's computer, and leadhound is open source, so -a developer who edits the code can skip those checks. The server, the signed tokens and the device record stop the -ordinary routes (deleting license.json, reinstalling, copying a file between computers), not a patched copy. +unlocked by editing this app. Automatic search and reply detection run on the user's computer, and leadhound is +open source, so a developer who edits the code can skip those checks. That is fine: Pro pays for convenience and +for the project, not for access to code that is already public. While PUBLIC_KEY_HEX is empty (a fresh checkout, a fork) licensing is off and everything is unlocked. If SERVER is empty the sign-up step is skipped and the trial is a plain 7-day clock on this computer. @@ -31,7 +34,6 @@ import urllib.error import urllib.request import uuid -from datetime import date from . import ed25519 @@ -48,10 +50,8 @@ def _setting(name: str, default: str) -> str: PRICE_MONTH = _setting("LEADHOUND_PRICE_MONTH", "$12.99") PRICE_YEAR = _setting("LEADHOUND_PRICE_YEAR", "$89.99") TRIAL_DAYS = 7 -TASTE_USES = 7 # uses before the email sign-up (needs SERVER) -FREE_SEARCHES = 3 # "find new clients" runs per day on Free -FREE_MAX_LEADS = 10 # matches shown on Free -FEATURES = ("send", "ai", "business", "autosearch") # what Free does not include +TASTE_USES = 7 # Pro uses before the email sign-up (needs SERVER) +FEATURES = ("ai", "autosearch", "replies") # what Free does not include DAY = 86400 EMAIL_RX = re.compile(r"^[^\s@<>\",;]{1,64}@[^\s@<>\",;]+\.[^\s@<>\",;]+$") @@ -150,9 +150,9 @@ def configured(self) -> bool: def status(self) -> dict: now, d = self.clock(), self._read() base = {"configured": self.configured, "server": bool(SERVER), "buy_url": BUY_URL, "price_month": PRICE_MONTH, - "price_year": PRICE_YEAR, "trial_days": TRIAL_DAYS, "free_searches": FREE_SEARCHES, - "free_max_leads": FREE_MAX_LEADS, "taste_uses": TASTE_USES, "email": "", "expires": 0, "trial_left": 0, - "uses_left": None, "key_state": "none", "searches_left": None, "need_signup": False, "trial_used": False} + "price_year": PRICE_YEAR, "trial_days": TRIAL_DAYS, "features": list(FEATURES), + "taste_uses": TASTE_USES, "email": "", "expires": 0, "trial_left": 0, + "uses_left": None, "key_state": "none", "need_signup": False, "trial_used": False} if not self.configured: # fresh checkout or fork: nothing is locked return {**base, "plan": "pro"} if "first_use" not in d: # the clock starts at the first look, even for someone who buys straight away @@ -181,8 +181,7 @@ def status(self) -> dict: if uses < TASTE_USES and d["first_use"] + TRIAL_DAYS * DAY > now: return {**base, "plan": "taste", "uses_left": TASTE_USES - uses} base["need_signup"] = True - used = d.get("searches", {}).get(date.fromtimestamp(now).isoformat(), 0) - return {**base, "plan": "free", "searches_left": max(0, FREE_SEARCHES - used)} + return {**base, "plan": "free"} def is_pro(self) -> bool: return self.status()["plan"] in ("pro", "trial", "taste") @@ -193,30 +192,14 @@ def require(self, feature: str) -> None: if not self.is_pro(): raise ProRequired(feature) - def max_leads(self) -> int: - return 100000 if self.is_pro() else FREE_MAX_LEADS - def count_use(self) -> None: - """One use of the product (a search, a sent message, an AI draft). Only the free taste counts them.""" + """One use of a Pro feature (an AI draft, a reply check). Only the free taste counts them.""" if self.status()["plan"] != "taste": return d = self._read() d["uses"] = d.get("uses", 0) + 1 self._write(d) - def use_search(self) -> None: - """Count one 'find new clients' run. Free users get FREE_SEARCHES a day.""" - st = self.status() - if st["plan"] != "free": - self.count_use() - return - d, today = self._read(), date.fromtimestamp(self.clock()).isoformat() - used = d.setdefault("searches", {}).get(today, 0) - if used >= FREE_SEARCHES: - raise ProRequired("searches") - d["searches"] = {today: used + 1} # older days are not needed - self._write(d) - def signup(self, email: str) -> dict: """Ask the server for the one free trial for this email and device.""" email = (email or "").strip() diff --git a/leadhound/replies.py b/leadhound/replies.py new file mode 100644 index 0000000..234bf56 --- /dev/null +++ b/leadhound/replies.py @@ -0,0 +1,102 @@ +"""Reply detection (Pro): find answers from leads you wrote to, and move those leads to Replied. + +It uses the email account you connected for sending (the same app password) over IMAP with TLS, and opens the +inbox read-only: it only searches by sender and date. It never downloads, marks, moves or deletes a message, +and nothing leaves your computer except the login to your own mail server. +""" +from __future__ import annotations + +import imaplib +import re +import ssl +import time + +from .send import SendError, clean_host + +EMAIL_RX = re.compile(r"[\w.+-]+@[\w-]+(?:\.[\w-]+)+") +IMAP_HOSTS = {"smtp.gmail.com": "imap.gmail.com", "smtp-mail.outlook.com": "outlook.office365.com", + "smtp.office365.com": "outlook.office365.com"} +MONTHS = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec") +LOOK_BACK_DAYS = 60 + + +def imap_host(settings: dict, cloud: bool = False) -> str: + """The IMAP server for an SMTP account: known providers, else smtp.example.com -> imap.example.com.""" + host = IMAP_HOSTS.get(settings.get("host", "")) or re.sub(r"^(smtp|mail)\.", "imap.", settings.get("host", "")) + return host if host in ("127.0.0.1", "localhost") and not cloud else clean_host(host, cloud) + + +def imap_date(ts: float) -> str: + t = time.gmtime(ts) # IMAP wants English month names whatever the computer's language + return f"{t.tm_mday:02d}-{MONTHS[t.tm_mon - 1]}-{t.tm_year}" + + +def candidates(store, now: float | None = None, days: int = LOOK_BACK_DAYS) -> list[tuple[int, list[str], float]]: + """(lead id, email addresses, when you first wrote) for contacted leads with a public email address.""" + now = now or time.time() + out = [] + for lead in store.query(status="contacted", limit=500): + addrs = EMAIL_RX.findall(lead.contact or "") + first = store.outreach(lead.id)["contacted_at"] + if addrs and first and first > now - days * 86400: + out.append((lead.id, addrs[:3], first)) + return out + + +def find(settings: dict, items: list, cloud: bool = False, imap_factory=None) -> list[int]: + """Ids of the leads in `items` that have a message from them in the inbox since you wrote.""" + if not items: + return [] + host = imap_host(settings, cloud) + try: + conn = (imap_factory or (lambda h: imaplib.IMAP4_SSL(h, 993, ssl_context=ssl.create_default_context(), timeout=20)))(host) + except (OSError, imaplib.IMAP4.error) as e: + raise SendError(f"Could not reach your mail server ({host}): {e}", 502) + found = [] + try: + try: + conn.login(settings["address"], settings["password"]) + except imaplib.IMAP4.error: + raise SendError("Your mail server refused the login. Reconnect your email account with an app password.", 502) + typ, _ = conn.select("INBOX", readonly=True) + if typ != "OK": + raise SendError("Could not open your inbox.", 502) + for lead_id, addrs, since in items: + for addr in addrs: # the address came from EMAIL_RX: no quotes or spaces to escape + typ, data = conn.search(None, "FROM", f'"{addr}"', "SINCE", imap_date(since)) + if typ == "OK" and data and data[0] and data[0].split(): + found.append(lead_id) + break + except (OSError, imaplib.IMAP4.error) as e: + raise SendError(f"The mail server stopped answering: {e}", 502) + finally: + try: + conn.logout() + except Exception: + pass + return found + + +def apply(store, ids: list[int]) -> int: + """Move leads that answered to Replied (only if they are still Contacted) and record it.""" + n = 0 + for lead_id in ids: + lead = store.get(lead_id) + if lead and lead.status == "contacted": + store.update(lead_id, status="replied") + store.log(lead_id, "replied", "email") + n += 1 + return n + + +def check(accounts, store, lock, cloud: bool = False, imap_factory=None) -> dict: + """The whole check. `lock` guards the shared store; the mail server is asked without holding it.""" + settings = accounts.get("email") + if not settings: + raise SendError("Connect your email account in Accounts first: replies are found in that inbox.") + with lock: + items = candidates(store) + ids = find(settings, items, cloud, imap_factory) + with lock: + moved = apply(store, ids) + return {"checked": len(items), "replied": moved} diff --git a/leadhound/score.py b/leadhound/score.py index 78ab934..f720a29 100644 --- a/leadhound/score.py +++ b/leadhound/score.py @@ -100,6 +100,8 @@ def score_intent_lead(lead: Lead, cfg, now: float) -> Lead: w.add(10, "bounty_label", "bounty label, amount unknown (may be points, not cash)") elif lead.source == "github": w.add(5, "help_wanted", "help wanted (often unpaid; good door-opener)") + elif lead.source == "himalayas": + w.add(15, "contract_role", "remote contract role") if lead.source == "hn" and "seeking freelancer" in " ".join(lead.signals).lower(): w.add(15, "hn_thread", "HN seeking-freelancer thread") intent = w.total - before diff --git a/leadhound/sources/__init__.py b/leadhound/sources/__init__.py index 128d9a0..88e1057 100644 --- a/leadhound/sources/__init__.py +++ b/leadhound/sources/__init__.py @@ -4,13 +4,14 @@ If some sub-requests fail (one feed of five), raise PartialFailure with the leads you did get. """ from .base import PartialFailure, collect_each # noqa: F401 -from . import freelancer, github, hn, mastodon, reddit, rss # noqa: E402 +from . import freelancer, github, hn, himalayas, mastodon, reddit, rss # noqa: E402 SOURCES = { "freelancer": freelancer.collect, "reddit": reddit.collect, "hn": hn.collect, "github": github.collect, + "himalayas": himalayas.collect, "mastodon": mastodon.collect, "rss": rss.collect, } diff --git a/leadhound/sources/himalayas.py b/leadhound/sources/himalayas.py new file mode 100644 index 0000000..620902f --- /dev/null +++ b/leadhound/sources/himalayas.py @@ -0,0 +1,83 @@ +"""Himalayas: remote contract roles (contractors only, not full-time jobs), searched by your skills. + +Public JSON API (https://himalayas.app/api). Each lead links back to the role on Himalayas, which is +the attribution they ask for. Three searches per run at most, one per top skill. +""" +from __future__ import annotations + +from urllib.parse import quote + +from ..models import Lead +from ..textutil import find_emails, strip_html +from .base import PartialFailure, collect_each + +SEARCH = "https://himalayas.app/jobs/api/search?q={}&employment_type=Contractor" +SYMBOL = {"USD": "$", "EUR": "€", "GBP": "£"} +MAX_QUERIES = 3 + + +def _num(v) -> float: + try: + return float(v) + except (TypeError, ValueError): + return 0.0 + + +def budget(job: dict) -> str: + """'$50-$80/hr' or '$90,000-$120,000' (a year); empty when the role states no pay.""" + lo, hi = _num(job.get("minSalary")), _num(job.get("maxSalary")) + if not lo and not hi: + return "" + cur = (job.get("currency") or "USD").upper() + sym = SYMBOL.get(cur) + fmt = (lambda v: f"{sym}{v:,.0f}") if sym else (lambda v: f"{v:,.0f} {cur}") + text = fmt(lo or hi) if not (lo and hi) or lo == hi else f"{fmt(lo)}-{fmt(hi)}" + return text + ("/hr" if (job.get("salaryPeriod") or "").lower().startswith("hour") else "") + + +def parse(data: dict, min_created: float) -> list[Lead]: + leads = [] + for job in data.get("jobs") or []: + url = job.get("applicationLink") or job.get("guid") or "" + guid = job.get("guid") or url + if not url.startswith("https://") or not job.get("title"): + continue + created = _num(job.get("pubDate")) + if created and created < min_created: + continue + body = strip_html(job.get("description") or job.get("excerpt") or "") + company = (job.get("companyName") or "").strip() + places = job.get("locationRestrictions") or [] + leads.append(Lead( + source="himalayas", external_id=guid.rstrip("/").rsplit("/", 1)[-1][:120] or guid[-120:], kind="post", + title=f"{job['title'].strip()[:160]}" + (f" · {company[:60]}" if company else ""), url=url, + body=body[:6000], author=company, created_at=created, budget=budget(job), + contact=", ".join(find_emails(body)) or "apply via himalayas.app", + location=", ".join(str(p) for p in places[:4]) if isinstance(places, list) else "", + signals=["remote contract role"], + extra={"skills": [str(c).replace("-", " ") for c in (job.get("categories") or [])[:12]], + "category": ((job.get("parentCategories") or [""])[0] or "")}, + )) + return leads + + +def collect(fetcher, cfg, now: float) -> list[Lead]: + if not getattr(cfg, "himalayas", False): + return [] + queries = [s for s in cfg.skills if s.strip()][:MAX_QUERIES] + if not queries: + return [] + min_created = now - cfg.max_age_days * 86400 + partial = None + try: + raw = collect_each(queries, lambda q: parse(fetcher.get_json(SEARCH.format(quote(q))), min_created)) + except PartialFailure as pf: + raw, partial = pf.leads, pf + seen, leads = set(), [] + for lead in raw: # the same role can match two skills + if lead.external_id not in seen: + seen.add(lead.external_id) + leads.append(lead) + if partial: + raise PartialFailure(leads, partial.errors) + return leads diff --git a/leadhound/store.py b/leadhound/store.py index 437bee9..a6ac664 100644 --- a/leadhound/store.py +++ b/leadhound/store.py @@ -1,4 +1,8 @@ -"""SQLite lead store. Re-scans update content and score but never touch status, notes or draft.""" +"""SQLite lead store. Re-scans update content and score but never touch status, notes or draft. + +The activity table records what you did, one row per event: contacted (first message), followup (a later +nudge), nofollow (stop reminding me), replied (found in your inbox). Follow-ups and the week chart read it. +""" from __future__ import annotations import json @@ -174,14 +178,78 @@ def stats(self) -> dict: out["sent_today"] = out["sent_week"][-1] return out + def log(self, lead_id: int, kind: str, via: str = "") -> None: + if kind not in ("contacted", "followup", "nofollow", "replied"): + raise ValueError(f"unknown activity {kind}") + self.db.execute("INSERT INTO activity (lead_id, kind, via, at) VALUES (?, ?, ?, ?)", + (lead_id, kind, str(via)[:30], time.time())) + self.db.commit() + + def outreach(self, lead_id: int) -> dict: + """When you first wrote, how many follow-ups went out, the last message, and whether reminders are off.""" + row = self.db.execute( + "SELECT MIN(CASE WHEN kind='contacted' THEN at END) first, MAX(CASE WHEN kind IN ('contacted','followup') THEN at END) last, " + "SUM(kind='followup') n, SUM(kind='nofollow') stop FROM activity WHERE lead_id=?", (lead_id,)).fetchone() + return {"contacted_at": row["first"] or 0, "last_at": row["last"] or 0, "followups": row["n"] or 0, + "stopped": bool(row["stop"])} + + def followups_due(self, days: int, max_n: int, now: float | None = None, limit: int = 50) -> list[tuple[Lead, dict]]: + """Contacted leads with no reply for `days` days and fewer than `max_n` follow-ups, oldest first.""" + if max_n <= 0: + return [] + now = now or time.time() + rows = self.db.execute( + "SELECT l.id, MAX(CASE WHEN a.kind IN ('contacted','followup') THEN a.at END) last, " + "SUM(a.kind='followup') n, SUM(a.kind='nofollow') stop FROM leads l JOIN activity a ON a.lead_id = l.id " + "WHERE l.status = 'contacted' GROUP BY l.id HAVING stop = 0 AND n < ? AND last IS NOT NULL AND last < ? " + "ORDER BY last LIMIT ?", (max_n, now - days * 86400, limit)).fetchall() + out = [] + for r in rows: + lead = self.get(r["id"]) + if lead: + out.append((lead, {**self.outreach(r["id"]), "days": int((now - r["last"]) // 86400)})) + return out + + def insights(self) -> dict: + """What works: per source, how many leads you wrote to, how many answered and how many you won, + plus plain tips. Every tip states the numbers behind it, like the score reasons do.""" + rows = self.db.execute( + "SELECT l.source, l.score, l.status, MAX(a.kind = 'replied') got_reply FROM leads l " + "JOIN activity a ON a.lead_id = l.id WHERE a.kind IN ('contacted', 'replied') GROUP BY l.id").fetchall() + by: dict[str, dict] = {} + bands = {"hi": [0, 0], "lo": [0, 0]} # [contacted, replied] for scores >= 60 and below + for r in rows: + replied = bool(r["got_reply"]) or r["status"] in ("replied", "won") + s = by.setdefault(r["source"], {"source": r["source"], "contacted": 0, "replied": 0, "won": 0}) + s["contacted"] += 1 + s["replied"] += replied + s["won"] += r["status"] == "won" + band = bands["hi" if r["score"] >= 60 else "lo"] + band[0] += 1 + band[1] += replied + sources = sorted(by.values(), key=lambda s: (-s["replied"] / s["contacted"], -s["contacted"])) + for s in sources: + s["rate"] = round(100 * s["replied"] / s["contacted"]) + tips = [] + tried = [s for s in sources if s["contacted"] >= 3] + if tried and tried[0]["replied"]: + tips.append(["best", {"src": tried[0]["source"], "rate": tried[0]["rate"], "n": tried[0]["contacted"]}]) + for s in sources: + if s["contacted"] >= 8 and not s["replied"]: + tips.append(["weak", {"src": s["source"], "n": s["contacted"]}]) + (hc, hr), (lc, lr) = bands["hi"], bands["lo"] + if hc >= 5 and lc >= 5 and hr / hc > lr / lc: + tips.append(["score", {"hi": round(100 * hr / hc), "lo": round(100 * lr / lc)}]) + return {"contacted": len(rows), "sources": sources, "tips": tips} + def sent_per_day(self, days: int) -> list[int]: - """Messages marked as sent per local day, oldest first, ending with today.""" + """Messages marked as sent (first messages and follow-ups) per local day, oldest first, ending with today.""" midnight = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0) counts = [] for i in range(days - 1, -1, -1): start = midnight - timedelta(days=i) end = start + timedelta(days=1) - row = self.db.execute("SELECT COUNT(*) c FROM activity WHERE kind='contacted' AND at >= ? AND at < ?", + row = self.db.execute("SELECT COUNT(*) c FROM activity WHERE kind IN ('contacted','followup') AND at >= ? AND at < ?", (start.timestamp(), end.timestamp())).fetchone() counts.append(row["c"]) return counts diff --git a/pyproject.toml b/pyproject.toml index e9e109d..95de3b1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "leadhound" -version = "0.4.3" +version = "0.5.0" description = "Find freelance clients worldwide: live hiring posts, Freelancer.com projects, paid issues and local businesses with weak websites. 11 languages, local-first, zero dependencies." readme = "README.md" license = { text = "MIT" } @@ -31,4 +31,4 @@ leadhound = "leadhound.cli:main" packages = ["leadhound", "leadhound.sources", "leadhound.dashboard", "leadhound.i18n", "leadhound.send"] [tool.setuptools.package-data] -"leadhound.dashboard" = ["*.html", "*.css", "*.js", "locales/*.json", "fonts/*.woff2", "fonts/OFL-*.txt"] +"leadhound.dashboard" = ["*.html", "*.css", "*.js", "*.svg", "locales/*.json", "fonts/*.woff2", "fonts/OFL-*.txt"] diff --git a/site/index.html b/site/index.html index 601b3fd..79f91d5 100644 --- a/site/index.html +++ b/site/index.html @@ -3,7 +3,11 @@ leadhound: find freelance clients who need you right now - + + + + +
-
leadhound
+
leadhound

For freelancers

Find clients who need you right now

leadhound finds people hiring freelancers today, shows exactly why each one fits, and writes your first message in their language. You read it and send it yourself.

- -

Windows, macOS and Linux. Runs on your computer. No account needed to start.

+ +

Windows, macOS and Linux. Runs on your computer. Free with no limits, no account needed. Just curious? pipx run leadhound demo opens it with sample leads.

@@ -97,26 +103,31 @@

Built for any freelancer

Honest scores

Each lead shows a line-by-line list of why it scored what it did. No black box.

Local businesses

Find shops, clinics and cafes in any country and check their websites for problems you can fix.

Send for you

Optionally connect email, Mastodon, GitHub or Reddit so leadhound sends through your own account, with daily limits that protect it.

-

Open source

The code is public. You can read exactly what it does.

+

Follow-ups

Leads that haven't answered come back after a few days with a short, polite follow-up ready. A short nudge often gets the reply.

+

Browser extension

Found a post or a business site yourself? Send it to leadhound in one click, scored and drafted like the rest.

+

Learns what works

See which sources actually reply to you, with tips that show the numbers behind them.

+

Open source

The code is public under the MIT license. You can read exactly what it does, and change it.

+ A lead in leadhound: score with reasons, website problems found, and a first message in Georgian +

A dental clinic in Tbilisi: the website check found three problems, so the message cites them, in Georgian.

Pricing

-

Start free. Upgrade when it pays for itself.

+

Free for everything you do yourself.

-

Free

$0

After your 7-day trial.

-
  • 3 searches a day
  • Your top 10 matches
  • Scores, reasons and drafted messages
  • Open Gmail, Outlook, WhatsApp and more with the message ready
+

Free

$0

Forever. No account, no limits.

+
  • Unlimited searches and all your matches
  • Local business finder and website checks
  • Drafts in the client's language, and follow-up reminders
  • Send from your own email, Mastodon, GitHub or Reddit, or open Gmail, Outlook and WhatsApp with the message ready
  • Use your own AI key (Claude, OpenAI) or a local model
Download

Pro

$12.99 a month

or $89.99 a year (save 42%)

-
  • Unlimited searches and all your matches
  • Send from your connected accounts
  • AI-written messages, no API key needed
  • Local business finder and website checks
  • Automatic search every few hours
+
  • AI-written messages, no API key needed
  • Automatic search every few hours, with an email of the best new matches
  • Reply detection: leads that answer move to Replied by themselves
  • Keeps leadhound independent and open source
Buy Pro
-

Every new install gets 7 uses free, then a 7-day Pro trial after a quick email sign-up. To buy: pay on Gumroad with a card, Apple Pay, Google Pay or PayPal, and your license key arrives by email right away. Paste it into the Pro button in the app.

+

You can try the Pro features a few times for free, then start a 7-day trial with a quick email sign-up. To buy: pay on Gumroad with a card, Apple Pay, Google Pay or PayPal, and your license key arrives by email right away. Paste it into the Pro button in the app.

@@ -126,7 +137,7 @@

Straight answers

Does it send messages on its own?

Never. You press send on every message. The daily limits exist to protect your accounts, not to set a target.

What data leaves my computer?

Searches go to the public sources (Freelancer.com, Reddit and so on) the way a browser would. If you sign up for the trial, your email and a device code go to the license server. If you use the hosted AI, the lead's text goes to the server and then to Anthropic to write the message. Nothing else.

Windows says "protected your PC". Is it safe?

The downloaded apps are not code-signed yet, so Windows and macOS warn you. On Windows click More info, then Run anyway. On macOS right-click the file and choose Open. The code is public if you want to check it, or install it with pip.

-
Is it really open source if Pro costs money?

Yes. The code is public under the MIT license. Pro is a license key for convenience features and the hosted AI. Anyone technical can read and change the code; paying supports the person who maintains it.

+
Is it really open source if Pro costs money?

Yes. The code is public under the MIT license, and everything you do yourself is free with no limits. Pro pays for the things that run for you or cost money to provide: the hosted AI, automatic search with email alerts, and reply detection. Paying supports the person who maintains it.

Will it get me banned on Reddit or other sites?

leadhound identifies itself, limits how fast it asks, and only reads public posts. When you connect an account to send, it caps messages per day and pauses between them. Cold messages can still break a site's rules, so keep them personal and short.

How do I get help?

Open an issue on GitHub.