|
| 1 | +"""Import command for basic-memory CLI to import chat data from conversations2.json format.""" |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import json |
| 5 | +from datetime import datetime |
| 6 | +from pathlib import Path |
| 7 | +from typing import Dict, Any, List, Annotated |
| 8 | + |
| 9 | +import typer |
| 10 | +from loguru import logger |
| 11 | +from rich.console import Console |
| 12 | +from rich.panel import Panel |
| 13 | +from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn |
| 14 | + |
| 15 | +from basic_memory.cli.app import claude_app |
| 16 | +from basic_memory.config import config |
| 17 | +from basic_memory.markdown import EntityParser, MarkdownProcessor |
| 18 | +from basic_memory.markdown.schemas import EntityMarkdown, EntityFrontmatter |
| 19 | + |
| 20 | +console = Console() |
| 21 | + |
| 22 | + |
| 23 | +def clean_filename(text: str) -> str: |
| 24 | + """Convert text to safe filename.""" |
| 25 | + # Remove invalid characters and convert spaces |
| 26 | + clean = "".join(c if c.isalnum() else "-" for c in text.lower()).strip("-") |
| 27 | + return clean |
| 28 | + |
| 29 | + |
| 30 | +def format_timestamp(ts: str) -> str: |
| 31 | + """Format ISO timestamp for display.""" |
| 32 | + dt = datetime.fromisoformat(ts.replace("Z", "+00:00")) |
| 33 | + return dt.strftime("%Y-%m-%d %H:%M:%S") |
| 34 | + |
| 35 | + |
| 36 | +def format_chat_markdown( |
| 37 | + name: str, messages: List[Dict[str, Any]], created_at: str, modified_at: str, permalink: str |
| 38 | +) -> str: |
| 39 | + """Format chat as clean markdown.""" |
| 40 | + |
| 41 | + # Start with frontmatter and title |
| 42 | + lines = [ |
| 43 | + f"# {name}\n", |
| 44 | + ] |
| 45 | + |
| 46 | + # Add messages |
| 47 | + for msg in messages: |
| 48 | + # Format timestamp |
| 49 | + ts = format_timestamp(msg["created_at"]) |
| 50 | + |
| 51 | + # Add message header |
| 52 | + lines.append(f"### {msg['sender'].title()} ({ts})") |
| 53 | + |
| 54 | + # Handle message content |
| 55 | + content = msg.get("text", "") |
| 56 | + if msg.get("content"): |
| 57 | + content = " ".join(c.get("text", "") for c in msg["content"]) |
| 58 | + lines.append(content) |
| 59 | + |
| 60 | + # Handle attachments |
| 61 | + attachments = msg.get("attachments", []) |
| 62 | + for attachment in attachments: |
| 63 | + if "file_name" in attachment: |
| 64 | + lines.append(f"\n**Attachment: {attachment['file_name']}**") |
| 65 | + if "extracted_content" in attachment: |
| 66 | + lines.append("```") |
| 67 | + lines.append(attachment["extracted_content"]) |
| 68 | + lines.append("```") |
| 69 | + |
| 70 | + # Add spacing between messages |
| 71 | + lines.append("") |
| 72 | + |
| 73 | + return "\n".join(lines) |
| 74 | + |
| 75 | + |
| 76 | +def format_chat_content( |
| 77 | + base_path: Path, name: str, messages: List[Dict[str, Any]], created_at: str, modified_at: str |
| 78 | +) -> EntityMarkdown: |
| 79 | + """Convert chat messages to Basic Memory entity format.""" |
| 80 | + |
| 81 | + # Generate permalink |
| 82 | + date_prefix = datetime.fromisoformat(created_at.replace("Z", "+00:00")).strftime("%Y%m%d") |
| 83 | + clean_title = clean_filename(name) |
| 84 | + permalink = f"{base_path}/{date_prefix}-{clean_title}" |
| 85 | + |
| 86 | + # Format content |
| 87 | + content = format_chat_markdown( |
| 88 | + name=name, |
| 89 | + messages=messages, |
| 90 | + created_at=created_at, |
| 91 | + modified_at=modified_at, |
| 92 | + permalink=permalink, |
| 93 | + ) |
| 94 | + |
| 95 | + # Create entity |
| 96 | + entity = EntityMarkdown( |
| 97 | + frontmatter=EntityFrontmatter( |
| 98 | + metadata={ |
| 99 | + "type": "conversation", |
| 100 | + "title": name, |
| 101 | + "created": created_at, |
| 102 | + "modified": modified_at, |
| 103 | + "permalink": permalink, |
| 104 | + } |
| 105 | + ), |
| 106 | + content=content, |
| 107 | + ) |
| 108 | + |
| 109 | + return entity |
| 110 | + |
| 111 | + |
| 112 | +async def process_conversations_json( |
| 113 | + json_path: Path, base_path: Path, markdown_processor: MarkdownProcessor |
| 114 | +) -> Dict[str, int]: |
| 115 | + """Import chat data from conversations2.json format.""" |
| 116 | + |
| 117 | + with Progress( |
| 118 | + SpinnerColumn(), |
| 119 | + TextColumn("[progress.description]{task.description}"), |
| 120 | + BarColumn(), |
| 121 | + TextColumn("[progress.percentage]{task.percentage:>3.0f}%"), |
| 122 | + console=console, |
| 123 | + ) as progress: |
| 124 | + read_task = progress.add_task("Reading chat data...", total=None) |
| 125 | + |
| 126 | + # Read chat data - handle array of arrays format |
| 127 | + data = json.loads(json_path.read_text()) |
| 128 | + conversations = [chat for chat in data] |
| 129 | + progress.update(read_task, total=len(conversations)) |
| 130 | + |
| 131 | + # Process each conversation |
| 132 | + messages_imported = 0 |
| 133 | + chats_imported = 0 |
| 134 | + |
| 135 | + for chat in conversations: |
| 136 | + # Convert to entity |
| 137 | + entity = format_chat_content( |
| 138 | + base_path=base_path, |
| 139 | + name=chat["name"], |
| 140 | + messages=chat["chat_messages"], |
| 141 | + created_at=chat["created_at"], |
| 142 | + modified_at=chat["updated_at"], |
| 143 | + ) |
| 144 | + |
| 145 | + # Write file |
| 146 | + file_path = Path(f"{entity.frontmatter.metadata['permalink']}.md") |
| 147 | + await markdown_processor.write_file(file_path, entity) |
| 148 | + |
| 149 | + chats_imported += 1 |
| 150 | + messages_imported += len(chat["chat_messages"]) |
| 151 | + progress.update(read_task, advance=1) |
| 152 | + |
| 153 | + return {"conversations": chats_imported, "messages": messages_imported} |
| 154 | + |
| 155 | + |
| 156 | +async def get_markdown_processor() -> MarkdownProcessor: |
| 157 | + """Get MarkdownProcessor instance.""" |
| 158 | + entity_parser = EntityParser(config.home) |
| 159 | + return MarkdownProcessor(entity_parser) |
| 160 | + |
| 161 | + |
| 162 | +@claude_app.command(name="conversations", help="Import chat conversations from Claude.ai.") |
| 163 | +def import_claude( |
| 164 | + conversations_json: Annotated[ |
| 165 | + Path, typer.Argument(..., help="Path to conversations.json file") |
| 166 | + ] = Path("conversations.json"), |
| 167 | + folder: Annotated[ |
| 168 | + str, typer.Option(help="The folder to place the files in.") |
| 169 | + ] = "conversations", |
| 170 | +): |
| 171 | + """Import chat conversations from conversations2.json format. |
| 172 | +
|
| 173 | + This command will: |
| 174 | + 1. Read chat data and nested messages |
| 175 | + 2. Create markdown files for each conversation |
| 176 | + 3. Format content in clean, readable markdown |
| 177 | +
|
| 178 | + After importing, run 'basic-memory sync' to index the new files. |
| 179 | + """ |
| 180 | + |
| 181 | + try: |
| 182 | + if not conversations_json.exists(): |
| 183 | + typer.echo(f"Error: File not found: {conversations_json}", err=True) |
| 184 | + raise typer.Exit(1) |
| 185 | + |
| 186 | + # Get markdown processor |
| 187 | + markdown_processor = asyncio.run(get_markdown_processor()) |
| 188 | + |
| 189 | + # Process the file |
| 190 | + base_path = config.home / folder |
| 191 | + console.print(f"\nImporting chats from {conversations_json}...writing to {base_path}") |
| 192 | + results = asyncio.run( |
| 193 | + process_conversations_json(conversations_json, base_path, markdown_processor) |
| 194 | + ) |
| 195 | + |
| 196 | + # Show results |
| 197 | + console.print( |
| 198 | + Panel( |
| 199 | + f"[green]Import complete![/green]\n\n" |
| 200 | + f"Imported {results['conversations']} conversations\n" |
| 201 | + f"Containing {results['messages']} messages", |
| 202 | + expand=False, |
| 203 | + ) |
| 204 | + ) |
| 205 | + |
| 206 | + console.print("\nRun 'basic-memory sync' to index the new files.") |
| 207 | + |
| 208 | + except Exception as e: |
| 209 | + logger.exception("Import failed") |
| 210 | + typer.echo(f"Error during import: {e}", err=True) |
| 211 | + raise typer.Exit(1) |
0 commit comments