-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgemini2md.py
118 lines (93 loc) · 4.61 KB
/
gemini2md.py
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
import json
import os
import glob
import re # Import the 're' module for regular expression operations
import zipfile
def format_markdown(json_data):
markdown_output = ""
# --- Header ---
markdown_output += "# Gemini Pro Conversation\n\n"
if 'runSettings' in json_data:
markdown_output += f"**Model:** {json_data['runSettings']['model']}\n"
markdown_output += f"**Temperature:** {json_data['runSettings']['temperature']}\n\n"
# --- Citations ---
if 'citations' in json_data and json_data['citations']:
markdown_output += "## Citations\n\n"
for citation in json_data['citations']:
if 'uri' in citation:
markdown_output += f"* [{citation['uri']
}]({citation['uri']})\n"
markdown_output += "\n"
# --- System Instructions (Optional) ---
if 'systemInstruction' in json_data and json_data['systemInstruction']:
markdown_output += "## System Instructions\n\n"
markdown_output += json_data['systemInstruction'].get(
'text', '') + "\n\n"
# --- Conversation ---
markdown_output += "## Conversation\n\n"
if 'chunkedPrompt' in json_data and 'chunks' in json_data['chunkedPrompt']:
for chunk in json_data['chunkedPrompt']['chunks']:
if chunk['role'] == 'user':
markdown_output += "### User\n\n"
elif chunk['role'] == 'model':
markdown_output += "### Model\n\n"
# Handle "thoughts" differently
if chunk.get('isThought', False):
markdown_output += "> " + \
chunk.get('text', '').replace("\n", "\n> ") + "\n\n"
else:
if 'text' in chunk:
# Improved code block detection using regular expressions
code_block_pattern = r"```(?:\w+\n)?(.*?)```"
matches = re.findall(code_block_pattern,
chunk['text'], re.DOTALL)
if matches:
for code_snippet in matches:
markdown_output += "```\n" + code_snippet.strip() + "\n```\n\n"
else:
markdown_output += chunk['text'] + "\n\n"
else:
markdown_output += "No conversation data available.\n\n"
return markdown_output
def convert_json_to_markdown(input_path, output_path): # Added output_path argument
try:
with open(input_path, 'r', encoding='utf-8') as f:
json_data = json.load(f)
markdown_content = format_markdown(json_data)
with open(output_path, 'w', encoding='utf-8') as f:
f.write(markdown_content)
print(f"Successfully converted '{input_path}' to '{output_path}'")
except (FileNotFoundError, json.JSONDecodeError, UnicodeDecodeError) as e:
print(f"Error processing '{input_path}': {e}")
def unzip_files(directory):
# Create the AI_Studio_Chats directory if it doesn't exist
output_dir = os.path.join(directory, 'AI_Studio_Chats')
os.makedirs(output_dir, exist_ok=True)
# Find all zip files in the directory
zip_files = [f for f in os.listdir(directory) if f.endswith('.zip')]
for zip_file in zip_files:
zip_path = os.path.join(directory, zip_file)
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
zip_ref.extractall(output_dir)
# Rename all files in the output directory to add .json extension
for filename in os.listdir(output_dir):
file_path = os.path.join(output_dir, filename)
if os.path.isfile(file_path) and not filename.endswith('.json'):
new_file_path = file_path + '.json'
os.rename(file_path, new_file_path)
if __name__ == "__main__":
script_dir = os.path.dirname(__file__)
unzip_files(script_dir)
print("Unzipping complete and .json extension added to files.")
# Construct the path to the AI_Studio_Chats directory
ai_studio_chats_dir = os.path.join(script_dir, "AI_Studio_Chats")
# Get all .json files in the AI_Studio_Chats directory
json_files = glob.glob(os.path.join(ai_studio_chats_dir, "*.json"))
# Create the Markdown Chats directory in the root
markdown_chats_dir = os.path.join(script_dir, "Markdown Chats")
os.makedirs(markdown_chats_dir, exist_ok=True)
for json_file in json_files:
# Create output file name with .md extension in the Markdown Chats directory
base_name = os.path.splitext(os.path.basename(json_file))[0]
output_file = os.path.join(markdown_chats_dir, f"{base_name}.md")
convert_json_to_markdown(json_file, output_file)