From a2768611ad726f66fb522d5185c32286feba5ed8 Mon Sep 17 00:00:00 2001 From: BlueJayLouche Date: Sun, 11 Oct 2026 13:25:00 +1100 Subject: [PATCH] Sessions, sharing recordings, and locating an original MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Sessions. A session is one project: its own recordings, recordings folder, clips, exports and search. Each is a folder in sessions/ laid out like the library itself, which stays where it is as the "Main library". Recordings… has a Session menu and a box to start a new one; the open session is reopened at the next launch. Sharing. "Collect and export" writes one .zip holding the open recording, its folder, or everything in the session: transcripts, corrections, listening copies and waveforms, and with "with the originals" the recordings themselves. "Import…" takes such a file into the open session, leaving recordings already there as they are. The file is someone else's, so file names and the shape of each transcript are checked before anything is written, and the sender's folder paths are left out of what is sent. Locating. When an export cannot find an original it names the recording and the file it wants and offers "Locate it…", so a copy under another name or in another folder can be used. A file of another length is questioned first. The system file dialog's prompt is now passed as an argument instead of being written into the script, since it can hold a file name that came from someone else. README: sections on sessions, sharing, where clips are cut from, and what to do when the first transcription goes wrong. Co-Authored-By: Claude Opus 5.5 --- README.md | 65 ++++++++++++- app.py | 242 +++++++++++++++++++++++++++++++++++++++++++--- smoke.py | 73 ++++++++++++++ static/index.html | 95 +++++++++++++++++- 4 files changed, 451 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index 99e6722..cb35fae 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,8 @@ Built for making selects from an archive of digitised cassette tapes: hours of s - **Correct the transcript** where the machine misheard. The original wording is kept and corrected words are marked. - **Mark a passage to review** when you are not yet sure of it: it gets its own colour and is kept out of the export until you clear the mark. - **Export** clips into named bins: each clip is cut from the original recording, in the original's format, with handles, plus a log sheet (`log.csv`) of tape, in and out points and words. +- **A session per project**, each with its own recordings, clips and search, so one job's tapes are not in the way of another's. +- **Hand recordings to someone else** already transcribed: collect them into one file, with or without the originals, and they import it. Nothing has to be transcribed twice. Nothing is uploaded. The recordings are only ever read, and the app answers only to the computer it runs on. @@ -33,7 +35,7 @@ The app is not signed by a registered Apple developer, so macOS will refuse to o xattr -dr com.apple.quarantine /Applications/Transclip.app ``` -The first launch downloads Python and the app's libraries (a minute or two) before its window opens. The first transcription downloads the speech model (a few GB). After that it works offline. +The first launch downloads Python and the app's libraries (a minute or two) before its window opens. The first transcription downloads the transcriber's libraries and the speech model, about 5 GB in all, and the status in **Recordings…** counts the model as it arrives. After that it works offline. If it does not get that far, see [If something goes wrong](#if-something-goes-wrong). If your recordings are on an external drive, macOS asks once whether to allow reading it, and the Recordings panel waits until you answer. The question names "python3.12" rather than Transclip: the app runs on the Python it downloaded, and that is the program macOS sees reading the drive. @@ -60,17 +62,72 @@ uv fetches Python and everything else the first time, ffmpeg included. On a Mac Closing the window quits Transclip; while a transcription is running it asks first, because quitting stops it. Where it runs in the browser instead, starting it again just shows it, and **Recordings… → Quit Transclip** stops it. +## Sessions + +A session is one project: its own recordings, its own recordings folder, its own clips and exports. Search looks through every recording of the open session and none of any other. + +- **Start one:** in **Recordings…**, type a name beside **Session** and press **New session**. It starts empty; choose its recordings folder and transcribe, or import recordings into it. +- **Switch:** pick another from the **Session** menu. The open session is named on the Recordings… button, and Transclip reopens the one you left. +- **Main library** is what you had before there were sessions. Nothing in it moves. +- **Saving** happens as you work; there is nothing to save or close. +- **Moving recordings into a session:** collect them in the session they are in, switch, and import the file (below). The first session keeps its copy. +- **Renaming or deleting** a session is renaming or deleting its folder in `sessions/` (see [Where things are kept](#where-things-are-kept)), with Transclip closed. + +A session cannot be changed while it is transcribing: stop the transcription first. + +## Sharing recordings + +Recordings you have transcribed can be handed to someone else, who then has nothing to transcribe. + +**Collect and export** (in **Recordings…**) writes one `.zip` into the exports folder and opens the folder. The menu beside it says what goes in: the open recording, the folder it is in, or everything in the session. The file holds each recording's transcript, your corrections, the listening copy and the waveform. That is enough to read, play, search and choose clips. It does not hold your clips, or the place the recordings are kept on your computer. + +Tick **with the originals** to put the recordings themselves in as well. The file is then as big as they are, and clips can be cut from them wherever it goes. + +**Import…** takes such a file into the open session. Recordings already there are left as they are. Originals that came in the file are kept in `originals/`. + +### Where clips are cut from + +A clip is always cut from an original recording, never from the listening copy. For each recording Transclip looks, in this order: + +1. In the session's recordings folder, for a file with the recording's own name in the same folders below it. For someone who imported your recordings, that means pointing **Recordings… → Folder containing the recordings** at their copies, named and arranged as yours were. The panel then counts them as transcribed, with none to do. +2. Where it was last told the original is: where it was when transcribed, where an import put it, or the file chosen with **Locate it…**. + +When an export cannot find an original it names the recording and the file it wants and offers **Locate it…**: choose the file, under any name and in any folder, and the export carries on. A file that runs more than a second longer or shorter than the recording is questioned first, since it is very likely a different recording; **Use it anyway** takes it. + +## If something goes wrong + +**The first transcription.** It needs about 5 GB of free disk: about 1.5 GB of libraries and a 3.1 GB speech model. On a Mac the status reads "Downloading the speech model: 1,240 of 3,084 MB" as it comes. With too little room it stops before starting and says how much is needed and how much is free; if the disk fills part-way it says so. Either way nothing is damaged: make room and press **Transcribe** again. + +**It sits on "Loading the speech model" for minutes with no count.** Another transcriber may be holding the download. Quit Transclip, run `pkill -f transcribe.py` in Terminal, and open it again. + +**Deleting and reinstalling the app changes nothing** about a download: the model and libraries are kept outside it, in `~/.cache/huggingface` and `~/.cache/uv`. + +**To watch the download happen**, from a copy of this repository: + +``` +echo '[]' > /tmp/none.json && uv run transcribe.py /tmp/none.json && echo "The speech model is ready." +``` + +It fetches the same model to the same place, and the app finds it there. If that stalls too, put `HF_HUB_DISABLE_XET=1 ` in front of `uv` to fetch it by the plain route. + +**macOS asks whether "python3.12" may read a folder.** That is Transclip (see [Install](#macos-app)). It can ask again for Downloads, Documents or Desktop when a file is imported or located there. + +**Anything else:** the app's own messages are in `Library/Logs/Transclip.log` in your home folder. + ## Where things are kept -Everything lives in one folder, `Transclip` in your home folder (set `TRANSCLIP_HOME` to put it elsewhere, or to keep a second, separate library): +Everything lives in one folder, `Transclip` in your home folder (set `TRANSCLIP_HOME` to put it elsewhere): | | | |---|---| -| `tapes/` | per recording: the transcript, a small listening copy, the waveform outline and the measurements music is found from, so everything but export works with the recordings' drive unplugged | +| `tapes/` | per recording: the transcript (which also says where the original is), a small listening copy, the waveform outline and the measurements music is found from, so everything but export works with the recordings' drive unplugged | | `selects.json` | your bins and clips, saved on every change, with one backup per day | -| `exports/` | a new dated folder per export | +| `exports/` | a new dated folder per export, and the files made by Collect and export | +| `originals/` | recordings that arrived inside an imported file | | `settings.json` | the recordings folder and depth | | `models/` | the small model that search by meaning uses | +| `sessions//` | each other session, laid out like the folder itself: `tapes/`, `selects.json`, `exports/`, `settings.json`, `originals/` | +| `session.txt` | which session to reopen | Deleting a recording's files from `tapes/` makes the app transcribe it again. diff --git a/app.py b/app.py index 1b5cf54..c26ba85 100644 --- a/app.py +++ b/app.py @@ -13,8 +13,11 @@ Everything it keeps is in one folder, Transclip in your home folder (TRANSCLIP_HOME moves it): tapes/ holds each recording's transcript, listening copy and waveform -outline, selects.json the clips, exports/ what you export. Exports are cut from the -original recordings, which are only ever read. Corrections to a transcript are kept +outline, selects.json the clips, exports/ what you export. A session is another such +folder inside it, in sessions/: one project's recordings, clips and search, apart +from every other's. Recordings can be collected into one file for someone else and +imported from one; originals that arrive that way are kept in originals/. Exports are +cut from the original recordings, which are only ever read. Corrections to a transcript are kept beside it in .fixes and laid over the machine's words when it is read; the machine's own transcript is never rewritten. Search by meaning uses a small language model kept in models/. Nothing is sent anywhere, and only this computer can reach the app. @@ -22,6 +25,7 @@ import csv import json import os +import posixpath import re import shutil import socket @@ -31,6 +35,7 @@ import time import urllib.request import webbrowser +import zipfile from pathlib import Path, PurePosixPath from urllib.parse import urlsplit @@ -39,8 +44,12 @@ from werkzeug.security import safe_join ROOT = Path(__file__).parent -HOME = Path(os.environ.get("TRANSCLIP_HOME") or Path.home() / "Transclip") +# The first library, and the home of what every session shares: the other sessions, which one is open, the model for meaning. +BASE = Path(os.environ.get("TRANSCLIP_HOME") or Path.home() / "Transclip") +# The library being worked on, which open_session() changes: the first one, or a session's folder laid out the same way. +HOME = BASE TAPES, SELECTS, SETTINGS, EXPORTS = HOME / "tapes", HOME / "selects.json", HOME / "settings.json", HOME / "exports" +ORIGINALS = HOME / "originals" # recordings that arrived with their transcripts, in a file someone collected PORT = int(os.environ.get("TRANSCLIP_PORT") or 8790) QUIET = "--no-open" in sys.argv # no window, no browser tab and no folder windows: for tests FFMPEG = imageio_ffmpeg.get_ffmpeg_exe() # comes with the package, so nothing has to be installed by hand @@ -53,6 +62,9 @@ # ponytail: one archive's convention, built in. A folder with this name holds raw transfers; a titled file # elsewhere with the same wording lends the transfer its name and is labelled as a copy. Make it a setting if another archive differs. RAW = "recordings" +# What a recording is in a collected file besides its transcript: corrections, the listening copy, the waveform. +# Where the music is gets measured again from the listening copy, in a second or two. +EXTRAS = (".fixes", ".m4a", ".peaks") # Music is looked for in the sound itself, about a quarter of a second at a time: where there are no words, # and the sound is made of tones rather than hiss (FLAT) and keeps changing rather than humming on (CHANGE). # ponytail: two measurements with limits found by trial on one archive of cassettes, checked against spectrograms. @@ -315,7 +327,7 @@ def embedder(): global _embedder if _embedder is None: from fastembed import TextEmbedding # imported late: it takes seconds and only meaning search needs it - _embedder = TextEmbedding("BAAI/bge-small-en-v1.5", cache_dir=str(HOME / "models")) + _embedder = TextEmbedding("BAAI/bge-small-en-v1.5", cache_dir=str(BASE / "models")) return _embedder @@ -360,6 +372,20 @@ def write_selects(sel): dump(SELECTS, sel) +def open_session(name): + """Work on a session from here on: its recordings, clips, settings and exports, and no other's. + One that does not exist yet is made. No name means the first library.""" + global HOME, TAPES, SELECTS, SETTINGS, EXPORTS, ORIGINALS + home = BASE / "sessions" / name if name else BASE + (home / "tapes").mkdir(parents=True, exist_ok=True) + HOME, TAPES, SELECTS, SETTINGS, EXPORTS, ORIGINALS = ( + home, home / "tapes", home / "selects.json", home / "settings.json", home / "exports", home / "originals") + backup = SELECTS.with_name(f"selects.{time.strftime('%Y-%m-%d')}.bak.json") + if SELECTS.exists() and not backup.exists(): + shutil.copy2(SELECTS, backup) # one copy per day, as things stood when first opened + (BASE / "session.txt").write_text(name, encoding="utf-8") # the one to come back to at the next launch + + def settings(): s = {"folder": "", "depth": 3} return {**s, **load(SETTINGS)} if SETTINGS.exists() else s @@ -397,6 +423,116 @@ def original(tid, tape): return here if here.exists() else Path(tape["source"]) +def collect(ids, raw): + """Gather recordings into one file to give to someone else: what this app keeps of each and, + with `raw`, the original recordings too. Returns the file.""" + what = posixpath.commonpath(ids) # the one recording, the folder they share, or nothing in particular + out = EXPORTS / f"{safe(what) if what else 'Recordings'} (Transclip {time.strftime('%Y-%m-%d %H.%M.%S')}).zip" + out.parent.mkdir(parents=True, exist_ok=True) + part = out.with_name(out.name + ".part") + # Stored, not squeezed: the sound is compressed already or too big to be worth the minutes. + # ponytail: one request does the whole job and the page just waits; give it a progress bar if tens of GB become usual. + with zipfile.ZipFile(part, "w") as z: + for tid in ids: + d = load_tape(tid) + src = original(tid, d) + # The transcript says where the original was on this computer. Its name is all anyone else needs. + z.writestr(f"tapes/{tid}.json", json.dumps({**d, "source": src.name}, ensure_ascii=False)) + for ext in EXTRAS: + if (TAPES / (tid + ext)).exists(): + z.write(TAPES / (tid + ext), f"tapes/{tid}{ext}") + if raw: + z.write(src, f"originals/{tid}{src.suffix}") + os.replace(part, out) + return out + + +def member(name): + """What a file in a collected file is, as (folder, recording, extension), or None for anything + that has no business there or would land outside the library.""" + parts = name.split("/") + ext = PurePosixPath(name).suffix + if (len(parts) < 2 or "\\" in name or ":" in name or any(part in ("", "..") or part.startswith(".") for part in parts) + or not (parts[0] == "tapes" and ext in (".json", *EXTRAS) or parts[0] == "originals" and ext.lower() in AUDIO)): + return None + return parts[0], "/".join(parts[1:])[:-len(ext)], ext + + +def well_formed(d, fixes): + """Whether a transcript and its corrections from elsewhere have the shape this app's own do. + One that had not would trip up the whole library, not just itself.""" + num = lambda v: type(v) in (int, float) and v - v == 0 # a number, and not one of the infinite or undefined ones + try: + return (num(d["duration"]) and isinstance(d["source"], str) + and all(num(c["start"]) and num(c["end"]) and bool(re.fullmatch("[a-z]{2,3}", c["lang"])) + and all(num(w["s"]) and num(w["e"]) and isinstance(w["w"], str) for w in c["words"]) + for c in d["chunks"]) + and all(num(f["s"]) and num(f["e"]) and isinstance(f["text"], str) and isinstance(f["was"], str) for f in fixes)) + except (KeyError, TypeError): + return False + + +def take_in(file): + """Add the recordings in a collected file to the library. Ones already here are left as they are. + The file is someone else's, so nothing in it is taken on trust: see member() and well_formed().""" + added = kept = bad = 0 + with zipfile.ZipFile(file) as z: + inside = {m: z.getinfo(n) for n in z.namelist() if (m := member(n))} + if sum(i.file_size for i in inside.values()) > shutil.disk_usage(HOME).free: + return None + + def put(info, root, name): + dest = Path(safe_join(str(root), name)) # refuses a name that climbs out of the folder, should member() ever let one by + dest.parent.mkdir(parents=True, exist_ok=True) + part = dest.with_name(dest.name + ".part") + with z.open(info) as a, open(part, "wb") as b: + shutil.copyfileobj(a, b) + os.replace(part, dest) + + for (kind, tid, ext), info in sorted(inside.items()): + if (kind, ext) != ("tapes", ".json"): + continue + if (TAPES / (tid + ".json")).exists(): + kept += 1 + continue + try: + # ponytail: read whole, like every transcript here; 50 MB is far beyond a day-long recording's. + assert info.file_size < 50e6 + d = json.loads(z.read(info)) + fixes = json.loads(z.read(inside["tapes", tid, ".fixes"])) if ("tapes", tid, ".fixes") in inside else [] + assert well_formed(d, fixes) + except (ValueError, AssertionError): + bad += 1 + continue + # Never somebody else's idea of where a file is on this computer: the original that came + # with it, or just its name, to be looked for in the recordings folder. + d["source"] = Path(d["source"].replace("\\", "/")).name + for (k, t, e), i in inside.items(): + if t != tid: + continue + if k == "originals": + put(i, ORIGINALS, tid + e) + d["source"] = str(ORIGINALS / (tid + e)) + elif e != ".json": + put(i, TAPES, tid + e) + dump(Path(safe_join(str(TAPES), tid + ".json")), d) # last: its presence is what makes a recording part of the library + added += 1 + return {"added": added, "kept": kept, "bad": bad} + + +def unfound(ids): + """The recordings among these whose original is not where it is looked for, each with the file name wanted.""" + tapes = library()["tapes"] + return [{"tape": t, "name": src.name} for t in sorted(set(ids), key=natural) if not (src := original(t, tapes[t])).exists()] + + +def length(path): + """How long a sound file runs, in seconds; None if ffmpeg cannot read it as one.""" + said = subprocess.run([FFMPEG, "-hide_banner", "-i", str(path)], capture_output=True, text=True, errors="replace").stderr + found = re.search(r"Duration: (\d+):(\d+):(\d+(?:\.\d+)?)", said) + return found and int(found[1]) * 3600 + int(found[2]) * 60 + float(found[3]) + + _job = {"proc": None, "state": {"running": False}} @@ -449,7 +585,9 @@ def stop_job(): def status(): folder, found, todo = pending() return {**settings(), "reachable": folder is not None, "found": len(found), "todo": len(todo), - "transcribed": len(library()["tapes"]), "job": _job["state"], "home": str(HOME)} + "transcribed": len(library()["tapes"]), "job": _job["state"], "home": str(HOME), + "session": "" if HOME == BASE else HOME.name, + "sessions": sorted((p.name for p in (BASE / "sessions").glob("[!.]*") if p.is_dir()), key=natural)} def window(webview, url): @@ -465,14 +603,16 @@ def window(webview, url): "recordings already finished are kept."}) -def choose_folder(): - """Ask for a folder with the system's own dialog. Empty if none was chosen.""" +def pick(what, prompt): + """Ask for a "folder" or a "file" with the system's own dialog. Empty if none was chosen.""" if sys.platform == "darwin": - cmd = ["osascript", "-e", "activate", "-e", 'POSIX path of (choose folder with prompt "The folder containing your recordings")'] + # The prompt goes in as an argument, not as part of the script: it may hold a file name that came from someone else. + cmd = ["osascript", "-e", "on run argv", "-e", "activate", "-e", f"POSIX path of (choose {what} with prompt (item 1 of argv))", + "-e", "end run", prompt] else: # ponytail: not tried on Windows or Linux yet; the folder can always be typed or pasted instead. cmd = [sys.executable, "-c", "import tkinter as t, tkinter.filedialog as f; r = t.Tk(); r.withdraw(); " - "r.attributes('-topmost', True); print(f.askdirectory() or '')"] + f"r.attributes('-topmost', True); print(f.{'askdirectory' if what == 'folder' else 'askopenfilename'}() or '')"] return subprocess.run(cmd, capture_output=True, text=True).stdout.strip() @@ -542,9 +682,67 @@ def put_library(): return jsonify(status()) +@app.put("/api/session") +def put_session(): + """Open the session of that name, making it if there is none; with no name, the first library.""" + if _job["state"]["running"]: + return jsonify({"error": "Stop the transcription before changing session: it belongs to this one."}), 409 + name = str(request.get_json().get("name") or "").strip() + open_session(safe(name) if name else "") + return jsonify(status()) + + @app.post("/api/choose-folder") def choose(): - return jsonify({"folder": choose_folder()}) + return jsonify({"folder": pick("folder", "The folder containing your recordings")}) + + +@app.post("/api/share") +def share(): + """Collect the named recordings into one file in the exports folder.""" + body = request.get_json() + tapes, raw = library()["tapes"], bool(body.get("raw")) + ids = [t for t in body.get("tapes") or [] if t in tapes] + missing = unfound(ids) if raw else [] + if missing or not ids: + return jsonify({"error": f"{len(missing)} original recording(s) not found. Is the drive connected, and is the " + "recordings folder the right one?" if missing else "No recordings to collect.", "missing": missing}), 409 + out = collect(ids, raw) + reveal(out.parent) + return jsonify({"file": str(out), "recordings": len(ids), "bytes": out.stat().st_size}) + + +@app.post("/api/locate") +def locate(): + """Say where a recording's original is: the file named, or one chosen in the system's dialog. + Clips are cut from it from then on, unless the recordings folder has the recording under its own name.""" + body = request.get_json() + tid = body.get("tape", "") + d = load_tape(tid) + file = body.get("file") or pick("file", f"The original recording of {tid}: {Path(d['source']).name}") + if not file: + return jsonify({"cancelled": True}) + runs = length(file) if Path(file).suffix.lower() in AUDIO and Path(file).is_file() else None + if runs is None: + return jsonify({"error": "That is not a sound file clips can be cut from."}), 409 + # A file of another length is very likely another recording, and clips would be cut from it at this one's times. + if abs(runs - d["duration"]) > 1 and not body.get("anyway"): + return jsonify({"mismatch": True, "file": file, "runs": runs, "was": d["duration"]}), 409 + dump(Path(safe_join(str(TAPES), tid + ".json")), {**d, "source": file}) + return jsonify({"source": file}) + + +@app.post("/api/import") +def import_recordings(): + """Take in a file made by /api/share: the one named, or one chosen in the system's dialog.""" + file = (request.get_json(silent=True) or {}).get("file") or pick("file", "A file of recordings collected in Transclip") + if not file: + return jsonify({"cancelled": True}) + try: + got = take_in(file) + except (OSError, RuntimeError, zipfile.BadZipFile) as e: # not there, not a zip, or one locked with a password + return jsonify({"error": f"That file could not be read as collected recordings: {e}"}), 409 + return jsonify(got) if got else (jsonify({"error": "There is not enough room on the disk for the recordings in that file."}), 409) @app.post("/api/transcribe") @@ -652,7 +850,7 @@ def export(): # do not change when it is let through later. jobs = [(b, n, c, transcript(c["tape"])) for b in sel["bins"] for n, c in enumerate(b["clips"], 1) if not c.get("review")] jobs = [(b, n, c, tape, original(c["tape"], tape)) for b, n, c, tape in jobs] - missing = sorted({str(src) for *_, src in jobs if not src.exists()}) + missing = unfound(c["tape"] for _, _, c, *_ in jobs) if missing: return jsonify({"error": f"{len(missing)} original recording(s) not found. Is the drive connected, " "and is the recordings folder the right one?", "missing": missing}), 409 @@ -692,6 +890,21 @@ def export(): def check(): + # A collected file from elsewhere: what is taken from it, and what is refused. + assert member("tapes/Proj/Tape 5.1.2/Side A.json") == ("tapes", "Proj/Tape 5.1.2/Side A", ".json") + assert member("originals/Side A.WAV") == ("originals", "Side A", ".WAV") and member("tapes/a.m4a") + for name in ("tapes/../../evil.json", "/tapes/a.json", "tapes//a.json", "a.json", "tapes/a.exe", "tapes/.hidden.json", + "tapes\\a.json", "tapes/C:/a.json", "originals/a.json", "elsewhere/a.json", "tapes/a.sound.npy", "tapes/x/"): + assert member(name) is None, name + word, good = {"s": 1, "e": 1.5, "w": "hello"}, {"s": 1, "e": 2, "text": "hallo", "was": "hello"} + ok = lambda **over: {"duration": 9.5, "source": "a.wav", "chunks": [{"start": 0, "end": 9, "lang": "en", "words": [word]}], **over} + assert well_formed(ok(), []) and well_formed(ok(), [good]) and well_formed(ok(chunks=[]), []) + for d, fixes in ((ok(duration="9"), []), (ok(duration=float("nan")), []), (ok(source=None), []), ({"chunks": []}, []), ([], []), + (ok(chunks=[{"start": 0, "end": 9, "lang": "", "words": []}]), []), (ok(chunks=[{"words": [word]}]), []), + (ok(chunks=[{"start": 0, "end": 9, "lang": "en", "words": [{"s": 1, "e": 2, "w": 3}]}]), []), + (ok(), [{**good, "was": None}]), (ok(), [["s"]]), (ok(), "nonsense")): + assert not well_formed(d, fixes), (d, fixes) + assert safe("8. /first/Side A") == "8. - first - Side A", safe("8. /first/Side A") assert safe('a:b?"c"') == "a_b__c_" and safe(" . ") == "untitled" assert stamp(754.3) == "12m34s" and clock(754.34) == "00:12:34.3" and clock(3599.96) == "01:00:00.0" @@ -762,10 +975,9 @@ def answering(port): QUIET or webbrowser.open(f"http://127.0.0.1:{port}") sys.exit() port += 1 # some other program has that port: take the next - TAPES.mkdir(parents=True, exist_ok=True) - backup = SELECTS.with_name(f"selects.{time.strftime('%Y-%m-%d')}.bak.json") - if SELECTS.exists() and not backup.exists(): - shutil.copy2(SELECTS, backup) # one copy per day, as things stood at first launch + last = BASE / "session.txt" + last = last.read_text(encoding="utf-8").strip() if last.exists() else "" + open_session(last if last == safe(last) and (BASE / "sessions" / last).is_dir() else "") # Get the meaning index ready in the background, so the first such search does not wait for it. threading.Thread(target=lambda: (meaning_index(), embedder()), daemon=True).start() url, serve = f"http://127.0.0.1:{port}", lambda: app.run(host="127.0.0.1", port=port, threaded=True) diff --git a/smoke.py b/smoke.py index 794b5c8..00fdf4d 100644 --- a/smoke.py +++ b/smoke.py @@ -25,6 +25,7 @@ import urllib.error import urllib.request import wave +import zipfile from pathlib import Path ROOT = Path(__file__).parent @@ -146,6 +147,78 @@ def finished(): assert len((Path(out["dir"]) / "log.csv").read_text(encoding="utf-8-sig").splitlines()) == 3 print("export", flush=True) + # Sharing. Collected without the originals, a recording is what the app keeps of it, and says + # nothing of where things are on this computer. + plain = call("POST", "/api/share", {"tapes": ["speech"], "raw": False}) + with zipfile.ZipFile(plain["file"]) as z: + assert set(z.namelist()) == {"tapes/speech" + e for e in (".json", ".fixes", ".m4a", ".peaks")}, z.namelist() + assert json.loads(z.read("tapes/speech.json"))["source"] == "speech.flac" + assert Path(plain["file"]).name.startswith("speech (Transclip "), plain["file"] + # Collected with them, forgotten here, and taken back in as on a computer that has no recordings folder: + # the one still here is left alone, the other returns as it was, and clips are cut from the original that came along. + whole = call("POST", "/api/share", {"tapes": ["speech", "Tape 1/Side A", "no such recording"], "raw": True}) + assert whole["recordings"] == 2 and whole["bytes"] > (folder / "speech.flac").stat().st_size, whole + for f in (tmp / "home" / "tapes").glob("speech.*"): + f.unlink() + assert set(t["id"] for t in call("GET", "/api/tapes")) == {"Tape 1/Side A"} + call("PUT", "/api/library", {"folder": str(tmp / "nowhere"), "depth": 1}) + assert call("POST", "/api/import", {"file": whole["file"]}) == {"added": 1, "kept": 1, "bad": 0} + back = call("GET", "/api/transcript/speech") + assert {**back, "source": ""} == {**before, "source": ""}, "the transcript changed on the way" + assert Path(back["source"]) == tmp / "home" / "originals" / "speech.flac", back["source"] + out = call("POST", "/api/export", {"handle": 0, "target": 0, "bins": [{"name": "Shared", "clips": [clip("speech", hit["t"], hit["end"], "")]}]}) + assert (out["clips"], out["failed"]) == (1, 0), out + # A file from someone else is not trusted: nothing lands outside the library, and a transcript + # of the wrong shape is refused rather than left to trip up every other recording. + junk = tmp / "junk.zip" + with zipfile.ZipFile(junk, "w") as z: + z.writestr("tapes/../../escaped.json", "{}"), z.writestr("tapes/broken.json", '{"chunks": 5}'), z.writestr("tapes/note.txt", "hello") + assert call("POST", "/api/import", {"file": str(junk)}) == {"added": 0, "kept": 0, "bad": 1} + assert not list(tmp.rglob("escaped.json")) and not list(tmp.rglob("broken.json")) + assert set(t["id"] for t in call("GET", "/api/tapes")) == {"Tape 1/Side A", "speech"} + try: + call("POST", "/api/import", {"file": str(tmp / "app.log")}) + raise AssertionError("a file that is no collection was taken in") + except urllib.error.HTTPError as e: + assert e.code == 409, e.code + print("sharing", flush=True) + + # Sessions: another project is another library, with its own recordings, clips, folder and search. + lib = call("PUT", "/api/session", {"name": "Second / project"}) + assert (lib["session"], lib["sessions"], lib["transcribed"], lib["folder"]) == ("Second - project", ["Second - project"], 0, ""), lib + assert call("GET", "/api/tapes") == [] and call("GET", "/api/search?q=country")["total"] == 0 + assert call("GET", "/api/selects")["bins"][0]["clips"] == [] + assert call("POST", "/api/import", {"file": plain["file"]})["added"] == 1 + assert [t["id"] for t in call("GET", "/api/tapes")] == ["speech"] and call("GET", "/api/search?q=country")["total"] >= 1 + + # It came without its original and there is no recordings folder here: export names the file it + # wants, and takes being told where it is. A file of another length is not taken without insisting. + def refused(path, body): + try: + call("POST", path, body) + except urllib.error.HTTPError as e: + assert e.code == 409, e.code + return json.loads(e.read()) + raise AssertionError(f"{path} was not refused") + cut = {"handle": 0, "target": 0, "bins": [{"name": "Located", "clips": [clip("speech", hit["t"], hit["end"], "")]}]} + assert refused("/api/export", cut)["missing"] == [{"tape": "speech", "name": "speech.flac"}] + assert "error" in refused("/api/locate", {"tape": "speech", "file": str(tmp / "app.log")}) + other = refused("/api/locate", {"tape": "speech", "file": str(folder / "Tape 1" / "Side A.wav")}) + assert other["mismatch"] and round(other["runs"]) == 6 and round(other["was"]) == 11, other + assert refused("/api/export", cut)["missing"], "a refused file was kept all the same" + moved = tmp / "renamed copy.flac" + shutil.copy(folder / "speech.flac", moved) + assert call("POST", "/api/locate", {"tape": "speech", "file": str(moved)}) == {"source": str(moved)} + out = call("POST", "/api/export", cut) + assert (out["clips"], out["failed"]) == (1, 0) and [p.suffix for p in (Path(out["dir"]) / "Located").iterdir()] == [".flac"], out + assert (tmp / "home" / "sessions" / "Second - project" / "tapes" / "speech.json").exists() + lib = call("PUT", "/api/session", {"name": ""}) + assert (lib["session"], lib["sessions"], lib["transcribed"]) == ("", ["Second - project"], 2), lib + assert call("GET", "/api/selects")["bins"][0]["name"] == "Shared" # the first library's clips, as they were left + assert call("PUT", "/api/session", {"name": "Second - project"})["transcribed"] == 1 + print("sessions", flush=True) + + assert (tmp / "home" / "session.txt").read_text(encoding="utf-8") == "Second - project" assert subprocess.run(start, env=env, timeout=300).returncode == 0 # a second launch finds the first and bows out call("POST", "/api/quit") assert app.wait(timeout=30) == 0 diff --git a/static/index.html b/static/index.html index 3c19e52..072a7ec 100644 --- a/static/index.html +++ b/static/index.html @@ -97,6 +97,14 @@ #bar { width: 100%; } #jobnote, dialog small, dialog .small { color: var(--dim); font-size: 13px; overflow-wrap: anywhere; } #closelib { margin-left: auto; } +#lib { white-space: nowrap; max-width: 24em; overflow: hidden; text-overflow: ellipsis; flex-shrink: 0; } /* a session's name can be long */ +#sessions { margin-bottom: 12px; padding-bottom: 12px; border-bottom: 1px solid var(--line); } +#session { flex: 1; min-width: 0; } +#newsession { flex: 1; min-width: 0; padding: 4px 8px; } +#share { margin: 14px 0 0; padding-top: 12px; border-top: 1px solid var(--line); flex-wrap: wrap; } +#share label { margin: 0; white-space: nowrap; } +#scope { flex: 1; min-width: 0; } +#sharenote.bad { color: var(--bad); } #gone { position: fixed; inset: 0; z-index: 10; display: grid; place-items: center; background: var(--bg); } footer { grid-column: 1 / -1; background: var(--panel); border-top: 1px solid var(--line); padding-top: 4px; } @@ -140,6 +148,10 @@

