import json import random from pathlib import Path from collections import defaultdict def sample_prompt_boxes(bboxes, k): """ 从 bboxes 中随机抽取 k 个作为 prompt 如果 bboxes 数量 < k,则全部返回 """ if len(bboxes) <= k: return bboxes.copy(), [] else: # 随机抽取 k 个作为 prompt prompt_indices = random.sample(range(len(bboxes)), k) prompt_boxes = [bboxes[i] for i in prompt_indices] # 剩余的作为 target(可选) target_boxes = [bboxes[i] for i in range(len(bboxes)) if i not in prompt_indices] return prompt_boxes, target_boxes def format_bbox_for_prompt(bbox): """ 将 bbox 格式化为字符串,用于 prompt 格式: [x1, y1, x2, y2] """ return f"[{bbox[0]}, {bbox[1]}, {bbox[2]}, {bbox[3]}]" def process_jsonl_for_fewshot(input_jsonl_path, output_dir, k_values=[1, 2, 4]): """ 处理原始 JSONL,生成 few-shot 格式的数据 Args: input_jsonl_path: 输入的 JSONL 文件路径 output_dir: 输出目录 k_values: few-shot 的 k 值列表 """ output_dir = Path(output_dir) output_dir.mkdir(parents=True, exist_ok=True) # 为每个 k 值创建输出文件 output_files = {} stats = {k: {'total_images': 0, 'total_prompts': 0, 'insufficient_count': 0} for k in k_values} for k in k_values: output_files[k] = open(output_dir / f"fewshot_k{k}.jsonl", 'w', encoding='utf-8') # 读取原始 JSONL with open(input_jsonl_path, 'r', encoding='utf-8') as f: for line_num, line in enumerate(f, 1): data = json.loads(line.strip()) image_path = data['image'] image_rel_path = data.get('image_path', image_path) width = data['width'] height = data['height'] bboxes = data['bboxes'] # 为每个 k 值生成数据 for k in k_values: # 随机抽取 prompt boxes prompt_boxes, remaining_boxes = sample_prompt_boxes(bboxes, k) # 统计信息 stats[k]['total_images'] += 1 stats[k]['total_prompts'] += len(prompt_boxes) if len(bboxes) < k: stats[k]['insufficient_count'] += 1 # 构建 few-shot 数据结构 fewshot_data = { "image": image_path, "image_path": image_rel_path, "width": width, "height": height, "k": k, # 记录 k 值 "total_gt_boxes": len(bboxes), "prompt_boxes": prompt_boxes, # 用于 few-shot 的框 "all_boxes": bboxes, # 所有 GT 框(用于评估) "prompt_boxes_count": len(prompt_boxes), "remaining_boxes_count": len(remaining_boxes) } # 写入对应的文件 output_files[k].write(json.dumps(fewshot_data, ensure_ascii=False) + '\n') # 关闭所有文件 for f in output_files.values(): f.close() # 打印统计信息 print("\n" + "="*60) print("Few-shot 数据生成完成!") print("="*60) for k in k_values: print(f"\nK={k}:") print(f" - 总图片数: {stats[k]['total_images']}") print(f" - 总 prompt 框数: {stats[k]['total_prompts']}") print(f" - 平均 prompt 框数: {stats[k]['total_prompts']/stats[k]['total_images']:.2f}") print(f" - 框数不足 k 的图片数: {stats[k]['insufficient_count']}") print(f" - 输出文件: {output_dir}/fewshot_k{k}.jsonl") return stats def convert_to_conversation_format(fewshot_jsonl_path, output_conversation_path): """ 将 few-shot JSONL 转换为对话格式 """ with open(fewshot_jsonl_path, 'r', encoding='utf-8') as infile, \ open(output_conversation_path, 'w', encoding='utf-8') as outfile: for line in infile: data = json.loads(line.strip()) # 格式化 prompt boxes prompt_boxes_str = ", ".join([format_bbox_for_prompt(box['bbox']) for box in data['prompt_boxes']]) # 构建对话 conversation = { "image": data['image'], "conversations": [ { "from": "human", "value": f"Please detect all objects belonging to the same category as the boxes [{prompt_boxes_str}] in the image." }, { "from": "gpt", "value": json.dumps({ "category": data['all_boxes'][0]['category'] if data['all_boxes'] else "unknown", "bboxes": [box['bbox'] for box in data['all_boxes']] }) } ], "metadata": { "k": data['k'], "total_gt_boxes": data['total_gt_boxes'], "prompt_boxes_count": data['prompt_boxes_count'] } } outfile.write(json.dumps(conversation, ensure_ascii=False) + '\n') print(f"对话格式已保存到: {output_conversation_path}") def main(): # 输入文件路径 input_jsonl = "/home/disk2/hjl/ICL_QWEN/ICL_benchmark/dataset.jsonl" # 输出目录 output_dir = "/home/disk2/hjl/ICL_QWEN/ICL_benchmark/fewshot_data" # 生成 few-shot JSONL 文件(k=1,2,4) print("步骤1: 生成 few-shot 结构化数据...") stats = process_jsonl_for_fewshot(input_jsonl, output_dir, k_values=[1, 2, 4]) # 可选:转换为对话格式 print("\n步骤2: 转换为对话格式...") for k in [1, 2, 4]: fewshot_file = output_dir / f"fewshot_k{k}.jsonl" conversation_file = output_dir / f"conversation_k{k}.jsonl" if fewshot_file.exists(): convert_to_conversation_format(fewshot_file, conversation_file) print("\n所有处理完成!") if __name__ == "__main__": # 设置随机种子,保证可重复性 random.seed(42) main()