import json import os import datasets import jsonlines logger = datasets.logging.get_logger(__name__) _CITATION = """\ @misc{chen2024gpradar, title={GPRadar-Defect-MultiTask Dataset}, author={Chen, Xingqiang}, year={2024}, publisher={Hugging Face} } """ _DESCRIPTION = """\ GPRadar-Defect-MultiTask Dataset This dataset contains ground penetrating radar (GPR) images and annotations for defect detection and analysis, designed for training and evaluating multimodal models for GPR defect detection. The dataset includes both basic defect detection samples and a larger set of 874 annotated images from real-world structural inspections focusing on voids and cracks. """ _HOMEPAGE = "https://huggingface.co/datasets/xingqiang/GPRadar-Defect-MultiTask" class PaligemmaDataset(datasets.GeneratorBasedBuilder): """GPRadar-Defect-MultiTask Dataset for GPR defect detection and analysis.""" VERSION = datasets.Version("1.1.0") def _info(self): return datasets.DatasetInfo( description=_DESCRIPTION, features=datasets.Features({ "image": datasets.Image(), "boxes": datasets.Sequence(datasets.Sequence(datasets.Value("float32"), length=4)), "labels": datasets.Sequence(datasets.ClassLabel(names=["void", "crack"])), "caption": datasets.Value("string"), }), supervised_keys=None, homepage=_HOMEPAGE, citation=_CITATION, ) def _split_generators(self, dl_manager): """Returns SplitGenerators.""" return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={ "split": "train", }, ), datasets.SplitGenerator( name=datasets.Split.VALIDATION, gen_kwargs={ "split": "val", }, ), datasets.SplitGenerator( name=datasets.Split.TEST, gen_kwargs={ "split": "test", }, ), ] def _generate_examples(self, split): """Yields examples.""" # 统一格式的注释文件 annotation_file = f"annotations/{split}_unified.json" if not os.path.exists(annotation_file): # 如果统一格式文件不存在,尝试转换 convert_annotations_to_unified_format() # 再次检查文件是否已创建 if not os.path.exists(annotation_file): logger.warning(f"找不到统一格式注释文件: {annotation_file},将返回空数据") return # 加载统一格式的注释 with open(annotation_file, "r", encoding="utf-8") as f: annotations = json.load(f) for idx, ann in enumerate(annotations): # 尝试在不同的可能路径中查找图像 image_found = False image_filename = ann["image_filename"] for image_path in [ f"images/{split}/{image_filename}", f"images/datasets/{image_filename}", f"images/{image_filename}", ]: if os.path.exists(image_path): yield idx, { "image": image_path, "boxes": ann["boxes"], "labels": ann["labels"], "caption": ann["caption"], } image_found = True break if not image_found: logger.warning(f"找不到图像文件: {image_filename},跳过该示例") def normalize_image_path(image_path): """规范化图像路径,移除多余的前缀""" # 处理特殊前缀 if "p-1.v1i.paligemma-multimodal/dataset/" in image_path: return image_path.split("p-1.v1i.paligemma-multimodal/dataset/")[-1] return image_path def convert_annotations_to_unified_format(): """将所有注释转换为统一格式""" print("开始转换注释为统一格式...") # 确保annotations目录存在 os.makedirs("annotations", exist_ok=True) # 增加对valid分割的处理(有些文件使用valid而不是val) for split in ["train", "val", "valid", "test"]: print(f"处理 {split} 分割...") unified_annotations = [] # 处理 JSON 注释 json_path = f"annotations/{split}.json" print(f"检查 JSON 文件: {json_path}") if os.path.exists(json_path): print(f"找到 JSON 文件: {json_path}") with open(json_path, encoding="utf-8") as f: try: annotations = json.load(f) print(f"从 {json_path} 加载了 {len(annotations)} 条注释") for ann in annotations: unified_annotations.append({ "image_filename": ann["image_filename"], "boxes": ann["boxes"], "labels": ann["labels"], "caption": ann["caption"], "source": "original" }) except json.JSONDecodeError: print(f"错误: {json_path} 不是有效的 JSON 文件") else: print(f"未找到 JSON 文件: {json_path}") # 查找所有可能的JSONL注释文件 # 1. 检查根目录 jsonl_files_to_check = [ f"_annotations.{split}.jsonl", f"_annotations.{split}1.jsonl" ] # 2. 递归查找子目录中的JSONL文件 for root, dirs, files in os.walk("annotations"): for file in files: if file.endswith(f"{split}.jsonl") or file.endswith(f"{split}1.jsonl") or file.endswith(f"{split}2.jsonl"): rel_path = os.path.relpath(os.path.join(root, file), "annotations") if rel_path != file: # 不是根目录的文件 jsonl_files_to_check.append(rel_path) # 处理所有找到的JSONL文件 for jsonl_path in jsonl_files_to_check: full_path = os.path.join("annotations", jsonl_path) print(f"检查 JSONL 文件: {full_path}") if os.path.exists(full_path): print(f"找到 JSONL 文件: {full_path}") annotation_count = 0 with open(full_path, encoding="utf-8") as f: for line_num, line in enumerate(f, 1): try: line = line.strip() if not line: # 跳过空行 print(f"跳过第 {line_num} 行: 空行") continue ann = json.loads(line) image_filename = ann.get("image", "") if not image_filename: print(f"跳过第 {line_num} 行: 没有图像文件名") continue # 规范化图像路径 image_filename = normalize_image_path(image_filename) # 检查图像是否存在 image_exists = False possible_image_paths = [ f"images/datasets/{image_filename}", f"images/train/{image_filename}", f"images/val/{image_filename}", f"images/test/{image_filename}", f"images/{image_filename}" # 直接在images目录下 ] for img_path in possible_image_paths: if os.path.exists(img_path): image_exists = True break if not image_exists: print(f"警告: 图像文件不存在: {image_filename}") continue # 转换为统一格式 if "annotations" in ann: # 处理新格式 boxes = [[b["x"], b["y"], b["width"], b["height"]] for b in ann["annotations"]] labels = [0 if b["class"] == "void" else 1 for b in ann["annotations"]] caption = f"Image contains {len(boxes)} defects: " + \ ", ".join([b["class"] for b in ann["annotations"]]) else: # 处理旧格式 (prefix/suffix) boxes = [] labels = [] caption = ann.get("prefix", "") if "suffix" in ann: parts = ann["suffix"].split() for i, part in enumerate(parts): if "")]) coords.append(coord_value / 1024) # 归一化坐标 # 移除已处理的部分 loc_str = loc_str[loc_str.find(">")+1:] except (ValueError, IndexError): break if len(coords) == 4: boxes.append(coords) # 查找标签(通常在下一个部分) label_idx = 1 while i + label_idx < len(parts) and not parts[i + label_idx].startswith("