Skip to content

Instantly share code, notes, and snippets.

@oquno
Created April 20, 2023 10:01
Show Gist options
  • Save oquno/6d6fdea5ac7eda5779524364b5e68125 to your computer and use it in GitHub Desktop.
Save oquno/6d6fdea5ac7eda5779524364b5e68125 to your computer and use it in GitHub Desktop.
GPT-4 に大体書いてもらった、ChatGPT からエクスポートした conversations.json を input.json として置いておくと Scrapbox インポート用の output.json を出力してくれるスクリプト
import json
USERNAME="oquno"
def get_ordered_nodes(mapping, current_node):
node_data = mapping[current_node]
children = node_data['children']
ordered_nodes = []
roles = {'assistant': '[ChatGPT.icon]', 'user': f'[{USERNAME}.icon]'}
if node_data['message'] is not None:
content = node_data['message']['content']['parts'][0]
role = node_data['message']['author']['role']
if role != 'system':
if role in roles.keys():
role = roles[role]
ordered_nodes.append((current_node, content, role))
for child in children:
ordered_nodes.extend(get_ordered_nodes(mapping, child))
return ordered_nodes
def convert_chatgpt_to_scrapbox(input_filename, output_filename):
with open(input_filename, 'r') as f:
chatgpt_list = json.load(f)
scrapbox_list = []
for chatgpt_json in chatgpt_list:
mapping = chatgpt_json['mapping']
root_node_id = [node for node, data in mapping.items() if data['parent'] is None][0]
sorted_nodes = get_ordered_nodes(mapping, root_node_id)
lines = [chatgpt_json['title']]
previous_role = None
for node in sorted_nodes:
in_code_block = False
node_id, content, role = node
if role != previous_role:
lines.append(role)
previous_role = role
for line in content.split('\n'):
if line.strip().startswith("```"):
in_code_block = not in_code_block
if in_code_block:
lang = "script"
if len(line.strip()) == 3:
lines.append(" code:script")
else:
lines.append(" code:" + line.strip()[3:])
continue
if len(line.strip()) == 0:
continue
if in_code_block:
lines.append(" " * 2 + line)
else:
lines.append(" " + line)
scrapbox_json = {
"title": chatgpt_json['title'],
"lines": lines
}
scrapbox_list.append(scrapbox_json)
with open(output_filename, 'w') as f:
json.dump({"pages": scrapbox_list}, f, ensure_ascii=False, indent=2)
if __name__ == '__main__':
input_filename = 'input.json'
output_filename = 'output.json'
convert_chatgpt_to_scrapbox(input_filename, output_filename)
@oquno
Copy link
Author

oquno commented Apr 22, 2023

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment