#!/usr/bin/env python3 """Novaferry:把 Codex 会话记录里生成的图片取出来存成文件(macOS / Linux)。 为什么需要:通过第三方 API(包括 Novaferry)使用 Codex 时,模型生成的图片会完整传回 Codex、存在会话记录里, 但 Codex 不会把它保存成图片文件,也不显示。这个脚本只读取本机的会话记录,不联网、不改任何文件, 把图片另存到 ~/Codex-images/。 用法:curl -fsSL https://novaferry.com/tools/codex-images.py | python3 - 默认只找最近 7 天的会话;要找更早的:curl -fsSL https://novaferry.com/tools/codex-images.py | python3 - 30 """ import base64 import os import re import sys import time from pathlib import Path TYPE_RE = re.compile(r'"type"\s*:\s*"image_generation_call"') RESULT_RE = re.compile(r'"result"\s*:\s*"([A-Za-z0-9+/=]{100,})"') ID_RE = re.compile(r'"id"\s*:\s*"([^"]+)"') TS_RE = re.compile(r'"timestamp"\s*:\s*"([0-9T:\-]+)') def main(): days = int(sys.argv[1]) if len(sys.argv) > 1 else 7 codex_home = Path(os.environ.get("CODEX_HOME") or Path.home() / ".codex") out_dir = Path.home() / "Codex-images" since = time.time() - days * 86400 dirs = [codex_home / d for d in ("sessions", "archived_sessions") if (codex_home / d).is_dir()] if not dirs: print(f"没找到 Codex 会话记录({codex_home}/sessions)。") return saved = skipped = 0 for d in dirs: for f in d.rglob("*.jsonl"): if f.stat().st_mtime < since: continue with open(f, encoding="utf-8", errors="replace") as fh: for line in fh: if not TYPE_RE.search(line): continue m = RESULT_RE.search(line) if not m: continue b64 = m.group(1) item_id = (ID_RE.search(line) or [None, ""])[1] ts = (TS_RE.search(line) or [None, ""])[1] ext = "jpg" if b64.startswith("/9j/") else "webp" if b64.startswith("UklGR") else "png" stamp = re.sub(r"[T:]", "-", ts)[:16] out_dir.mkdir(exist_ok=True) path = out_dir / f"{stamp}-{item_id[-8:]}.{ext}" if path.exists(): skipped += 1 continue path.write_bytes(base64.b64decode(b64)) saved += 1 print(f"已保存 {path}") if saved == 0 and skipped == 0: print(f"最近 {days} 天的 Codex 会话里没有找到生成的图片。") else: print(f"完成:新保存 {saved} 张,之前已保存过 {skipped} 张。图片在 {out_dir}") if __name__ == "__main__": main()