|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Turn an opencode session export (JSON) into a browsable folder: |
| 3 | + <outdir>/transcript.md full ordered chat + model/token/context header |
| 4 | + <outdir>/index.html self-contained render (double-click -> browser) |
| 5 | + <outdir>/attachments/ images/files in order |
| 6 | + <outdir>/metadata.json raw session info |
| 7 | + <outdir>/.export-manifest.json tracks written attachments (incremental) |
| 8 | +Re-running against the same <outdir> regenerates transcript/html and writes only |
| 9 | +NEW attachments (no re-storing from scratch). |
| 10 | +Usage: oc_chat_save.py <session.json> <outdir> |
| 11 | +""" |
| 12 | +import json, sys, os, base64, datetime, html, re |
| 13 | + |
| 14 | +IMG_EXT = {"image/png": ".png", "image/jpeg": ".jpg", "image/gif": ".gif", "image/webp": ".webp"} |
| 15 | + |
| 16 | +def ts(ms): |
| 17 | + return datetime.datetime.fromtimestamp(ms / 1000).strftime("%Y-%m-%d %H:%M:%S") if ms else "" |
| 18 | + |
| 19 | +def data_url_bytes(url): |
| 20 | + if not isinstance(url, str) or not url.startswith("data:") or ";base64," not in url: |
| 21 | + return None, None |
| 22 | + head, b64 = url.split(";base64,", 1) |
| 23 | + return head[5:], base64.b64decode(b64) |
| 24 | + |
| 25 | +# ---- minimal, dependency-free markdown -> HTML for text parts ---- |
| 26 | +def _inline(s): |
| 27 | + s = html.escape(s) |
| 28 | + s = re.sub(r"`([^`]+)`", r"<code>\1</code>", s) |
| 29 | + s = re.sub(r"\*\*([^*]+)\*\*", r"<strong>\1</strong>", s) |
| 30 | + return s |
| 31 | + |
| 32 | +def md_text_to_html(text): |
| 33 | + out = [] |
| 34 | + for seg in re.split(r"(```[\s\S]*?```)", text): |
| 35 | + if seg.startswith("```"): |
| 36 | + m = re.match(r"```\w*\n?([\s\S]*?)```", seg) |
| 37 | + out.append("<pre><code>%s</code></pre>" % html.escape(m.group(1) if m else seg.strip("`"))) |
| 38 | + else: |
| 39 | + for block in seg.split("\n\n"): |
| 40 | + block = block.strip("\n") |
| 41 | + if not block: |
| 42 | + continue |
| 43 | + lines = [l for l in block.split("\n")] |
| 44 | + if all(l.lstrip().startswith(("- ", "* ")) for l in lines if l.strip()): |
| 45 | + out.append("<ul>%s</ul>" % "".join("<li>%s</li>" % _inline(l.lstrip()[2:]) for l in lines if l.strip())) |
| 46 | + else: |
| 47 | + out.append("<p>%s</p>" % "<br>".join(_inline(l) for l in lines)) |
| 48 | + return "\n".join(out) |
| 49 | + |
| 50 | +HTML_STYLE = """body{font:15px/1.6 system-ui,-apple-system,sans-serif;max-width:840px;margin:2rem auto;padding:0 1rem;color:#e8e8ea;background:#1b1b1d} |
| 51 | +h1,h2{border-bottom:1px solid #333;padding-bottom:.25em}h2{margin-top:2.2em} |
| 52 | +pre{background:#111214;padding:.8em 1em;border-radius:6px;overflow:auto} |
| 53 | +code{background:#111214;padding:.1em .35em;border-radius:4px;font-size:.92em}pre code{padding:0;background:none} |
| 54 | +img{max-width:100%;border:1px solid #333;border-radius:6px;margin:.4em 0} |
| 55 | +table{border-collapse:collapse;margin:.6em 0}td,th{border:1px solid #333;padding:.35em .8em;text-align:left} |
| 56 | +blockquote{color:#9aa;border-left:3px solid #444;margin:.4em 0;padding:.1em 1em} |
| 57 | +.user{color:#7db3ff}.assistant{color:#8fd694}details{margin:.5em 0}summary{cursor:pointer;color:#bbb} |
| 58 | +.att{color:#c9a}""" |
| 59 | + |
| 60 | +def main(json_path, outdir): |
| 61 | + d = json.load(open(json_path)) |
| 62 | + info = d["info"] |
| 63 | + att_dir = os.path.join(outdir, "attachments") |
| 64 | + os.makedirs(att_dir, exist_ok=True) |
| 65 | + |
| 66 | + man_path = os.path.join(outdir, ".export-manifest.json") |
| 67 | + manifest = json.load(open(man_path)) if os.path.exists(man_path) else {"attachments": {}} |
| 68 | + written = manifest["attachments"] |
| 69 | + counter = [len(written)] |
| 70 | + |
| 71 | + def save_attachment(part_id, mime, filename, raw): |
| 72 | + key = str(part_id) |
| 73 | + if key in written: |
| 74 | + return written[key] |
| 75 | + counter[0] += 1 |
| 76 | + name = os.path.basename(filename) if filename else "" |
| 77 | + if not name or "." not in name: |
| 78 | + name = (name or "attachment") + IMG_EXT.get(mime, "") |
| 79 | + fn = "%03d_%s" % (counter[0], name) |
| 80 | + open(os.path.join(att_dir, fn), "wb").write(raw) |
| 81 | + written[key] = fn |
| 82 | + return fn |
| 83 | + |
| 84 | + # collect (role, blocks) so md and html stay in sync |
| 85 | + m, tok, t = info.get("model", {}), info.get("tokens", {}), info.get("time", {}) |
| 86 | + cache = tok.get("cache", {}) or {} |
| 87 | + meta = [ |
| 88 | + ("Session", info.get("id")), |
| 89 | + ("Model", "%s/%s (variant: %s)" % (m.get("providerID"), m.get("id"), m.get("variant"))), |
| 90 | + ("Directory", info.get("directory")), |
| 91 | + ("Tokens", "input %s / output %s / reasoning %s / cache r%s w%s" % ( |
| 92 | + tok.get("input"), tok.get("output"), tok.get("reasoning"), cache.get("read"), cache.get("write"))), |
| 93 | + ("Cost", "$%s" % info.get("cost")), |
| 94 | + ("Created", ts(t.get("created"))), |
| 95 | + ("Updated", ts(t.get("updated"))), |
| 96 | + ] |
| 97 | + |
| 98 | + rendered = [] |
| 99 | + for msg in d["messages"]: |
| 100 | + role = msg["info"].get("role", "?") |
| 101 | + blocks = [] |
| 102 | + for p in msg.get("parts", []): |
| 103 | + pt = p.get("type") |
| 104 | + if pt == "text": |
| 105 | + blocks.append(("note" if p.get("synthetic") else "text", p.get("text", ""))) |
| 106 | + elif pt == "file": |
| 107 | + mime, raw = data_url_bytes(p.get("url", "")) |
| 108 | + if raw is not None: |
| 109 | + fn = save_attachment(p.get("id"), mime, p.get("filename"), raw) |
| 110 | + blocks.append(("image", (p.get("filename") or fn, fn))) |
| 111 | + elif pt == "tool": |
| 112 | + st = p.get("state", {}) or {} |
| 113 | + blocks.append(("tool", (p.get("tool"), st))) |
| 114 | + for k, att in enumerate(st.get("attachments", []) or []): |
| 115 | + mime, raw = data_url_bytes(att.get("url", "")) |
| 116 | + if raw is not None: |
| 117 | + fn = save_attachment(att.get("id") or "%s_att%d" % (p.get("id"), k), |
| 118 | + mime, att.get("filename"), raw) |
| 119 | + blocks.append(("image", (att.get("filename") or fn, fn))) |
| 120 | + if blocks: |
| 121 | + rendered.append((role, blocks)) |
| 122 | + |
| 123 | + # ---- transcript.md ---- |
| 124 | + L = ["# " + str(info.get("title", "opencode session")) + "\n", "| Field | Value |", "|---|---|"] |
| 125 | + L += ["| %s | %s |" % (k, v) for k, v in meta] |
| 126 | + L += ["", "---", ""] |
| 127 | + for role, blocks in rendered: |
| 128 | + L.append({"user": "## User", "assistant": "## Assistant"}.get(role, "## " + role) + "\n") |
| 129 | + for kind, val in blocks: |
| 130 | + if kind == "text": |
| 131 | + L.append(val + "\n") |
| 132 | + elif kind == "note": |
| 133 | + L.append("> _%s_\n" % val) |
| 134 | + elif kind == "image": |
| 135 | + name, fn = val |
| 136 | + L.append("**Attachment: %s**\n" % name) |
| 137 | + L.append("\n" % (name, fn)) |
| 138 | + elif kind == "tool": |
| 139 | + tool, st = val |
| 140 | + L.append("<details><summary>tool: <code>%s</code> (%s)</summary>\n" % (tool, st.get("status"))) |
| 141 | + if st.get("input") is not None: |
| 142 | + L.append("\nInput:\n```json\n%s\n```\n" % json.dumps(st["input"], indent=2)[:2000]) |
| 143 | + if isinstance(st.get("output"), str) and st["output"].strip(): |
| 144 | + L.append("\nOutput:\n```\n%s\n```\n" % st["output"][:2000]) |
| 145 | + L.append("</details>\n") |
| 146 | + L.append("\n---\n") |
| 147 | + open(os.path.join(outdir, "transcript.md"), "w").write("\n".join(L)) |
| 148 | + |
| 149 | + # ---- index.html ---- |
| 150 | + H = ["<!DOCTYPE html><html><head><meta charset='utf-8'><title>%s</title><style>%s</style></head><body>" |
| 151 | + % (html.escape(str(info.get("title", "chat"))), HTML_STYLE)] |
| 152 | + H.append("<h1>%s</h1>" % html.escape(str(info.get("title", "opencode session")))) |
| 153 | + H.append("<table>" + "".join("<tr><th>%s</th><td>%s</td></tr>" % (html.escape(k), html.escape(str(v))) for k, v in meta) + "</table>") |
| 154 | + for role, blocks in rendered: |
| 155 | + cls = role if role in ("user", "assistant") else "role" |
| 156 | + H.append("<h2 class='%s'>%s</h2>" % (cls, html.escape(role.capitalize()))) |
| 157 | + for kind, val in blocks: |
| 158 | + if kind == "text": |
| 159 | + H.append(md_text_to_html(val)) |
| 160 | + elif kind == "note": |
| 161 | + H.append("<blockquote>%s</blockquote>" % html.escape(val)) |
| 162 | + elif kind == "image": |
| 163 | + name, fn = val |
| 164 | + H.append("<div class='att'>Attachment: %s</div><img src='attachments/%s' alt='%s'>" |
| 165 | + % (html.escape(name), html.escape(fn), html.escape(name))) |
| 166 | + elif kind == "tool": |
| 167 | + tool, st = val |
| 168 | + H.append("<details><summary>tool: <code>%s</code> (%s)</summary>" % (html.escape(str(tool)), html.escape(str(st.get("status"))))) |
| 169 | + if st.get("input") is not None: |
| 170 | + H.append("<pre><code>%s</code></pre>" % html.escape(json.dumps(st["input"], indent=2)[:2000])) |
| 171 | + if isinstance(st.get("output"), str) and st["output"].strip(): |
| 172 | + H.append("<pre><code>%s</code></pre>" % html.escape(st["output"][:2000])) |
| 173 | + H.append("</details>") |
| 174 | + H.append("<hr>") |
| 175 | + H.append("</body></html>") |
| 176 | + open(os.path.join(outdir, "index.html"), "w").write("\n".join(H)) |
| 177 | + |
| 178 | + json.dump(info, open(os.path.join(outdir, "metadata.json"), "w"), indent=2) |
| 179 | + manifest["attachments"] = written |
| 180 | + json.dump(manifest, open(man_path, "w"), indent=2) |
| 181 | + print("wrote %s : transcript.md + index.html (%d attachment(s))" % (outdir, len(written))) |
| 182 | + |
| 183 | +if __name__ == "__main__": |
| 184 | + if len(sys.argv) != 3: |
| 185 | + print("usage: oc_chat_save.py <session.json> <outdir>"); sys.exit(1) |
| 186 | + main(sys.argv[1], sys.argv[2]) |
0 commit comments