Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d9d0a2e849 | ||
|
|
2a147c911a | ||
|
|
1fda5c09b7 | ||
|
|
ec34fc005c | ||
|
|
f49ba2a84b | ||
|
|
c84f536c76 | ||
|
|
2005db22e6 | ||
|
|
766b2bbaeb | ||
|
|
550c94d58a | ||
|
|
a58546900f | ||
|
|
1fb1a23eea | ||
|
|
d4fd08cabe | ||
|
|
1214e00300 | ||
|
|
1dc582d689 | ||
|
|
366d6bb97a | ||
|
|
e71f7089d3 | ||
|
|
e427a4079c | ||
|
|
633bbf35a0 | ||
|
|
10f5811d7f | ||
|
|
b8773b8fc2 | ||
|
|
b4dfbd7540 | ||
|
|
62923e8344 | ||
|
|
9821fde02b | ||
|
|
9264bd0adf | ||
|
|
9cb78880ce |
No files matched your search
@@ -8,9 +8,9 @@ Deliberate decisions in this repo - do NOT silently revert them:
|
||||
- Pi is managed the same way: `home/.pi/agent/{settings,models}.json`, `themes/`, and custom extensions (`terminal-status-title`, `calm`). Do not symlink the whole `~/.pi/agent` tree - sessions, auth, npm cache, and herdr's `extensions/herdr-agent-state.ts` stay live.
|
||||
- herdr stores runtime state beside its config, so `~/.config/herdr` stays a real directory and only `config.toml` is symlinked; `home.activation.herdrConfigDir` migrates the old whole-directory symlink and clears leaked artifacts. Do not symlink the whole directory - rationale and artifact list are in `home.nix`.
|
||||
- Codex runs on the OpenCode Go subscription. The ChatGPT app owns and rewrites the live `~/.codex/config.toml`, so it is NOT symlinked; `home.activation.codexOpenCodeGo` merges the repo fragment `home/.codex/config.toml` into it on every rebuild, and the app's own sections (`[desktop]`, `[plugins]`, `[mcp_servers]`, ...) survive. Auth is command-backed via `~/.local/bin/opencode-go-token` (prints the key from the opencode store), so `~/.codex/auth.json` stays in ChatGPT mode and ChatGPT sign-in coexists with Go. Only Go models that speak the Responses API work (`deepseek-v4.1-flash`, `gpt-6-luna`, `gpt-5.6-luna`, `grok-4.7/4.6`); GLM/Kimi/MiMo/LongCat are chat-completions-only and need a proxy. Desktop Codex is now the `chatgpt` cask - do not use the deprecated `codex-app` cask.
|
||||
- firstmate lives at `~/Documents/firstmate` as a mutable git clone (not in the Nix store). `home.activation.firstmate` clones it if missing and seeds `config/backend=herdr` + `config/crew-harness=opencode` only when those files are absent. Crew routing is `home/.config/firstmate/crew-dispatch.json` (symlinked in): per the captain's order 2026-10-21, every coding crewmate and scout uses `opencode` + `opencode-go/deepseek-v4.1-flash` through the OpenCode CLI. The free `deepseek-v4.1-flash-free` order of 2026-10-20 resumes when that lane resets. The validation pipeline stays on Pi with `opencode-go/deepseek-v4.1-flash` steps and the `opencode-go/glm-5.3-flash` reviewer. Avoid the `muse-spark-*-contributor` models, which train on prompts, and the `exo-free`, `mimo-*-free`, and `nemotron-*-free` models, whose data may be used to improve the model. `cat-jam-free` retains for 30 days. Crews inherit the primary's OpenCode login through the spawn-owned symlink (the isolated worker data root links the primary `<XDG_DATA_HOME>/opencode/auth.json`; no `~/.pi/agent/auth.json` reliance). Launch with shell alias `fm` (`cd` + OpenCode 2 via `~/.local/bin/oc2`); the primary stays OpenCode 2, only crews run on the opencode harness. Self-update via `/updatefirstmate`, not rebuild.
|
||||
- OpenCode 2 is the firstmate primary. It is not a Homebrew formula: install `@opencode-ai/cli@beta` with Homebrew's npm (`home.activation.opencode2`). Launch through `home/bin/oc2` so `OPENCODE_CONFIG` stays at `home/.config/opencode2/opencode.json` and cannot rewrite OpenCode 1.x's `~/.config/opencode`. Do not add a brew `opencode` / `opencode2` formula; `zap` would fight the npm install. firstmate harness detection matches `*opencode*`, so the `opencode2` process name still classifies as OpenCode.
|
||||
- Shell aliases: `cc` (Claude skip-permissions), `co` (Codex full-auto), `gb` (Grok --yolo), `fm` (firstmate via OpenCode 2), `oc2` (OpenCode 2, isolated). They are intentional high-agency shortcuts.
|
||||
- firstmate lives at `~/Documents/firstmate` as a mutable git clone (not in the Nix store). `home.activation.firstmate` clones it if missing and seeds `config/backend=herdr` + `config/crew-harness=opencode` only when those files are absent. Crew routing is `home/.config/firstmate/crew-dispatch.json` (symlinked in): per the captain's order 2026-10-21, coding crewmates and scouts use `opencode` + `opencode-go/deepseek-v4.1-flash` through the OpenCode CLI. Design, architecture, and design-review tasks are the exception: the file's first rule sends them to Pi with `openai-codex/gpt-6.1-sol` at `xhigh`, and implementation tasks re-resolve their profile instead of keeping that model. The free `deepseek-v4.1-flash-free` order of 2026-10-20 resumes when that lane resets. The validation pipeline stays on Pi with `opencode-go/deepseek-v4.1-flash` steps and the `opencode-go/glm-5.3-flash` reviewer. Avoid the `muse-spark-*-contributor` models, which train on prompts, and the `exo-free`, `mimo-*-free`, and `nemotron-*-free` models, whose data may be used to improve the model. `cat-jam-free` retains for 30 days. Crews inherit the primary's OpenCode login through the spawn-owned symlink (the isolated worker data root links the primary `<XDG_DATA_HOME>/opencode/auth.json`; no `~/.pi/agent/auth.json` reliance). Launch with shell alias `fm` (`cd` + `pi` with the two firstmate primary extensions); the primary runs Pi on the OpenCode Go subscription, while crews run on the opencode harness unless a dispatch rule selects another harness. `oc2` remains the isolated OpenCode 2 fallback. Self-update via `/updatefirstmate`, not rebuild.
|
||||
- OpenCode 2 is the isolated OpenCode harness behind `oc2`, not the firstmate primary. It is the stable Homebrew `opencode` formula, installed with `link = false` so the OpenCode 1.x CLI keeps `/opt/homebrew/bin/opencode`, and launched only through `home/bin/oc2` so `OPENCODE_CONFIG` stays at `home/.config/opencode2/opencode.json` and cannot rewrite OpenCode 1.x's `~/.config/opencode`. Switching between builds needs `opencode service restart`, because the client refuses a background service left over from the other build with `Background service uses an incompatible health protocol`. The npm beta package `@opencode-ai/cli` that `home.activation.opencode2` used to install is removed by `rebuild.sh` at rebuild time, so the stable formula is the only OpenCode 2 install. firstmate harness detection matches `*opencode*`, so it still classifies as OpenCode.
|
||||
- Shell aliases: `cc` (Claude skip-permissions), `co` (Codex full-auto), `gb` (Grok --yolo), `fm` (firstmate via Pi), `oc2` (OpenCode 2, isolated). They are intentional high-agency shortcuts.
|
||||
- OpenSuperWhisper is installed by the `opensuperwhisper` cask, and `home.activation.openSuperWhisper` downloads its Whisper model (`ggml-large-v3-turbo.bin` under the app's Application Support directory, never the Nix store) and seeds the model selection only when it is missing or dangling. All other app settings (trigger, language, paste behavior) belong to the app and must not be rewritten by a rebuild, so `modifierOnlyHotkey = rightOption` on this machine stays the effective trigger. Microphone/Accessibility/Input Monitoring grants stay manual because macOS TCC cannot be declarative; do not kill a running app to apply defaults. The model is local-only.
|
||||
|
||||
## Maintaining this file
|
||||
|
||||
+12
-1
@@ -45,6 +45,7 @@
|
||||
onActivation.extraFlags = [ "--force" ];
|
||||
brews = [
|
||||
"ffmpeg"
|
||||
"gallery-dl" # X/Twitter media download for yt-transcribe (X video needs auth yt-dlp can't get)
|
||||
"gh"
|
||||
"herdr"
|
||||
# Client-only psql for read-only DB investigation. libpq is the keg-only
|
||||
@@ -53,11 +54,19 @@
|
||||
# resolves on the normal PATH. No server, service, database, or
|
||||
# connection is configured.
|
||||
{ name = "libpq"; link = true; }
|
||||
"node" # required: opencode2 is an npm global, not a Homebrew formula
|
||||
"node" # required: opencode-ai, backpass, and acpx are npm globals,
|
||||
# not formulae
|
||||
# OpenCode 2 stable. Installed unlinked so it never replaces the
|
||||
# npm-installed OpenCode 1.x CLI at /opt/homebrew/bin/opencode (the crew
|
||||
# harness); home/bin/oc2 runs this keg binary directly. `link = false`
|
||||
# makes brew bundle unlink after install, which is deterministic.
|
||||
{ name = "opencode"; link = false; }
|
||||
"pi-coding-agent"
|
||||
"tea" # Gitea CLI - PRs for firstmate crewmates on unraid.local:3003
|
||||
"tmux"
|
||||
"treehouse"
|
||||
"whisper-cpp" # whisper-cli for yt-transcribe (reuses OpenSuperWhisper's model)
|
||||
"yt-dlp" # yt-transcribe engine; same engine reclip runs in its container
|
||||
];
|
||||
casks = [
|
||||
# Codex desktop home: the standalone Codex.app was folded into the ChatGPT
|
||||
@@ -73,5 +82,7 @@
|
||||
"wezterm"
|
||||
];
|
||||
};
|
||||
|
||||
launchd.user.agents = { };
|
||||
}
|
||||
|
||||
@@ -4,6 +4,35 @@ let
|
||||
home = config.home.homeDirectory;
|
||||
dotfiles = "${home}/.dotfiles";
|
||||
firstmateHome = "${home}/Documents/firstmate";
|
||||
# yt-transcribe: captions-first transcription for YouTube/X/local media.
|
||||
# Source of truth is this repo's home/bin scripts; nix copies them into the
|
||||
# store so every context (launchd, shells) executes from local disk. Stable
|
||||
# ~/.local/bin symlinks below survive store-path changes between rebuilds.
|
||||
ytTranscribe = pkgs.runCommand "yt-transcribe" { } ''
|
||||
install -Dm755 ${./home/bin/yt-transcribe} $out/bin/yt-transcribe
|
||||
'';
|
||||
# Pinned pstack skills tree (cursor/plugins). `tdd` is deliberately absent:
|
||||
# an existing user-level tdd skill owns that name. See firstmate's
|
||||
# docs/adopted-skills.md for why these eleven skills exist.
|
||||
pstackSkillNames = [
|
||||
"statechart"
|
||||
"create-verification-skill"
|
||||
"maintain-verification-skill"
|
||||
"correct"
|
||||
"benchmark-checklist"
|
||||
"architect"
|
||||
"technical-writing"
|
||||
"unslop"
|
||||
"recall"
|
||||
"ketchup"
|
||||
"blast-radius"
|
||||
];
|
||||
pstackSkills = pkgs.fetchFromGitHub {
|
||||
owner = "cursor";
|
||||
repo = "plugins";
|
||||
rev = "6b0300214a09fd6029cfb7077043125758cd1fd2";
|
||||
hash = "sha256-TDuZ1v+taPdqyvvCs1VHUjtpSy8zHxhQKJv/kIPTpK8=";
|
||||
};
|
||||
in
|
||||
|
||||
{
|
||||
@@ -24,7 +53,7 @@ in
|
||||
nerd-fonts.hack
|
||||
ngrok # reverse TCP tunnel so the phone can SSH in over cellular (unfree)
|
||||
beets # music tagger / library organizer + navidrome sync plugin
|
||||
];
|
||||
] ++ [ ytTranscribe ];
|
||||
fonts.fontconfig.enable = true;
|
||||
home.sessionVariables.EDITOR = "nvim";
|
||||
|
||||
@@ -34,6 +63,11 @@ in
|
||||
syntaxHighlighting.enable = true; # commands turn green when valid
|
||||
initContent = ''
|
||||
bindkey '^f' autosuggest-accept
|
||||
# Keep the OpenCode Go CLI, Pi, no-mistakes, and Hermes key aligned with
|
||||
# the desktop app login after an account switch.
|
||||
if [ -x "$HOME/.local/bin/opencode-go-key-sync" ]; then
|
||||
"$HOME/.local/bin/opencode-go-key-sync" >/dev/null 2>&1 || true
|
||||
fi
|
||||
'';
|
||||
shellAliases = {
|
||||
".." = "cd ..";
|
||||
@@ -46,11 +80,15 @@ in
|
||||
cc = "claude --dangerously-skip-permissions";
|
||||
co = "codex --full-auto";
|
||||
gb = "grok --yolo";
|
||||
# firstmate primary session via OpenCode 2 (isolated config; crewmates = OpenCode)
|
||||
fm = "cd ${firstmateHome} && exec ${home}/.local/bin/oc2";
|
||||
# firstmate primary session via Pi on the OpenCode Go subscription; crewmates = OpenCode by default
|
||||
fm = "cd ${firstmateHome} && exec pi";
|
||||
oc2 = "${home}/.local/bin/oc2";
|
||||
# Sync ~/Music into the beets library on Unraid (requires NAS mounted).
|
||||
sync-music = "~/.local/bin/sync-music";
|
||||
# Transcribe a YouTube/X URL or a local media file. Tool code lives in
|
||||
# this repo (nix store); the Unraid share holds only data — mount it at
|
||||
# /Volumes/data (or set YT_SHARE_ROOT for a different mount point).
|
||||
yt-transcribe = "${home}/.local/bin/yt-transcribe";
|
||||
# Start the reverse tunnel so you can SSH into this Mac from your phone.
|
||||
# Run once when you go remote: `ngrok-tunnel`. Reads authtoken from
|
||||
# ~/.config/ngrok (set once per machine with `ngrok config add-authtoken <TOK>`)
|
||||
@@ -157,6 +195,12 @@ in
|
||||
source = config.lib.file.mkOutOfStoreSymlink "${dotfiles}/home/bin/opencode-go-token";
|
||||
force = true;
|
||||
};
|
||||
# Copy the desktop app's OpenCode Go login into the CLI, Pi, and Hermes stores.
|
||||
# The app writes opencode.db only; those tools read auth.json and .env.
|
||||
home.file.".local/bin/opencode-go-key-sync" = {
|
||||
source = config.lib.file.mkOutOfStoreSymlink "${dotfiles}/home/bin/opencode-go-key-sync";
|
||||
force = true;
|
||||
};
|
||||
# Codex 0.160+ profiles live in $CODEX_HOME/<name>.config.toml. The app does not
|
||||
# touch these, so they can be symlinked normally.
|
||||
home.file.".codex/luna.config.toml" = {
|
||||
@@ -192,6 +236,12 @@ in
|
||||
source = config.lib.file.mkOutOfStoreSymlink "${dotfiles}/home/bin/security-audit-sandbox";
|
||||
force = true;
|
||||
};
|
||||
# Stable symlink for yt-transcribe: shells exec it from local disk. The
|
||||
# repo's home/bin script is the source of truth — a repo edit takes effect
|
||||
# on the next rebuild; the Unraid share holds only data.
|
||||
home.file.".local/bin/yt-transcribe" = {
|
||||
source = "${ytTranscribe}/bin/yt-transcribe";
|
||||
};
|
||||
home.file.".grok/AGENTS.md" = {
|
||||
source = config.lib.file.mkOutOfStoreSymlink "${dotfiles}/home/AGENTS.md";
|
||||
force = true;
|
||||
@@ -319,23 +369,8 @@ in
|
||||
"$HOME/.codex/config.toml"
|
||||
'';
|
||||
|
||||
# OpenCode 2 is not on Homebrew (beta). Install via Homebrew's npm, never
|
||||
# Nix's npm (EACCES on the store). Skip when already present so a rebuild
|
||||
# does not pull a new beta under a live TUI. Activation blocks are inlined
|
||||
# into one flat script, so never `exit 0` here: that would skip every later
|
||||
# block (securityAuditSkill, setupLaunchAgents, syncMusic).
|
||||
home.activation.opencode2 = lib.hm.dag.entryAfter [ "writeBoundary" ] ''
|
||||
set -euo pipefail
|
||||
npm=/opt/homebrew/bin/npm
|
||||
bin=/opt/homebrew/bin/opencode2
|
||||
if [ ! -x "$bin" ]; then
|
||||
if [ ! -x "$npm" ]; then
|
||||
echo "opencode2: /opt/homebrew/bin/npm missing (declare node in homebrew.brews)" >&2
|
||||
exit 1
|
||||
fi
|
||||
"$npm" install -g --allow-scripts=@opencode-ai/cli @opencode-ai/cli@beta
|
||||
fi
|
||||
'';
|
||||
# OpenCode 2 is the stable Homebrew `opencode` formula, declared unlinked in
|
||||
# configuration.nix; home/bin/oc2 runs its keg binary. Nothing to install here.
|
||||
|
||||
# backpass (kunchenguid/backpass) - gradient descent for agent memory: reads
|
||||
# the transcript stores of the harnesses this config already declares
|
||||
@@ -344,8 +379,8 @@ in
|
||||
# to a harness you already authenticated, so acpx is a hard runtime dep and
|
||||
# must be on PATH. Homebrew node v26 satisfies backpass (>= 22.5) and acpx
|
||||
# (>= 22.13). Neither is a Homebrew formula: install via Homebrew's npm,
|
||||
# never Nix's npm (EACCES on the store). Skip-if-present like opencode2 so a
|
||||
# rebuild never pulls a new version mid-session; refresh manually with
|
||||
# never Nix's npm (EACCES on the store). Skip-if-present so a rebuild never
|
||||
# pulls a new version mid-session; refresh manually with
|
||||
# /opt/homebrew/bin/npm update -g backpass acpx
|
||||
home.activation.backpass = lib.hm.dag.entryAfter [ "writeBoundary" ] ''
|
||||
set -euo pipefail
|
||||
@@ -418,7 +453,7 @@ in
|
||||
# ~/.config/opencode/skills: home-manager owns that path with force = true and
|
||||
# mkOutOfStoreSymlink into the mutable dotfiles checkout, so a rebuild would
|
||||
# clobber the CLI's link and CLI writes would land in the git checkout. Skip
|
||||
# when installed, like opencode2/backpass, so a rebuild never pulls a new skill
|
||||
# when installed, like backpass, so a rebuild never pulls a new skill
|
||||
# version mid-session. The skill's own README still requires an OS-enforced
|
||||
# sandbox before it may run target-controlled builds, tests, browsers, or
|
||||
# fuzzers. That sandbox is home/bin/security-audit-sandbox; without it, those
|
||||
@@ -453,6 +488,42 @@ in
|
||||
fi
|
||||
'';
|
||||
|
||||
# pstack skills installed from the pinned `pstackSkills` source above (folder
|
||||
# pstack/skills). The record of why these eleven skills exist is firstmate's
|
||||
# docs/adopted-skills.md. They live only in ~/.agents/skills, which is outside
|
||||
# git and Nix, so this block restores them on a fresh machine.
|
||||
# `tdd` is skipped on purpose: an existing user-level tdd skill owns that
|
||||
# name, so the pstack copy is never installed.
|
||||
# Each run replaces only the eleven target directories; every other skill,
|
||||
# including an existing tdd skill, stays untouched. No `exit 0` here,
|
||||
# because activation blocks are inlined into one flat script, so an early
|
||||
# exit would skip the blocks that follow.
|
||||
home.activation.pstackSkills = lib.hm.dag.entryAfter [ "writeBoundary" ] ''
|
||||
set -euo pipefail
|
||||
src="${pstackSkills}/pstack/skills"
|
||||
dest="$HOME/.agents/skills"
|
||||
if [ ! -d "$src" ]; then
|
||||
echo "pstackSkills: pinned source tree missing at $src" >&2
|
||||
exit 1
|
||||
fi
|
||||
mkdir -p "$dest"
|
||||
for name in ${lib.concatStringsSep " " pstackSkillNames}; do
|
||||
if [ ! -d "$src/$name" ]; then
|
||||
echo "pstackSkills: pinned source is missing skill $name" >&2
|
||||
exit 1
|
||||
fi
|
||||
# Remove first so a renamed source file never lingers in the old copy.
|
||||
rm -rf "$dest/$name"
|
||||
if ! cp -R "$src/$name" "$dest/$name"; then
|
||||
echo "pstackSkills: failed to install $name" >&2
|
||||
exit 1
|
||||
fi
|
||||
# Store files are read-only; make the installed copy writable again.
|
||||
chmod -R u+w "$dest/$name"
|
||||
done
|
||||
echo "pstackSkills: installed ${toString (lib.length pstackSkillNames)} pinned skills into $dest"
|
||||
'';
|
||||
|
||||
# OpenSuperWhisper - local voice-first prompting (cask in configuration.nix).
|
||||
# The app reads its model from its own Application Support directory, so the
|
||||
# 1.6 GB Whisper model is downloaded here once and kept outside the Nix store.
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
{
|
||||
"rules": [
|
||||
{
|
||||
"when": "Design, architecture, architectural review, or design review tasks. This includes product design, UI/UX design, system design, and design investigations. For design tasks with screenshots or other image context, this rule takes precedence over the UI implementation rule. Ordinary implementation and routine code validation do not match this rule. When a task moves from design to implementation, resolve the implementation profile again rather than retaining this model for continuity.",
|
||||
"use": {
|
||||
"harness": "pi",
|
||||
"model": "openai-codex/gpt-6.1-sol",
|
||||
"effort": "xhigh",
|
||||
"provider": "codex"
|
||||
},
|
||||
"why": "Captain's order: use GPT-6.1 Sol through openai-codex in Pi for design and architectural review tasks. Other task types retain their existing profiles."
|
||||
},
|
||||
{
|
||||
"when": "UI work where supplied screenshots or other image context materially affect the implementation or verification.",
|
||||
"use": [
|
||||
|
||||
@@ -16,3 +16,7 @@ copy_mode = "prefix+y" # herdr's copy-mode entry key; copy-mode's own internal
|
||||
[ui]
|
||||
# Agents panel order: explicit choice of "spaces" (grouped by space, the default) over "priority".
|
||||
agent_panel_sort = "spaces"
|
||||
|
||||
[theme]
|
||||
name = "dracula"
|
||||
auto_switch = false
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"lastChangelogVersion": "1.0.4",
|
||||
"lastChangelogVersion": "1.5.0",
|
||||
"theme": "rose-pine-moon",
|
||||
"defaultProvider": "opencode-go",
|
||||
"defaultModel": "deepseek-v4.1-flash",
|
||||
@@ -33,5 +33,9 @@
|
||||
"quietStartup": true,
|
||||
"steeringMode": "all",
|
||||
"followUpMode": "all",
|
||||
"collapseChangelog": true
|
||||
}
|
||||
"collapseChangelog": true,
|
||||
"extensionChangelogVersions": {
|
||||
"{\"source\":\"npm:pi-web-access@0.36.0\",\"scope\":\"user\"}": "0.36.0",
|
||||
"{\"source\":\"git:github.com/algal/pi-openai-server-compaction@c6d593087709e9481223dc6c6c2269b371b5e055\",\"scope\":\"user\"}": "0.1.0"
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -3,12 +3,12 @@
|
||||
# ~/.config/opencode/opencode.json (OpenCode 1 / firstmate).
|
||||
set -euo pipefail
|
||||
|
||||
bin="${OPENCODE2_BIN:-/opt/homebrew/bin/opencode2}"
|
||||
bin="${OPENCODE2_BIN:-/opt/homebrew/opt/opencode/bin/opencode}"
|
||||
cfg="${OPENCODE_CONFIG:-$HOME/.config/opencode2/opencode.json}"
|
||||
|
||||
if [ ! -x "$bin" ]; then
|
||||
echo "oc2: opencode2 not installed. Rebuild, or run:" >&2
|
||||
echo " /opt/homebrew/bin/npm install -g --allow-scripts=@opencode-ai/cli @opencode-ai/cli@beta" >&2
|
||||
echo "oc2: stable opencode not installed. Rebuild, or run:" >&2
|
||||
echo " brew install opencode && brew unlink opencode" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ ! -e "$cfg" ]; then
|
||||
|
||||
Executable
+178
@@ -0,0 +1,178 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Copy the OpenCode Go key from the desktop app store into the CLI auth files.
|
||||
|
||||
The OpenCode desktop app writes its login to
|
||||
<XDG_DATA_HOME>/opencode/opencode.db (table credential, integration opencode-go)
|
||||
but the opencode CLI, firstmate workers, pi, and no-mistakes read
|
||||
<XDG_DATA_HOME>/opencode/auth.json (opencode-go.key)
|
||||
~/.pi/agent/auth.json (opencode-go.key)
|
||||
|
||||
After an account switch the app store is current and those JSON files still hold
|
||||
the old key, so workers and the validation pipeline fail with a usage or auth
|
||||
error. Run this after switching accounts.
|
||||
|
||||
Safety:
|
||||
* The app credential is the source only when it is newer than the target file.
|
||||
* If a target file is newer than the app credential, it is left alone and the
|
||||
command reports a conflict instead of overwriting a manual login.
|
||||
* The key is never printed.
|
||||
|
||||
Exit status: 0 in sync or updated, 2 conflict, 1 no source credential.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
|
||||
def data_home():
|
||||
return os.environ.get("XDG_DATA_HOME") or os.path.expanduser("~/.local/share")
|
||||
|
||||
|
||||
def app_credential():
|
||||
db = os.path.join(data_home(), "opencode", "opencode.db")
|
||||
if not os.path.exists(db):
|
||||
return None
|
||||
con = sqlite3.connect(f"file:{db}?mode=ro", uri=True)
|
||||
try:
|
||||
row = con.execute(
|
||||
"select value, time_updated from credential"
|
||||
" where integration_id='opencode-go' order by time_updated desc limit 1"
|
||||
).fetchone()
|
||||
finally:
|
||||
con.close()
|
||||
if not row:
|
||||
return None
|
||||
try:
|
||||
payload = json.loads(row[0])
|
||||
except Exception:
|
||||
return None
|
||||
key = payload.get("key") if isinstance(payload, dict) else None
|
||||
if not key:
|
||||
return None
|
||||
return key, int(row[1]) / 1000.0
|
||||
|
||||
|
||||
def read_target(path):
|
||||
with open(path) as fh:
|
||||
data = json.load(fh)
|
||||
entry = data.get("opencode-go")
|
||||
key = entry.get("key") if isinstance(entry, dict) else None
|
||||
return data, key
|
||||
|
||||
|
||||
def write_target(path, data):
|
||||
directory = os.path.dirname(path)
|
||||
fd, tmp = tempfile.mkstemp(dir=directory, prefix=".auth.", suffix=".json")
|
||||
try:
|
||||
with os.fdopen(fd, "w") as fh:
|
||||
json.dump(data, fh)
|
||||
os.chmod(tmp, 0o600)
|
||||
os.replace(tmp, path)
|
||||
finally:
|
||||
if os.path.exists(tmp):
|
||||
os.unlink(tmp)
|
||||
|
||||
|
||||
def target_paths():
|
||||
return [
|
||||
os.path.join(data_home(), "opencode", "auth.json"),
|
||||
os.path.expanduser("~/.pi/agent/auth.json"),
|
||||
]
|
||||
|
||||
|
||||
def sync_hermes(source_key, check):
|
||||
"""Update OPENCODE_GO_API_KEY in the Hermes env file when it differs."""
|
||||
path = os.path.expanduser("~/.hermes/.env")
|
||||
if not os.path.exists(path):
|
||||
return 0
|
||||
with open(path) as fh:
|
||||
lines = fh.readlines()
|
||||
current = None
|
||||
for line in lines:
|
||||
stripped = line.rstrip("\n")
|
||||
if stripped.startswith("OPENCODE_GO_API_KEY="):
|
||||
current = stripped.split("=", 1)[1]
|
||||
break
|
||||
if current is None:
|
||||
return 0
|
||||
label = "hermes/.env"
|
||||
if current == source_key:
|
||||
print(f"{label}: in sync")
|
||||
return 0
|
||||
if check:
|
||||
print(f"{label}: stale, would update", file=sys.stderr)
|
||||
return 2
|
||||
rewritten = []
|
||||
for line in lines:
|
||||
if line.startswith("OPENCODE_GO_API_KEY="):
|
||||
rewritten.append(f"OPENCODE_GO_API_KEY={source_key}\n")
|
||||
else:
|
||||
rewritten.append(line)
|
||||
with open(path, "w") as fh:
|
||||
fh.writelines(rewritten)
|
||||
os.chmod(path, 0o600)
|
||||
print(f"{label}: updated")
|
||||
return 0
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument(
|
||||
"--check",
|
||||
action="store_true",
|
||||
help="report drift and exit 2 instead of updating",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
source = app_credential()
|
||||
if not source:
|
||||
print(
|
||||
"opencode-go-key-sync: no opencode-go credential in the app store",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 1
|
||||
source_key, source_time = source
|
||||
|
||||
status = 0
|
||||
for path in target_paths():
|
||||
label = os.path.basename(os.path.dirname(path)) + "/" + os.path.basename(path)
|
||||
if not os.path.exists(path):
|
||||
print(f"{label}: missing, skipped", file=sys.stderr)
|
||||
status = max(status, 2)
|
||||
continue
|
||||
data, current_key = read_target(path)
|
||||
if current_key == source_key:
|
||||
print(f"{label}: in sync")
|
||||
continue
|
||||
target_time = os.path.getmtime(path)
|
||||
if target_time > source_time:
|
||||
print(
|
||||
f"{label}: has a newer key than the app store, left unchanged"
|
||||
" (log in again in the app, or update this file by hand)",
|
||||
file=sys.stderr,
|
||||
)
|
||||
status = max(status, 2)
|
||||
continue
|
||||
if args.check:
|
||||
print(f"{label}: stale, would update", file=sys.stderr)
|
||||
status = max(status, 2)
|
||||
continue
|
||||
entry = data.get("opencode-go")
|
||||
if not isinstance(entry, dict):
|
||||
entry = {"type": "api"}
|
||||
entry["key"] = source_key
|
||||
data["opencode-go"] = entry
|
||||
write_target(path, data)
|
||||
print(f"{label}: updated")
|
||||
|
||||
status = max(status, sync_hermes(source_key, args.check))
|
||||
return status
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Executable
+339
@@ -0,0 +1,339 @@
|
||||
#!/usr/bin/env bash
|
||||
# ============================================================================
|
||||
# yt-transcribe — repeatable YouTube/X transcription
|
||||
#
|
||||
# Strategy: captions first (exact text, fast); Whisper fallback ONLY when no
|
||||
# captions exist, reusing the OpenSuperWhisper model already on this Mac.
|
||||
# Accepts a URL (YouTube, X/Twitter, anything yt-dlp supports) OR a local
|
||||
# media file (skips straight to Whisper; used by the watcher for reclip
|
||||
# downloads).
|
||||
#
|
||||
# Usage:
|
||||
# yt-transcribe <url-or-file> # transcript → media/transcripts/<id>/ (URL)
|
||||
# # or <file>.txt sidecar (file)
|
||||
# yt-transcribe <url> --lang de # prefer German captions
|
||||
# yt-transcribe <url> --srt # also produce an .srt (whisper path)
|
||||
# yt-transcribe <url> --force # redo even if transcript exists
|
||||
#
|
||||
# X/Twitter: X has no public captions and now requires auth for most video
|
||||
# extraction, so URLs on x.com/twitter.com go through gallery-dl (set
|
||||
# YT_COOKIES=/path/to/cookies.txt for locked/NSFW/older tweets; exported
|
||||
# cookies.txt format from a browser extension works for both yt-dlp and
|
||||
# gallery-dl).
|
||||
#
|
||||
# Outputs (URL mode) in <share>/media/transcripts/<id>/:
|
||||
# <id>.txt plain transcript (always)
|
||||
# <id>.vtt raw captions (captions path)
|
||||
# <id>.srt subtitles (whisper path, with --srt)
|
||||
# <id>.metadata.json provenance: title, channel, source, date
|
||||
#
|
||||
# Dependencies (declared in dotfiles configuration.nix homebrew.brews):
|
||||
# yt-dlp, gallery-dl (X only), whisper-cli (whisper-cpp), ffmpeg (fallback only)
|
||||
# Whisper model: auto-detected from OpenSuperWhisper's model store,
|
||||
# or WHISPER_MODEL=/path/to/ggml-*.bin, or --model.
|
||||
# Env overrides: YT_SHARE_ROOT (data share mount, default /Volumes/data),
|
||||
# YT_TRANSCRIBE_ROOT (transcript root), YT_MEDIA_DIR (reclip download dir),
|
||||
# YT_COOKIES (cookies.txt for yt-dlp/gallery-dl).
|
||||
# Index: `yt-transcribe --list` prints id->title mapping; --index rewrites
|
||||
# INDEX.md next to the transcripts; both modes refresh it after each run.
|
||||
# ============================================================================
|
||||
set -euo pipefail
|
||||
|
||||
# --- locate the data share ---------------------------------------------------
|
||||
# The tool lives in this repo (installed into the nix store by the dotfiles
|
||||
# rebuild; stable symlink at ~/.local/bin/yt-transcribe). The Unraid share
|
||||
# holds only data — media and transcripts.
|
||||
SHARE_ROOT="${YT_SHARE_ROOT:-/Volumes/data}"
|
||||
OUT_ROOT="${YT_TRANSCRIBE_ROOT:-$SHARE_ROOT/media/transcripts}"
|
||||
|
||||
# --- PATH: cover Homebrew on Apple Silicon / Intel (launchd PATH too) ------
|
||||
for p in /opt/homebrew/bin /usr/local/bin; do
|
||||
[ -d "$p" ] && [[ ":$PATH:" != *":$p:"* ]] && PATH="$p:$PATH"
|
||||
done
|
||||
|
||||
LANG_PREF="en"
|
||||
KEEP_SRT=false
|
||||
FORCE=false
|
||||
DO_INDEX=false
|
||||
DO_LIST=false
|
||||
WHISPER_MODEL_ARG=""
|
||||
INPUT=""
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--lang) LANG_PREF="$2"; shift 2 ;;
|
||||
--srt) KEEP_SRT=true; shift ;;
|
||||
--force) FORCE=true; shift ;;
|
||||
--model) WHISPER_MODEL_ARG="$2"; shift 2 ;;
|
||||
--index) DO_INDEX=true; shift ;;
|
||||
--list) DO_LIST=true; shift ;;
|
||||
-h|--help) grep '^# ' "$0" | sed 's/^# //'; exit 0 ;;
|
||||
*) INPUT="$1"; shift ;;
|
||||
esac
|
||||
done
|
||||
[ -n "$INPUT" ] || $DO_INDEX || $DO_LIST || { echo "usage: yt-transcribe <url-or-file> [--lang L] [--srt] [--force] [--model ggml.bin] [--index|--list]" >&2; exit 1; }
|
||||
|
||||
# --- transcript index (INDEX.md / --list) -----------------------------------
|
||||
rebuild_index() {
|
||||
python3 - "$OUT_ROOT" "${YT_MEDIA_DIR:-$SHARE_ROOT/media/video}" <<'PY'
|
||||
import json, os, sys, time
|
||||
out_root, scan_dir = sys.argv[1], sys.argv[2]
|
||||
rows = []
|
||||
for dirpath, _, files in os.walk(out_root):
|
||||
for fn in files:
|
||||
if fn.endswith(".metadata.json"):
|
||||
try:
|
||||
d = json.load(open(os.path.join(dirpath, fn), encoding="utf-8"))
|
||||
except Exception:
|
||||
continue
|
||||
rows.append((d.get("transcribed_at") or "", d))
|
||||
rows.sort(key=lambda r: r[0], reverse=True)
|
||||
clean = lambda s: (s or "").replace("|", "/").replace("`", "/")
|
||||
L = ["# Transcript Index", "",
|
||||
"URL transcripts live in `media/transcripts/<id>/` — the `<id>.txt` is the",
|
||||
"transcript, `<id>.metadata.json` has full provenance. Local files keep their",
|
||||
"`.txt` sidecar next to the media file.", "",
|
||||
"## URL transcripts", "", "| transcribed | id | title | channel | source |", "|---|---|---|---|---|"]
|
||||
for ts, d in rows:
|
||||
L.append(f'| {ts} | `{clean(d.get("id"))}` | {clean(d.get("title"))} | {clean(d.get("channel"))} | {clean(d.get("source"))} |')
|
||||
L += ["", "## Local media files (sidecar .txt in media/video)", "", "| file | modified |", "|---|---|"]
|
||||
found = False
|
||||
for dirpath, dirs, files in os.walk(scan_dir):
|
||||
dirs[:] = [d for d in dirs if not d.startswith(".")]
|
||||
for fn in sorted(files):
|
||||
if fn.endswith(".txt"):
|
||||
found = True
|
||||
p = os.path.join(dirpath, fn)
|
||||
mt = time.strftime("%Y-%m-%d", time.localtime(os.path.getmtime(p)))
|
||||
L.append(f"| `{clean(fn)}` | {mt} |")
|
||||
if not found:
|
||||
L.append("| _(none yet — patched reclip or manual file-mode runs add one per download)_ | |")
|
||||
print("\n".join(L))
|
||||
PY
|
||||
}
|
||||
if $DO_INDEX || $DO_LIST; then
|
||||
mkdir -p "$OUT_ROOT"
|
||||
if $DO_LIST; then
|
||||
rebuild_index
|
||||
else
|
||||
rebuild_index > "$OUT_ROOT/INDEX.md"
|
||||
echo "== index rebuilt: $OUT_ROOT/INDEX.md"
|
||||
fi
|
||||
exit 0
|
||||
fi
|
||||
|
||||
need() { command -v "$1" >/dev/null || { echo "MISSING DEP: $1 — install it first" >&2; exit 2; }; }
|
||||
|
||||
DL_ARGS=()
|
||||
[ -n "${YT_COOKIES:-}" ] && DL_ARGS=(--cookies "$YT_COOKIES")
|
||||
|
||||
resolve_model() {
|
||||
local MODEL="${WHISPER_MODEL_ARG:-${WHISPER_MODEL:-}}"
|
||||
if [ -z "$MODEL" ]; then
|
||||
MODEL="$(find "$HOME/Library/Application Support/ru.starmel.OpenSuperWhisper/whisper-models" \
|
||||
-name 'ggml-*.bin' 2>/dev/null | head -1 || true)"
|
||||
fi
|
||||
printf '%s' "$MODEL"
|
||||
}
|
||||
|
||||
# whisper_transcribe <wav> <out-stem> — writes <out-stem>.txt (and .srt w/ --srt)
|
||||
whisper_transcribe() {
|
||||
local WAV="$1" STEM="$2" MODEL
|
||||
MODEL="$(resolve_model)"
|
||||
[ -n "$MODEL" ] && [ -f "$MODEL" ] || {
|
||||
echo "ERROR: no whisper model. Download one (e.g. ggml-large-v3-turbo.bin from huggingface.co/ggerganov/whisper.cpp)" >&2
|
||||
echo " and pass --model or set WHISPER_MODEL." >&2; exit 4; }
|
||||
echo ">> model: $MODEL"
|
||||
local WARGS=(-m "$MODEL" -f "$WAV" -of "$STEM" -otxt)
|
||||
$KEEP_SRT && WARGS+=(-osrt)
|
||||
echo ">> transcribing with whisper-cli (this is the slow part)..."
|
||||
whisper-cli "${WARGS[@]}" 2>>"$(dirname "$STEM")/whisper.log"
|
||||
[ -s "$STEM.txt" ] || { echo "ERROR: whisper produced no text" >&2; exit 6; }
|
||||
}
|
||||
|
||||
TMPD="$(mktemp -d)"
|
||||
cleanup() { rm -rf "$TMPD"; }
|
||||
trap cleanup EXIT
|
||||
|
||||
SOURCE=""
|
||||
SOURCE_PREFIX=""
|
||||
if [ -f "$INPUT" ]; then
|
||||
# ==========================================================================
|
||||
# FILE MODE — local media (reclip download, screen recording, anything)
|
||||
# ==========================================================================
|
||||
need ffmpeg; need whisper-cli
|
||||
SRC_FILE="$INPUT"
|
||||
STEM="$(basename "$SRC_FILE")"
|
||||
STEM="${STEM%.*}"
|
||||
OUT_DIR="$(cd "$(dirname "$SRC_FILE")" && pwd)"
|
||||
TXT="$OUT_DIR/$STEM.txt"
|
||||
if [ -s "$TXT" ] && ! $FORCE; then
|
||||
echo "== already transcribed: $TXT (use --force to redo)"
|
||||
exit 0
|
||||
fi
|
||||
echo ">> file mode: $SRC_FILE"
|
||||
echo ">> converting to 16 kHz mono wav..."
|
||||
ffmpeg -y -loglevel error -i "$SRC_FILE" -ac 1 -ar 16000 "$TMPD/in.wav"
|
||||
whisper_transcribe "$TMPD/in.wav" "$OUT_DIR/$STEM"
|
||||
SOURCE="whisper-local"
|
||||
rebuild_index > "$OUT_ROOT/INDEX.md" 2>/dev/null || true
|
||||
echo "== done: $TXT (source: $SOURCE)"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# ==========================================================================
|
||||
# URL MODE
|
||||
# ==========================================================================
|
||||
need yt-dlp
|
||||
URL="$INPUT"
|
||||
IS_X=false
|
||||
case "$URL" in
|
||||
*x.com/*|*twitter.com/*|*//t.co/*) IS_X=true ;;
|
||||
esac
|
||||
|
||||
# --- metadata (yt-dlp; gallery-dl for X when yt-dlp can't) -------------------
|
||||
VIDEO_ID=""; TITLE=""; CHANNEL=""
|
||||
if META="$(yt-dlp --no-playlist --skip-download --no-warnings "${DL_ARGS[@]}" \
|
||||
--print "id=%(id)s" --print "title=%(title)s" --print "channel=%(channel|uploader)s" "$URL" 2>/dev/null)"; then
|
||||
VIDEO_ID="$(printf '%s\n' "$META" | sed -n 's/^id=//p')"
|
||||
TITLE="$(printf '%s\n' "$META" | sed -n 's/^title=//p')"
|
||||
CHANNEL="$(printf '%s\n' "$META" | sed -n 's/^channel=//p')"
|
||||
fi
|
||||
|
||||
if $IS_X && [ -z "$VIDEO_ID" ]; then
|
||||
# X/Twitter via gallery-dl
|
||||
need gallery-dl
|
||||
echo ">> X URL — resolving via gallery-dl: $URL"
|
||||
VIDEO_ID="$(printf '%s' "$URL" | grep -oE 'status(es)?/[0-9]+' | grep -oE '[0-9]+' | head -1 || true)"
|
||||
if [ -z "$VIDEO_ID" ] && GJ="$(gallery-dl -j "$URL" 2>/dev/null | head -1)"; then
|
||||
VIDEO_ID="$(printf '%s' "$GJ" | python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('tweet_id',''))" 2>/dev/null || true)"
|
||||
TITLE="$(printf '%s' "$GJ" | python3 -c "import json,sys; d=json.load(sys.stdin); print((d.get('content') or '')[:200])" 2>/dev/null || true)"
|
||||
CHANNEL="$(printf '%s' "$GJ" | python3 -c "import json,sys; d=json.load(sys.stdin); a=d.get('author') or {}; print(a.get('nick') or a.get('name') or '')" 2>/dev/null || true)"
|
||||
fi
|
||||
[ -n "$VIDEO_ID" ] || { echo "ERROR: could not resolve a tweet id from: $URL" >&2; exit 3; }
|
||||
fi
|
||||
# Fill X title/channel from gallery-dl metadata when yt-dlp gave none
|
||||
if $IS_X && { [ -z "$TITLE" ] || [ -z "$CHANNEL" ] || [ "$CHANNEL" = "uploader" ]; } && command -v gallery-dl >/dev/null; then
|
||||
GJ="$(gallery-dl -j "$URL" 2>/dev/null | head -1 || true)"
|
||||
if [ -n "$GJ" ]; then
|
||||
XMETA="$(printf '%s' "$GJ" | python3 -c '
|
||||
import json, sys
|
||||
def walk(o):
|
||||
if isinstance(o, dict):
|
||||
if "author" in o or "tweet_id" in o:
|
||||
yield o
|
||||
for v in o.values(): yield from walk(v)
|
||||
elif isinstance(o, list):
|
||||
for v in o: yield from walk(v)
|
||||
items = list(walk(json.load(sys.stdin)))
|
||||
d = items[-1] if items else {}
|
||||
a = d.get("author") or {}
|
||||
print(d.get("tweet_id") or "")
|
||||
print((d.get("content") or "").replace("\n", " ")[:200])
|
||||
print(a.get("nick") or a.get("name") or "")
|
||||
' 2>/dev/null || true)"
|
||||
if [ -n "$XMETA" ]; then
|
||||
[ -z "$VIDEO_ID" ] && VIDEO_ID="$(printf '%s\n' "$XMETA" | sed -n '1p')"
|
||||
[ -z "$TITLE" ] && TITLE="$(printf '%s\n' "$XMETA" | sed -n '2p')"
|
||||
if [ -z "$CHANNEL" ] || [ "$CHANNEL" = "uploader" ]; then
|
||||
CHANNEL="$(printf '%s\n' "$XMETA" | sed -n '3p')"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
TITLE="${TITLE:-x.com post}"
|
||||
CHANNEL="${CHANNEL:-x.com}"
|
||||
OUT_DIR="$OUT_ROOT/$VIDEO_ID"
|
||||
mkdir -p "$OUT_DIR"
|
||||
TXT="$OUT_DIR/$VIDEO_ID.txt"
|
||||
else
|
||||
[ -n "$VIDEO_ID" ] || { echo "ERROR: yt-dlp could not resolve the URL (private, geo-blocked, or unsupported?)" >&2; exit 3; }
|
||||
OUT_DIR="$OUT_ROOT/$VIDEO_ID"
|
||||
mkdir -p "$OUT_DIR"
|
||||
TXT="$OUT_DIR/$VIDEO_ID.txt"
|
||||
fi
|
||||
|
||||
if [ -s "$TXT" ] && ! $FORCE; then
|
||||
echo "== already transcribed: $TXT (use --force to redo)"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# --- path 1: captions -------------------------------------------------------
|
||||
echo ">> trying captions ($LANG_PREF)..."
|
||||
yt-dlp --no-playlist --skip-download --no-warnings "${DL_ARGS[@]}" \
|
||||
--write-subs --write-auto-subs \
|
||||
--sub-langs "$LANG_PREF" --sub-format "vtt" \
|
||||
-o "$OUT_DIR/%(id)s.%(ext)s" "$URL" 2>/dev/null || true
|
||||
VTT="$(find "$OUT_DIR" -maxdepth 1 -name "$VIDEO_ID.$LANG_PREF.vtt" | head -1)"
|
||||
if [ -z "$VTT" ]; then
|
||||
# exact code missing (e.g. video tagged en-US only) — broaden once, keep best, delete the rest
|
||||
yt-dlp --no-playlist --skip-download --no-warnings "${DL_ARGS[@]}" \
|
||||
--write-subs --write-auto-subs \
|
||||
--sub-langs "$LANG_PREF.*" --sub-format "vtt" \
|
||||
-o "$OUT_DIR/%(id)s.%(ext)s" "$URL" 2>/dev/null || true
|
||||
VTT="$(find "$OUT_DIR" -maxdepth 1 -name "$VIDEO_ID.$LANG_PREF-*.vtt" | sort | head -1)"
|
||||
find "$OUT_DIR" -maxdepth 1 -name "$VIDEO_ID.*.vtt" ! -path "$VTT" -delete 2>/dev/null || true
|
||||
fi
|
||||
if [ -n "$VTT" ]; then
|
||||
echo ">> captions found: $(basename "$VTT") -> converting"
|
||||
python3 - "$VTT" "$TXT" <<'PY'
|
||||
import re, sys
|
||||
src, dst = sys.argv[1], sys.argv[2]
|
||||
out, prev = [], None
|
||||
for raw in open(src, encoding="utf-8", errors="replace"):
|
||||
line = raw.strip()
|
||||
if (not line or "-->" in line or line.startswith(("WEBVTT", "Kind:", "Language:", "NOTE", "STYLE"))
|
||||
or re.match(r"^\d+$", line)):
|
||||
continue
|
||||
line = re.sub(r"<[^>]+>", "", line) # strip inline tags
|
||||
if line and line != prev:
|
||||
out.append(line); prev = line
|
||||
text = " ".join(out)
|
||||
open(dst, "w", encoding="utf-8").write(text + "\n")
|
||||
print(f" {len(text.split())} words")
|
||||
PY
|
||||
if $IS_X; then SOURCE="x-captions"; else SOURCE="youtube-captions"; fi
|
||||
else
|
||||
# --- path 2: Whisper fallback --------------------------------------------
|
||||
echo ">> no captions — falling back to Whisper"
|
||||
need ffmpeg; need whisper-cli
|
||||
MEDIA_DIR="${YT_MEDIA_DIR:-$SHARE_ROOT/media/video}" # e.g. reclip's downloads on the share
|
||||
echo ">> checking $MEDIA_DIR for an existing download..."
|
||||
LOCAL_MEDIA="$(find "$MEDIA_DIR" -maxdepth 4 -iname "*$VIDEO_ID*" \
|
||||
\( -iname '*.mp4' -o -iname '*.mkv' -o -iname '*.webm' -o -iname '*.m4a' \
|
||||
-o -iname '*.mp3' -o -iname '*.flac' -o -iname '*.mov' -o -iname '*.avi' -o -iname '*.wav' \) \
|
||||
2>/dev/null | head -1 || true)"
|
||||
WAV="$TMPD/in.wav"
|
||||
if [ -n "$LOCAL_MEDIA" ]; then
|
||||
echo ">> reusing existing file: $LOCAL_MEDIA"
|
||||
ffmpeg -y -loglevel error -i "$LOCAL_MEDIA" -ac 1 -ar 16000 "$WAV"
|
||||
elif $IS_X && command -v gallery-dl >/dev/null; then
|
||||
echo ">> downloading X media via gallery-dl..."
|
||||
gallery-dl "${DL_ARGS[@]}" \
|
||||
--filter "extension not in ('jpg','jpeg','png','webp','gif')" \
|
||||
-o "filename={tweet_id}.{extension}" \
|
||||
-D "$TMPD" "$URL"
|
||||
XMEDIA="$(find "$TMPD" -maxdepth 1 -type f \( -iname '*.mp4' -o -iname '*.m4a' -o -iname '*.mov' -o -iname '*.webm' \) | sort | tail -1)"
|
||||
[ -n "$XMEDIA" ] || { echo "ERROR: gallery-dl found no video (private tweet? set YT_COOKIES=/path/to/cookies.txt)" >&2; exit 5; }
|
||||
ffmpeg -y -loglevel error -i "$XMEDIA" -ac 1 -ar 16000 "$WAV"
|
||||
SOURCE_PREFIX="gallery-dl"
|
||||
else
|
||||
echo ">> not found — downloading audio (16 kHz mono)..."
|
||||
yt-dlp --no-playlist --no-warnings "${DL_ARGS[@]}" -x --audio-format wav \
|
||||
--postprocessor-args "ffmpeg:-ac 1 -ar 16000" \
|
||||
-o "$TMPD/%(id)s.%(ext)s" "$URL"
|
||||
fi
|
||||
[ -f "$WAV" ] || { echo "ERROR: audio acquisition failed" >&2; exit 5; }
|
||||
whisper_transcribe "$WAV" "$OUT_DIR/$VIDEO_ID"
|
||||
SOURCE="${SOURCE_PREFIX:+$SOURCE_PREFIX+}whisper-local"
|
||||
fi
|
||||
|
||||
# --- provenance --------------------------------------------------------------
|
||||
TRANSCRIBED_AT="$(date -u +"%Y-%m-%dT%H:%M:%SZ")"
|
||||
python3 - "$VIDEO_ID" "$TITLE" "$CHANNEL" "$URL" "$SOURCE" "$LANG_PREF" "$TRANSCRIBED_AT" \
|
||||
> "$OUT_DIR/$VIDEO_ID.metadata.json" <<'PY'
|
||||
import json, sys
|
||||
keys = ["id", "title", "channel", "url", "source", "lang_pref", "transcribed_at"]
|
||||
print(json.dumps(dict(zip(keys, sys.argv[1:])), indent=2, ensure_ascii=False))
|
||||
PY
|
||||
|
||||
echo "== done: $TXT (source: $SOURCE)"
|
||||
rebuild_index > "$OUT_ROOT/INDEX.md" 2>/dev/null || true
|
||||
@@ -0,0 +1,44 @@
|
||||
# Patched reclip — source of truth
|
||||
|
||||
Our transcription + history additions to [averygan/reclip](https://github.com/averygan/reclip),
|
||||
kept here so container updates and new machines can't lose them.
|
||||
|
||||
- `app.py`, `index.html` — the full patched files (deployed via bind-mounts
|
||||
from `documents/reclip/` on the Unraid share; see that dir's DEPLOY.md)
|
||||
- `reclip-transcript.patch` — the same delta as a diff against upstream,
|
||||
for rebasing onto future upstream versions
|
||||
|
||||
Patch base: upstream `1d161d1` (cloned 2026-10-25).
|
||||
|
||||
## What the patch adds
|
||||
|
||||
1. `fetch_transcript()` — after each download, pull yt-dlp captions
|
||||
(YouTube subs; X auto-captions) → `<stem>.txt` sidecar, never fails the job
|
||||
2. `/api/transcript/<job_id>` + Transcript button + auto-save in the UI
|
||||
3. Persisted download history (`history.json` in the downloads volume) +
|
||||
`/api/history` + History section with a live transcript-available flag
|
||||
(manual `yt-transcribe` sidecars are detected at read time)
|
||||
4. `/api/file` + `/api/transcript` fall back to history, so old links
|
||||
survive restarts
|
||||
|
||||
## Updating reclip (when upstream changes)
|
||||
|
||||
git clone --depth 1 https://github.com/averygan/reclip.git /tmp/reclip-new
|
||||
cd /tmp/reclip-new
|
||||
git apply --3way ~/Documents/dotfiles/patches/reclip/reclip-transcript.patch
|
||||
|
||||
Resolve any conflicts (the additions are mostly self-contained: one new
|
||||
function, two routes, one status field, UI button + History section), then
|
||||
copy the updated `app.py` + `templates/index.html`:
|
||||
|
||||
- into this directory (commit — new source of truth)
|
||||
- to the share: `/Volumes/data/documents/reclip/{app.py,index.html}`
|
||||
- restart the reclip container (gunicorn reloads at start; the entrypoint
|
||||
also pip-updates yt-dlp at every container start)
|
||||
|
||||
If `git apply` fails on a drifted file, the fastest path is re-porting by
|
||||
hand from the conflict markers — the four additions are small and greppable
|
||||
(`fetch_transcript`, `history.json`, `resolve_download`, `saveTranscript`).
|
||||
|
||||
If an image update happens WITHOUT re-porting: the old patched files keep
|
||||
working (bind-mounts win), you just may miss upstream improvements.
|
||||
@@ -0,0 +1,403 @@
|
||||
import os
|
||||
import uuid
|
||||
import glob
|
||||
import json
|
||||
import re
|
||||
import hashlib
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from flask import Flask, request, jsonify, send_file, render_template
|
||||
|
||||
app = Flask(__name__)
|
||||
DOWNLOAD_DIR = os.path.join(os.path.dirname(__file__), "downloads")
|
||||
os.makedirs(DOWNLOAD_DIR, exist_ok=True)
|
||||
|
||||
jobs = {}
|
||||
|
||||
HISTORY_FILE = os.path.join(DOWNLOAD_DIR, "history.json")
|
||||
_history_lock = threading.Lock()
|
||||
|
||||
|
||||
def load_history():
|
||||
try:
|
||||
with open(HISTORY_FILE, encoding="utf-8") as fh:
|
||||
data = json.load(fh)
|
||||
return data if isinstance(data, list) else []
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
|
||||
def save_history(history):
|
||||
try:
|
||||
tmp = HISTORY_FILE + ".tmp"
|
||||
with open(tmp, "w", encoding="utf-8") as fh:
|
||||
json.dump(history, fh, indent=2)
|
||||
os.replace(tmp, HISTORY_FILE)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def sidecar_transcript(file_path):
|
||||
"""Manual-fallback transcripts (yt-transcribe <file>) live beside the
|
||||
media as <stem>.txt — recognize them at read time so history stays
|
||||
truthful without re-downloading anything."""
|
||||
if not file_path:
|
||||
return None
|
||||
stem = os.path.splitext(file_path)[0] + ".txt"
|
||||
return stem if os.path.exists(stem) else None
|
||||
|
||||
|
||||
def record_history(job):
|
||||
"""Persist the completed job so history + file/transcript downloads
|
||||
survive process restarts (downloads dir is the mapped volume)."""
|
||||
with _history_lock:
|
||||
history = [h for h in load_history() if h.get("job_id") != job.get("job_id")]
|
||||
history.insert(0, {
|
||||
"job_id": job.get("job_id"),
|
||||
"url": job.get("url", ""),
|
||||
"title": job.get("title", ""),
|
||||
"thumbnail": job.get("thumbnail", ""),
|
||||
"filename": job.get("filename", ""),
|
||||
"file": job.get("file", ""),
|
||||
"transcript": job.get("transcript") or "",
|
||||
"transcript_name": job.get("transcript_name", ""),
|
||||
"has_transcript": bool(job.get("transcript")),
|
||||
"size": os.path.getsize(job["file"]) if job.get("file") and os.path.exists(job["file"]) else 0,
|
||||
"date": time.strftime("%Y-%m-%d %H:%M:%S"),
|
||||
})
|
||||
save_history(history[:200])
|
||||
|
||||
|
||||
MEDIA_EXTS = (".mp4", ".mkv", ".webm", ".m4a", ".mp3", ".flac", ".mov", ".avi", ".wav", ".ts")
|
||||
|
||||
|
||||
def backfill_history():
|
||||
"""Add on-disk downloads that predate history.json (or were dropped into
|
||||
the downloads dir manually) so the whole library shows up on the page.
|
||||
The transcript flag is resolved live at read time, so backfilled entries
|
||||
pick up manual yt-transcribe sidecars automatically."""
|
||||
for name in sorted(os.listdir(DOWNLOAD_DIR)):
|
||||
path = os.path.join(DOWNLOAD_DIR, name)
|
||||
if not os.path.isfile(path) or not name.lower().endswith(MEDIA_EXTS):
|
||||
continue
|
||||
with _history_lock:
|
||||
history = load_history()
|
||||
if any(h.get("file") == path for h in history):
|
||||
continue
|
||||
stem = os.path.splitext(name)[0]
|
||||
# a 10-hex stem is a reclip job id — the real title wasn't kept
|
||||
title = "" if re.fullmatch(r"[0-9a-f]{10}", stem) else stem
|
||||
history.insert(0, {
|
||||
"job_id": hashlib.sha1(path.encode()).hexdigest()[:10],
|
||||
"url": "",
|
||||
"title": title,
|
||||
"filename": name,
|
||||
"file": path,
|
||||
"transcript": "",
|
||||
"transcript_name": "",
|
||||
"has_transcript": False,
|
||||
"size": os.path.getsize(path),
|
||||
"date": time.strftime("%Y-%m-%d %H:%M:%S",
|
||||
time.localtime(os.path.getmtime(path))),
|
||||
})
|
||||
save_history(history[:200])
|
||||
|
||||
|
||||
backfill_history()
|
||||
|
||||
|
||||
def parse_ytdlp_json(stdout):
|
||||
"""Parse yt-dlp JSON output.
|
||||
|
||||
With ``-j`` yt-dlp prints one JSON object per line. Some extractors
|
||||
emit multiple videos even with ``--no-playlist``, so stdout contains
|
||||
several objects and a plain ``json.loads`` raises "Extra data".
|
||||
Return the first valid object.
|
||||
"""
|
||||
for line in stdout.splitlines():
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
return json.loads(line)
|
||||
raise ValueError("yt-dlp returned no data")
|
||||
|
||||
|
||||
def fetch_transcript(url, chosen_path):
|
||||
"""Best-effort transcript via yt-dlp captions (manual or auto-generated;
|
||||
includes X's auto-captions). Writes <video stem>.txt beside the download.
|
||||
Returns the .txt path, or None when the video has no captions. Never
|
||||
raises — a transcript is a bonus, not a download requirement."""
|
||||
stem = os.path.splitext(chosen_path)[0]
|
||||
try:
|
||||
cmd = ["yt-dlp", "--no-playlist", "--skip-download", "--no-warnings",
|
||||
"--write-subs", "--write-auto-subs",
|
||||
"--sub-langs", "en,en-orig",
|
||||
"--sub-format", "vtt",
|
||||
"-o", stem + ".%(ext)s", url]
|
||||
subprocess.run(cmd, capture_output=True, text=True, timeout=180)
|
||||
|
||||
vtts = glob.glob(stem + ".*.vtt")
|
||||
if not vtts:
|
||||
return None
|
||||
vtts.sort(key=lambda p: (0 if p.endswith(".en.vtt") else 1, p))
|
||||
|
||||
lines, prev = [], None
|
||||
with open(vtts[0], encoding="utf-8", errors="replace") as fh:
|
||||
for raw in fh:
|
||||
line = raw.strip()
|
||||
if (not line or "-->" in line
|
||||
or line.startswith(("WEBVTT", "Kind:", "Language:", "NOTE", "STYLE"))
|
||||
or re.match(r"^\d+$", line)):
|
||||
continue
|
||||
line = re.sub(r"<[^>]+>", "", line)
|
||||
if line and line != prev:
|
||||
lines.append(line)
|
||||
prev = line
|
||||
|
||||
txt = stem + ".txt"
|
||||
with open(txt, "w", encoding="utf-8") as out:
|
||||
out.write(" ".join(lines) + "\n")
|
||||
|
||||
for f in vtts:
|
||||
try:
|
||||
os.remove(f)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
return txt if lines else None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def run_download(job_id, url, format_choice, format_id):
|
||||
job = jobs[job_id]
|
||||
out_template = os.path.join(DOWNLOAD_DIR, f"{job_id}.%(ext)s")
|
||||
|
||||
cmd = ["yt-dlp", "--no-playlist", "-o", out_template]
|
||||
|
||||
if format_choice == "audio":
|
||||
cmd += ["-x", "--audio-format", "mp3"]
|
||||
elif format_id:
|
||||
cmd += ["-f", f"{format_id}+bestaudio/best", "--merge-output-format", "mp4"]
|
||||
else:
|
||||
cmd += ["-f", "bestvideo+bestaudio/best", "--merge-output-format", "mp4"]
|
||||
|
||||
cmd.append(url)
|
||||
|
||||
try:
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
|
||||
if result.returncode != 0:
|
||||
job["status"] = "error"
|
||||
job["error"] = result.stderr.strip().split("\n")[-1]
|
||||
return
|
||||
|
||||
files = glob.glob(os.path.join(DOWNLOAD_DIR, f"{job_id}.*"))
|
||||
if not files:
|
||||
job["status"] = "error"
|
||||
job["error"] = "Download completed but no file was found"
|
||||
return
|
||||
|
||||
if format_choice == "audio":
|
||||
target = [f for f in files if f.endswith(".mp3")]
|
||||
chosen = target[0] if target else files[0]
|
||||
else:
|
||||
target = [f for f in files if f.endswith(".mp4")]
|
||||
chosen = target[0] if target else files[0]
|
||||
|
||||
for f in files:
|
||||
if f != chosen:
|
||||
try:
|
||||
os.remove(f)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
job["status"] = "done"
|
||||
job["file"] = chosen
|
||||
ext = os.path.splitext(chosen)[1]
|
||||
title = job.get("title", "").strip()
|
||||
# Sanitize title for filename
|
||||
if title:
|
||||
safe_title = "".join(c for c in title if c not in r'\/:*?"<>|').strip()[:100].strip()
|
||||
job["filename"] = f"{safe_title}{ext}" if safe_title else os.path.basename(chosen)
|
||||
else:
|
||||
job["filename"] = os.path.basename(chosen)
|
||||
|
||||
# Best-effort transcript sidecar: yt-dlp captions (X auto-captions
|
||||
# included) -> plain .txt next to the chosen file. Never fails the job.
|
||||
job["transcript"] = fetch_transcript(url, chosen)
|
||||
job["transcript_name"] = os.path.splitext(job["filename"])[0] + ".txt"
|
||||
record_history(job)
|
||||
except subprocess.TimeoutExpired:
|
||||
job["status"] = "error"
|
||||
job["error"] = "Download timed out (5 min limit)"
|
||||
except Exception as e:
|
||||
job["status"] = "error"
|
||||
job["error"] = str(e)
|
||||
|
||||
|
||||
@app.route("/")
|
||||
def index():
|
||||
return render_template("index.html")
|
||||
|
||||
|
||||
@app.route("/api/info", methods=["POST"])
|
||||
def get_info():
|
||||
data = request.json
|
||||
url = data.get("url", "").strip()
|
||||
if not url:
|
||||
return jsonify({"error": "No URL provided"}), 400
|
||||
|
||||
cmd = ["yt-dlp", "--no-playlist", "-j", url]
|
||||
try:
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
|
||||
if result.returncode != 0:
|
||||
return jsonify({"error": result.stderr.strip().split("\n")[-1]}), 400
|
||||
|
||||
info = parse_ytdlp_json(result.stdout)
|
||||
|
||||
# Build quality options — keep best format per resolution
|
||||
best_by_height = {}
|
||||
for f in info.get("formats", []):
|
||||
height = f.get("height")
|
||||
if height and f.get("vcodec", "none") != "none":
|
||||
tbr = f.get("tbr") or 0
|
||||
if height not in best_by_height or tbr > (best_by_height[height].get("tbr") or 0):
|
||||
best_by_height[height] = f
|
||||
|
||||
formats = []
|
||||
for height, f in best_by_height.items():
|
||||
formats.append({
|
||||
"id": f["format_id"],
|
||||
"label": f"{height}p",
|
||||
"height": height,
|
||||
})
|
||||
formats.sort(key=lambda x: x["height"], reverse=True)
|
||||
|
||||
return jsonify({
|
||||
"title": info.get("title", ""),
|
||||
"thumbnail": info.get("thumbnail", ""),
|
||||
"duration": info.get("duration"),
|
||||
"uploader": info.get("uploader", ""),
|
||||
"formats": formats,
|
||||
})
|
||||
except subprocess.TimeoutExpired:
|
||||
return jsonify({"error": "Timed out fetching video info"}), 400
|
||||
except Exception as e:
|
||||
return jsonify({"error": str(e)}), 400
|
||||
|
||||
|
||||
@app.route("/api/playlist", methods=["POST"])
|
||||
def get_playlist_info():
|
||||
data = request.json
|
||||
url = data.get("url", "").strip()
|
||||
if not url:
|
||||
return jsonify({"error": "No URL provided"}), 400
|
||||
|
||||
cmd = ["yt-dlp", "--flat-playlist", "-J", url]
|
||||
try:
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
|
||||
if result.returncode != 0:
|
||||
return jsonify({"error": result.stderr.strip().split("\n")[-1]}), 400
|
||||
|
||||
info = json.loads(result.stdout)
|
||||
entries = info.get("entries", [])
|
||||
urls = [entry.get("url") for entry in entries if entry.get("url")]
|
||||
return jsonify({"urls": urls})
|
||||
except subprocess.TimeoutExpired:
|
||||
return jsonify({"error": "Timed out fetching playlist info"}), 400
|
||||
except Exception as e:
|
||||
return jsonify({"error": str(e)}), 400
|
||||
|
||||
|
||||
@app.route("/api/download", methods=["POST"])
|
||||
def start_download():
|
||||
data = request.json
|
||||
url = data.get("url", "").strip()
|
||||
format_choice = data.get("format", "video")
|
||||
format_id = data.get("format_id")
|
||||
title = data.get("title", "")
|
||||
|
||||
if not url:
|
||||
return jsonify({"error": "No URL provided"}), 400
|
||||
|
||||
job_id = uuid.uuid4().hex[:10]
|
||||
jobs[job_id] = {"job_id": job_id, "status": "downloading", "url": url, "title": title,
|
||||
"thumbnail": (data.get("thumbnail") or "")[:500]}
|
||||
|
||||
thread = threading.Thread(target=run_download, args=(job_id, url, format_choice, format_id))
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
return jsonify({"job_id": job_id})
|
||||
|
||||
|
||||
def resolve_download(job_id, key):
|
||||
"""Find a completed job in memory, falling back to the on-disk history
|
||||
(paths point into DOWNLOAD_DIR, so they survive restarts)."""
|
||||
job = jobs.get(job_id)
|
||||
if job and job.get("status") == "done" and job.get(key):
|
||||
return job
|
||||
for entry in load_history():
|
||||
if entry.get("job_id") == job_id and entry.get(key):
|
||||
return entry
|
||||
return None
|
||||
|
||||
|
||||
@app.route("/api/status/<job_id>")
|
||||
def check_status(job_id):
|
||||
job = jobs.get(job_id)
|
||||
if not job:
|
||||
return jsonify({"error": "Job not found"}), 404
|
||||
return jsonify({
|
||||
"status": job["status"],
|
||||
"error": job.get("error"),
|
||||
"filename": job.get("filename"),
|
||||
"transcript": bool(job.get("transcript")),
|
||||
})
|
||||
|
||||
|
||||
@app.route("/api/history")
|
||||
def get_history():
|
||||
rows = load_history()[:50]
|
||||
for r in rows:
|
||||
# Truth at read time: a recorded caption-transcript may have been
|
||||
# deleted, and a manual yt-transcribe sidecar may have appeared since.
|
||||
path = r.get("transcript") or sidecar_transcript(r.get("file"))
|
||||
if path and os.path.exists(path):
|
||||
r["transcript"] = path
|
||||
r["has_transcript"] = True
|
||||
if not r.get("transcript_name"):
|
||||
r["transcript_name"] = os.path.splitext(os.path.basename(path))[0] + ".txt"
|
||||
else:
|
||||
r["transcript"] = ""
|
||||
r["has_transcript"] = False
|
||||
return jsonify(rows)
|
||||
|
||||
|
||||
@app.route("/api/transcript/<job_id>")
|
||||
def download_transcript(job_id):
|
||||
rec = resolve_download(job_id, "file") or resolve_download(job_id, "transcript")
|
||||
path = (rec.get("transcript") if rec else None) \
|
||||
or (sidecar_transcript(rec.get("file")) if rec else None)
|
||||
if not rec or not path or not os.path.exists(path):
|
||||
return jsonify({"error": "Transcript not found"}), 404
|
||||
default_name = os.path.splitext(os.path.basename(path))[0] + ".txt"
|
||||
return send_file(path, as_attachment=True,
|
||||
download_name=rec.get("transcript_name") or default_name)
|
||||
|
||||
|
||||
@app.route("/api/file/<job_id>")
|
||||
def download_file(job_id):
|
||||
rec = resolve_download(job_id, "file")
|
||||
path = rec.get("file") if rec else None
|
||||
if not rec or not path or not os.path.exists(path):
|
||||
return jsonify({"error": "File not found"}), 404
|
||||
return send_file(path, as_attachment=True,
|
||||
download_name=rec.get("filename") or os.path.basename(path))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
port = int(os.environ.get("PORT", 8899))
|
||||
host = os.environ.get("HOST", "127.0.0.1")
|
||||
app.run(host=host, port=port)
|
||||
@@ -0,0 +1,772 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>ReClip — Free Media Downloader</title>
|
||||
<link rel="icon" href="/static/favicon.svg" type="image/svg+xml">
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link href="https://fonts.googleapis.com/css2?family=Instrument+Serif:ital@0;1&family=DM+Mono:wght@400;500&display=swap" rel="stylesheet">
|
||||
<style>
|
||||
:root {
|
||||
--bg: #f4f1eb;
|
||||
--fg: #3a3a38;
|
||||
--accent: #e85d2a;
|
||||
--accent-hover: #d04e1f;
|
||||
--muted: #9c9889;
|
||||
--card: #fff;
|
||||
--card-border: #e2ded6;
|
||||
--success: #2d8a4e;
|
||||
--error: #c43d3d;
|
||||
--radius: 14px;
|
||||
--shimmer: linear-gradient(90deg, #ebe8e2 25%, #f0ede7 50%, #ebe8e2 75%);
|
||||
}
|
||||
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
|
||||
body {
|
||||
font-family: 'DM Mono', monospace;
|
||||
background: var(--bg);
|
||||
color: var(--fg);
|
||||
min-height: 100vh;
|
||||
overflow-x: hidden;
|
||||
}
|
||||
|
||||
body::after {
|
||||
content: '';
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
opacity: 0.03;
|
||||
pointer-events: none;
|
||||
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)'/%3E%3C/svg%3E");
|
||||
background-size: 128px;
|
||||
}
|
||||
|
||||
.page {
|
||||
max-width: 620px;
|
||||
margin: 0 auto;
|
||||
padding: 60px 24px 80px;
|
||||
}
|
||||
|
||||
.brand { margin-bottom: 48px; }
|
||||
.brand h1 {
|
||||
font-family: 'Instrument Serif', serif;
|
||||
font-size: 4.2rem;
|
||||
font-weight: 400;
|
||||
letter-spacing: -0.03em;
|
||||
line-height: 1;
|
||||
color: var(--fg);
|
||||
}
|
||||
.brand h1 em { font-style: italic; color: var(--accent); }
|
||||
.brand p {
|
||||
margin-top: 10px;
|
||||
font-size: 0.78rem;
|
||||
color: var(--muted);
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
textarea {
|
||||
width: 100%;
|
||||
padding: 18px 20px;
|
||||
border: 1.5px solid var(--card-border);
|
||||
border-radius: var(--radius);
|
||||
background: var(--card);
|
||||
color: var(--fg);
|
||||
font-family: 'DM Mono', monospace;
|
||||
font-size: 0.88rem;
|
||||
outline: none;
|
||||
resize: none;
|
||||
min-height: 56px;
|
||||
transition: border-color 0.25s, box-shadow 0.25s;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
textarea:focus {
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 0 0 3px rgba(232, 93, 42, 0.08);
|
||||
}
|
||||
textarea::placeholder { color: var(--muted); }
|
||||
|
||||
.hint {
|
||||
font-size: 0.7rem;
|
||||
color: var(--muted);
|
||||
margin-bottom: 20px;
|
||||
letter-spacing: 0.02em;
|
||||
}
|
||||
|
||||
.controls {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
margin-bottom: 6px;
|
||||
align-items: center;
|
||||
}
|
||||
.pill-group {
|
||||
display: flex;
|
||||
border: 1.5px solid var(--card-border);
|
||||
border-radius: 10px;
|
||||
overflow: hidden;
|
||||
background: var(--card);
|
||||
}
|
||||
.pill {
|
||||
padding: 9px 18px;
|
||||
font-family: 'DM Mono', monospace;
|
||||
font-size: 0.76rem;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--muted);
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
letter-spacing: 0.03em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
.pill.active { background: var(--fg); color: var(--bg); }
|
||||
.pill:not(.active):hover { color: var(--fg); }
|
||||
|
||||
.fetch-btn {
|
||||
flex: 1;
|
||||
padding: 10px 20px;
|
||||
border: none;
|
||||
border-radius: 10px;
|
||||
background: var(--accent);
|
||||
color: #fff;
|
||||
font-family: 'DM Mono', monospace;
|
||||
font-size: 0.82rem;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: background 0.2s, transform 0.1s;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
.fetch-btn:hover { background: var(--accent-hover); }
|
||||
.fetch-btn:active { transform: scale(0.98); }
|
||||
.fetch-btn:disabled { opacity: 0.5; cursor: not-allowed; transform: none; }
|
||||
|
||||
/* Cards */
|
||||
.cards { margin-top: 24px; }
|
||||
|
||||
.card {
|
||||
display: flex;
|
||||
gap: 14px;
|
||||
border: 1.5px solid var(--card-border);
|
||||
border-radius: var(--radius);
|
||||
background: var(--card);
|
||||
padding: 14px;
|
||||
margin-bottom: 10px;
|
||||
animation: slideUp 0.4s cubic-bezier(0.16, 1, 0.3, 1);
|
||||
}
|
||||
@keyframes slideUp {
|
||||
from { opacity: 0; transform: translateY(12px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
|
||||
.card-thumb {
|
||||
width: 120px;
|
||||
min-width: 120px;
|
||||
height: 80px;
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
background: var(--card-border);
|
||||
flex-shrink: 0;
|
||||
position: relative;
|
||||
}
|
||||
.card-thumb img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
display: block;
|
||||
}
|
||||
/* No-thumbnail icon */
|
||||
.card-thumb .no-thumb {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: var(--muted);
|
||||
}
|
||||
.card-thumb .no-thumb svg {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
/* Shimmer skeleton for loading state */
|
||||
.card-thumb.loading {
|
||||
background: var(--shimmer);
|
||||
background-size: 200% 100%;
|
||||
animation: shimmer 1.5s infinite;
|
||||
}
|
||||
.skeleton-line {
|
||||
height: 12px;
|
||||
border-radius: 4px;
|
||||
background: var(--shimmer);
|
||||
background-size: 200% 100%;
|
||||
animation: shimmer 1.5s infinite;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
.skeleton-line.short { width: 40%; height: 10px; }
|
||||
.skeleton-line.medium { width: 75%; }
|
||||
@keyframes shimmer {
|
||||
0% { background-position: 200% 0; }
|
||||
100% { background-position: -200% 0; }
|
||||
}
|
||||
|
||||
.card-body {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
}
|
||||
.card-title {
|
||||
font-family: 'Instrument Serif', serif;
|
||||
font-size: 1rem;
|
||||
line-height: 1.3;
|
||||
color: var(--fg);
|
||||
margin-bottom: 2px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.card-meta {
|
||||
font-size: 0.68rem;
|
||||
color: var(--muted);
|
||||
letter-spacing: 0.03em;
|
||||
text-transform: uppercase;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.card-actions {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.card-dl-btn {
|
||||
padding: 6px 14px;
|
||||
border: none;
|
||||
border-radius: 7px;
|
||||
background: var(--fg);
|
||||
color: var(--bg);
|
||||
font-family: 'DM Mono', monospace;
|
||||
font-size: 0.7rem;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
letter-spacing: 0.03em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
.card-dl-btn:hover { background: #2d2d2a; }
|
||||
.card-dl-btn:disabled { opacity: 0.4; cursor: not-allowed; }
|
||||
.card-dl-btn.done { background: var(--success); color: #fff; }
|
||||
.card-dl-btn.error { background: var(--error); color: #fff; }
|
||||
|
||||
.card-status {
|
||||
font-size: 0.68rem;
|
||||
color: var(--muted);
|
||||
}
|
||||
.card-status.downloading { color: var(--accent); }
|
||||
.card-status.done { color: var(--success); }
|
||||
.card-status.error { color: var(--error); }
|
||||
|
||||
.q-chip {
|
||||
padding: 4px 10px;
|
||||
border: 1.5px solid var(--card-border);
|
||||
border-radius: 6px;
|
||||
background: transparent;
|
||||
color: var(--muted);
|
||||
font-family: 'DM Mono', monospace;
|
||||
font-size: 0.65rem;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
.q-chip.active {
|
||||
border-color: var(--fg);
|
||||
color: var(--fg);
|
||||
background: rgba(26,26,24,0.04);
|
||||
}
|
||||
.q-chip:hover:not(.active) { border-color: var(--muted); }
|
||||
|
||||
/* Error card */
|
||||
.card.card-error {
|
||||
border-color: rgba(196, 61, 61, 0.2);
|
||||
background: rgba(196, 61, 61, 0.03);
|
||||
}
|
||||
.card-error-icon {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: rgba(196, 61, 61, 0.08);
|
||||
color: var(--error);
|
||||
}
|
||||
.card-error-icon svg {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
}
|
||||
.card-error-msg {
|
||||
font-size: 0.72rem;
|
||||
color: var(--error);
|
||||
margin-top: 2px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
.card-error-url {
|
||||
font-size: 0.65rem;
|
||||
color: var(--muted);
|
||||
word-break: break-all;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
/* Download all bar */
|
||||
.dl-all-bar {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
margin-top: 16px;
|
||||
}
|
||||
.dl-all-btn {
|
||||
flex: 1;
|
||||
padding: 12px;
|
||||
border: none;
|
||||
border-radius: 10px;
|
||||
background: var(--fg);
|
||||
color: var(--bg);
|
||||
font-family: 'DM Mono', monospace;
|
||||
font-size: 0.82rem;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
.dl-all-btn:hover { background: #2d2d2a; }
|
||||
.dl-all-btn:disabled { opacity: 0.4; cursor: not-allowed; }
|
||||
|
||||
/* History — same card language as the fetch results */
|
||||
.hist-h {
|
||||
font-family: 'Instrument Serif', serif;
|
||||
font-size: 1.9rem;
|
||||
font-weight: 400;
|
||||
letter-spacing: -0.02em;
|
||||
margin: 44px 0 14px;
|
||||
color: var(--fg);
|
||||
}
|
||||
#history .card { animation: slideUp 0.4s cubic-bezier(0.16, 1, 0.3, 1); }
|
||||
a.card-dl-btn { text-decoration: none; display: inline-block; }
|
||||
|
||||
.spin {
|
||||
display: inline-block;
|
||||
width: 10px; height: 10px;
|
||||
border: 2px solid currentColor;
|
||||
border-right-color: transparent;
|
||||
border-radius: 50%;
|
||||
animation: spin 0.6s linear infinite;
|
||||
vertical-align: middle;
|
||||
}
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
|
||||
.footer {
|
||||
margin-top: 48px;
|
||||
text-align: center;
|
||||
font-size: 0.68rem;
|
||||
color: var(--muted);
|
||||
letter-spacing: 0.05em;
|
||||
text-transform: uppercase;
|
||||
line-height: 1.8;
|
||||
}
|
||||
|
||||
/* Mobile */
|
||||
@media (max-width: 500px) {
|
||||
.brand h1 { font-size: 3rem; }
|
||||
.page { padding: 40px 16px 60px; }
|
||||
.card { flex-direction: column; gap: 10px; }
|
||||
.card-thumb {
|
||||
width: 100%;
|
||||
min-width: unset;
|
||||
height: 160px;
|
||||
}
|
||||
.card-title { white-space: normal; }
|
||||
.controls { flex-wrap: wrap; }
|
||||
.fetch-btn { width: 100%; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="page">
|
||||
<div class="brand">
|
||||
<h1>Re<em>Clip</em></h1>
|
||||
<p>Free media downloader</p>
|
||||
</div>
|
||||
|
||||
<textarea id="urls" placeholder="Paste one or more URLs..." rows="2"></textarea>
|
||||
<p class="hint">Multiple links? Separate with spaces, commas, or newlines.</p>
|
||||
|
||||
<div class="controls">
|
||||
<div class="pill-group">
|
||||
<button class="pill active" data-format="video" onclick="setFormat(this)">MP4</button>
|
||||
<button class="pill" data-format="audio" onclick="setFormat(this)">MP3</button>
|
||||
</div>
|
||||
<button class="fetch-btn" id="goBtn" onclick="go()">Fetch</button>
|
||||
</div>
|
||||
|
||||
<div id="cards" class="cards"></div>
|
||||
<div id="history"></div>
|
||||
|
||||
<div class="footer">
|
||||
YouTube · TikTok · Instagram · Twitter/X · Reddit · Facebook<br>
|
||||
Vimeo · Twitch · Dailymotion · SoundCloud · Loom · Streamable<br>
|
||||
Pinterest · Tumblr · Threads · LinkedIn · 1000+ more
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
let currentFormat = 'video';
|
||||
let cardData = [];
|
||||
|
||||
function setFormat(btn) {
|
||||
document.querySelectorAll('.pill').forEach(b => b.classList.remove('active'));
|
||||
btn.classList.add('active');
|
||||
currentFormat = btn.dataset.format;
|
||||
}
|
||||
|
||||
function parseUrls(text) {
|
||||
return [...new Set(text.split(/[\s,]+/).map(u => u.trim()).filter(u => u.startsWith('http')))];
|
||||
}
|
||||
|
||||
function fmtDur(s) {
|
||||
if (!s) return '';
|
||||
const m = Math.floor(s / 60);
|
||||
const sec = Math.floor(s % 60);
|
||||
return `${m}:${sec.toString().padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
function esc(s) {
|
||||
const d = document.createElement('div');
|
||||
d.textContent = s;
|
||||
return d.innerHTML;
|
||||
}
|
||||
|
||||
function friendlyError(err) {
|
||||
if (err.includes('Unsupported URL')) return 'This URL is not supported';
|
||||
if (err.includes('Video unavailable')) return 'Video is unavailable or private';
|
||||
if (err.includes('Private video')) return 'This video is private';
|
||||
if (err.includes('HTTP Error 403')) return 'Access denied by the platform';
|
||||
if (err.includes('HTTP Error 404')) return 'Video not found';
|
||||
if (err.includes('copyright')) return 'Video blocked due to copyright';
|
||||
if (err.includes('geo')) return 'Video not available in your region';
|
||||
if (err.includes('timed out') || err.includes('Timed out')) return 'Request timed out — try again';
|
||||
if (err.includes('network') || err.includes('Network')) return 'Network error — check your connection';
|
||||
return err.length > 80 ? err.slice(0, 80) + '...' : err;
|
||||
}
|
||||
|
||||
document.getElementById('urls').addEventListener('keydown', e => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); go(); }
|
||||
});
|
||||
|
||||
async function go() {
|
||||
const urls = parseUrls(document.getElementById('urls').value);
|
||||
if (!urls.length) return;
|
||||
|
||||
const btn = document.getElementById('goBtn');
|
||||
const container = document.getElementById('cards');
|
||||
btn.disabled = true;
|
||||
btn.textContent = 'Loading...';
|
||||
container.innerHTML = '';
|
||||
cardData = [];
|
||||
|
||||
// Check if youtube playlist URL
|
||||
for (let i = 0; i < urls.length; i++) {
|
||||
if (urls[i].includes('list=')) {
|
||||
const res = await fetch('/api/playlist', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ url: urls[i] }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.urls) {
|
||||
// replace playlist URL with individual video URLs
|
||||
urls.splice(i, 1, ...data.urls);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = 0; i < urls.length; i++) {
|
||||
const url = urls[i];
|
||||
const idx = cardData.length;
|
||||
cardData.push({ url, status: 'loading' });
|
||||
renderCard(idx);
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/info', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ url }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.error) {
|
||||
cardData[idx] = { ...cardData[idx], status: 'info-error', error: data.error };
|
||||
} else {
|
||||
cardData[idx] = {
|
||||
...cardData[idx],
|
||||
status: 'ready',
|
||||
title: data.title || '',
|
||||
thumbnail: data.thumbnail || '',
|
||||
duration: data.duration,
|
||||
uploader: data.uploader || '',
|
||||
formats: data.formats || [],
|
||||
selectedFormatId: data.formats?.[0]?.id || null,
|
||||
};
|
||||
}
|
||||
} catch (err) {
|
||||
cardData[idx] = { ...cardData[idx], status: 'info-error', error: err.message };
|
||||
}
|
||||
renderCard(idx);
|
||||
}
|
||||
|
||||
if (cardData.filter(c => c.status === 'ready').length > 1) {
|
||||
renderDownloadAll();
|
||||
}
|
||||
|
||||
btn.disabled = false;
|
||||
btn.textContent = 'Fetch';
|
||||
}
|
||||
|
||||
function renderCard(idx) {
|
||||
const c = cardData[idx];
|
||||
let el = document.getElementById(`card-${idx}`);
|
||||
if (!el) {
|
||||
el = document.createElement('div');
|
||||
el.id = `card-${idx}`;
|
||||
el.className = 'card';
|
||||
document.getElementById('cards').appendChild(el);
|
||||
}
|
||||
|
||||
// Loading skeleton
|
||||
if (c.status === 'loading') {
|
||||
el.className = 'card';
|
||||
el.innerHTML = `
|
||||
<div class="card-thumb loading"></div>
|
||||
<div class="card-body">
|
||||
<div class="skeleton-line medium"></div>
|
||||
<div class="skeleton-line short"></div>
|
||||
</div>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
|
||||
// Error state
|
||||
if (c.status === 'info-error') {
|
||||
el.className = 'card card-error';
|
||||
el.innerHTML = `
|
||||
<div class="card-thumb">
|
||||
<div class="card-error-icon">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="card-title" style="color:var(--error)">Could not fetch video</div>
|
||||
<div class="card-error-msg">${esc(friendlyError(c.error || ''))}</div>
|
||||
<div class="card-error-url">${esc(c.url)}</div>
|
||||
</div>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
|
||||
// Ready / downloading / done / error states
|
||||
el.className = 'card';
|
||||
const isAudio = currentFormat === 'audio';
|
||||
|
||||
let thumbHtml;
|
||||
if (isAudio) {
|
||||
thumbHtml = `<div class="no-thumb" style="color:var(--accent)"><svg viewBox="0 0 24 24" fill="currentColor" stroke="none"><polygon points="5 3 19 12 5 21 5 3"/></svg></div>`;
|
||||
} else if (c.thumbnail) {
|
||||
thumbHtml = `<img src="${c.thumbnail}" alt="">`;
|
||||
} else {
|
||||
thumbHtml = `<div class="no-thumb"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="20" height="20" rx="2"/><circle cx="8" cy="8" r="1.5"/><path d="m21 15-5-5L5 21"/></svg></div>`;
|
||||
}
|
||||
|
||||
let qualityChips = '';
|
||||
if (!isAudio && c.formats && c.formats.length > 1) {
|
||||
qualityChips = c.formats.map(f =>
|
||||
`<button class="q-chip${f.id === c.selectedFormatId ? ' active' : ''}" onclick="pickFormat(${idx}, '${f.id}')">${f.label}</button>`
|
||||
).join('');
|
||||
}
|
||||
|
||||
let actionHtml = '';
|
||||
if (c.status === 'ready') {
|
||||
actionHtml = `<button class="card-dl-btn" onclick="dlCard(${idx})">Download</button>${qualityChips}`;
|
||||
} else if (c.status === 'downloading') {
|
||||
actionHtml = `<span class="card-status downloading"><span class="spin"></span> Downloading...</span>`;
|
||||
} else if (c.status === 'done') {
|
||||
actionHtml = `<button class="card-dl-btn done" onclick="saveCard(${idx})">Save</button>` +
|
||||
(c.hasTranscript ? `<button class="card-dl-btn" onclick="saveTranscript(${idx})">Transcript</button>` : '') +
|
||||
`<span class="card-status done">${esc(c.filename || '')}</span>`;
|
||||
} else if (c.status === 'error') {
|
||||
actionHtml = `<button class="card-dl-btn" onclick="dlCard(${idx})">Retry</button>
|
||||
<span class="card-status error">${esc(friendlyError(c.error || 'Download failed'))}</span>`;
|
||||
}
|
||||
|
||||
el.innerHTML = `
|
||||
<div class="card-thumb">${thumbHtml}</div>
|
||||
<div class="card-body">
|
||||
<div class="card-title">${esc(c.title || 'Untitled')}</div>
|
||||
<div class="card-meta">${esc(c.uploader)}${c.duration ? ' · ' + fmtDur(c.duration) : ''}</div>
|
||||
<div class="card-actions">${actionHtml}</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function renderDownloadAll() {
|
||||
const existing = document.getElementById('dl-all-bar');
|
||||
if (existing) existing.remove();
|
||||
|
||||
const bar = document.createElement('div');
|
||||
bar.id = 'dl-all-bar';
|
||||
bar.className = 'dl-all-bar';
|
||||
bar.innerHTML = `<button class="dl-all-btn" onclick="dlAll()">Download All</button>`;
|
||||
document.getElementById('cards').appendChild(bar);
|
||||
}
|
||||
|
||||
function pickFormat(idx, formatId) {
|
||||
cardData[idx].selectedFormatId = formatId;
|
||||
renderCard(idx);
|
||||
}
|
||||
|
||||
async function dlCard(idx) {
|
||||
const c = cardData[idx];
|
||||
c.status = 'downloading';
|
||||
c.error = null;
|
||||
renderCard(idx);
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/download', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
url: c.url,
|
||||
format: currentFormat,
|
||||
format_id: c.selectedFormatId,
|
||||
title: c.title || '',
|
||||
thumbnail: c.thumbnail || '',
|
||||
}),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.error) {
|
||||
c.status = 'error';
|
||||
c.error = data.error;
|
||||
renderCard(idx);
|
||||
return;
|
||||
}
|
||||
c.jobId = data.job_id;
|
||||
pollCard(idx);
|
||||
} catch (err) {
|
||||
c.status = 'error';
|
||||
c.error = err.message;
|
||||
renderCard(idx);
|
||||
}
|
||||
}
|
||||
|
||||
function pollCard(idx) {
|
||||
const c = cardData[idx];
|
||||
const iv = setInterval(async () => {
|
||||
try {
|
||||
const res = await fetch(`/api/status/${c.jobId}`);
|
||||
const data = await res.json();
|
||||
if (data.status === 'done') {
|
||||
clearInterval(iv);
|
||||
c.status = 'done';
|
||||
c.filename = data.filename;
|
||||
c.hasTranscript = !!data.transcript;
|
||||
renderCard(idx);
|
||||
saveCard(idx);
|
||||
if (c.hasTranscript) saveTranscript(idx);
|
||||
} else if (data.status === 'error') {
|
||||
clearInterval(iv);
|
||||
c.status = 'error';
|
||||
c.error = data.error;
|
||||
renderCard(idx);
|
||||
}
|
||||
} catch {
|
||||
clearInterval(iv);
|
||||
c.status = 'error';
|
||||
c.error = 'Lost connection to server';
|
||||
renderCard(idx);
|
||||
}
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
function saveCard(idx) {
|
||||
const c = cardData[idx];
|
||||
if (!c.jobId) return;
|
||||
const a = document.createElement('a');
|
||||
a.href = `/api/file/${c.jobId}`;
|
||||
a.download = c.filename || '';
|
||||
a.click();
|
||||
}
|
||||
|
||||
function saveTranscript(idx) {
|
||||
const c = cardData[idx];
|
||||
if (!c.jobId || !c.hasTranscript) return;
|
||||
const a = document.createElement('a');
|
||||
a.href = `/api/transcript/${c.jobId}`;
|
||||
a.download = (c.filename || 'transcript').replace(/\.[^.]+$/, '') + '.txt';
|
||||
a.click();
|
||||
}
|
||||
|
||||
async function dlAll() {
|
||||
const btn = document.querySelector('.dl-all-btn');
|
||||
if (btn) { btn.disabled = true; btn.textContent = 'Downloading...'; }
|
||||
|
||||
for (let i = 0; i < cardData.length; i++) {
|
||||
if (cardData[i].status === 'ready') {
|
||||
await dlCard(i);
|
||||
}
|
||||
}
|
||||
|
||||
if (btn) { btn.disabled = false; btn.textContent = 'Download All'; }
|
||||
}
|
||||
|
||||
function fmtSize(bytes) {
|
||||
if (!bytes) return '';
|
||||
const mb = bytes / 1048576;
|
||||
return mb >= 1024 ? (mb / 1024).toFixed(2) + ' GB' : mb.toFixed(1) + ' MB';
|
||||
}
|
||||
|
||||
async function loadHistory() {
|
||||
try {
|
||||
const res = await fetch('/api/history');
|
||||
const rows = await res.json();
|
||||
const box = document.getElementById('history');
|
||||
if (!Array.isArray(rows) || !rows.length) return;
|
||||
const items = rows.map(r => {
|
||||
let thumbHtml;
|
||||
if (r.thumbnail) {
|
||||
thumbHtml = `<img src="${r.thumbnail}" alt="">`;
|
||||
} else {
|
||||
thumbHtml = `<div class="no-thumb"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="20" height="20" rx="2"/><circle cx="8" cy="8" r="1.5"/><path d="m21 15-5-5L5 21"/></svg></div>`;
|
||||
}
|
||||
const flag = r.has_transcript
|
||||
? `<span class="card-status done">transcript ✓</span>`
|
||||
: `<span class="card-status">no transcript</span>`;
|
||||
return `
|
||||
<div class="card">
|
||||
<div class="card-thumb">${thumbHtml}</div>
|
||||
<div class="card-body">
|
||||
<div class="card-title">${esc(r.title || r.filename || r.url || 'Untitled')}</div>
|
||||
<div class="card-meta">${esc(r.date || '')}${r.size ? ' · ' + fmtSize(r.size) : ''} · <span class="${r.has_transcript ? 'card-status done' : ''}">${r.has_transcript ? 'transcript ✓' : 'no transcript'}</span></div>
|
||||
<div class="card-actions">
|
||||
<a class="card-dl-btn" href="/api/file/${r.job_id}" download>Save</a>
|
||||
${r.has_transcript ? `<a class="card-dl-btn" href="/api/transcript/${r.job_id}" download>Transcript</a>` : ''}
|
||||
</div>
|
||||
</div>
|
||||
</div>`;
|
||||
}).join('');
|
||||
box.innerHTML = `<h2 class="hist-h">History</h2>${items}`;
|
||||
} catch { /* history unavailable */ }
|
||||
}
|
||||
|
||||
loadHistory();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,389 @@
|
||||
diff --git a/app.py b/app.py
|
||||
index 2b5eaa5..1dfbbd0 100644
|
||||
--- a/app.py
|
||||
+++ b/app.py
|
||||
@@ -2,8 +2,11 @@ import os
|
||||
import uuid
|
||||
import glob
|
||||
import json
|
||||
+import re
|
||||
+import hashlib
|
||||
import subprocess
|
||||
import threading
|
||||
+import time
|
||||
from flask import Flask, request, jsonify, send_file, render_template
|
||||
|
||||
app = Flask(__name__)
|
||||
@@ -12,6 +15,97 @@ os.makedirs(DOWNLOAD_DIR, exist_ok=True)
|
||||
|
||||
jobs = {}
|
||||
|
||||
+HISTORY_FILE = os.path.join(DOWNLOAD_DIR, "history.json")
|
||||
+_history_lock = threading.Lock()
|
||||
+
|
||||
+
|
||||
+def load_history():
|
||||
+ try:
|
||||
+ with open(HISTORY_FILE, encoding="utf-8") as fh:
|
||||
+ data = json.load(fh)
|
||||
+ return data if isinstance(data, list) else []
|
||||
+ except Exception:
|
||||
+ return []
|
||||
+
|
||||
+
|
||||
+def save_history(history):
|
||||
+ try:
|
||||
+ tmp = HISTORY_FILE + ".tmp"
|
||||
+ with open(tmp, "w", encoding="utf-8") as fh:
|
||||
+ json.dump(history, fh, indent=2)
|
||||
+ os.replace(tmp, HISTORY_FILE)
|
||||
+ except OSError:
|
||||
+ pass
|
||||
+
|
||||
+
|
||||
+def sidecar_transcript(file_path):
|
||||
+ """Manual-fallback transcripts (yt-transcribe <file>) live beside the
|
||||
+ media as <stem>.txt — recognize them at read time so history stays
|
||||
+ truthful without re-downloading anything."""
|
||||
+ if not file_path:
|
||||
+ return None
|
||||
+ stem = os.path.splitext(file_path)[0] + ".txt"
|
||||
+ return stem if os.path.exists(stem) else None
|
||||
+
|
||||
+
|
||||
+def record_history(job):
|
||||
+ """Persist the completed job so history + file/transcript downloads
|
||||
+ survive process restarts (downloads dir is the mapped volume)."""
|
||||
+ with _history_lock:
|
||||
+ history = [h for h in load_history() if h.get("job_id") != job.get("job_id")]
|
||||
+ history.insert(0, {
|
||||
+ "job_id": job.get("job_id"),
|
||||
+ "url": job.get("url", ""),
|
||||
+ "title": job.get("title", ""),
|
||||
+ "thumbnail": job.get("thumbnail", ""),
|
||||
+ "filename": job.get("filename", ""),
|
||||
+ "file": job.get("file", ""),
|
||||
+ "transcript": job.get("transcript") or "",
|
||||
+ "transcript_name": job.get("transcript_name", ""),
|
||||
+ "has_transcript": bool(job.get("transcript")),
|
||||
+ "size": os.path.getsize(job["file"]) if job.get("file") and os.path.exists(job["file"]) else 0,
|
||||
+ "date": time.strftime("%Y-%m-%d %H:%M:%S"),
|
||||
+ })
|
||||
+ save_history(history[:200])
|
||||
+
|
||||
+
|
||||
+MEDIA_EXTS = (".mp4", ".mkv", ".webm", ".m4a", ".mp3", ".flac", ".mov", ".avi", ".wav", ".ts")
|
||||
+
|
||||
+
|
||||
+def backfill_history():
|
||||
+ """Add on-disk downloads that predate history.json (or were dropped into
|
||||
+ the downloads dir manually) so the whole library shows up on the page.
|
||||
+ The transcript flag is resolved live at read time, so backfilled entries
|
||||
+ pick up manual yt-transcribe sidecars automatically."""
|
||||
+ for name in sorted(os.listdir(DOWNLOAD_DIR)):
|
||||
+ path = os.path.join(DOWNLOAD_DIR, name)
|
||||
+ if not os.path.isfile(path) or not name.lower().endswith(MEDIA_EXTS):
|
||||
+ continue
|
||||
+ with _history_lock:
|
||||
+ history = load_history()
|
||||
+ if any(h.get("file") == path for h in history):
|
||||
+ continue
|
||||
+ stem = os.path.splitext(name)[0]
|
||||
+ # a 10-hex stem is a reclip job id — the real title wasn't kept
|
||||
+ title = "" if re.fullmatch(r"[0-9a-f]{10}", stem) else stem
|
||||
+ history.insert(0, {
|
||||
+ "job_id": hashlib.sha1(path.encode()).hexdigest()[:10],
|
||||
+ "url": "",
|
||||
+ "title": title,
|
||||
+ "filename": name,
|
||||
+ "file": path,
|
||||
+ "transcript": "",
|
||||
+ "transcript_name": "",
|
||||
+ "has_transcript": False,
|
||||
+ "size": os.path.getsize(path),
|
||||
+ "date": time.strftime("%Y-%m-%d %H:%M:%S",
|
||||
+ time.localtime(os.path.getmtime(path))),
|
||||
+ })
|
||||
+ save_history(history[:200])
|
||||
+
|
||||
+
|
||||
+backfill_history()
|
||||
+
|
||||
|
||||
def parse_ytdlp_json(stdout):
|
||||
"""Parse yt-dlp JSON output.
|
||||
@@ -29,6 +123,53 @@ def parse_ytdlp_json(stdout):
|
||||
raise ValueError("yt-dlp returned no data")
|
||||
|
||||
|
||||
+def fetch_transcript(url, chosen_path):
|
||||
+ """Best-effort transcript via yt-dlp captions (manual or auto-generated;
|
||||
+ includes X's auto-captions). Writes <video stem>.txt beside the download.
|
||||
+ Returns the .txt path, or None when the video has no captions. Never
|
||||
+ raises — a transcript is a bonus, not a download requirement."""
|
||||
+ stem = os.path.splitext(chosen_path)[0]
|
||||
+ try:
|
||||
+ cmd = ["yt-dlp", "--no-playlist", "--skip-download", "--no-warnings",
|
||||
+ "--write-subs", "--write-auto-subs",
|
||||
+ "--sub-langs", "en,en-orig",
|
||||
+ "--sub-format", "vtt",
|
||||
+ "-o", stem + ".%(ext)s", url]
|
||||
+ subprocess.run(cmd, capture_output=True, text=True, timeout=180)
|
||||
+
|
||||
+ vtts = glob.glob(stem + ".*.vtt")
|
||||
+ if not vtts:
|
||||
+ return None
|
||||
+ vtts.sort(key=lambda p: (0 if p.endswith(".en.vtt") else 1, p))
|
||||
+
|
||||
+ lines, prev = [], None
|
||||
+ with open(vtts[0], encoding="utf-8", errors="replace") as fh:
|
||||
+ for raw in fh:
|
||||
+ line = raw.strip()
|
||||
+ if (not line or "-->" in line
|
||||
+ or line.startswith(("WEBVTT", "Kind:", "Language:", "NOTE", "STYLE"))
|
||||
+ or re.match(r"^\d+$", line)):
|
||||
+ continue
|
||||
+ line = re.sub(r"<[^>]+>", "", line)
|
||||
+ if line and line != prev:
|
||||
+ lines.append(line)
|
||||
+ prev = line
|
||||
+
|
||||
+ txt = stem + ".txt"
|
||||
+ with open(txt, "w", encoding="utf-8") as out:
|
||||
+ out.write(" ".join(lines) + "\n")
|
||||
+
|
||||
+ for f in vtts:
|
||||
+ try:
|
||||
+ os.remove(f)
|
||||
+ except OSError:
|
||||
+ pass
|
||||
+
|
||||
+ return txt if lines else None
|
||||
+ except Exception:
|
||||
+ return None
|
||||
+
|
||||
+
|
||||
def run_download(job_id, url, format_choice, format_id):
|
||||
job = jobs[job_id]
|
||||
out_template = os.path.join(DOWNLOAD_DIR, f"{job_id}.%(ext)s")
|
||||
@@ -81,6 +222,12 @@ def run_download(job_id, url, format_choice, format_id):
|
||||
job["filename"] = f"{safe_title}{ext}" if safe_title else os.path.basename(chosen)
|
||||
else:
|
||||
job["filename"] = os.path.basename(chosen)
|
||||
+
|
||||
+ # Best-effort transcript sidecar: yt-dlp captions (X auto-captions
|
||||
+ # included) -> plain .txt next to the chosen file. Never fails the job.
|
||||
+ job["transcript"] = fetch_transcript(url, chosen)
|
||||
+ job["transcript_name"] = os.path.splitext(job["filename"])[0] + ".txt"
|
||||
+ record_history(job)
|
||||
except subprocess.TimeoutExpired:
|
||||
job["status"] = "error"
|
||||
job["error"] = "Download timed out (5 min limit)"
|
||||
@@ -175,7 +322,8 @@ def start_download():
|
||||
return jsonify({"error": "No URL provided"}), 400
|
||||
|
||||
job_id = uuid.uuid4().hex[:10]
|
||||
- jobs[job_id] = {"status": "downloading", "url": url, "title": title}
|
||||
+ jobs[job_id] = {"job_id": job_id, "status": "downloading", "url": url, "title": title,
|
||||
+ "thumbnail": (data.get("thumbnail") or "")[:500]}
|
||||
|
||||
thread = threading.Thread(target=run_download, args=(job_id, url, format_choice, format_id))
|
||||
thread.daemon = True
|
||||
@@ -184,6 +332,18 @@ def start_download():
|
||||
return jsonify({"job_id": job_id})
|
||||
|
||||
|
||||
+def resolve_download(job_id, key):
|
||||
+ """Find a completed job in memory, falling back to the on-disk history
|
||||
+ (paths point into DOWNLOAD_DIR, so they survive restarts)."""
|
||||
+ job = jobs.get(job_id)
|
||||
+ if job and job.get("status") == "done" and job.get(key):
|
||||
+ return job
|
||||
+ for entry in load_history():
|
||||
+ if entry.get("job_id") == job_id and entry.get(key):
|
||||
+ return entry
|
||||
+ return None
|
||||
+
|
||||
+
|
||||
@app.route("/api/status/<job_id>")
|
||||
def check_status(job_id):
|
||||
job = jobs.get(job_id)
|
||||
@@ -193,15 +353,48 @@ def check_status(job_id):
|
||||
"status": job["status"],
|
||||
"error": job.get("error"),
|
||||
"filename": job.get("filename"),
|
||||
+ "transcript": bool(job.get("transcript")),
|
||||
})
|
||||
|
||||
|
||||
+@app.route("/api/history")
|
||||
+def get_history():
|
||||
+ rows = load_history()[:50]
|
||||
+ for r in rows:
|
||||
+ # Truth at read time: a recorded caption-transcript may have been
|
||||
+ # deleted, and a manual yt-transcribe sidecar may have appeared since.
|
||||
+ path = r.get("transcript") or sidecar_transcript(r.get("file"))
|
||||
+ if path and os.path.exists(path):
|
||||
+ r["transcript"] = path
|
||||
+ r["has_transcript"] = True
|
||||
+ if not r.get("transcript_name"):
|
||||
+ r["transcript_name"] = os.path.splitext(os.path.basename(path))[0] + ".txt"
|
||||
+ else:
|
||||
+ r["transcript"] = ""
|
||||
+ r["has_transcript"] = False
|
||||
+ return jsonify(rows)
|
||||
+
|
||||
+
|
||||
+@app.route("/api/transcript/<job_id>")
|
||||
+def download_transcript(job_id):
|
||||
+ rec = resolve_download(job_id, "file") or resolve_download(job_id, "transcript")
|
||||
+ path = (rec.get("transcript") if rec else None) \
|
||||
+ or (sidecar_transcript(rec.get("file")) if rec else None)
|
||||
+ if not rec or not path or not os.path.exists(path):
|
||||
+ return jsonify({"error": "Transcript not found"}), 404
|
||||
+ default_name = os.path.splitext(os.path.basename(path))[0] + ".txt"
|
||||
+ return send_file(path, as_attachment=True,
|
||||
+ download_name=rec.get("transcript_name") or default_name)
|
||||
+
|
||||
+
|
||||
@app.route("/api/file/<job_id>")
|
||||
def download_file(job_id):
|
||||
- job = jobs.get(job_id)
|
||||
- if not job or job["status"] != "done":
|
||||
- return jsonify({"error": "File not ready"}), 404
|
||||
- return send_file(job["file"], as_attachment=True, download_name=job["filename"])
|
||||
+ rec = resolve_download(job_id, "file")
|
||||
+ path = rec.get("file") if rec else None
|
||||
+ if not rec or not path or not os.path.exists(path):
|
||||
+ return jsonify({"error": "File not found"}), 404
|
||||
+ return send_file(path, as_attachment=True,
|
||||
+ download_name=rec.get("filename") or os.path.basename(path))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
diff --git a/templates/index.html b/templates/index.html
|
||||
index 1f566d1..4807aa1 100644
|
||||
--- a/templates/index.html
|
||||
+++ b/templates/index.html
|
||||
@@ -343,6 +343,18 @@
|
||||
.dl-all-btn:hover { background: #2d2d2a; }
|
||||
.dl-all-btn:disabled { opacity: 0.4; cursor: not-allowed; }
|
||||
|
||||
+ /* History — same card language as the fetch results */
|
||||
+ .hist-h {
|
||||
+ font-family: 'Instrument Serif', serif;
|
||||
+ font-size: 1.9rem;
|
||||
+ font-weight: 400;
|
||||
+ letter-spacing: -0.02em;
|
||||
+ margin: 44px 0 14px;
|
||||
+ color: var(--fg);
|
||||
+ }
|
||||
+ #history .card { animation: slideUp 0.4s cubic-bezier(0.16, 1, 0.3, 1); }
|
||||
+ a.card-dl-btn { text-decoration: none; display: inline-block; }
|
||||
+
|
||||
.spin {
|
||||
display: inline-block;
|
||||
width: 10px; height: 10px;
|
||||
@@ -399,6 +411,7 @@
|
||||
</div>
|
||||
|
||||
<div id="cards" class="cards"></div>
|
||||
+ <div id="history"></div>
|
||||
|
||||
<div class="footer">
|
||||
YouTube · TikTok · Instagram · Twitter/X · Reddit · Facebook<br>
|
||||
@@ -586,8 +599,9 @@
|
||||
} else if (c.status === 'downloading') {
|
||||
actionHtml = `<span class="card-status downloading"><span class="spin"></span> Downloading...</span>`;
|
||||
} else if (c.status === 'done') {
|
||||
- actionHtml = `<button class="card-dl-btn done" onclick="saveCard(${idx})">Save</button>
|
||||
- <span class="card-status done">${esc(c.filename || '')}</span>`;
|
||||
+ actionHtml = `<button class="card-dl-btn done" onclick="saveCard(${idx})">Save</button>` +
|
||||
+ (c.hasTranscript ? `<button class="card-dl-btn" onclick="saveTranscript(${idx})">Transcript</button>` : '') +
|
||||
+ `<span class="card-status done">${esc(c.filename || '')}</span>`;
|
||||
} else if (c.status === 'error') {
|
||||
actionHtml = `<button class="card-dl-btn" onclick="dlCard(${idx})">Retry</button>
|
||||
<span class="card-status error">${esc(friendlyError(c.error || 'Download failed'))}</span>`;
|
||||
@@ -634,6 +648,7 @@
|
||||
format: currentFormat,
|
||||
format_id: c.selectedFormatId,
|
||||
title: c.title || '',
|
||||
+ thumbnail: c.thumbnail || '',
|
||||
}),
|
||||
});
|
||||
const data = await res.json();
|
||||
@@ -662,8 +677,10 @@
|
||||
clearInterval(iv);
|
||||
c.status = 'done';
|
||||
c.filename = data.filename;
|
||||
+ c.hasTranscript = !!data.transcript;
|
||||
renderCard(idx);
|
||||
saveCard(idx);
|
||||
+ if (c.hasTranscript) saveTranscript(idx);
|
||||
} else if (data.status === 'error') {
|
||||
clearInterval(iv);
|
||||
c.status = 'error';
|
||||
@@ -688,6 +705,15 @@
|
||||
a.click();
|
||||
}
|
||||
|
||||
+ function saveTranscript(idx) {
|
||||
+ const c = cardData[idx];
|
||||
+ if (!c.jobId || !c.hasTranscript) return;
|
||||
+ const a = document.createElement('a');
|
||||
+ a.href = `/api/transcript/${c.jobId}`;
|
||||
+ a.download = (c.filename || 'transcript').replace(/\.[^.]+$/, '') + '.txt';
|
||||
+ a.click();
|
||||
+ }
|
||||
+
|
||||
async function dlAll() {
|
||||
const btn = document.querySelector('.dl-all-btn');
|
||||
if (btn) { btn.disabled = true; btn.textContent = 'Downloading...'; }
|
||||
@@ -700,6 +726,47 @@
|
||||
|
||||
if (btn) { btn.disabled = false; btn.textContent = 'Download All'; }
|
||||
}
|
||||
+
|
||||
+ function fmtSize(bytes) {
|
||||
+ if (!bytes) return '';
|
||||
+ const mb = bytes / 1048576;
|
||||
+ return mb >= 1024 ? (mb / 1024).toFixed(2) + ' GB' : mb.toFixed(1) + ' MB';
|
||||
+ }
|
||||
+
|
||||
+ async function loadHistory() {
|
||||
+ try {
|
||||
+ const res = await fetch('/api/history');
|
||||
+ const rows = await res.json();
|
||||
+ const box = document.getElementById('history');
|
||||
+ if (!Array.isArray(rows) || !rows.length) return;
|
||||
+ const items = rows.map(r => {
|
||||
+ let thumbHtml;
|
||||
+ if (r.thumbnail) {
|
||||
+ thumbHtml = `<img src="${r.thumbnail}" alt="">`;
|
||||
+ } else {
|
||||
+ thumbHtml = `<div class="no-thumb"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="20" height="20" rx="2"/><circle cx="8" cy="8" r="1.5"/><path d="m21 15-5-5L5 21"/></svg></div>`;
|
||||
+ }
|
||||
+ const flag = r.has_transcript
|
||||
+ ? `<span class="card-status done">transcript ✓</span>`
|
||||
+ : `<span class="card-status">no transcript</span>`;
|
||||
+ return `
|
||||
+ <div class="card">
|
||||
+ <div class="card-thumb">${thumbHtml}</div>
|
||||
+ <div class="card-body">
|
||||
+ <div class="card-title">${esc(r.title || r.filename || r.url || 'Untitled')}</div>
|
||||
+ <div class="card-meta">${esc(r.date || '')}${r.size ? ' · ' + fmtSize(r.size) : ''} · <span class="${r.has_transcript ? 'card-status done' : ''}">${r.has_transcript ? 'transcript ✓' : 'no transcript'}</span></div>
|
||||
+ <div class="card-actions">
|
||||
+ <a class="card-dl-btn" href="/api/file/${r.job_id}" download>Save</a>
|
||||
+ ${r.has_transcript ? `<a class="card-dl-btn" href="/api/transcript/${r.job_id}" download>Transcript</a>` : ''}
|
||||
+ </div>
|
||||
+ </div>
|
||||
+ </div>`;
|
||||
+ }).join('');
|
||||
+ box.innerHTML = `<h2 class="hist-h">History</h2>${items}`;
|
||||
+ } catch { /* history unavailable */ }
|
||||
+ }
|
||||
+
|
||||
+ loadHistory();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -13,7 +13,7 @@ The firstmate crew dispatch + Gitea PR helper are wired by `darwin-rebuild`, but
|
||||
cd ~/Documents/investor-flow
|
||||
git remote set-url origin http://unraid.local:3003/transnet/investor-flow
|
||||
|
||||
Verify: `fm` launches OpenCode 2 as the first mate (isolated `~/.config/opencode2`); `oc2 --version` prints an OpenCode 2 version; `pi --list-models mimo` shows `opencode-go/mimo-v2.5-pro`; `tea pulls list --repo transnet/investor-flow` works.
|
||||
Verify: `fm` launches Pi as the first mate (accept project trust once); `oc2 --version` prints an OpenCode 2 version; `pi --list-models mimo` shows `opencode-go/mimo-v2.5-pro`; `tea pulls list --repo transnet/investor-flow` works.
|
||||
|
||||
## security-audit skill (agent security reviews)
|
||||
|
||||
@@ -82,6 +82,14 @@ Container controls:
|
||||
|
||||
Use dummy data only. The exclusions cover common secrets and the top-level `data` directory, not every possible secret path. Review the copied tree, or add `--exclude` patterns, before you run a target that reads credentials from unexpected places. Audit findings do not belong in this repo or in the run directory.
|
||||
|
||||
## pstack skills (pinned on every rebuild)
|
||||
|
||||
`home.activation.pstackSkills` restores the eleven adopted pstack skills into `~/.agents/skills`, the shared user-level skill directory that the security-audit section describes. The source is `https://github.com/cursor/plugins` at a fixed commit (folder `pstack/skills`), pinned by the `pstackSkills` `fetchFromGitHub` in `home.nix`. That pin is the only record of the commit in this repo: to move to newer upstream content, change `rev` and `hash` together, then rerun `./rebuild.sh`.
|
||||
|
||||
Each run removes and recopies only those eleven directories, so a renamed upstream file never lingers and every other skill in `~/.agents/skills` stays untouched, including an existing tdd skill. `tdd` is skipped on purpose: an existing user-level tdd skill owns that name, so the pstack copy is never installed. The block adds no `~/.claude/skills` link, so Claude Code does not see these eleven skills.
|
||||
|
||||
Why these eleven skills exist is recorded in firstmate's `docs/adopted-skills.md`, outside this repo.
|
||||
|
||||
## OpenSuperWhisper (local voice input)
|
||||
|
||||
Hold a shortcut, speak, release, and the transcript pastes into the focused app. Everything runs on the Mac: no audio or transcript leaves the machine.
|
||||
|
||||
+19
-2
@@ -2,7 +2,8 @@
|
||||
# Rebuild nix-darwin + home-manager. Rotates stale home-manager *.backup files
|
||||
# so a second switch never fails with "would be clobbered".
|
||||
# Also updates flake inputs, upgrades grok-build, installs OpenCode 1.x
|
||||
# (stable CLI for free-tier), updates no-mistakes, and updates pi extensions.
|
||||
# (stable CLI for free-tier), removes the retired OpenCode 2 npm beta, updates
|
||||
# no-mistakes, and updates pi extensions.
|
||||
set -euo pipefail
|
||||
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
|
||||
ln -sfn "$DIR" ~/.dotfiles
|
||||
@@ -17,7 +18,7 @@ else
|
||||
fi
|
||||
|
||||
# Install OpenCode 1.x (stable CLI, binary "opencode") if absent.
|
||||
# Required for free-tier models; opencode2 beta returns HTTP 426 on those endpoints.
|
||||
# Required for free-tier models; OpenCode 2 is the separate stable `oc2` build.
|
||||
# Uses Homebrew's npm (not Nix's npm) to avoid EACCES on the store.
|
||||
# Skip if npm is unavailable (e.g., network issues preventing fetch).
|
||||
OPENCODE_BIN=/opt/homebrew/bin/opencode
|
||||
@@ -32,6 +33,21 @@ else
|
||||
echo "==> OpenCode 1.x already installed: $(${OPENCODE_BIN} --version)"
|
||||
fi
|
||||
|
||||
# Remove the retired OpenCode 2 beta (@opencode-ai/cli, binary "opencode2") if
|
||||
# an older rebuild installed it. The stable Homebrew `opencode` formula declared
|
||||
# in configuration.nix is now the only OpenCode 2 install. Local check only, so
|
||||
# an offline rebuild skips this instead of failing.
|
||||
NPM=/opt/homebrew/bin/npm
|
||||
if [ -x "$NPM" ] && beta_root="$("$NPM" root -g 2>/dev/null)" && [ -d "$beta_root/@opencode-ai/cli" ]; then
|
||||
echo "==> Removing retired OpenCode 2 beta (@opencode-ai/cli)..."
|
||||
if "$NPM" uninstall -g @opencode-ai/cli 2>&1; then
|
||||
echo "==> OpenCode 2 beta removed"
|
||||
else
|
||||
echo "==> WARNING: OpenCode 2 beta removal failed. Remove it manually:"
|
||||
echo " $NPM uninstall -g @opencode-ai/cli"
|
||||
fi
|
||||
fi
|
||||
|
||||
echo "==> Updating no-mistakes..."
|
||||
NO_MISTAKES_BIN="$HOME/.no-mistakes/bin/no-mistakes"
|
||||
if [ -x "$NO_MISTAKES_BIN" ]; then
|
||||
@@ -66,6 +82,7 @@ managed=(
|
||||
"$HOME/.config/opencode2/AGENTS.md"
|
||||
"$HOME/.local/bin/oc2"
|
||||
"$HOME/.local/bin/opencode-go-token"
|
||||
"$HOME/.local/bin/opencode-go-key-sync"
|
||||
"$HOME/.pi/agent/settings.json"
|
||||
"$HOME/.pi/agent/models.json"
|
||||
"$HOME/.pi/agent/AGENTS.md"
|
||||
|
||||
Reference in new issue
Block a user