File size: 1,253 Bytes
0d23382 | 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 | import json
import re
from tqdm import tqdm
# Read the original JSON data from the file
with open('/root/Monkey_Data/train_monkey.json', 'r') as file:
original_json = json.load(file)
# Desired JSON format
desired_json = []
# Regex pattern to match the entire <img>...</img> string
pattern = r"<img>.*?</img>"
#count = 0
# Extract and transform the data
for item in tqdm(original_json, desc="Processing"):
new_conversations = []
for conv in item["conversations"]:
if conv["from"] == "user":
new_value = re.sub(pattern, "<image>\n", conv["value"])
new_conversations.append({
"from": "human",
"value": new_value
})
elif conv["from"] == "assistant":
new_conversations.append({
"from": "gpt",
"value": conv["value"]
})
desired_json.append({
"id": item["id"],
"image": item["id"],
"conversations": new_conversations
})
#count += 1
#if count > 10:
# break
# Optionally, write the transformed JSON to a new file
with open('/root/Monkey_Data/transformed_train_monkey.json', 'w') as outfile:
json.dump(desired_json, outfile, indent=4, ensure_ascii=False)
|