Repository navigation
Expand file tree
/
Copy pathtranscripts.py
More file actions
executable file
·171 lines (156 loc) · 7.56 KB
/
Copy pathtranscripts.py
File metadata and controls
executable file
·171 lines (156 loc) · 7.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
#!/usr/bin/env python3
"""Shared transcript store and stdin adapter. Python standard library only."""
import argparse
import datetime as dt
import json
import os
from pathlib import Path
import sqlite3
import subprocess
import sys
def connect():
base = Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local/share"))
directory = Path(os.environ.get("OMARCHY_TRANSCRIPTS_DIR", base / "omarchy-transcripts"))
directory.mkdir(mode=0o700, parents=True, exist_ok=True)
directory.chmod(0o700)
db = directory / "history.sqlite3"
connection = sqlite3.connect(db, timeout=1.0)
db.chmod(0o600)
connection.row_factory = sqlite3.Row
connection.executescript("""
CREATE TABLE IF NOT EXISTS transcripts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
created_at TEXT NOT NULL,
source TEXT NOT NULL,
text TEXT NOT NULL,
trashed INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX IF NOT EXISTS transcripts_visible ON transcripts(trashed, id DESC);
CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT NOT NULL);
""")
return connection
def is_paused(db):
row = db.execute("SELECT value FROM settings WHERE key = 'paused'").fetchone()
return row is not None and row[0] == "true"
def save(db, text, source):
if not text.strip():
return None
now = dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds")
with db:
cursor = db.execute(
"""INSERT INTO transcripts(created_at, source, text)
SELECT ?, ?, ? WHERE NOT EXISTS (
SELECT 1 FROM settings WHERE key = 'paused' AND value = 'true'
)""",
(now, source, text),
)
return cursor.lastrowid if cursor.rowcount else None
def ingest(args):
# Preserve exact bytes, including Unicode, whitespace and trailing newlines.
raw = sys.stdin.buffer.read()
error = None
try:
with connect() as db:
save(db, raw.decode("utf-8"), args.source)
except (OSError, sqlite3.Error, UnicodeError) as exc:
error = exc
# Storage failure must never eat a dictation in a post-processing pipeline.
if args.passthrough:
sys.stdout.buffer.write(raw)
sys.stdout.buffer.flush()
if error:
print("Transcripts: could not save transcript (" + type(error).__name__ + ").", file=sys.stderr)
return 0 if args.passthrough else 1
return 0
def snapshot(db, args):
where = "trashed = ?"
params = (int(args.trash),)
if args.query:
where += " AND (instr(lower(text), lower(?)) > 0 OR instr(lower(source), lower(?)) > 0)"
params += (args.query, args.query)
offset = args.offset
# Keep the page, count, and paused state consistent during concurrent writes.
with db:
db.execute("BEGIN")
total = None
if not args.page_only:
total = db.execute("SELECT count(*) FROM transcripts WHERE " + where, params).fetchone()[0]
if offset >= total:
offset = max(0, (total - 1) // args.limit * args.limit)
sql = "SELECT * FROM transcripts WHERE " + where + " ORDER BY id DESC LIMIT ? OFFSET ?"
rows = db.execute(sql, (*params, args.limit + 1, offset)).fetchall()
if not rows and offset:
# A last-page entry may have been trashed since the previous request.
total = db.execute("SELECT count(*) FROM transcripts WHERE " + where, params).fetchone()[0]
offset = max(0, (total - 1) // args.limit * args.limit)
rows = db.execute(sql, (*params, args.limit + 1, offset)).fetchall()
has_more = len(rows) > args.limit
if not has_more:
total = offset + len(rows)
return {"entries": [dict(row) for row in rows[:args.limit]], "total": total,
"has_more": has_more, "paused": is_paused(db), "offset": offset}
def main():
os.umask(0o077)
parser = argparse.ArgumentParser(description=__doc__)
commands = parser.add_subparsers(dest="command", required=True)
add = commands.add_parser("ingest", help="Save UTF-8 text from stdin")
add.add_argument("--source", default="Unknown")
add.add_argument("--passthrough", action="store_true", help="Echo exact input, even if saving fails")
listing = commands.add_parser("list", help="Search history as JSON")
listing.add_argument("--query", default="")
listing.add_argument("--limit", type=int, default=50)
listing.add_argument("--offset", type=int, default=0)
listing.add_argument("--trash", action="store_true")
listing.add_argument("--page-only", action="store_true",
help="Skip full counts; total is null until the last page")
for name in ("get", "copy", "trash", "restore"):
item = commands.add_parser(name)
item.add_argument("id", type=int)
commands.add_parser("pause")
commands.add_parser("resume")
commands.add_parser("capture-clipboard", help="Explicitly save clipboard text once")
commands.add_parser("export", help="Write all non-trashed entries as JSON to stdout")
commands.add_parser("open", help="Open the Omarchy panel")
args = parser.parse_args()
if args.command == "ingest":
return ingest(args)
if args.command == "open":
return subprocess.call(["omarchy-shell", "shell", "summon", "io.github.davefano.transcripts"])
try:
with connect() as db:
if args.command == "list":
args.limit = max(1, min(args.limit, 100))
args.offset = max(0, args.offset)
print(json.dumps(snapshot(db, args), ensure_ascii=False))
elif args.command in ("pause", "resume"):
db.execute("INSERT OR REPLACE INTO settings VALUES ('paused', ?)",
("true" if args.command == "pause" else "false",))
elif args.command in ("trash", "restore"):
db.execute("UPDATE transcripts SET trashed = ? WHERE id = ?",
(int(args.command == "trash"), args.id))
elif args.command in ("copy", "get"):
row = db.execute("SELECT text FROM transcripts WHERE id = ?", (args.id,)).fetchone()
if row is None:
raise ValueError("Transcript no longer exists")
if args.command == "copy":
subprocess.run(["wl-copy", "--type", "text/plain;charset=utf-8"],
input=row[0].encode("utf-8"), check=True, timeout=3)
else:
sys.stdout.write(row[0])
elif args.command == "capture-clipboard":
if is_paused(db):
raise ValueError("History is paused; resume before saving")
result = subprocess.run(["wl-paste", "--no-newline", "--type", "text"],
capture_output=True, check=True, timeout=3)
if save(db, result.stdout.decode("utf-8"), "Clipboard (manual)") is None:
raise ValueError("Clipboard has no text")
elif args.command == "export":
rows = db.execute("SELECT * FROM transcripts WHERE trashed = 0 ORDER BY id").fetchall()
print(json.dumps([dict(row) for row in rows], ensure_ascii=False, indent=2))
return 0
except (OSError, sqlite3.Error, UnicodeError, subprocess.SubprocessError, ValueError) as exc:
# Never include transcript contents in diagnostics.
print("Transcripts: operation failed (" + type(exc).__name__ + ").", file=sys.stderr)
return 1
if __name__ == "__main__":
sys.exit(main())