Initial ChatGPT share exporter

This commit is contained in:
Meghdad committed 2026-06-30 15:25:25 +03:30
commit 94f179ad6d
10 files changed
+1130

No files matched your search

+12
View File
@@ -0,0 +1,12 @@
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 4
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false
+32
View File
@@ -0,0 +1,32 @@
name: Tests
on:
push:
branches: ["main", "master"]
pull_request:
jobs:
test:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"]
steps:
- name: Check out repository
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name: Install package
run: python -m pip install -e .
- name: Compile Python files
run: python -m py_compile main.py chatgpt_share_exporter.py tests/test_exporter.py
- name: Run tests
run: python -m unittest discover -s tests
+30
View File
@@ -0,0 +1,30 @@
# Python
__pycache__/
*.py[cod]
*$py.class
.python-version
.pytest_cache/
.mypy_cache/
.ruff_cache/
.coverage
htmlcov/
# Virtual environments
.venv/
venv/
env/
# Packaging
build/
dist/
*.egg-info/
# Local IDE/editor files
.idea/
.vscode/
.DS_Store
# Generated exports and local scratch files
exports/
*.html
*.log
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Meghdad
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+76
View File
@@ -0,0 +1,76 @@
# ChatGPT Shared Chat Exporter
Export a public ChatGPT shared conversation link to a clean Markdown file.
The exporter reads the structured conversation data embedded in ChatGPT share pages, then writes the visible user/assistant conversation path as Markdown with clean metadata tables.
## Features
- exports public `https://chatgpt.com/share/...` links
- preserves Markdown-formatted message content, including headings, lists, code blocks, and tables
- includes conversation metadata such as title, source URL, conversation ID, timestamps, and model slug
- includes per-message metadata such as author, message ID, created/updated time, status, channel, recipient, model, request ID, and turn ID
- records uploaded image/file metadata such as name, MIME type, size, dimensions, and source pointer
- can include hidden/system/internal nodes when requested
- uses only the Python standard library
## Requirements
- Python 3.9 or newer
- network access to `chatgpt.com` for live exports
## Quick Start
Run directly from the repository:
```bash
python3 main.py "https://chatgpt.com/share/YOUR_SHARE_ID"
```
By default, exports are written to `exports/`, which is ignored by Git so private chat content is not committed accidentally.
## Install Locally
```bash
python3 -m pip install -e .
chatgpt-share-exporter "https://chatgpt.com/share/YOUR_SHARE_ID"
```
## Options
```bash
chatgpt-share-exporter URL --timezone UTC
chatgpt-share-exporter URL --include-hidden
chatgpt-share-exporter URL --all-nodes
chatgpt-share-exporter URL --stdout
chatgpt-share-exporter URL -o my_exports --overwrite
```
- `--timezone`: format message times in `local`, `UTC`, or an IANA timezone like `Asia/Tehran`
- `--include-hidden`: include system/internal messages that ChatGPT normally hides
- `--all-nodes`: export every mapping node, including non-selected branches
- `--stdout`: print Markdown instead of writing a file
- `--overwrite`: replace the default output file instead of creating a numbered copy
- `--html-file`: parse an already downloaded share page instead of fetching the URL
- `--timeout`: set the download timeout in seconds
## Development
Run tests:
```bash
python3 -m unittest discover -s tests
```
Run a syntax check:
```bash
python3 -m py_compile main.py chatgpt_share_exporter.py tests/test_exporter.py
```
## Notes
- Only public ChatGPT shared links are supported.
- If ChatGPT returns a browser challenge instead of the shared chat HTML, the exporter cannot parse that response.
- ChatGPT may change its share-page format; the parser is tested against the current embedded React Router payload and a fallback `__NEXT_DATA__` payload.
- This project is not affiliated with OpenAI.
+750
View File
@@ -0,0 +1,750 @@
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:
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())
+5
View File
@@ -0,0 +1,5 @@
from chatgpt_share_exporter import main
if __name__ == "__main__":
raise SystemExit(main())
+31
View File
@@ -0,0 +1,31 @@
[metadata]
name = chatgpt-share-exporter
version = 0.1.0
description = Export public ChatGPT shared conversations to clean Markdown files.
long_description = file: README.md
long_description_content_type = text/markdown
license = MIT
license_files = LICENSE
author = Meghdad
keywords = chatgpt, markdown, export, conversation
classifiers =
Development Status :: 3 - Alpha
Environment :: Console
Intended Audience :: End Users/Desktop
License :: OSI Approved :: MIT License
Programming Language :: Python :: 3
Programming Language :: Python :: 3.9
Programming Language :: Python :: 3.10
Programming Language :: Python :: 3.11
Programming Language :: Python :: 3.12
Programming Language :: Python :: 3.13
Topic :: Text Processing :: Markup :: Markdown
[options]
py_modules = chatgpt_share_exporter
python_requires = >=3.9
install_requires =
[options.entry_points]
console_scripts =
chatgpt-share-exporter = chatgpt_share_exporter:main
+4
View File
@@ -0,0 +1,4 @@
from setuptools import setup
setup()
+169
View File
@@ -0,0 +1,169 @@
import json
import unittest
from chatgpt_share_exporter import extract_conversation, render_markdown
def compact_payload(root):
table = [None]
def ref(value):
table.append(encoded(value))
return len(table) - 1
def encoded(value):
if isinstance(value, dict):
return {f"_{ref(key)}": ref(item) for key, item in value.items()}
if isinstance(value, list):
return [ref(item) for item in value]
return value
table[0] = encoded(root)
return table
def page_with_payload(root):
payload = json.dumps(compact_payload(root))
stream_argument = json.dumps(payload + "\n")
return (
"<html><body><script>"
f"window.__reactRouterContext.streamController.enqueue({stream_argument});"
"</script></body></html>"
)
class ChatGPTShareExporterTests(unittest.TestCase):
def test_extracts_conversation_from_react_router_stream(self):
root = {
"loaderData": {
"routes/share.$shareId.($action)": {
"serverResponse": {
"type": "data",
"data": sample_conversation(),
}
}
}
}
conversation = extract_conversation(page_with_payload(root))
self.assertEqual(conversation["title"], "Demo Chat")
self.assertEqual(conversation["conversation_id"], "share-123")
self.assertEqual(len(conversation["linear_conversation"]), 3)
def test_renders_visible_messages_with_clean_metadata(self):
markdown, count = render_markdown(
sample_conversation(),
"https://chatgpt.com/share/share-123",
timezone_name="UTC",
)
self.assertEqual(count, 2)
self.assertIn("# Demo Chat", markdown)
self.assertIn("## 1. User - 1970-01-01T00:16:40+00:00", markdown)
self.assertIn("| Message ID | user-1 |", markdown)
self.assertIn("**Attachments**", markdown)
self.assertIn("scan.jpg", markdown)
self.assertIn("What does this mean?", markdown)
self.assertIn("## 2. Assistant - 1970-01-01T00:16:45+00:00", markdown)
self.assertIn("Here is the answer.", markdown)
self.assertNotIn("internal note", markdown)
def test_can_include_hidden_messages(self):
markdown, count = render_markdown(
sample_conversation(),
"https://chatgpt.com/share/share-123",
include_hidden=True,
timezone_name="UTC",
)
self.assertEqual(count, 3)
self.assertIn("internal note", markdown)
self.assertIn("## 1. System", markdown)
def sample_conversation():
return {
"title": "Demo Chat",
"conversation_id": "share-123",
"create_time": 1000,
"update_time": 1010,
"default_model_slug": "gpt-test",
"current_node": "assistant-1",
"mapping": {},
"linear_conversation": [
{
"id": "system-1",
"message": {
"id": "system-1",
"author": {"role": "system", "metadata": {}},
"content": {"content_type": "text", "parts": ["internal note"]},
"status": "finished_successfully",
"metadata": {"is_visually_hidden_from_conversation": True},
},
"children": ["user-1"],
},
{
"id": "user-1",
"message": {
"id": "user-1",
"author": {"role": "user", "metadata": {}},
"create_time": 1000,
"content": {
"content_type": "multimodal_text",
"parts": [
{
"content_type": "image_asset_pointer",
"asset_pointer": "sediment://file_demo123?shared_conversation_id=share-123",
"size_bytes": 2048,
"width": 640,
"height": 480,
},
"What does this mean?",
],
},
"status": "finished_successfully",
"metadata": {
"attachments": [
{
"id": "file_demo123",
"name": "scan.jpg",
"size": 2048,
"mime_type": "image/jpeg",
}
],
},
"recipient": "all",
},
"parent": "system-1",
"children": ["assistant-1"],
},
{
"id": "assistant-1",
"message": {
"id": "assistant-1",
"author": {"role": "assistant", "metadata": {}},
"create_time": 1005,
"update_time": 1008,
"content": {
"content_type": "text",
"parts": ["Here is the answer."],
},
"status": "finished_successfully",
"end_turn": True,
"metadata": {
"resolved_model_slug": "gpt-test",
"request_id": "request-1",
},
"recipient": "all",
"channel": "final",
},
"parent": "user-1",
"children": [],
},
],
}
if __name__ == "__main__":
unittest.main()