1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
| import json import os import re import html from datetime import datetime from typing import Dict, List, Any, Optional from pathlib import Path
def extract_conversation_messages(mapping: Dict[str, Any], start_node_id: str = "root") -> List[Dict[str, Any]]: """ 从mapping的树形结构中递归提取对话消息,处理复杂的树形结构 """ messages = [] visited_nodes = set() def traverse_node(node_id: str): """递归遍历节点""" if node_id in visited_nodes or node_id not in mapping: return visited_nodes.add(node_id) current_node = mapping[node_id] message_data = current_node.get("message") if message_data and isinstance(message_data, dict): process_message_data(message_data) children = current_node.get("children", []) for child_id in children: if isinstance(child_id, str): traverse_node(child_id) def process_message_data(message_data: Dict[str, Any]): """处理消息数据""" fragments = message_data.get("fragments", []) files = message_data.get("files", []) for file_info in files: if isinstance(file_info, dict): file_content = f"\n\n[文件: {file_info.get('file_name', 'unnamed')}]\n{file_info.get('content', '')}\n" messages.append({ "role": "system", "content": file_content, "type": "FILE_ATTACHMENT", "inserted_at": message_data.get("inserted_at", "") }) for fragment in fragments: if not isinstance(fragment, dict): continue fragment_type = fragment.get("type") content = fragment.get("content", "") if fragment_type == "REQUEST": role = "user" elif fragment_type == "RESPONSE": role = "assistant" elif fragment_type == "THINK": role = "assistant_think" else: continue messages.append({ "role": role, "content": content, "type": fragment_type, "inserted_at": message_data.get("inserted_at", "") }) traverse_node(start_node_id) return messages
def detect_code_language(content: str) -> str: """自动检测代码语言""" if not content.strip(): return '' content_lower = content.lower().strip() first_line = content_lower.split('\n')[0] if '\n' in content_lower else content_lower language_patterns = [ (r'^<\?php|php\$|->|function\s*\(|use\s+\\', 'php'), (r'^from\s+|^run\s+|^cmd\s+|^expose\s+|^copy\s+', 'dockerfile'), (r'^<script|document\.|console\.|function\s*\w*\s*\(|const\s+|let\s+|var\s+', 'javascript'), (r'^#!/usr/bin/env\s+bash|^#!/bin/bash|^\$|echo\s+|ls\s+|cd\s+', 'bash'), (r'^<?xml|^<html|^<!doctype|^<head|^<body', 'html'), (r'^\s*{\s*\"|\"\s*:\s*\"|\"\s*,\s*\"', 'json'), (r'^import\s+|^from\s+\w+\s+import|^def\s+|^class\s+|^print\s*\(|@', 'python'), (r'^#|^//|^<!--', 'plaintext') ] for pattern, lang in language_patterns: if re.search(pattern, content_lower, re.MULTILINE): return lang keyword_patterns = [ (r'\bSELECT\b.*\bFROM\b|\bINSERT\b.*\bINTO\b|\bUPDATE\b.*\bSET\b', 'sql'), (r'\bgit\s+|\bcommit\s+|\bpush\s+|\bpull\s+', 'bash'), (r'\bdocker\s+|\bcontainer\s+|\bimage\s+', 'bash'), (r'\bnginx\s+|\bapache\s+|\bserver\s+{', 'nginx'), ] for pattern, lang in keyword_patterns: if re.search(pattern, content_lower, re.IGNORECASE): return lang return ''
def format_content(content: str, role: str) -> str: """格式化内容,智能识别代码块""" if not content.strip(): return content if role in ["system", "FILE_ATTACHMENT"]: return content language = detect_code_language(content) if language: return f"```{language}\n{content}\n```" return content
def sanitize_filename(filename: str, max_length: int = 50) -> str: """清理文件名,移除非法字符并处理换行符""" if not filename: return "untitled_conversation" filename = filename.replace('\n', ' ').replace('\r', ' ').replace('\t', ' ') illegal_chars = r'[<>:"/\\|?*#]' filename = re.sub(illegal_chars, '', filename) filename = filename.strip().strip('.') if len(filename) > max_length: if ' ' in filename: parts = filename.split(' ') truncated = [] current_length = 0 for part in parts: if current_length + len(part) + 1 <= max_length - 3: truncated.append(part) current_length += len(part) + 1 else: break filename = ' '.join(truncated) + '...' else: filename = filename[:max_length - 3] + '...' if not filename: filename = f"conversation_{datetime.now().strftime('%Y%m%d_%H%M%S')}" return filename
def parse_timestamp(timestamp_str: str) -> str: """解析时间戳""" if not timestamp_str: return "Unknown time" try: if 'T' in timestamp_str: if timestamp_str.endswith('Z'): dt = datetime.fromisoformat(timestamp_str[:-1] + '+00:00') else: dt = datetime.fromisoformat(timestamp_str) return dt.strftime("%Y-%m-%d %H:%M:%S") else: return timestamp_str except (ValueError, AttributeError): return str(timestamp_str)[:19]
def create_obsidian_note(content: str, filepath: str) -> bool: """创建Obsidian笔记文件""" try: os.makedirs(os.path.dirname(filepath), exist_ok=True) with open(filepath, 'w', encoding='utf-8') as f: f.write(content) return True except Exception as e: print(f" 创建文件失败: {e}") return False
def generate_markdown_content(title: str, conv_id: str, timestamp: str, messages: List[Dict[str, Any]]) -> str: """生成Markdown内容""" lines = [ f"# {html.escape(title)}", "", f"**Conversation ID:** `{conv_id}` ", f"**Created:** {timestamp}", f"**Total Messages:** {len(messages)}", "", "---", "" ] for msg in messages: role = msg["role"] content = msg["content"] msg_type = msg.get("type", "") if role == "user": lines.extend([ "<div style=\"display: flex; justify-content: flex-end; margin: 20px 0;\">", "<div style=\"background: #e3f2fd; padding: 12px 16px; border-radius: 18px 18px 0 18px; max-width: 80%; margin-left: 20%;\">", "<div style=\"display: flex; align-items: center; justify-content: flex-end; margin-bottom: 8px;\">", "<span style=\"font-weight: 500; color: #1976d2; margin-right: 8px;\">👤 User</span>", "</div>" ]) elif role == "assistant": lines.extend([ "<div style=\"display: flex; justify-content: flex-start; margin: 20px 0;\">", "<div style=\"background: #f5f5f5; padding: 12px 16px; border-radius: 18px 18px 18px 0; max-width: 80%; margin-right: 20%;\">", "<div style=\"display: flex; align-items: center; margin-bottom: 8px;\">", "<span style=\"font-weight: 500; color: #666; margin-right: 8px;\">🤖 Assistant</span>", "</div>" ]) elif role == "assistant_think": lines.extend([ "<div style=\"background: #fff3e0; padding: 12px 16px; border-radius: 8px; margin: 15px 0; border-left: 4px solid #ff9800;\">", "<div style=\"font-weight: 500; color: #e65100; margin-bottom: 8px;\">🤖 Assistant (内部思考)</div>" ]) elif role == "system": lines.extend([ "<div style=\"background: #e8f5e8; padding: 12px 16px; border-radius: 8px; margin: 15px 0; border-left: 4px solid #4caf50;\">", "<div style=\"font-weight: 500; color: #2e7d32; margin-bottom: 8px;\">📎 文件附件</div>" ]) formatted_content = format_content(content, role) if formatted_content: lines.append(formatted_content) lines.append("</div>") if role in ["user", "assistant"]: lines.append("</div>") inserted_at = msg.get("inserted_at") if inserted_at: time_str = parse_timestamp(inserted_at) time_style = "text-align: right;" if role == "user" else "text-align: left;" lines.append(f"<div style=\"font-size: 0.8em; color: #999; {time_style} margin-top: 4px;\">{time_str}</div>") lines.append("") return '\n'.join(lines)
def json_to_obsidian(): """主函数:将JSON转换为Obsidian格式""" json_path = "新建 文本文档 (5).txt" output_folder = r"C:\Users\dog\Documents\Obsidian Vault\deepseek" os.makedirs(output_folder, exist_ok=True) try: with open(json_path, 'r', encoding='utf-8') as f: data = json.load(f) print(f"成功加载JSON数据") except Exception as e: print(f"加载JSON文件失败: {e}") return if isinstance(data, dict): conversations = [data] elif isinstance(data, list): conversations = data else: print("错误:不支持的JSON数据格式") return print(f"开始处理 {len(conversations)} 个对话...") stats = { 'successful': 0, 'skipped': 0, 'error': 0, 'total_messages': 0 } for index, conversation in enumerate(conversations): if not isinstance(conversation, dict): print(f"跳过非字典类型的对话 {index}") stats['skipped'] += 1 continue conv_id = conversation.get("id", f"unknown_{index}") title = conversation.get("title", f"Conversation {conv_id}") inserted_at = conversation.get("inserted_at", "") mapping = conversation.get("mapping", {}) print(f"\n[{index + 1}/{len(conversations)}] 处理: {repr(title)}") try: messages = extract_conversation_messages(mapping) stats['total_messages'] += len(messages) except Exception as e: print(f" 提取消息时出错: {e}") stats['error'] += 1 continue if not messages: print(f" 跳过空对话") stats['skipped'] += 1 continue safe_title = sanitize_filename(title) filename = f"{safe_title}.md" filepath = os.path.join(output_folder, filename) counter = 1 base_name = safe_title while os.path.exists(filepath): filename = f"{base_name}_{counter}.md" filepath = os.path.join(output_folder, filename) counter += 1 try: timestamp = parse_timestamp(inserted_at) md_content = generate_markdown_content(title, conv_id, timestamp, messages) if create_obsidian_note(md_content, filepath): print(f" 成功创建: {filename} ({len(messages)} 条消息)") stats['successful'] += 1 else: stats['error'] += 1 except Exception as e: print(f" 处理对话失败: {e}") stats['error'] += 1 print(f"\n=== 处理完成 ===") print(f"总对话数: {len(conversations)}") print(f"成功导出: {stats['successful']}") print(f"跳过: {stats['skipped']}") print(f"错误: {stats['error']}") print(f"总消息数: {stats['total_messages']}") print(f"输出文件夹: {output_folder}")
if __name__ == "__main__": json_to_obsidian()
|