Spaces:
Runtime error
Runtime error
Speed + UX: trim scored schema, cache prompt, lighter ctx, live status
Browse filesApp-only deploy to the Space. Same app changes as origin commit 6408b42 but
without the demo/ video tooling (and its font binary, which HF rejects and the
running app never uses).
- PARSE schema trimmed to ranker-only fields (~20-35% fewer output tokens)
- Why column derived from score.explain (deterministic, zero tokens)
- cache_prompt: reuse system-prompt KV between calls
- llama-server ctx 8192 -> 4096
- prioritize() streams an instant status so CPU inference isn't a frozen wait
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Files changed (6)
- app.py+61-13
- llm.py+4
- prompts.py+1-4
- score.py+30-55
- start.sh+1-1
- test_score.py-13
36 unmodified lines37383940414216 unmodified lines596061626364656667686970717273747576772 unmodified lines8081828384858687889 unmodified lines989910010110210310416 unmodified lines1211221231241251261271281291301311328 unmodified lines14114214314414514614736 unmodified linesDF_HEADERS = ["#", "Task", "Score", "Due", "Flag", "Why", "I", "R", "EffΒ·h"]DF_DATATYPES = ["number", "str", "str", "str", "str", "str", "number", "number", "number"]def _label(t: dict) -> str:return f"{t['id']} Β· {t['title']}"16 unmodified linesscore.format_score(c["display"]),score.due_label(t.get("due_date"), now) if t.get("due_date") else "β",flag,t.get("reason", "") or "",round(c["I"]),round(c["R"]),round(t["effort_hours"], 2),])top = ranked[0]header = f"### βΆ Do this first: **{top['title']}** Β· score {score.format_score(score.priority(top))}"return header, rows, [_label(t) for t in ranked]def prioritize(text, image, tasks):if not llm.is_ready():return tasks, "### β³ The local model is still loading β give it a moment and try again.", [], gr.update()collected = []if text and text.strip():collected += llm.parse_braindump(text)2 unmodified linesfor i, t in enumerate(collected):t["id"] = f"t{i}"if not collected:return collected, "### Nothing actionable found β try a different dump or photo.", [], gr.update(choices=[], value=None)header, rows, choices = render(collected)return collected, header, rows, gr.update(choices=choices, value=(choices[0] if choices else None))def load_task(sel, tasks):9 unmodified linest["impact"] = int(impact)t["readiness"] = int(readiness)t["effort_hours"] = float(effort)t["reason"] = (t.get("reason") or "").split(" Β· edited")[0] + " Β· edited"header, rows, choices = render(tasks)keep = sel if sel in choices else (choices[0] if choices else None)return tasks, header, rows, gr.update(choices=choices, value=keep)16 unmodified linesreturn next((x for x in tasks if x["id"] == tid), None)with gr.Blocks(title="whatfirst-small", theme=gr.themes.Soft()) as demo:gr.Markdown("# whatfirst Β· small\n""Dump everything on your mind β or snap a photo of your to-do list β and a ""**small local model** turns it into structured tasks. A **transparent scoring ""engine** then tells you what to do *first*, and shows its work. No cloud, no API keys.")tasks_state = gr.State([])8 unmodified linesgo = gr.Button("Prioritize", variant="primary")sample = gr.Button("Try a sample")with gr.Column(scale=3):header = gr.Markdown("### Add a brain-dump or a photo, then hit **Prioritize**.")table = gr.Dataframe(headers=DF_HEADERS, datatype=DF_DATATYPES, interactive=False,wrap=True, label="Ranked",36 unmodified lines373839404142434445464748495051525354555657585960616263646566676869707116 unmodified lines8889909192939495969798991001011021031041051061071081091101111121131141151161172 unmodified lines1201211221231241251261271281299 unmodified lines13914014114214314414516 unmodified lines1621631641651661671681691701711721731741751761778 unmodified lines18618718818919019119219319419536 unmodified linesDF_HEADERS = ["#", "Task", "Score", "Due", "Flag", "Why", "I", "R", "EffΒ·h"]DF_DATATYPES = ["number", "str", "str", "str", "str", "str", "number", "number", "number"]# ββ Branding, borrowed from the full what-first.com app βββββββββββββββββββββββ# Indigo β blue gradient, slate/ink text, Roboto β the palette the marketing# site and the demo video (demo/compose.py) share.INDIGO, BLUE = "#4F46E5", "#2563EB"SLATE, INK, MUTED = "#1E293B", "#111827", "#5A6473"THEME = gr.themes.Soft(primary_hue=gr.themes.colors.indigo,secondary_hue=gr.themes.colors.blue,neutral_hue=gr.themes.colors.slate,font=[gr.themes.GoogleFont("Roboto"), "system-ui", "sans-serif"],).set(button_primary_background_fill=f"linear-gradient(90deg, {INDIGO}, {BLUE})",button_primary_background_fill_hover=f"linear-gradient(90deg, {BLUE}, {INDIGO})",button_primary_text_color="white",block_title_text_weight="600",)CSS = f"""#wf-hero {{background: linear-gradient(120deg, {INDIGO}, {BLUE});color: #fff; border-radius: 16px; padding: 26px 30px; margin-bottom: 8px;}}#wf-hero h1 {{ margin: 0 0 6px; font-weight: 700; letter-spacing: -0.5px; }}#wf-hero p {{ margin: 0; opacity: 0.92; font-size: 1.02em; line-height: 1.5; }}#wf-hero a {{ color: #fff; text-decoration: underline; }}#wf-first {{ color: {SLATE}; font-weight: 600; }}"""def _label(t: dict) -> str:return f"{t['id']} Β· {t['title']}"16 unmodified linesscore.format_score(c["display"]),score.due_label(t.get("due_date"), now) if t.get("due_date") else "β",flag,score.explain(t, now) + (" Β· edited" if t.get("edited") else ""),round(c["I"]),round(c["R"]),round(t["effort_hours"], 2),])top = ranked[0]header = (f"### <span id='wf-first'>βΆ Do this first: {top['title']}</span>"f" Β· score {score.format_score(score.priority(top))}")return header, rows, [_label(t) for t in ranked]def prioritize(text, image, tasks):# A generator: the first yield lands instantly so the ~60s CPU inference# doesn't look like a frozen app. Gradio streams each yield to the UI.if not llm.is_ready():yield tasks, "### β³ The local model is still loading β give it a moment and try again.", [], gr.update()returnhint = ""if text and text.strip():n = len([ln for ln in text.splitlines() if ln.strip()])hint = f" ~{n} item{'s' if n != 1 else ''}"yield tasks, f"### β³ Reading and scoring{hint} on the local modelβ¦ (~60s on free CPU)", [], gr.update()collected = []if text and text.strip():collected += llm.parse_braindump(text)2 unmodified linesfor i, t in enumerate(collected):t["id"] = f"t{i}"if not collected:yield collected, "### Nothing actionable found β try a different dump or photo.", [], gr.update(choices=[], value=None)returnheader, rows, choices = render(collected)yield collected, header, rows, gr.update(choices=choices, value=(choices[0] if choices else None))def load_task(sel, tasks):9 unmodified linest["impact"] = int(impact)t["readiness"] = int(readiness)t["effort_hours"] = float(effort)t["edited"] = Trueheader, rows, choices = render(tasks)keep = sel if sel in choices else (choices[0] if choices else None)return tasks, header, rows, gr.update(choices=choices, value=keep)16 unmodified linesreturn next((x for x in tasks if x["id"] == tid), None)with gr.Blocks(title="whatfirst-small", theme=THEME, css=CSS) as demo:gr.HTML("<div id='wf-hero'>""<h1>whatfirst Β· small</h1>""<p>Dump everything on your mind β or snap a photo of your to-do list β and a ""<strong>small local model</strong> turns it into structured tasks. A ""<strong>transparent scoring engine</strong> then tells you what to do <em>first</em>, ""and shows its work. No cloud, no API keys. The full app lives at ""<a href='https://what-first.com'>what-first.com</a>.</p>""</div>")tasks_state = gr.State([])8 unmodified linesgo = gr.Button("Prioritize", variant="primary")sample = gr.Button("Try a sample")with gr.Column(scale=3):header = gr.Markdown("### Add a brain-dump or a photo, then hit **Prioritize**.",sanitize_html=False,)table = gr.Dataframe(headers=DF_HEADERS, datatype=DF_DATATYPES, interactive=False,wrap=True, label="Ranked",
62 unmodified lines63646566676862 unmodified lines"top_p": 0.9,"stream": False,"response_format": {"type": "json_object"},}r = requests.post(CHAT_URL, json=payload, timeout=REQUEST_TIMEOUT)r.raise_for_status()62 unmodified lines6364656667686970717262 unmodified lines"top_p": 0.9,"stream": False,"response_format": {"type": "json_object"},# Keep the (identical, ~400-token) system-prompt prefix in the server's# KV cache between calls, so repeated requests β the image flow's two# passes, per-task re-suggest, back-to-back demos β skip re-processing it."cache_prompt": True,}r = requests.post(CHAT_URL, json=payload, timeout=REQUEST_TIMEOUT)r.raise_for_status()
22 unmodified lines23242526272829303132333435363738394022 unmodified linesPARSE_SYSTEM_PROMPT = f"""You turn a messy brain-dump into a prioritized task list for a personal productivity app. The text is one person listing things they need to do; it may ramble, run several tasks together, or include filler.Output a JSON object: {{ "items": [ {{ "title": string, "category": string | null, "notes": string | null, "due_date": string | null, "due_time": string | null, "impact": integer, "readiness": integer, "effort_hours": number, "reason": string }} ] }}{SCALE_GUIDE}Rules:- title is a short imperative phrase, sentence case, no trailing period, under 90 characters. Prefer the person's own words.- category is a 1-2 word project name if obvious (e.g. "Work", "Home", "Errands"); otherwise null.- notes is a clarifying detail that won't fit in the title; otherwise null.- due_date: if a day, date, or deadline is named ("Friday", "tomorrow", "by the 5th", "end of week"), resolve it to YYYY-MM-DD relative to the current date given below. Otherwise null.- due_time: if a clock time is named ("at 11pm", "by 9am", "noon"), resolve it to 24-hour HH:MM. If a day but no clock time, null. Never invent a time.- impact, readiness, effort_hours: always score every task using the scale above. If importance is stated ("really important", "no rush"), let it guide impact.- reason: one short lowercase sentence, no exclamations, under 14 words, explaining the scores.- Split distinct tasks into separate items. Skip greetings, filler, and self-talk that isn't a task.- Return at most 25 items. Drop near-duplicates.- If there are no actionable tasks, return {{ "items": [] }}.22 unmodified lines23242526272829303132333435363722 unmodified linesPARSE_SYSTEM_PROMPT = f"""You turn a messy brain-dump into a prioritized task list for a personal productivity app. The text is one person listing things they need to do; it may ramble, run several tasks together, or include filler.Output a JSON object: {{ "items": [ {{ "title": string, "due_date": string | null, "due_time": string | null, "impact": integer, "readiness": integer, "effort_hours": number }} ] }}{SCALE_GUIDE}Rules:- title is a short imperative phrase, sentence case, no trailing period, under 90 characters. Prefer the person's own words.- due_date: if a day, date, or deadline is named ("Friday", "tomorrow", "by the 5th", "end of week"), resolve it to YYYY-MM-DD relative to the current date given below. Otherwise null.- due_time: if a clock time is named ("at 11pm", "by 9am", "noon"), resolve it to 24-hour HH:MM. If a day but no clock time, null. Never invent a time.- impact, readiness, effort_hours: always score every task using the scale above. If importance is stated ("really important", "no rush"), let it guide impact.- Split distinct tasks into separate items. Skip greetings, filler, and self-talk that isn't a task.- Return at most 25 items. Drop near-duplicates.- If there are no actionable tasks, return {{ "items": [] }}.
21 unmodified lines2223242526272829303134 unmodified lines6667686970717273747576777836 unmodified lines11511611711811912012112212312412512612712812913013113213313413513613713841 unmodified lines1801811821831841851863 unmodified lines19019119219319419519619712 unmodified lines2102112122132142152162 unmodified lines2192202212222232242252262272282299 unmodified lines2392402412422432442452462472482492502512522532542552562572582592602612622631 unmodified line26526626726826927021 unmodified linesSCORE_CAP = 1000 # backstop guard, above the formula's natural maxTIE_BAND = 0.10 # value-closeness band (log-bucketed for transitivity)# Quick-win lens: a short, ready-to-start task for a spare moment.QUICK_WIN_MAX_EFFORT_HOURS = 0.25 # 15 minutesQUICK_WIN_MIN_READINESS = 7def clamp(x: float, lo: float, hi: float) -> float:return max(lo, min(hi, x))34 unmodified linesreturn min(30, base + accel)def urgency(due_date, effort_hours) -> float:if not due_date:return 2d = days_to_due_raw(due_date)return max(cal_urgency(d), comp_urgency(d, effort_hours or 0.05))# -- Core score ---------------------------------------------------------------def score_components(t: dict) -> dict:36 unmodified linesreturn math.floor(math.log(max(v, 0.1)) / math.log(1 + TIE_BAND))# -- Assignment (collapses to "always mine" with no teams) --------------------def assignee_ids(task: dict) -> list:ids = task.get("assignee_user_ids")if isinstance(ids, list):return idsif task.get("assignee_user_id") is not None:return [task["assignee_user_id"]]return []def mine_to_do(task: dict, current_user_id=None) -> bool:if current_user_id is None:return Trueids = assignee_ids(task)return len(ids) == 0 or current_user_id in ids# -- Dates --------------------------------------------------------------------def normalize_iso(due_date):41 unmodified lines# -- Ranking ------------------------------------------------------------------def deadline_risk_map(sorted_active: list, now: datetime | None = None, current_user_id=None) -> dict:"""Walk the queue in priority order, accumulate effort, and flag any taskwhose projected wall-clock finish lands past its deadline. Returns{id: 'at-risk' | 'tight'}."""3 unmodified linesfor t in sorted_active:if not t or t.get("completed"):continueif not mine_to_do(t, current_user_id):continueE = max(t.get("effort_hours") or 0, 0)acc += Eif not t.get("due_date"):12 unmodified linesreturn outdef rank_active(tasks: list, now: datetime | None = None, current_user_id=None) -> list:"""Rank with deadlines as a constraint, not a blended term. Three tiers:0 overdue (EDF), 1 binding/at-risk (EDF, lifted above the value pack),2 value pack (value bucket, then sooner due breaks near-ties)."""2 unmodified linesV = {t["id"]: priority(t) for t in active}D = {t["id"]: days_to_due_raw(t.get("due_date"), now) for t in active}by_value = sorted(active, key=lambda t: V[t["id"]], reverse=True)risk = deadline_risk_map(by_value, now, current_user_id)def tier_of(t):if not mine_to_do(t, current_user_id):return 2if t.get("due_date") and D[t["id"]] <= 0:return 0return 1 if risk.get(t["id"]) == "at-risk" else 29 unmodified linesreturn sorted(by_value, key=sort_key)# -- Quick-win lens -----------------------------------------------------------def is_quick_win(task: dict) -> bool:if not task or task.get("completed"):return Falsee = task.get("effort_hours")if not isinstance(e, (int, float)) or not math.isfinite(e) or e <= 0 or e > QUICK_WIN_MAX_EFFORT_HOURS:return Falsereturn readiness_of(task) >= QUICK_WIN_MIN_READINESS or bool(task.get("execute_anyway"))def quick_wins(tasks: list) -> list:"""Quick wins, shortest first, ties by priority desc."""return sorted((t for t in tasks if is_quick_win(t)),key=lambda t: (t["effort_hours"], -priority(t)),)# -- Display helpers ----------------------------------------------------------def format_score(n: float) -> str:1 unmodified linereturn str(int(rounded)) if rounded == int(rounded) else f"{rounded:.1f}"def due_label(due_date, now: datetime | None = None) -> str:"""Compact relative deadline label ('now', '3h', 'tomorrow', '2d', '5d late')."""if not due_date:21 unmodified lines22232425262734 unmodified lines62636465666736 unmodified lines10410510610710810941 unmodified lines1511521531541551561573 unmodified lines16116216316416516612 unmodified lines1791801811821831841852 unmodified lines1881891901911921931941951969 unmodified lines2062072082092102111 unmodified line21321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424521 unmodified linesSCORE_CAP = 1000 # backstop guard, above the formula's natural maxTIE_BAND = 0.10 # value-closeness band (log-bucketed for transitivity)def clamp(x: float, lo: float, hi: float) -> float:return max(lo, min(hi, x))34 unmodified linesreturn min(30, base + accel)# -- Core score ---------------------------------------------------------------def score_components(t: dict) -> dict:36 unmodified linesreturn math.floor(math.log(max(v, 0.1)) / math.log(1 + TIE_BAND))# -- Dates --------------------------------------------------------------------def normalize_iso(due_date):41 unmodified lines# -- Ranking ------------------------------------------------------------------def deadline_risk_map(sorted_active: list, now: datetime | None = None) -> dict:"""Walk the queue in priority order, accumulate effort, and flag any taskwhose projected wall-clock finish lands past its deadline. Returns{id: 'at-risk' | 'tight'}."""3 unmodified linesfor t in sorted_active:if not t or t.get("completed"):continueE = max(t.get("effort_hours") or 0, 0)acc += Eif not t.get("due_date"):12 unmodified linesreturn outdef rank_active(tasks: list, now: datetime | None = None) -> list:"""Rank with deadlines as a constraint, not a blended term. Three tiers:0 overdue (EDF), 1 binding/at-risk (EDF, lifted above the value pack),2 value pack (value bucket, then sooner due breaks near-ties)."""2 unmodified linesV = {t["id"]: priority(t) for t in active}D = {t["id"]: days_to_due_raw(t.get("due_date"), now) for t in active}by_value = sorted(active, key=lambda t: V[t["id"]], reverse=True)risk = deadline_risk_map(by_value, now)def tier_of(t):if t.get("due_date") and D[t["id"]] <= 0:return 0return 1 if risk.get(t["id"]) == "at-risk" else 29 unmodified linesreturn sorted(by_value, key=sort_key)# -- Display helpers ----------------------------------------------------------def format_score(n: float) -> str:1 unmodified linereturn str(int(rounded)) if rounded == int(rounded) else f"{rounded:.1f}"def explain(t: dict, now: datetime | None = None) -> str:"""A short, deterministic 'why it ranks here' phrase, read off the samecomponents that drive the score. This replaces a model-written reason: itcosts the model no tokens to produce and can never drift from the math theway an LLM sentence can."""now = now or datetime.now()c = score_components(t)I, R, E = c["I"], c["R"], c["E"]status = deadline_status(t, now)if status == "overdue":return "overdue β start now"if c["prep_wins"]:return ("high-value but not ready β de-risk first" if I >= 5else "not ready β needs a first step")if status in ("today", "tomorrow"):return f"due {status} β time-sensitive"if E <= 1 and R >= 7:return "quick win β short and ready"if R <= 3:return "blocked β next step unclear"if I >= 8:return "high-impact work"if I <= 3:return "minor β low impact"return "steady priority"def due_label(due_date, now: datetime | None = None) -> str:"""Compact relative deadline label ('now', '3h', 'tomorrow', '2d', '5d late')."""if not due_date:
13 unmodified lines1415161718192013 unmodified lines--model "${MODEL_DIR}/${MODEL_FILE}" \--mmproj "${MODEL_DIR}/${MMPROJ_FILE}" \--host 127.0.0.1 --port 8080 \--ctx-size 8192 \--threads "$(nproc)" &# 3. Start the Gradio app (foreground). is_ready() polls the server's /health,13 unmodified lines1415161718192013 unmodified lines--model "${MODEL_DIR}/${MODEL_FILE}" \--mmproj "${MODEL_DIR}/${MMPROJ_FILE}" \--host 127.0.0.1 --port 8080 \--ctx-size 4096 \--threads "$(nproc)" &# 3. Start the Gradio app (foreground). is_ready() polls the server's /health,
122 unmodified lines123124125126127128129130131132133134135136137138139140141122 unmodified linesassert order == ["live"]# -- Quick wins ---------------------------------------------------------------def test_quick_win_filter_and_order():tasks = [{"id": "a", "impact": 5, "readiness": 9, "effort_hours": 0.1}, # qualifies{"id": "b", "impact": 9, "readiness": 9, "effort_hours": 0.05}, # qualifies, shorter{"id": "c", "impact": 5, "readiness": 3, "effort_hours": 0.1}, # too unready{"id": "d", "impact": 5, "readiness": 9, "effort_hours": 2}, # too long]order = [t["id"] for t in s.quick_wins(tasks)]assert order == ["b", "a"], order # shortest firstdef test_due_label():assert s.due_label("2026-06-08T12:00:00", NOW) == "tomorrow"assert s.due_label("2026-06-12T12:00:00", NOW) == "5d"122 unmodified lines123124125126127128122 unmodified linesassert order == ["live"]def test_due_label():assert s.due_label("2026-06-08T12:00:00", NOW) == "tomorrow"assert s.due_label("2026-06-12T12:00:00", NOW) == "5d"
app.py+61-13
llm.py+4
prompts.py+1-4
score.py+30-55
start.sh+1-1
test_score.py-13