import json import random def get_qa_type(question): question_type = "other" if "how did the camera" in question.lower() or "is the camera moving" in question.lower(): question_type = "action_sequence" if ("need to go" in question.lower()): question_type = "goal_aim" if "any of the objects in the initial" in question.lower(): question_type = "obj_movement" if "if i" in question.lower(): question_type = "action_consequence" if 'if i move to the' in question.lower() or "for someone at the" in question.lower(): question_type = "perspective" return question_type def convert_to_conversation(json_data): for item in json_data: question = item["question"] answers = item["answers"] correct_answer = item["correct_answer"] # 更新question_type item["question_type"] = get_qa_type(question) # 构造human部分 prompt = question + " Answer the question using a single word or phrase." # 处理答案选项 if len(answers) > 1: ans_choice_order = answers.copy() ans_choice_order = ['"' + ans + '"' for ans in ans_choice_order] random.shuffle(ans_choice_order) answer_choices_format = " or ".join(ans_choice_order) if answer_choices_format != "": prompt += f" Choose between the following options: {answer_choices_format}." # 添加conversations字段到原数据 item["conversations"] = [ { "from": "human", "value": prompt }, { "from": "gpt", "value": correct_answer } ] return json_data # 读取JSON文件 def process_json_file(input_file, output_file): with open(input_file, 'r', encoding='utf-8') as f: data = json.load(f) # 转换为conversations格式 enhanced_data = convert_to_conversation(data) # 保存结果 with open(output_file, 'w', encoding='utf-8') as f: json.dump(enhanced_data, f, ensure_ascii=False, indent=2) print(f"已处理 {len(enhanced_data)} 条数据,结果保存到 {output_file}") # 使用示例 if __name__ == "__main__": # 如果要处理文件,取消注释下面的行 process_json_file('train_data.json', 'train_data_convs.json')