File size: 2,774 Bytes
4863c9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
修复多图数据集,为第一个用户消息添加 <image> token
"""

import json
import os
from pathlib import Path

def fix_multi_image_data(input_file, output_file):
    """
    修复多图数据集,在第一个用户消息前添加相应数量的 <image> token
    
    Args:
        input_file: 原始数据文件路径
        output_file: 输出文件路径
    """
    print(f"正在处理文件: {input_file}")
    
    # 读取原始数据
    with open(input_file, 'r', encoding='utf-8') as f:
        data = json.load(f)
    
    print(f"总样本数: {len(data)}")
    
    # 处理每个样本
    for i, sample in enumerate(data):
        # 获取图片数量
        num_images = len(sample['images'])
        
        # 生成 <image> token 字符串
        image_tokens = '<image>' * num_images
        
        # 找到第一个用户消息并添加 <image> token
        conversations = sample['conversations']
        for j, conv in enumerate(conversations):
            if conv['from'] == 'human':
                # 在第一个用户消息前添加图片token
                original_value = conv['value']
                conv['value'] = f"{image_tokens}\n{original_value}"
                break
        
        # 进度显示
        if (i + 1) % 1000 == 0:
            print(f"已处理: {i + 1}/{len(data)} 样本")
    
    # 保存修改后的数据
    print(f"保存到: {output_file}")
    with open(output_file, 'w', encoding='utf-8') as f:
        json.dump(data, f, indent=2, ensure_ascii=False)
    
    print("处理完成!")
    
    # 显示示例
    print("\n处理后的示例:")
    sample = data[0]
    print(f"图片数量: {len(sample['images'])}")
    print(f"第一个用户消息: {sample['conversations'][0]['value'][:100]}...")

def main():
    # 定义文件路径
    base_dir = Path(__file__).parent
    
    # 处理训练集
    train_input = base_dir / "data_train_multi_llava_vasevl_v6.json"
    train_output = base_dir / "data_train_multi_llava_vasevl_v6_fixed.json"
    
    # 处理测试集
    test_input = base_dir / "data_test_multi_llava_vasevl_v6.json"
    test_output = base_dir / "data_test_multi_llava_vasevl_v6_fixed.json"
    
    print("开始处理多图数据集...")
    print("=" * 50)
    
    # 处理训练集
    if train_input.exists():
        fix_multi_image_data(train_input, train_output)
        print()
    else:
        print(f"训练集文件不存在: {train_input}")
    
    # 处理测试集
    if test_input.exists():
        fix_multi_image_data(test_input, test_output)
    else:
        print(f"测试集文件不存在: {test_input}")
    
    print("=" * 50)
    print("所有文件处理完成!")

if __name__ == "__main__":
    main()