Recordings

+
+ Session + +
@@ -149,6 +161,12 @@

Recordings

+
+ + + +
+

Recordings are only read, never changed, and nothing leaves this computer. Transcripts, listening copies, your clips and exports are kept in .

@@ -556,13 +574,29 @@

Recordings

}); } +// An original that is not where it is looked for is named, with a way to say where it is. Then what was being done is tried again. +function offerLocate(tell, el, missing, again, problem) { + const [m, ...more] = missing, name = `${m.tape.replaceAll('/', ' / ')} (${m.name})`; + const ask = async file => { + const r = await fetch('/api/locate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ tape: m.tape, file, anyway: !!file }) }).catch(() => null); + const d = await r?.json().catch(() => null); + if (r?.ok && d && !d.cancelled) return again(); + if (!d?.cancelled) offerLocate(tell, el, missing, again, d ?? { error: 'That did not work. Is Transclip still running?' }); + }; + const button = (textContent, file) => h('button', { type: 'button', textContent, onclick: () => ask(file) }); + tell(problem?.mismatch ? `That file runs ${span(problem.runs)}, and ${name} runs ${span(problem.was)}.` + : problem?.error || `The original of ${name} was not found` + (more.length ? `, nor ${more.length} more` : '') + + '. Set the recordings folder to where your copies are, or say where this one is.', true); + el.append(' ', ...(problem?.mismatch ? [button('Use it anyway', problem.file), ' '] : []), button('Locate it…')); +} + $('#export').onclick = async () => { await saving; say('Exporting…'); try { const r = await fetch('/api/export', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(sel) }); const d = await r.json(); - if (!r.ok) return say(d.error || 'Export failed.', true); + if (!r.ok) return d.missing?.length ? offerLocate(say, $('#status'), d.missing, () => $('#export').click()) : say(d.error || 'Export failed.', true); say(`Exported ${d.clips - d.failed} of ${d.clips} clips to ${d.dir}` + (d.failed ? `. ${d.failed} failed: see log.csv.` : '') + (held() ? `. ${held()} still to review left out.` : ''), d.failed > 0); } catch { say('Export failed. Is Transclip still running?', true); } }; @@ -612,7 +646,8 @@

