claude2md 0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
claude2md-0.1/LICENSE ADDED
@@ -0,0 +1,121 @@
1
+ Creative Commons Legal Code
2
+
3
+ CC0 1.0 Universal
4
+
5
+ CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
6
+ LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
7
+ ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
8
+ INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
9
+ REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
10
+ PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
11
+ THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
12
+ HEREUNDER.
13
+
14
+ Statement of Purpose
15
+
16
+ The laws of most jurisdictions throughout the world automatically confer
17
+ exclusive Copyright and Related Rights (defined below) upon the creator
18
+ and subsequent owner(s) (each and all, an "owner") of an original work of
19
+ authorship and/or a database (each, a "Work").
20
+
21
+ Certain owners wish to permanently relinquish those rights to a Work for
22
+ the purpose of contributing to a commons of creative, cultural and
23
+ scientific works ("Commons") that the public can reliably and without fear
24
+ of later claims of infringement build upon, modify, incorporate in other
25
+ works, reuse and redistribute as freely as possible in any form whatsoever
26
+ and for any purposes, including without limitation commercial purposes.
27
+ These owners may contribute to the Commons to promote the ideal of a free
28
+ culture and the further production of creative, cultural and scientific
29
+ works, or to gain reputation or greater distribution for their Work in
30
+ part through the use and efforts of others.
31
+
32
+ For these and/or other purposes and motivations, and without any
33
+ expectation of additional consideration or compensation, the person
34
+ associating CC0 with a Work (the "Affirmer"), to the extent that he or she
35
+ is an owner of Copyright and Related Rights in the Work, voluntarily
36
+ elects to apply CC0 to the Work and publicly distribute the Work under its
37
+ terms, with knowledge of his or her Copyright and Related Rights in the
38
+ Work and the meaning and intended legal effect of CC0 on those rights.
39
+
40
+ 1. Copyright and Related Rights. A Work made available under CC0 may be
41
+ protected by copyright and related or neighboring rights ("Copyright and
42
+ Related Rights"). Copyright and Related Rights include, but are not
43
+ limited to, the following:
44
+
45
+ i. the right to reproduce, adapt, distribute, perform, display,
46
+ communicate, and translate a Work;
47
+ ii. moral rights retained by the original author(s) and/or performer(s);
48
+ iii. publicity and privacy rights pertaining to a person's image or
49
+ likeness depicted in a Work;
50
+ iv. rights protecting against unfair competition in regards to a Work,
51
+ subject to the limitations in paragraph 4(a), below;
52
+ v. rights protecting the extraction, dissemination, use and reuse of data
53
+ in a Work;
54
+ vi. database rights (such as those arising under Directive 96/9/EC of the
55
+ European Parliament and of the Council of 11 March 1996 on the legal
56
+ protection of databases, and under any national implementation
57
+ thereof, including any amended or successor version of such
58
+ directive); and
59
+ vii. other similar, equivalent or corresponding rights throughout the
60
+ world based on applicable law or treaty, and any national
61
+ implementations thereof.
62
+
63
+ 2. Waiver. To the greatest extent permitted by, but not in contravention
64
+ of, applicable law, Affirmer hereby overtly, fully, permanently,
65
+ irrevocably and unconditionally waives, abandons, and surrenders all of
66
+ Affirmer's Copyright and Related Rights and associated claims and causes
67
+ of action, whether now known or unknown (including existing as well as
68
+ future claims and causes of action), in the Work (i) in all territories
69
+ worldwide, (ii) for the maximum duration provided by applicable law or
70
+ treaty (including future time extensions), (iii) in any current or future
71
+ medium and for any number of copies, and (iv) for any purpose whatsoever,
72
+ including without limitation commercial, advertising or promotional
73
+ purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
74
+ member of the public at large and to the detriment of Affirmer's heirs and
75
+ successors, fully intending that such Waiver shall not be subject to
76
+ revocation, rescission, cancellation, termination, or any other legal or
77
+ equitable action to disrupt the quiet enjoyment of the Work by the public
78
+ as contemplated by Affirmer's express Statement of Purpose.
79
+
80
+ 3. Public License Fallback. Should any part of the Waiver for any reason
81
+ be judged legally invalid or ineffective under applicable law, then the
82
+ Waiver shall be preserved to the maximum extent permitted taking into
83
+ account Affirmer's express Statement of Purpose. In addition, to the
84
+ extent the Waiver is so judged Affirmer hereby grants to each affected
85
+ person a royalty-free, non transferable, non sublicensable, non exclusive,
86
+ irrevocable and unconditional license to exercise Affirmer's Copyright and
87
+ Related Rights in the Work (i) in all territories worldwide, (ii) for the
88
+ maximum duration provided by applicable law or treaty (including future
89
+ time extensions), (iii) in any current or future medium and for any number
90
+ of copies, and (iv) for any purpose whatsoever, including without
91
+ limitation commercial, advertising or promotional purposes (the
92
+ "License"). The License shall be deemed effective as of the date CC0 was
93
+ applied by Affirmer to the Work. Should any part of the License for any
94
+ reason be judged legally invalid or ineffective under applicable law, such
95
+ partial invalidity or ineffectiveness shall not invalidate the remainder
96
+ of the License, and in such case Affirmer hereby affirms that he or she
97
+ will not (i) exercise any of his or her remaining Copyright and Related
98
+ Rights in the Work or (ii) assert any associated claims and causes of
99
+ action with respect to the Work, in either case contrary to Affirmer's
100
+ express Statement of Purpose.
101
+
102
+ 4. Limitations and Disclaimers.
103
+
104
+ a. No trademark or patent rights held by Affirmer are waived, abandoned,
105
+ surrendered, licensed or otherwise affected by this document.
106
+ b. Affirmer offers the Work as-is and makes no representations or
107
+ warranties of any kind concerning the Work, express, implied,
108
+ statutory or otherwise, including without limitation warranties of
109
+ title, merchantability, fitness for a particular purpose, non
110
+ infringement, or the absence of latent or other defects, accuracy, or
111
+ the present or absence of errors, whether or not discoverable, all to
112
+ the greatest extent permissible under applicable law.
113
+ c. Affirmer disclaims responsibility for clearing rights of other persons
114
+ that may apply to the Work or any use thereof, including without
115
+ limitation any person's Copyright and Related Rights in the Work.
116
+ Further, Affirmer disclaims responsibility for obtaining any necessary
117
+ consents, permissions or other rights required for any use of the
118
+ Work.
119
+ d. Affirmer understands and acknowledges that Creative Commons is not a
120
+ party to this document and has no duty or obligation with respect to
121
+ this CC0 or use of the Work.
claude2md-0.1/PKG-INFO ADDED
@@ -0,0 +1,120 @@
1
+ Metadata-Version: 2.4
2
+ Name: claude2md
3
+ Version: 0.1
4
+ Summary: Convert Claude.ai or Claude Code chats to Markdown
5
+ Keywords: claude,markdown,chat,export,converter
6
+ Author-email: Ultrathinkers Anonymous <ultrathink@twilligon.com>
7
+ Requires-Python: >= 3.10
8
+ Description-Content-Type: text/markdown
9
+ License-Expression: CC0-1.0
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Environment :: Console
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Topic :: Text Processing :: Markup :: Markdown
18
+ Classifier: Topic :: Utilities
19
+ License-File: LICENSE
20
+ Project-URL: Issues, https://github.com/twilliddgon/claude2md/issues
21
+ Project-URL: Repository, https://github.com/twilligon/claude2md
22
+
23
+ # `claude2md`
24
+
25
+ Convert Claude.ai or Claude Code chat exports to Markdown format.
26
+
27
+ `claude2md` converts chats exported from Claude.ai or Claude Code to Markdown format. This lets you efficiently show entire chats to other models or instances until you struggle to remember which transcript of a chat full of transcripts of chats full of transcripts of chats is the right one (aka slopception).
28
+
29
+ ## Features
30
+
31
+ You can filter the exports to any subset of user, assistant, and thinking blocks. For context management I've found it's often helpful to only export user messages, though obviously for the strongest "continuity" between an exported chat transcript and its consumer you want all context from the prior chat. Though Claude typically does not get to see its past thinking, so `--no-thinking` (our default) ought to be just as good if not better than including thinking blocks (by virtue of being on-distribution).
32
+
33
+ We try to include Claude.ai attachments when they're available in the export, but the format we parse right now does not have them embedded in the JSON or anything, so in practice only attachments with `extracted_content`, i.e. text files, markdown, etc. will be present in the transcripts.
34
+
35
+ You can branch conversations on Claude.ai (and to a lesser extent in Claude Code), and `claude2md` can export any branch. You can list the branches of a chat and their UUIDs with `claude2md --branches` and export a specific branch with `claude2md --branch UUID`.
36
+
37
+ We don't support "Claude Code on the Web" yet, though ostensibly if you "teleport" a Web session to a local Claude Code instance, you can export the history as normal from there.
38
+
39
+ ## Install
40
+
41
+ The blazing fast and memory safe way:
42
+
43
+ $ uvx claude2md --help # installed on demand
44
+
45
+ The traditional way:
46
+
47
+ $ pip install claude2md
48
+ $ claude2md --help
49
+
50
+ The bleeding-edge way:
51
+
52
+ $ git clone https://github.com/twilligon/claude2md
53
+ $ cd claude2md
54
+ $ python3 -m venv venv; . venv/bin/activate # you probably want a venv
55
+ $ pip install -e .
56
+ $ claude2md --help
57
+
58
+ ## Usage
59
+
60
+ $ claude2md --help
61
+ usage: claude2md [-h] [--branches | --branch UUID] [--user] [--no-user]
62
+ [--assistant] [--no-assistant] [--thinking]
63
+ [--no-thinking] [--title] [--no-title]
64
+ [file]
65
+
66
+ Convert Claude.ai or Claude Code chats to Markdown
67
+
68
+ positional arguments:
69
+ file JSON file to convert (default: stdin)
70
+
71
+ options:
72
+ -h, --help show this help message and exit
73
+ --branches List all branch message UUIDs
74
+ --branch UUID Show chain to specific branch
75
+ --user Show user messages (default)
76
+ --no-user Hide user messages
77
+ --assistant Show assistant (default)
78
+ --no-assistant Hide assistant
79
+ --thinking Show thinking blocks
80
+ --no-thinking Hide thinking (default)
81
+ --title Always show title (or "Untitled" if none)
82
+ --no-title Never show title
83
+
84
+ ## Examples
85
+
86
+ #### Claude.ai
87
+
88
+ $ claude2md --title --thinking ~/.local/share/claude-backup/f50d0792-fa79-4d2d-a945-c8f709e9e7a7/c6a33008-39b3-45ed-a00e-413141c89a90.json | head -n20
89
+ # Python packaging complexity
90
+
91
+ > why is python packaging such a clusterfuck? ultrathink
92
+
93
+ <thinking>
94
+ The user is asking about Python packaging and why it's so complicated/messy. They've also said "ultrathink" which I interpret as wanting a very thorough, deep analysis.
95
+
96
+ This is a great question that many Python developers have strong feelings about. Let me think through the historical and technical reasons why Python packaging became so complex.
97
+
98
+ Key issues to cover:
99
+ 1. Historical evolution - how we got here
100
+ 2. Multiple competing tools and standards
101
+ 3. The various problems each tool tries to solve
102
+ 4. Why there's no single "right" way
103
+ 5. The current state and attempts to fix things
104
+
105
+ Let me structure this thoughtfully and comprehensively since they asked for "ultrathink."
106
+ </thinking>
107
+
108
+ Python packaging *is* notoriously complex, and there are deep historical and technical reasons for this. Let me break down why it became such a mess:
109
+
110
+ #### Claude Code
111
+
112
+ $ claude2md ~/.claude/projects/-home-claude-claude2md/0c8de429-fb29-4096-925e-6d81a0437f09.jsonl --branch 670e0906-013b-4c83-b7c7-ecf8e12aab3e | head -n3
113
+ > rename --leaves and --leaf to --branches and --branch. no need to change how we refer to this stuff internally, only user facing matters. in @claude2md/__init__.py . ultrathink
114
+
115
+ I'll help you rename the command-line arguments from `--leaves`/`--leaf` to `--branches`/`--branch` in the user-facing interface. Let me start by creating a todo list for this task.
116
+
117
+ ## License
118
+
119
+ `claude2md` is dedicated to the public domain where possible via CC0-1.0.
120
+
@@ -0,0 +1,97 @@
1
+ # `claude2md`
2
+
3
+ Convert Claude.ai or Claude Code chat exports to Markdown format.
4
+
5
+ `claude2md` converts chats exported from Claude.ai or Claude Code to Markdown format. This lets you efficiently show entire chats to other models or instances until you struggle to remember which transcript of a chat full of transcripts of chats full of transcripts of chats is the right one (aka slopception).
6
+
7
+ ## Features
8
+
9
+ You can filter the exports to any subset of user, assistant, and thinking blocks. For context management I've found it's often helpful to only export user messages, though obviously for the strongest "continuity" between an exported chat transcript and its consumer you want all context from the prior chat. Though Claude typically does not get to see its past thinking, so `--no-thinking` (our default) ought to be just as good if not better than including thinking blocks (by virtue of being on-distribution).
10
+
11
+ We try to include Claude.ai attachments when they're available in the export, but the format we parse right now does not have them embedded in the JSON or anything, so in practice only attachments with `extracted_content`, i.e. text files, markdown, etc. will be present in the transcripts.
12
+
13
+ You can branch conversations on Claude.ai (and to a lesser extent in Claude Code), and `claude2md` can export any branch. You can list the branches of a chat and their UUIDs with `claude2md --branches` and export a specific branch with `claude2md --branch UUID`.
14
+
15
+ We don't support "Claude Code on the Web" yet, though ostensibly if you "teleport" a Web session to a local Claude Code instance, you can export the history as normal from there.
16
+
17
+ ## Install
18
+
19
+ The blazing fast and memory safe way:
20
+
21
+ $ uvx claude2md --help # installed on demand
22
+
23
+ The traditional way:
24
+
25
+ $ pip install claude2md
26
+ $ claude2md --help
27
+
28
+ The bleeding-edge way:
29
+
30
+ $ git clone https://github.com/twilligon/claude2md
31
+ $ cd claude2md
32
+ $ python3 -m venv venv; . venv/bin/activate # you probably want a venv
33
+ $ pip install -e .
34
+ $ claude2md --help
35
+
36
+ ## Usage
37
+
38
+ $ claude2md --help
39
+ usage: claude2md [-h] [--branches | --branch UUID] [--user] [--no-user]
40
+ [--assistant] [--no-assistant] [--thinking]
41
+ [--no-thinking] [--title] [--no-title]
42
+ [file]
43
+
44
+ Convert Claude.ai or Claude Code chats to Markdown
45
+
46
+ positional arguments:
47
+ file JSON file to convert (default: stdin)
48
+
49
+ options:
50
+ -h, --help show this help message and exit
51
+ --branches List all branch message UUIDs
52
+ --branch UUID Show chain to specific branch
53
+ --user Show user messages (default)
54
+ --no-user Hide user messages
55
+ --assistant Show assistant (default)
56
+ --no-assistant Hide assistant
57
+ --thinking Show thinking blocks
58
+ --no-thinking Hide thinking (default)
59
+ --title Always show title (or "Untitled" if none)
60
+ --no-title Never show title
61
+
62
+ ## Examples
63
+
64
+ #### Claude.ai
65
+
66
+ $ claude2md --title --thinking ~/.local/share/claude-backup/f50d0792-fa79-4d2d-a945-c8f709e9e7a7/c6a33008-39b3-45ed-a00e-413141c89a90.json | head -n20
67
+ # Python packaging complexity
68
+
69
+ > why is python packaging such a clusterfuck? ultrathink
70
+
71
+ <thinking>
72
+ The user is asking about Python packaging and why it's so complicated/messy. They've also said "ultrathink" which I interpret as wanting a very thorough, deep analysis.
73
+
74
+ This is a great question that many Python developers have strong feelings about. Let me think through the historical and technical reasons why Python packaging became so complex.
75
+
76
+ Key issues to cover:
77
+ 1. Historical evolution - how we got here
78
+ 2. Multiple competing tools and standards
79
+ 3. The various problems each tool tries to solve
80
+ 4. Why there's no single "right" way
81
+ 5. The current state and attempts to fix things
82
+
83
+ Let me structure this thoughtfully and comprehensively since they asked for "ultrathink."
84
+ </thinking>
85
+
86
+ Python packaging *is* notoriously complex, and there are deep historical and technical reasons for this. Let me break down why it became such a mess:
87
+
88
+ #### Claude Code
89
+
90
+ $ claude2md ~/.claude/projects/-home-claude-claude2md/0c8de429-fb29-4096-925e-6d81a0437f09.jsonl --branch 670e0906-013b-4c83-b7c7-ecf8e12aab3e | head -n3
91
+ > rename --leaves and --leaf to --branches and --branch. no need to change how we refer to this stuff internally, only user facing matters. in @claude2md/__init__.py . ultrathink
92
+
93
+ I'll help you rename the command-line arguments from `--leaves`/`--leaf` to `--branches`/`--branch` in the user-facing interface. Let me start by creating a todo list for this task.
94
+
95
+ ## License
96
+
97
+ `claude2md` is dedicated to the public domain where possible via CC0-1.0.
@@ -0,0 +1,339 @@
1
+ #!/usr/bin/env python3
2
+
3
+ # SPDX-License-Identifier: CC0-1.0
4
+
5
+ """Convert Claude.ai or Claude Code chats to Markdown"""
6
+
7
+ __version__ = "0.1"
8
+
9
+ from contextlib import suppress
10
+ from dataclasses import dataclass, field
11
+ from enum import Enum
12
+ from json import JSONDecodeError
13
+ from uuid import UUID
14
+
15
+ import argparse
16
+ import json
17
+ import os
18
+ import re
19
+ import sys
20
+
21
+ NULL_UUID = "00000000-0000-4000-8000-000000000000"
22
+
23
+
24
+ class Role(Enum):
25
+ USER = "user"
26
+ ASSISTANT = "assistant"
27
+
28
+ @classmethod
29
+ def from_json(cls, value):
30
+ match value:
31
+ case "user" | "human":
32
+ return cls.USER
33
+ case "assistant":
34
+ return cls.ASSISTANT
35
+ case _:
36
+ raise ValueError(f'Unknown role: "{value}"')
37
+
38
+
39
+ @dataclass(slots=True, frozen=True)
40
+ class Block:
41
+ type: str
42
+ content: str
43
+
44
+ @classmethod
45
+ def from_json(cls, obj):
46
+ match obj["type"]:
47
+ case "text":
48
+ return cls("text", obj["text"])
49
+ case "thinking":
50
+ return cls("thinking", obj["thinking"])
51
+ case "token_budget" | "tool_result" | "tool_use" | "voice_note":
52
+ return None
53
+ case block_type:
54
+ raise NotImplementedError(f'Unsupported block type "{block_type}"')
55
+
56
+
57
+ @dataclass(slots=True, frozen=True)
58
+ class Message:
59
+ uuid: str
60
+ parent: str | None
61
+ role: Role
62
+ blocks: list[Block]
63
+ attachments: list
64
+
65
+ @classmethod
66
+ def from_json(cls, data):
67
+ # Try to get content from different possible locations
68
+ content = data.get("message", {}).get("content") or data.get("content")
69
+ if not content:
70
+ raise KeyError("No content field found in message data")
71
+
72
+ # Handle content as either a string or an array of block objects
73
+ if isinstance(content, str):
74
+ # Simple string content - create a text block
75
+ blocks = [Block("text", content)]
76
+ elif isinstance(content, list):
77
+ # Array of block objects
78
+ blocks = [
79
+ block for block in (Block.from_json(obj) for obj in content) if block
80
+ ]
81
+ else:
82
+ blocks = []
83
+ parent = data.get("parentUuid") or data.get("parent_message_uuid")
84
+ # Treat null UUID as None (no parent)
85
+ if parent == NULL_UUID:
86
+ parent = None
87
+
88
+ # Try to get role from different possible locations
89
+ role_value = data.get("message", {}).get("role") or data.get("sender")
90
+ if not role_value:
91
+ raise KeyError("No role field found in message data")
92
+
93
+ return cls(
94
+ uuid=data["uuid"],
95
+ parent=parent,
96
+ role=Role.from_json(role_value),
97
+ blocks=blocks,
98
+ attachments=data.get("attachments", []),
99
+ )
100
+
101
+ def render(self, thinking=True):
102
+ parts = []
103
+
104
+ if self.role == Role.USER:
105
+ if self.attachments:
106
+ lines = ["<documents>"]
107
+ for index, attachment in enumerate(self.attachments, 1):
108
+ file_name = attachment.get("file_name")
109
+ file_type = attachment.get("file_type")
110
+ extracted = attachment["extracted_content"]
111
+
112
+ doc = f'<document index="{index}"'
113
+ if file_type:
114
+ doc += f' media_type="{file_type}"'
115
+ doc += ">"
116
+ if file_name:
117
+ doc += f"<source>{file_name}</source>"
118
+ doc += (
119
+ f"<document_content>{extracted}</document_content></document>"
120
+ )
121
+ lines.append(doc)
122
+ lines.append("</documents>")
123
+ parts.append("\n".join(lines))
124
+
125
+ for block in self.blocks:
126
+ parts.append(block.content)
127
+
128
+ text = "\n\n".join(parts)
129
+ return re.sub(r"^", "> ", text, flags=re.MULTILINE)
130
+
131
+ elif self.role == Role.ASSISTANT:
132
+ for block in self.blocks:
133
+ if block.type == "thinking" and not thinking:
134
+ continue
135
+ if block.type == "thinking":
136
+ parts.append(f"<thinking>\n{block.content}\n</thinking>")
137
+ else:
138
+ parts.append(block.content)
139
+
140
+ return "\n\n".join(parts)
141
+
142
+ return ""
143
+
144
+
145
+ @dataclass(slots=True)
146
+ class Chat:
147
+ file: object
148
+
149
+ messages: dict = field(init=False, default_factory=dict)
150
+ metadata: dict = field(init=False, default_factory=dict)
151
+ leaves: list = field(init=False, default_factory=list)
152
+
153
+ def __post_init__(self):
154
+ unparsed = self.file.read()
155
+
156
+ try:
157
+ parsed = json.loads(unparsed)
158
+ for msg_data in parsed["chat_messages"]:
159
+ msg = Message.from_json(msg_data)
160
+ self.messages[msg.uuid] = msg
161
+ self.metadata = parsed
162
+ except (JSONDecodeError, KeyError, TypeError):
163
+ for line in unparsed.split("\n"):
164
+ with suppress(JSONDecodeError, KeyError, TypeError):
165
+ msg = Message.from_json(json.loads(line))
166
+ self.messages[msg.uuid] = msg
167
+
168
+ all_parents = {msg.parent for msg in self.messages.values() if msg.parent}
169
+ self.leaves = [uuid for uuid in self.messages.keys() if uuid not in all_parents]
170
+
171
+ def print_branch(self, uuid, user=True, assistant=True, thinking=False, title=None):
172
+ msg = self.messages[uuid]
173
+
174
+ if msg.parent:
175
+ self.print_branch(msg.parent, user, assistant, thinking, title)
176
+ elif title:
177
+ chat_name = self.metadata.get("name")
178
+ if title is True:
179
+ title_text = chat_name or "Untitled"
180
+ print(f"# {title_text}\n")
181
+ elif chat_name:
182
+ print(f"# {chat_name}\n")
183
+
184
+ if msg.role == Role.USER and not user:
185
+ return
186
+ if msg.role == Role.ASSISTANT and not assistant:
187
+ return
188
+
189
+ rendered = msg.render(thinking=thinking)
190
+ if rendered:
191
+ print(rendered)
192
+ print()
193
+
194
+ def print_leaves(self, uuids=None, file=None):
195
+ if uuids is None:
196
+ uuids = self.leaves
197
+
198
+ width = 80
199
+ if sys.stdout.isatty():
200
+ with suppress(AttributeError, OSError):
201
+ width = os.get_terminal_size().columns
202
+ preview_len = max(20, width - 36 - 4)
203
+
204
+ for uuid in uuids:
205
+ current = uuid
206
+ preview = ""
207
+
208
+ while current:
209
+ msg = self.messages[current]
210
+ if msg.role == Role.USER:
211
+ for block in msg.blocks:
212
+ if block.type == "text":
213
+ preview = block.content
214
+ break
215
+ if preview:
216
+ break
217
+ current = msg.parent
218
+
219
+ if preview:
220
+ preview = preview.replace("\n", " ").replace("\r", " ")
221
+ preview = " ".join(preview.split())
222
+ if len(preview) > preview_len:
223
+ preview = preview[: preview_len - 1] + "…"
224
+ else:
225
+ preview = ""
226
+
227
+ print(f"{uuid}\t{preview}", file=file)
228
+
229
+ def get_leaf(self, prefix=""):
230
+ with suppress(ValueError):
231
+ return str(UUID(prefix))
232
+
233
+ matches = [uuid for uuid in self.leaves if uuid.startswith(prefix)]
234
+
235
+ match matches:
236
+ case []:
237
+ print(f'Error: No leaf matches prefix "{prefix}"', file=sys.stderr)
238
+ return None
239
+ case [single]:
240
+ return single
241
+ case multiple:
242
+ print(
243
+ f'Error: Multiple leaves match prefix "{prefix}":',
244
+ file=sys.stderr,
245
+ )
246
+ self.print_leaves(multiple, file=sys.stderr)
247
+ return None
248
+
249
+
250
+ def main():
251
+ sys.setrecursionlimit(100_000) # lol
252
+
253
+ parser = argparse.ArgumentParser(
254
+ description="Convert Claude.ai or Claude Code chats to Markdown"
255
+ )
256
+ parser.add_argument(
257
+ "file",
258
+ nargs="?",
259
+ type=argparse.FileType("r"),
260
+ default=sys.stdin,
261
+ help="JSON file to convert (default: stdin)",
262
+ )
263
+
264
+ nav_group = parser.add_mutually_exclusive_group()
265
+ nav_group.add_argument(
266
+ "--branches",
267
+ dest="leaves",
268
+ action="store_true",
269
+ help="List all branch message UUIDs",
270
+ )
271
+ nav_group.add_argument(
272
+ "--branch", dest="leaf", metavar="UUID", help="Show chain to specific branch"
273
+ )
274
+
275
+ parser.add_argument(
276
+ "--user",
277
+ dest="user",
278
+ action="store_true",
279
+ default=True,
280
+ help="Show user messages (default)",
281
+ )
282
+ parser.add_argument(
283
+ "--no-user", dest="user", action="store_false", help="Hide user messages"
284
+ )
285
+ parser.add_argument(
286
+ "--human", dest="user", action="store_true", help=argparse.SUPPRESS
287
+ )
288
+ parser.add_argument(
289
+ "--no-human", dest="user", action="store_false", help=argparse.SUPPRESS
290
+ )
291
+ parser.add_argument(
292
+ "--assistant",
293
+ dest="assistant",
294
+ action="store_true",
295
+ default=True,
296
+ help="Show assistant (default)",
297
+ )
298
+ parser.add_argument(
299
+ "--no-assistant", dest="assistant", action="store_false", help="Hide assistant"
300
+ )
301
+ parser.add_argument(
302
+ "--thinking",
303
+ dest="thinking",
304
+ action="store_true",
305
+ default=False,
306
+ help="Show thinking blocks",
307
+ )
308
+ parser.add_argument(
309
+ "--no-thinking",
310
+ dest="thinking",
311
+ action="store_false",
312
+ help="Hide thinking (default)",
313
+ )
314
+ parser.add_argument(
315
+ "--title",
316
+ dest="title",
317
+ action="store_true",
318
+ default=None,
319
+ help='Always show title (or "Untitled" if none)',
320
+ )
321
+ parser.add_argument(
322
+ "--no-title", dest="title", action="store_false", help="Never show title"
323
+ )
324
+ args = parser.parse_args()
325
+
326
+ chat = Chat(args.file)
327
+
328
+ if args.leaves:
329
+ chat.print_leaves()
330
+ elif uuid := (
331
+ (args.leaf and chat.get_leaf(args.leaf))
332
+ or chat.metadata.get("current_leaf_message_uuid")
333
+ or chat.get_leaf()
334
+ ):
335
+ chat.print_branch(uuid, args.user, args.assistant, args.thinking, args.title)
336
+
337
+
338
+ if __name__ == "__main__":
339
+ main()
@@ -0,0 +1,4 @@
1
+ from claude2md import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
@@ -0,0 +1,30 @@
1
+ [build-system]
2
+ requires = ["flit-core >=3.11,<4"]
3
+ build-backend = "flit_core.buildapi"
4
+
5
+ [project]
6
+ name = "claude2md"
7
+ readme = "README.md"
8
+ requires-python = ">= 3.10"
9
+ license = "CC0-1.0"
10
+ authors = [{name = "Ultrathinkers Anonymous", email = "ultrathink@twilligon.com"}]
11
+ keywords = ["claude", "markdown", "chat", "export", "converter"]
12
+ classifiers = [
13
+ "Development Status :: 4 - Beta",
14
+ "Environment :: Console",
15
+ "Programming Language :: Python :: 3",
16
+ "Programming Language :: Python :: 3.10",
17
+ "Programming Language :: Python :: 3.11",
18
+ "Programming Language :: Python :: 3.12",
19
+ "Programming Language :: Python :: 3.13",
20
+ "Topic :: Text Processing :: Markup :: Markdown",
21
+ "Topic :: Utilities",
22
+ ]
23
+ dynamic = ["version", "description"]
24
+
25
+ [project.scripts]
26
+ claude2md = "claude2md:main"
27
+
28
+ [project.urls]
29
+ Repository = "https://github.com/twilligon/claude2md"
30
+ Issues = "https://github.com/twilliddgon/claude2md/issues"