File size: 6,236 Bytes
f706a86 |
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 170 171 |
import json
import os
from pathlib import Path
from tqdm import tqdm
def check_json_data(json_file_path, images_root_dir):
"""检查JSON数据的完整性 - 只过滤有image字段但图像不存在的数据"""
# 加载JSON文件
try:
with open(json_file_path, 'r', encoding='utf-8') as f:
data = json.load(f)
except Exception as e:
print(f"加载JSON文件失败: {e}")
return []
anomalous_data = []
total_entries = len(data)
print(f"开始检查 {total_entries} 条数据...")
for i, entry in enumerate(tqdm(data, desc="检查图像文件", unit="条")):
issues = []
# 只检查image字段相关的问题
if 'image' in entry:
image_path = entry['image']
# if not image_path or image_path.strip() == '':
# issues.append("图像路径为空")
# else:
# # 检查图像文件是否存在
# if images_root_dir:
# # 构建完整的图像文件路径
# full_image_path = Path(images_root_dir) / image_path
# else:
# full_image_path = Path(json_file_path).parent / image_path
# if not full_image_path.exists():
# issues.append(f"图像文件不存在: {image_path}")
if len(image_path) == 0:
issues.append("图像路径为空")
else:
for img in image_path:
if not Path(img).exists():
issues.append(f"图像文件不存在: {img}")
# 如果有问题,记录异常数据
if issues:
anomalous_entry = {
'index': i,
'id': entry.get('id', 'Unknown'),
'image': entry.get('image', 'N/A'),
'entry': entry,
'issues': issues
}
anomalous_data.append(anomalous_entry)
return anomalous_data
def save_valid_data(json_file_path, anomalous_data, output_file='filtered_data.json'):
"""保存过滤后的有效数据"""
# 加载原始数据
with open(json_file_path, 'r', encoding='utf-8') as f:
original_data = json.load(f)
# 获取异常数据的索引
anomalous_indices = {anomaly['index'] for anomaly in anomalous_data}
# 过滤出有效数据
valid_data = [entry for i, entry in enumerate(original_data) if i not in anomalous_indices]
# 保存有效数据
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(valid_data, f, indent=2, ensure_ascii=False)
print(f"过滤后的有效数据已保存到: {output_file}")
print(f"原始数据: {len(original_data)} 条")
print(f"有效数据: {len(valid_data)} 条")
print(f"过滤掉: {len(anomalous_data)} 条")
def save_anomalous_data(anomalous_data, output_file='anomalous_data.json'):
"""保存异常数据到文件"""
if anomalous_data:
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(anomalous_data, f, indent=2, ensure_ascii=False)
print(f"异常数据已保存到: {output_file}")
else:
print("没有异常数据需要保存")
def print_statistics(json_file_path, anomalous_data):
"""打印统计信息"""
with open(json_file_path, 'r', encoding='utf-8') as f:
data = json.load(f)
total_entries = len(data)
anomalous_count = len(anomalous_data)
print(f"\n=== 数据统计 ===")
print(f"总条目数: {total_entries}")
print(f"图像异常条目数: {anomalous_count}")
print(f"有效条目数: {total_entries - anomalous_count}")
print(f"数据有效率: {((total_entries - anomalous_count) / total_entries * 100):.2f}%")
# 字段存在统计
fields_stats = {
'id': sum(1 for entry in data if 'id' in entry),
'image': sum(1 for entry in data if 'image' in entry),
'conversations': sum(1 for entry in data if 'conversations' in entry)
}
print(f"\n=== 字段存在统计 ===")
for field, count in fields_stats.items():
print(f"包含'{field}'字段的条目: {count}/{total_entries} ({count/total_entries*100:.1f}%)")
# 主执行函数
def main():
json_file = 'train_data_processed.json'
images_root_dir = 'images'
# 检查文件是否存在
if not os.path.exists(json_file):
print(f"文件不存在: {json_file}")
return
# 检查数据
anomalous_data = check_json_data(json_file, images_root_dir)
# 输出结果
if anomalous_data:
print(f"\n发现 {len(anomalous_data)} 条图像异常数据:")
print("=" * 50)
# 只显示前10条异常数据,避免输出过多
for anomaly in anomalous_data[:10]:
print(f"索引: {anomaly['index']}")
print(f"ID: {anomaly['id']}")
print(f"图像: {anomaly['image']}")
print(f"问题: {', '.join(anomaly['issues'])}")
print("-" * 30)
if len(anomalous_data) > 10:
print(f"... 还有 {len(anomalous_data) - 10} 条异常数据")
# 保存异常数据
# save_anomalous_data(anomalous_data)
# 保存过滤后的有效数据
# save_valid_data(json_file, anomalous_data)
# 按问题类型统计
issue_counts = {}
for anomaly in anomalous_data:
for issue in anomaly['issues']:
issue_type = issue.split(':')[0] if ':' in issue else issue
issue_counts[issue_type] = issue_counts.get(issue_type, 0) + 1
print(f"\n=== 问题类型统计 ===")
for issue_type, count in sorted(issue_counts.items()):
print(f"{issue_type}: {count}次")
else:
print("✅ 所有数据的图像文件都正常!")
# 即使没有异常数据,也保存一份完整的数据
# save_valid_data(json_file, anomalous_data, 'filtered_filtered_data.json')
# 打印统计信息
print_statistics(json_file, anomalous_data)
if __name__ == "__main__":
main()
|