Files
chatgpt-share-exporter/chatgpt_share_exporter.py
T

757 lines
24 KiB
Python

from __future__ import annotations
import argparse
import html
import json
import re
import sys
import unicodedata
import urllib.error
import urllib.request
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, Iterable, List, Mapping, Optional, Sequence, Set, Tuple
try:
from zoneinfo import ZoneInfo
except ImportError: # pragma: no cover - Python 3.8 fallback.
ZoneInfo = None # type: ignore
STREAM_ENQUEUE_RE = re.compile(
r"streamController\.enqueue\((\"(?:\\.|[^\"\\])*\")\)",
re.DOTALL,
)
NEXT_DATA_RE = re.compile(
r"<script[^>]+id=[\"']__NEXT_DATA__[\"'][^>]*>(.*?)</script>",
re.DOTALL | re.IGNORECASE,
)
SHARE_ID_RE = re.compile(r"/share/([^/?#]+)")
MARKDOWN_FENCE_RE = re.compile(r"```+")
class ExportError(Exception):
"""Base error for expected exporter failures."""
class FetchError(ExportError):
"""Raised when the share page cannot be downloaded."""
class ParseError(ExportError):
"""Raised when no conversation payload can be extracted."""
@dataclass
class ExportResult:
path: Optional[Path]
title: str
conversation_id: str
message_count: int
def fetch_html(url: str, timeout: int = 30) -> str:
request = urllib.request.Request(
url,
headers={
"User-Agent": (
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/126.0 Safari/537.36"
),
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.9",
},
)
try:
with urllib.request.urlopen(request, timeout=timeout) as response:
body = response.read()
encoding = response.headers.get_content_charset() or "utf-8"
return body.decode(encoding, errors="replace")
except urllib.error.HTTPError as exc:
raise FetchError(f"HTTP {exc.code} while downloading {url}") from exc
except urllib.error.URLError as exc:
raise FetchError(f"Could not download {url}: {exc.reason}") from exc
except TimeoutError as exc:
raise FetchError(f"Timed out downloading {url}") from exc
def extract_conversation(html_text: str) -> Dict[str, Any]:
for stream_payload in _extract_react_router_streams(html_text):
if not stream_payload.lstrip().startswith("["):
continue
try:
decoded = decode_react_router_payload(stream_payload)
except (json.JSONDecodeError, TypeError, IndexError):
continue
conversation = _find_conversation_dict(decoded)
if conversation:
return conversation
next_data = _extract_next_data(html_text)
if next_data is not None:
conversation = _find_conversation_dict(next_data)
if conversation:
return conversation
if "challenge-error-text" in html_text or "Enable JavaScript and cookies" in html_text:
raise ParseError(
"ChatGPT returned a browser challenge instead of the shared chat data."
)
raise ParseError(
"Could not find a shared ChatGPT conversation payload in the page. "
"The link may be private, expired, or ChatGPT may have changed its share format."
)
def decode_react_router_payload(serialized: str) -> Any:
table = json.loads(serialized)
if not isinstance(table, list) or not table:
raise ParseError("React Router payload was not a non-empty array.")
return _decode_ref(0, table, set())
def render_markdown(
conversation: Mapping[str, Any],
source_url: str,
include_hidden: bool = False,
all_nodes: bool = False,
timezone_name: str = "local",
) -> Tuple[str, int]:
tz = resolve_timezone(timezone_name)
title = str(conversation.get("title") or "ChatGPT Shared Chat")
conversation_id = str(
conversation.get("conversation_id")
or conversation.get("id")
or extract_share_id(source_url)
or ""
)
nodes = list(iter_conversation_nodes(conversation, all_nodes=all_nodes))
messages = [
(node, node.get("message"))
for node in nodes
if isinstance(node, Mapping)
and isinstance(node.get("message"), Mapping)
and _should_export_message(node.get("message"), include_hidden=include_hidden)
]
frontmatter = [
"---",
f"title: {_yaml_string(title)}",
f"source_url: {_yaml_string(source_url)}",
f"conversation_id: {_yaml_string(conversation_id)}",
f"created_at: {_yaml_string(format_timestamp(conversation.get('create_time'), tz))}",
f"updated_at: {_yaml_string(format_timestamp(conversation.get('update_time'), tz))}",
f"default_model_slug: {_yaml_string(conversation.get('default_model_slug'))}",
f"message_count: {len(messages)}",
f"exported_at: {_yaml_string(datetime.now(tz).isoformat(timespec='seconds'))}",
"exporter: chatgpt-share-exporter",
"---",
"",
]
lines: List[str] = []
lines.extend(frontmatter)
lines.append(f"# {title}")
lines.append("")
lines.extend(
_render_table(
[
("Source", source_url),
("Conversation ID", conversation_id),
("Created", format_timestamp(conversation.get("create_time"), tz)),
("Updated", format_timestamp(conversation.get("update_time"), tz)),
("Default model", conversation.get("default_model_slug")),
("Visible messages exported", len(messages)),
]
)
)
for index, (_node, message) in enumerate(messages, start=1):
assert isinstance(message, Mapping)
role = _role_for_message(message)
created = format_timestamp(message.get("create_time"), tz)
heading_time = f" - {created}" if created else ""
lines.append("")
lines.append("---")
lines.append("")
lines.append(f"## {index}. {role}{heading_time}")
lines.append("")
lines.extend(_render_message_metadata(message, tz))
body = render_message_body(message)
if body:
lines.append("")
lines.append(body)
elif include_hidden:
lines.append("")
lines.append("_No visible content._")
return "\n".join(lines).rstrip() + "\n", len(messages)
def iter_conversation_nodes(
conversation: Mapping[str, Any],
all_nodes: bool = False,
) -> Iterable[Mapping[str, Any]]:
mapping = conversation.get("mapping")
if all_nodes and isinstance(mapping, Mapping):
nodes = [node for node in mapping.values() if isinstance(node, Mapping)]
return sorted(nodes, key=_node_sort_key)
linear = conversation.get("linear_conversation")
if isinstance(linear, Sequence) and not isinstance(linear, (str, bytes)):
return [node for node in linear if isinstance(node, Mapping)]
if isinstance(mapping, Mapping):
path = _path_from_mapping(mapping, conversation.get("current_node"))
if path:
return path
return [node for node in mapping.values() if isinstance(node, Mapping)]
return []
def render_message_body(message: Mapping[str, Any]) -> str:
content = message.get("content")
if not isinstance(content, Mapping):
return ""
parts = content.get("parts")
if not isinstance(parts, Sequence) or isinstance(parts, (str, bytes)):
fallback = content.get("text") or content.get("result")
return str(fallback).rstrip() if fallback else ""
text_sections: List[str] = []
image_parts: List[Mapping[str, Any]] = []
for part in parts:
if isinstance(part, str):
if part.strip():
text_sections.append(part.rstrip())
elif isinstance(part, Mapping):
if part.get("content_type") == "image_asset_pointer":
image_parts.append(part)
else:
text_sections.append(_json_code_block(part))
elif part is not None:
text_sections.append(str(part))
sections: List[str] = []
attachment_section = _render_attachment_section(message, image_parts)
if attachment_section:
sections.append(attachment_section)
sections.extend(text_sections)
return "\n\n".join(section for section in sections if section.strip()).rstrip()
def export_share(
url: str,
output_dir: Path,
include_hidden: bool = False,
all_nodes: bool = False,
timezone_name: str = "local",
timeout: int = 30,
overwrite: bool = False,
html_file: Optional[Path] = None,
stdout: bool = False,
) -> ExportResult:
html_text = html_file.read_text(encoding="utf-8") if html_file else fetch_html(url, timeout)
conversation = extract_conversation(html_text)
markdown, message_count = render_markdown(
conversation,
source_url=url,
include_hidden=include_hidden,
all_nodes=all_nodes,
timezone_name=timezone_name,
)
title = str(conversation.get("title") or "ChatGPT Shared Chat")
conversation_id = str(
conversation.get("conversation_id")
or conversation.get("id")
or extract_share_id(url)
or ""
)
if stdout:
sys.stdout.write(markdown)
return ExportResult(None, title, conversation_id, message_count)
output_dir.mkdir(parents=True, exist_ok=True)
target = output_dir / _export_filename(title, conversation_id)
if not overwrite:
target = _unique_path(target)
target.write_text(markdown, encoding="utf-8")
return ExportResult(target, title, conversation_id, message_count)
def extract_share_id(url: str) -> Optional[str]:
match = SHARE_ID_RE.search(url)
return match.group(1) if match else None
def resolve_timezone(timezone_name: str):
if timezone_name == "local":
return datetime.now().astimezone().tzinfo or timezone.utc
if timezone_name.upper() == "UTC":
return timezone.utc
if ZoneInfo is None:
raise ExportError("Named time zones require Python 3.9 or newer.")
try:
return ZoneInfo(timezone_name)
except Exception as exc:
raise ExportError(f"Unknown timezone: {timezone_name}") from exc
def format_timestamp(value: Any, tz) -> str:
if value in (None, ""):
return ""
try:
numeric = float(value)
except (TypeError, ValueError):
return str(value)
return datetime.fromtimestamp(numeric, timezone.utc).astimezone(tz).isoformat(
timespec="seconds"
)
def main(argv: Optional[Sequence[str]] = None) -> int:
argv = list(argv) if argv is not None else sys.argv[1:]
if argv and argv[0] == "pdf":
from chatgpt_pdf_converter import main as pdf_main
return pdf_main(argv[1:])
parser = argparse.ArgumentParser(
description="Export a public ChatGPT shared conversation to Markdown."
)
parser.add_argument("url", help="Public ChatGPT share URL.")
parser.add_argument(
"-o",
"--output-dir",
default="exports",
type=Path,
help="Directory for Markdown exports. Default: exports",
)
parser.add_argument(
"--timezone",
default="local",
help="Timezone for message times, for example UTC or Asia/Tehran. Default: local",
)
parser.add_argument(
"--include-hidden",
action="store_true",
help="Include hidden/system/internal messages in the Markdown.",
)
parser.add_argument(
"--all-nodes",
action="store_true",
help="Export every node from the conversation mapping, including non-selected branches.",
)
parser.add_argument(
"--overwrite",
action="store_true",
help="Overwrite the default output file instead of creating a numbered copy.",
)
parser.add_argument(
"--stdout",
action="store_true",
help="Print Markdown to stdout instead of writing a file.",
)
parser.add_argument(
"--html-file",
type=Path,
help="Read an already downloaded ChatGPT share HTML file instead of fetching the URL.",
)
parser.add_argument(
"--timeout",
type=int,
default=30,
help="Download timeout in seconds. Default: 30",
)
args = parser.parse_args(argv)
try:
result = export_share(
args.url,
output_dir=args.output_dir,
include_hidden=args.include_hidden,
all_nodes=args.all_nodes,
timezone_name=args.timezone,
timeout=args.timeout,
overwrite=args.overwrite,
html_file=args.html_file,
stdout=args.stdout,
)
except ExportError as exc:
print(f"error: {exc}", file=sys.stderr)
return 1
if not args.stdout:
assert result.path is not None
print(
f"Exported {result.message_count} messages from "
f"{result.title!r} to {result.path}"
)
return 0
def _extract_react_router_streams(html_text: str) -> Iterable[str]:
for match in STREAM_ENQUEUE_RE.finditer(html_text):
try:
yield json.loads(match.group(1))
except json.JSONDecodeError:
continue
def _extract_next_data(html_text: str) -> Optional[Any]:
match = NEXT_DATA_RE.search(html_text)
if not match:
return None
raw = html.unescape(match.group(1))
try:
return json.loads(raw)
except json.JSONDecodeError:
return None
def _decode_ref(ref: Any, table: Sequence[Any], seen: Set[int]) -> Any:
if not isinstance(ref, int):
return ref
if ref < 0:
return None
if ref >= len(table):
return ref
if ref in seen:
return f"<cycle:{ref}>"
return _decode_value(table[ref], table, seen | {ref})
def _decode_value(value: Any, table: Sequence[Any], seen: Set[int]) -> Any:
if isinstance(value, Mapping):
decoded: Dict[Any, Any] = {}
for key, item in value.items():
decoded_key: Any = key
if isinstance(key, str) and key.startswith("_") and key[1:].isdigit():
decoded_key = _decode_ref(int(key[1:]), table, seen)
if not isinstance(decoded_key, (str, int, float, bool, type(None))):
decoded_key = str(decoded_key)
decoded[decoded_key] = _decode_ref(item, table, seen)
return decoded
if isinstance(value, list):
return [_decode_ref(item, table, seen) for item in value]
return value
def _find_conversation_dict(value: Any, visited: Optional[Set[int]] = None) -> Optional[Dict[str, Any]]:
if visited is None:
visited = set()
object_id = id(value)
if object_id in visited:
return None
visited.add(object_id)
if isinstance(value, dict):
if _looks_like_conversation(value):
return value
for item in value.values():
found = _find_conversation_dict(item, visited)
if found:
return found
elif isinstance(value, list):
for item in value:
found = _find_conversation_dict(item, visited)
if found:
return found
return None
def _looks_like_conversation(value: Mapping[str, Any]) -> bool:
linear = value.get("linear_conversation")
return (
isinstance(value.get("mapping"), Mapping)
and (
isinstance(linear, Sequence)
and not isinstance(linear, (str, bytes))
or value.get("current_node") is not None
or value.get("conversation_id") is not None
)
)
def _path_from_mapping(
mapping: Mapping[str, Any],
current_node: Any,
) -> List[Mapping[str, Any]]:
if not current_node:
return []
path: List[Mapping[str, Any]] = []
node_id = str(current_node)
visited: Set[str] = set()
while node_id and node_id not in visited:
visited.add(node_id)
node = mapping.get(node_id)
if not isinstance(node, Mapping):
break
path.append(node)
parent = node.get("parent")
node_id = str(parent) if parent else ""
path.reverse()
return path
def _node_sort_key(node: Mapping[str, Any]) -> Tuple[int, float, str]:
message = node.get("message")
create_time = None
if isinstance(message, Mapping):
create_time = message.get("create_time")
try:
timestamp = float(create_time)
except (TypeError, ValueError):
timestamp = -1.0
return (0 if timestamp >= 0 else 1, timestamp, str(node.get("id") or ""))
def _should_export_message(message: Any, include_hidden: bool) -> bool:
if not isinstance(message, Mapping):
return False
if include_hidden:
return True
author = message.get("author")
role = author.get("role") if isinstance(author, Mapping) else None
if role not in {"user", "assistant"}:
return False
metadata = message.get("metadata")
if isinstance(metadata, Mapping) and metadata.get("is_visually_hidden_from_conversation"):
return False
content = message.get("content")
content_type = content.get("content_type") if isinstance(content, Mapping) else None
if content_type in {"model_editable_context"}:
return False
return bool(render_message_body(message).strip())
def _role_for_message(message: Mapping[str, Any]) -> str:
author = message.get("author")
role = author.get("role") if isinstance(author, Mapping) else None
if not role:
return "Unknown"
return str(role).replace("_", " ").title()
def _render_message_metadata(message: Mapping[str, Any], tz) -> List[str]:
metadata = message.get("metadata")
metadata = metadata if isinstance(metadata, Mapping) else {}
content = message.get("content")
content = content if isinstance(content, Mapping) else {}
model = (
metadata.get("resolved_model_slug")
or metadata.get("model_slug")
or metadata.get("default_model_slug")
)
finish_details = metadata.get("finish_details")
finish_type = None
if isinstance(finish_details, Mapping):
finish_type = finish_details.get("type")
rows = [
("Author", _role_for_message(message)),
("Message ID", message.get("id")),
("Created", format_timestamp(message.get("create_time"), tz)),
("Updated", format_timestamp(message.get("update_time"), tz)),
("Status", message.get("status")),
("Channel", message.get("channel")),
("Recipient", message.get("recipient")),
("Content type", content.get("content_type")),
("Model", model),
("Finish", finish_type),
("End turn", message.get("end_turn")),
("Parent ID", metadata.get("parent_id")),
("Request ID", metadata.get("request_id")),
("Turn exchange ID", metadata.get("turn_exchange_id")),
("Hidden in UI", metadata.get("is_visually_hidden_from_conversation")),
]
return _render_table(rows)
def _render_attachment_section(
message: Mapping[str, Any],
image_parts: Sequence[Mapping[str, Any]],
) -> str:
metadata = message.get("metadata")
metadata = metadata if isinstance(metadata, Mapping) else {}
raw_attachments = metadata.get("attachments")
attachments = (
raw_attachments
if isinstance(raw_attachments, Sequence) and not isinstance(raw_attachments, (str, bytes))
else []
)
attachments_by_id: Dict[str, Mapping[str, Any]] = {}
for item in attachments:
if isinstance(item, Mapping) and item.get("id"):
attachments_by_id[str(item.get("id"))] = item
rows: List[Tuple[str, Any, Any, Any, Any]] = []
seen_ids: Set[str] = set()
for part in image_parts:
pointer = str(part.get("asset_pointer") or "")
file_id = _file_id_from_asset_pointer(pointer)
attachment = attachments_by_id.get(file_id or "", {})
if file_id:
seen_ids.add(file_id)
rows.append(
(
attachment.get("name") or file_id or "image",
attachment.get("mime_type") or "image",
_human_size(part.get("size_bytes") or attachment.get("size")),
_dimensions(part),
pointer,
)
)
for attachment in attachments:
if not isinstance(attachment, Mapping):
continue
file_id = str(attachment.get("id") or "")
if file_id and file_id in seen_ids:
continue
rows.append(
(
attachment.get("name") or file_id or "attachment",
attachment.get("mime_type"),
_human_size(attachment.get("size")),
"",
file_id,
)
)
if not rows:
return ""
rendered = ["**Attachments**", "", "| Name | Type | Size | Dimensions | Source |", "|---|---|---:|---|---|"]
for row in rows:
rendered.append("| " + " | ".join(_table_cell(value) for value in row) + " |")
return "\n".join(rendered)
def _render_table(rows: Sequence[Tuple[str, Any]]) -> List[str]:
clean_rows = [(label, value) for label, value in rows if not _blank(value)]
if not clean_rows:
return []
rendered = ["| Field | Value |", "|---|---|"]
for label, value in clean_rows:
rendered.append(f"| {_table_cell(label)} | {_table_cell(value)} |")
return rendered
def _blank(value: Any) -> bool:
return value is None or value == "" or value == [] or value == {}
def _table_cell(value: Any) -> str:
if isinstance(value, bool):
text = "yes" if value else "no"
elif isinstance(value, (dict, list)):
text = json.dumps(value, ensure_ascii=False, sort_keys=True)
else:
text = str(value)
return text.replace("\\", "\\\\").replace("|", "\\|").replace("\n", "<br>")
def _json_code_block(value: Mapping[str, Any]) -> str:
dumped = json.dumps(value, ensure_ascii=False, indent=2, sort_keys=True)
fence = _safe_fence(dumped)
return f"{fence}json\n{dumped}\n{fence}"
def _safe_fence(text: str) -> str:
longest = 2
for match in MARKDOWN_FENCE_RE.finditer(text):
longest = max(longest, len(match.group(0)))
return "`" * (longest + 1)
def _file_id_from_asset_pointer(pointer: str) -> Optional[str]:
match = re.search(r"file_[A-Za-z0-9]+", pointer)
return match.group(0) if match else None
def _dimensions(part: Mapping[str, Any]) -> str:
width = part.get("width")
height = part.get("height")
if width and height:
return f"{width}x{height}"
return ""
def _human_size(value: Any) -> str:
try:
size = float(value)
except (TypeError, ValueError):
return ""
units = ["B", "KB", "MB", "GB"]
unit = 0
while size >= 1024 and unit < len(units) - 1:
size /= 1024
unit += 1
if unit == 0:
return f"{int(size)} {units[unit]}"
return f"{size:.1f} {units[unit]}"
def _yaml_string(value: Any) -> str:
if value is None:
value = ""
return json.dumps(str(value), ensure_ascii=False)
def _export_filename(title: str, conversation_id: str) -> str:
slug = _slugify(title) or "chatgpt-share"
suffix = conversation_id[:8] if conversation_id else datetime.now().strftime("%Y%m%d")
return f"{slug}-{suffix}.md"
def _slugify(value: str) -> str:
normalized = unicodedata.normalize("NFKD", value)
ascii_text = normalized.encode("ascii", "ignore").decode("ascii")
slug = re.sub(r"[^a-zA-Z0-9]+", "-", ascii_text).strip("-").lower()
return re.sub(r"-{2,}", "-", slug)
def _unique_path(path: Path) -> Path:
if not path.exists():
return path
stem = path.stem
suffix = path.suffix
parent = path.parent
counter = 2
while True:
candidate = parent / f"{stem}-{counter}{suffix}"
if not candidate.exists():
return candidate
counter += 1
if __name__ == "__main__":
raise SystemExit(main())