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
| import json import os from datetime import datetime
def extract_conversation_messages(mapping, start_node_id="root"): """ 从mapping的树形结构中递归提取对话消息 """ messages = [] current_node_id = start_node_id visited_nodes = set() while current_node_id and current_node_id in mapping and current_node_id not in visited_nodes: visited_nodes.add(current_node_id) current_node = mapping[current_node_id] message_data = current_node.get("message") if message_data and isinstance(message_data, dict): fragments = message_data.get("fragments", []) files = message_data.get("files", []) if files and isinstance(files, list): 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" }) for fragment in fragments: if not isinstance(fragment, dict): continue if "type" not in fragment: continue fragment_type = fragment.get("type") if fragment_type == "REQUEST": role = "user" elif fragment_type == "RESPONSE": role = "assistant" elif fragment_type == "THINK": role = "assistant_think" else: continue content = fragment.get("content", "") messages.append({ "role": role, "content": content, "type": fragment_type, "inserted_at": message_data.get("inserted_at", "") }) children = current_node.get("children", []) if children and isinstance(children, list): current_node_id = children[0] else: current_node_id = None return messages
def json_to_obsidian(): json_path = "新建 文本文档.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)} 个对话...")
successful_count = 0 skipped_count = 0 error_count = 0 for index, conversation in enumerate(conversations): if not isinstance(conversation, dict): print(f"跳过非字典类型的对话 {index}") skipped_count += 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)}] 处理: {title}") try: messages = extract_conversation_messages(mapping) except Exception as e: print(f" 提取消息时出错: {e}") error_count += 1 continue if not messages: print(f" 跳过空对话") skipped_count += 1 continue
valid_title = "".join(c for c in str(title) if c not in '<>:"/\\|?*').strip() if not valid_title or len(valid_title) > 100: valid_title = f"conversation_{conv_id[:8]}" if len(valid_title) > 50: valid_title = valid_title[:50] + "..." filename = f"{valid_title}.md" filepath = os.path.join(output_folder, filename)
counter = 1 original_filepath = filepath while os.path.exists(filepath): filename = f"{valid_title}_{counter}.md" filepath = os.path.join(output_folder, filename) counter += 1
time_str = "Unknown time" if inserted_at: try: if isinstance(inserted_at, str): time_part = inserted_at.split('T')[0] if 'T' in inserted_at else inserted_at time_str = time_part except: time_str = str(inserted_at)[:19]
try: md_content = f"# {title}\n\n" md_content += f"**Conversation ID:** `{conv_id}` \n" md_content += f"**Created:** {time_str}\n\n" md_content += "---\n\n"
for msg in messages: if msg["role"] == "user": md_content += f"### 👤 User\n\n" elif msg["role"] == "assistant": md_content += f"### 🤖 Assistant\n\n" elif msg["role"] == "assistant_think": md_content += f"### 🤖 Assistant (内部思考)\n\n" elif msg["role"] == "system": md_content += f"### 📎 文件附件\n\n" content = msg['content'] if content.strip().startswith(('<?php', '<script', 'FROM ', 'RUN ', '#!/')): language = 'php' if '<?php' in content else 'dockerfile' if 'FROM ' in content else 'javascript' if '<script' in content else '' md_content += f"```{language}\n{content}\n```\n\n" else: md_content += f"{content}\n\n" md_content += "---\n\n"
with open(filepath, 'w', encoding='utf-8') as md_file: md_file.write(md_content) print(f" 成功创建: {filename} ({len(messages)} 条消息)") successful_count += 1 except Exception as e: print(f" 创建文件失败: {e}") error_count += 1
print(f"\n=== 处理完成 ===") print(f"总对话数: {len(conversations)}") print(f"成功导出: {successful_count}") print(f"跳过: {skipped_count}") print(f"错误: {error_count}") print(f"输出文件夹: {output_folder}")
if __name__ == "__main__": json_to_obsidian()
|