File size: 6,399 Bytes
2c986a2 | 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 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 | 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() |