Recordings

listed = lib.transcribed; tapes = await fetch('/api/tapes').then(r => r.json()); renderTapes(); - if (!tape && tapes.length) loadTape(firstTape().id); + if (!tape && tapes.length) await loadTape(firstTape().id).catch(() => {}); + renderScope(); } } @@ -620,6 +655,10 @@

Recordings

const j = lib.job, n = (count, word) => `${count} ${word}${count === 1 ? '' : 's'}`; if (document.activeElement !== $('#folder')) $('#folder').value = lib.folder; if (document.activeElement !== $('#depth')) $('#depth').value = lib.depth; + if (document.activeElement !== $('#session')) { + $('#session').replaceChildren(...['', ...lib.sessions].map(s => h('option', { value: s, textContent: s || 'Main library' }))); + $('#session').value = lib.session; + } $('#home').textContent = lib.home; $('#found').textContent = !lib.folder ? 'Choose the folder your recordings are in.' : !lib.reachable ? 'That folder cannot be read. Is the drive connected, and has this computer been told to let Transclip read it? Everything already transcribed still works without it, except export.' @@ -631,11 +670,57 @@

Recordings

$('#go').textContent = j.running ? 'Stop transcribing' : `Transcribe ${n(lib.todo, 'recording')}`; $('#go').disabled = !j.running && !lib.todo; $('#quit').textContent = j.running ? 'Quit Transclip (stops transcribing)' : 'Quit Transclip'; - $('#lib').textContent = j.running ? `Transcribing ${j.i || 1} of ${j.n}…` : 'Recordings…'; + $('#lib').textContent = (lib.session ? lib.session + ' · ' : '') + (j.running ? `Transcribing ${j.i || 1} of ${j.n}…` : 'Recordings…'); +} + +// Sharing: collect recordings into one file for someone else, or take in a file from them. +const inFolder = () => tapes.filter(t => t.id.startsWith(tape.id.split('/')[0] + '/')); +function renderScope() { + const many = list => `${list.length} recording${list.length === 1 ? '' : 's'}`; + const choices = [...(tape ? [['one', 'The open recording']] : []), + ...(tape?.id.includes('/') ? [['folder', `Its folder, ${tape.id.split('/')[0]} (${many(inFolder())})`]] : []), + ['all', `Everything here (${many(tapes)})`]]; + $('#scope').replaceChildren(...choices.map(([value, textContent]) => h('option', { value, textContent }))); + $('#collect').disabled = !tapes.length; +} +const shareNote = (text, bad) => { $('#sharenote').textContent = text; $('#sharenote').className = bad ? 'small bad' : 'small'; }; +async function shareCall(path, body, busy) { + shareNote(busy); + $('#collect').disabled = $('#import').disabled = true; + const r = await fetch(path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }).catch(() => null); + const d = await r?.json().catch(() => null); + $('#collect').disabled = !tapes.length; $('#import').disabled = false; + if (d?.missing?.length) offerLocate(shareNote, $('#sharenote'), d.missing, () => $('#collect').click()); + else if (!r?.ok || !d) shareNote(d?.error || 'That did not work. Is Transclip still running?', true); + return r?.ok ? d : null; +} +$('#collect').onclick = async () => { + const which = $('#scope').value, ids = which === 'one' ? [tape.id] : (which === 'folder' ? inFolder() : tapes).map(t => t.id); + const d = await shareCall('/api/share', { tapes: ids, raw: $('#raw').checked }, 'Collecting…'); + if (d) shareNote(`Collected ${d.recordings} recording${d.recordings === 1 ? '' : 's'} into ${d.file} (${d.bytes < 1e9 ? Math.ceil(d.bytes / 1e6) + ' MB' : (d.bytes / 1e9).toFixed(1) + ' GB'}).`); +}; +$('#import').onclick = async () => { + const d = await shareCall('/api/import', {}, 'Choose the file you were given…'); + if (!d || d.cancelled) return d && shareNote(''); + shareNote(`Added ${d.added} recording${d.added === 1 ? '' : 's'}` + (d.kept ? `, left ${d.kept} already here as they were` : '') + + (d.bad ? `, could not read ${d.bad}` : '') + '.', !d.added && d.bad > 0); + library(); // lists what came in +}; + +// A session is another library. Everything on the page belongs to the one that is open, so changing it starts the page afresh. +async function openSession(name) { + await saving; + const r = await fetch('/api/session', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name }) }).catch(() => null); + if (r?.ok) return location.reload(); + shareNote((await r?.json().catch(() => null))?.error || 'The session could not be changed. Is Transclip still running?', true); + library(); // puts the list back on the session that is still open } +$('#session').onchange = () => { $('#session').blur(); openSession($('#session').value); }; +$('#makesession').onclick = () => $('#newsession').value.trim() && openSession($('#newsession').value); +$('#newsession').onkeydown = e => e.key === 'Enter' && $('#makesession').click(); const saveLibrary = () => library({ folder: $('#folder').value, depth: +$('#depth').value }); -$('#lib').onclick = () => { $('#library').showModal(); library(); }; +$('#lib').onclick = () => { $('#library').showModal(); renderScope(); library(); }; $('#closelib').onclick = () => $('#library').close(); $('#folder').onchange = $('#depth').onchange = saveLibrary; $('#choose').onclick = async () => { @@ -678,7 +763,7 @@

Recordings

else $('#transcript').append(h('div', { className: 'gap', textContent: 'No recordings yet. Choose the folder they are in under "Recordings…", then transcribe them.' })); requestAnimationFrame(tick); await library(); - if (!tapes.length) $('#library').showModal(); + if (!tapes.length) { renderScope(); $('#library').showModal(); } })();