xingqiang commited on
Commit
6e9bd3c
·
verified ·
1 Parent(s): b606c5d

Upload paligemma_dataset.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. paligemma_dataset.py +143 -175
paligemma_dataset.py CHANGED
@@ -1,16 +1,14 @@
1
  import json
2
  import os
3
- from pathlib import Path
4
-
5
  import datasets
6
- from PIL import Image
7
  import jsonlines
8
 
9
  logger = datasets.logging.get_logger(__name__)
10
 
11
  _CITATION = """\
12
- @misc{chen2024paligemma,
13
- title={PaliGemma Multitask Dataset},
14
  author={Chen, Xingqiang},
15
  year={2024},
16
  publisher={Hugging Face}
@@ -18,16 +16,18 @@ _CITATION = """\
18
  """
19
 
20
  _DESCRIPTION = """\
21
- This dataset contains images and annotations for defect detection and analysis,
22
- designed for training and evaluating the PaliGemma multitask model.
 
 
23
  The dataset includes both basic defect detection samples and a larger set of
24
- 874 annotated images from real-world structural inspections.
25
  """
26
 
27
- _HOMEPAGE = "https://huggingface.co/datasets/xingqiang/paligemma-multitask-dataset"
28
 
29
  class PaligemmaDataset(datasets.GeneratorBasedBuilder):
30
- """PaliGemma Multitask Dataset for defect detection and analysis."""
31
 
32
  VERSION = datasets.Version("1.1.0")
33
 
@@ -39,7 +39,6 @@ class PaligemmaDataset(datasets.GeneratorBasedBuilder):
39
  "boxes": datasets.Sequence(datasets.Sequence(datasets.Value("float32"), length=4)),
40
  "labels": datasets.Sequence(datasets.ClassLabel(names=["void", "crack"])),
41
  "caption": datasets.Value("string"),
42
- "source": datasets.Value("string"),
43
  }),
44
  supervised_keys=None,
45
  homepage=_HOMEPAGE,
@@ -70,121 +69,54 @@ class PaligemmaDataset(datasets.GeneratorBasedBuilder):
70
  ]
71
 
72
  def _generate_examples(self, split):
73
- """生成示例。"""
74
- # 优先加载统一格式的注释
75
- unified_path = os.path.join("annotations", f"{split}_unified.json")
76
- if os.path.exists(unified_path):
77
- logger.info(f"使用统一格式的注释文件: {unified_path}")
78
- with open(unified_path, encoding="utf-8") as f:
79
- annotations = json.load(f)
80
- for idx, ann in enumerate(annotations):
81
- image_path = os.path.join("images", split, ann["image_filename"])
82
- try:
83
- yield f"unified_{idx}", {
84
- "image": image_path,
85
- "boxes": ann["boxes"],
86
- "labels": ann["labels"],
87
- "caption": ann["caption"],
88
- "source": ann.get("source", "unified")
89
- }
90
- except Exception as e:
91
- logger.warning(f"跳过无效图像 {image_path}: {e}")
92
- continue
93
- return # 如果使用了统一格式,不再处理其他格式
94
 
95
- # 如果没有统一格式,则回退到原始格式
96
- # 加载原始 JSON 注释
97
- json_path = os.path.join("annotations", f"{split}.json")
98
- if os.path.exists(json_path):
99
- with open(json_path, encoding="utf-8") as f:
100
- annotations = json.load(f)
101
- for idx, ann in enumerate(annotations):
102
- image_path = os.path.join("images", split, ann["image_filename"])
103
- try:
104
- # 不要尝试在这里打开图像,只返回路径
105
- yield f"orig_{idx}", {
106
- "image": image_path,
107
- "boxes": ann["boxes"],
108
- "labels": ann["labels"],
109
- "caption": ann["caption"],
110
- "source": "original"
111
- }
112
- except Exception as e:
113
- logger.warning(f"跳过无效图像 {image_path}: {e}")
114
- continue
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
 
116
- # 加载 JSONL 注释
117
- jsonl_path = os.path.join("annotations", f"_annotations.{split}.jsonl")
118
- if os.path.exists(jsonl_path):
119
- with jsonlines.open(jsonl_path) as reader:
120
- for idx, ann in enumerate(reader):
121
- # 确保使用正确的图像文件名
122
- image_filename = ann.get("image", "")
123
- image_path = os.path.join("images", split, image_filename)
124
-
125
- try:
126
- # 不要尝试在这里打开图像,只返回路径
127
- # 转换注释为我们的格式
128
- if "annotations" in ann:
129
- # 处理新格式
130
- boxes = [[b["x"], b["y"], b["width"], b["height"]] for b in ann["annotations"]]
131
- labels = [0 if b["class"] == "void" else 1 for b in ann["annotations"]]
132
- caption = f"Image contains {len(boxes)} defects: " + \
133
- ", ".join([b["class"] for b in ann["annotations"]])
134
- else:
135
- # 处理旧格式 (prefix/suffix)
136
- # 这里需要解析 suffix 中的位置信息
137
- boxes = []
138
- labels = []
139
- if "suffix" in ann:
140
- parts = ann["suffix"].split(";")
141
- for part in parts:
142
- part = part.strip()
143
- if "<loc" in part:
144
- # 解析位置和标签
145
- loc_parts = part.split()
146
- if len(loc_parts) >= 2:
147
- # 提取坐标
148
- coords = []
149
- for loc in loc_parts[0].split("><"):
150
- if loc.startswith("<loc"):
151
- coords.append(int(loc[4:-1]) / 1024) # 归一化坐标
152
-
153
- if len(coords) == 4:
154
- boxes.append(coords)
155
- label = 0 if "void" in loc_parts[1] else 1
156
- labels.append(label)
157
-
158
- caption = ann.get("prefix", "")
159
-
160
- # 检查图像是否存在
161
- image_exists = False
162
-
163
- # 检查images/datasets目录
164
- if os.path.exists(f"images/datasets/{image_filename}"):
165
- image_exists = True
166
-
167
- # 检查原始路径
168
- if not image_exists:
169
- for img_split in ["train", "val", "test"]:
170
- if os.path.exists(f"images/{img_split}/{image_filename}"):
171
- image_exists = True
172
- break
173
-
174
- if not image_exists:
175
- print(f"警告: 图像文件不存在: {image_filename}")
176
- continue
177
-
178
- yield f"p1v1_{idx}", {
179
- "image": image_path,
180
- "boxes": boxes,
181
- "labels": labels,
182
- "caption": caption,
183
- "source": "p1v1"
184
- }
185
- except Exception as e:
186
- logger.warning(f"跳过��效注释 {image_path}: {e}")
187
- continue
188
 
189
  def convert_annotations_to_unified_format():
190
  """将所有注释转换为统一格式"""
@@ -220,21 +152,29 @@ def convert_annotations_to_unified_format():
220
  else:
221
  print(f"未找到 JSON 文件: {json_path}")
222
 
223
- # 处理 JSONL 注释,包括目录p-1.v1i.paligemma下的文件
224
- jsonl_variants = [
 
225
  f"_annotations.{split}.jsonl",
226
- f"_annotations.{split}1.jsonl",
227
- f"p-1.v1i.paligemma/_annotations.{split}.jsonl",
228
- f"p-1.v1i.paligemma/_annotations.{split}1.jsonl"
229
  ]
230
 
231
- for jsonl_variant in jsonl_variants:
232
- jsonl_path = f"annotations/{jsonl_variant}"
233
- print(f"检查 JSONL 文件: {jsonl_path}")
234
- if os.path.exists(jsonl_path):
235
- print(f"找到 JSONL 文件: {jsonl_path}")
 
 
 
 
 
 
 
 
 
236
  annotation_count = 0
237
- with open(jsonl_path, encoding="utf-8") as f:
238
  for line_num, line in enumerate(f, 1):
239
  try:
240
  line = line.strip()
@@ -248,20 +188,24 @@ def convert_annotations_to_unified_format():
248
  if not image_filename:
249
  print(f"跳过第 {line_num} 行: 没有图像文件名")
250
  continue
 
 
 
251
 
252
  # 检查图像是否存在
253
  image_exists = False
 
 
 
 
 
 
 
254
 
255
- # 检查images/datasets目录
256
- if os.path.exists(f"images/datasets/{image_filename}"):
257
- image_exists = True
258
-
259
- # 检查原始路径
260
- if not image_exists:
261
- for img_split in ["train", "val", "test"]:
262
- if os.path.exists(f"images/{img_split}/{image_filename}"):
263
- image_exists = True
264
- break
265
 
266
  if not image_exists:
267
  print(f"警告: 图像文件不存在: {image_filename}")
@@ -281,26 +225,39 @@ def convert_annotations_to_unified_format():
281
  caption = ann.get("prefix", "")
282
 
283
  if "suffix" in ann:
284
- parts = ann["suffix"].split(";")
285
- for part in parts:
286
- part = part.strip()
287
  if "<loc" in part:
288
- # 解析位置和标签
289
- loc_parts = part.split()
290
- if len(loc_parts) >= 2:
291
- # 提取坐标
292
- coords = []
293
- for loc in loc_parts[0].split("><"):
294
- if loc.startswith("<loc"):
295
- try:
296
- coords.append(int(loc[4:-1]) / 1024) # 归一化坐标
297
- except ValueError:
298
- continue
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
299
 
300
- if len(coords) == 4:
301
- boxes.append(coords)
302
- label = 0 if "void" in loc_parts[1] else 1
303
- labels.append(label)
304
 
305
  unified_annotations.append({
306
  "image_filename": image_filename,
@@ -311,22 +268,33 @@ def convert_annotations_to_unified_format():
311
  })
312
  annotation_count += 1
313
  except json.JSONDecodeError as e:
314
- print(f"警告: {jsonl_path} 第 {line_num} 行不是有效的 JSON: {e}")
315
  continue
316
- print(f"从 {jsonl_path} 加载了 {annotation_count} 条注释")
317
  else:
318
- print(f"未找到 JSONL 文件: {jsonl_path}")
319
 
320
  # 如果是valid分割,与val合并
321
- if split == "valid" and os.path.exists(f"annotations/val_unified.json"):
322
- try:
323
- with open(f"annotations/val_unified.json", "r", encoding="utf-8") as f:
324
- val_annotations = json.load(f)
325
- unified_annotations.extend(val_annotations)
326
- print(f"将valid分割与val分割合并,共 {len(unified_annotations)} 条记录")
327
- except Exception as e:
328
- print(f"合并valid和val分割时出错: {e}")
329
-
 
 
 
 
 
 
 
 
 
 
 
330
  # 保存统一格式的注释
331
  if unified_annotations:
332
  # 对于valid分割,保存为val_unified.json
 
1
  import json
2
  import os
 
 
3
  import datasets
4
+
5
  import jsonlines
6
 
7
  logger = datasets.logging.get_logger(__name__)
8
 
9
  _CITATION = """\
10
+ @misc{chen2024gpradar,
11
+ title={GPRadar-Defect-MultiTask Dataset},
12
  author={Chen, Xingqiang},
13
  year={2024},
14
  publisher={Hugging Face}
 
16
  """
17
 
18
  _DESCRIPTION = """\
19
+ GPRadar-Defect-MultiTask Dataset
20
+
21
+ This dataset contains ground penetrating radar (GPR) images and annotations for defect detection and analysis,
22
+ designed for training and evaluating multimodal models for GPR defect detection.
23
  The dataset includes both basic defect detection samples and a larger set of
24
+ 874 annotated images from real-world structural inspections focusing on voids and cracks.
25
  """
26
 
27
+ _HOMEPAGE = "https://huggingface.co/datasets/xingqiang/GPRadar-Defect-MultiTask"
28
 
29
  class PaligemmaDataset(datasets.GeneratorBasedBuilder):
30
+ """GPRadar-Defect-MultiTask Dataset for GPR defect detection and analysis."""
31
 
32
  VERSION = datasets.Version("1.1.0")
33
 
 
39
  "boxes": datasets.Sequence(datasets.Sequence(datasets.Value("float32"), length=4)),
40
  "labels": datasets.Sequence(datasets.ClassLabel(names=["void", "crack"])),
41
  "caption": datasets.Value("string"),
 
42
  }),
43
  supervised_keys=None,
44
  homepage=_HOMEPAGE,
 
69
  ]
70
 
71
  def _generate_examples(self, split):
72
+ """Yields examples."""
73
+ # 统一格式的注释文件
74
+ annotation_file = f"annotations/{split}_unified.json"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
+ if not os.path.exists(annotation_file):
77
+ # 如果统一格式文件不存在,尝试转换
78
+ convert_annotations_to_unified_format()
79
+
80
+ # 再次检查文件是否已创建
81
+ if not os.path.exists(annotation_file):
82
+ logger.warning(f"找不到统一格式注释文件: {annotation_file},将返回空数据")
83
+ return
84
+
85
+ # 加载统一格式的注释
86
+ with open(annotation_file, "r", encoding="utf-8") as f:
87
+ annotations = json.load(f)
88
+
89
+ for idx, ann in enumerate(annotations):
90
+ # 尝试在不同的可能路径中查找图���
91
+ image_found = False
92
+ image_filename = ann["image_filename"]
93
+
94
+ for image_path in [
95
+ f"images/{split}/{image_filename}",
96
+ f"images/datasets/{image_filename}",
97
+ f"images/{image_filename}",
98
+ ]:
99
+ if os.path.exists(image_path):
100
+ yield idx, {
101
+ "image": image_path,
102
+ "boxes": ann["boxes"],
103
+ "labels": ann["labels"],
104
+ "caption": ann["caption"],
105
+ }
106
+ image_found = True
107
+ break
108
+
109
+ if not image_found:
110
+ logger.warning(f"找不到图像文件: {image_filename},跳过该示例")
111
+
112
+
113
+ def normalize_image_path(image_path):
114
+ """规范化图像路径,移除多余的前缀"""
115
+ # 处理特殊前缀
116
+ if "p-1.v1i.paligemma-multimodal/dataset/" in image_path:
117
+ return image_path.split("p-1.v1i.paligemma-multimodal/dataset/")[-1]
118
+ return image_path
119
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
 
121
  def convert_annotations_to_unified_format():
122
  """将所有注释转换为统一格式"""
 
152
  else:
153
  print(f"未找到 JSON 文件: {json_path}")
154
 
155
+ # 查找所有可能的JSONL注释文件
156
+ # 1. 检查根目录
157
+ jsonl_files_to_check = [
158
  f"_annotations.{split}.jsonl",
159
+ f"_annotations.{split}1.jsonl"
 
 
160
  ]
161
 
162
+ # 2. 递归查找子目录中的JSONL文件
163
+ for root, dirs, files in os.walk("annotations"):
164
+ for file in files:
165
+ if file.endswith(f"{split}.jsonl") or file.endswith(f"{split}1.jsonl") or file.endswith(f"{split}2.jsonl"):
166
+ rel_path = os.path.relpath(os.path.join(root, file), "annotations")
167
+ if rel_path != file: # 不是根目录的文件
168
+ jsonl_files_to_check.append(rel_path)
169
+
170
+ # 处理所有找到的JSONL文件
171
+ for jsonl_path in jsonl_files_to_check:
172
+ full_path = os.path.join("annotations", jsonl_path)
173
+ print(f"检查 JSONL 文件: {full_path}")
174
+ if os.path.exists(full_path):
175
+ print(f"找到 JSONL 文件: {full_path}")
176
  annotation_count = 0
177
+ with open(full_path, encoding="utf-8") as f:
178
  for line_num, line in enumerate(f, 1):
179
  try:
180
  line = line.strip()
 
188
  if not image_filename:
189
  print(f"跳过第 {line_num} 行: 没有图像文件名")
190
  continue
191
+
192
+ # 规范化图像路径
193
+ image_filename = normalize_image_path(image_filename)
194
 
195
  # 检查图像是否存在
196
  image_exists = False
197
+ possible_image_paths = [
198
+ f"images/datasets/{image_filename}",
199
+ f"images/train/{image_filename}",
200
+ f"images/val/{image_filename}",
201
+ f"images/test/{image_filename}",
202
+ f"images/{image_filename}" # 直接在images目录下
203
+ ]
204
 
205
+ for img_path in possible_image_paths:
206
+ if os.path.exists(img_path):
207
+ image_exists = True
208
+ break
 
 
 
 
 
 
209
 
210
  if not image_exists:
211
  print(f"警告: 图像文件不存在: {image_filename}")
 
225
  caption = ann.get("prefix", "")
226
 
227
  if "suffix" in ann:
228
+ parts = ann["suffix"].split()
229
+ for i, part in enumerate(parts):
 
230
  if "<loc" in part:
231
+ # 解析位置
232
+ coords = []
233
+ loc_str = part
234
+ while loc_str.startswith("<loc") and len(coords) < 4:
235
+ try:
236
+ # 提取坐标
237
+ coord_value = int(loc_str[4:loc_str.find(">")])
238
+ coords.append(coord_value / 1024) # 归一化坐标
239
+ # 移除已处理的部分
240
+ loc_str = loc_str[loc_str.find(">")+1:]
241
+ except (ValueError, IndexError):
242
+ break
243
+
244
+ if len(coords) == 4:
245
+ boxes.append(coords)
246
+ # 查找标签(通常在下一个部分)
247
+ label_idx = 1
248
+ while i + label_idx < len(parts) and not parts[i + label_idx].startswith("<loc"):
249
+ label_text = parts[i + label_idx]
250
+ if "void" in label_text:
251
+ labels.append(0)
252
+ break
253
+ elif "crack" in label_text:
254
+ labels.append(1)
255
+ break
256
+ label_idx += 1
257
 
258
+ # 如果未找到特定标签,默认为void
259
+ if len(labels) < len(boxes):
260
+ labels.append(0)
 
261
 
262
  unified_annotations.append({
263
  "image_filename": image_filename,
 
268
  })
269
  annotation_count += 1
270
  except json.JSONDecodeError as e:
271
+ print(f"警告: {full_path} 第 {line_num} 行不是有效的 JSON: {e}")
272
  continue
273
+ print(f"从 {full_path} 加载了 {annotation_count} 条注释")
274
  else:
275
+ print(f"未找到 JSONL 文件: {full_path}")
276
 
277
  # 如果是valid分割,与val合并
278
+ if split == "valid":
279
+ val_annotations = []
280
+ if os.path.exists(f"annotations/val_unified.json"):
281
+ try:
282
+ with open(f"annotations/val_unified.json", "r", encoding="utf-8") as f:
283
+ val_annotations = json.load(f)
284
+ print(f"加载现有val分割注释,共 {len(val_annotations)} 条记录")
285
+
286
+ # 合并注释,避免重复
287
+ existing_filenames = {ann["image_filename"] for ann in val_annotations}
288
+ for ann in unified_annotations:
289
+ if ann["image_filename"] not in existing_filenames:
290
+ val_annotations.append(ann)
291
+ existing_filenames.add(ann["image_filename"])
292
+
293
+ print(f"将valid分割与val分割合并,共 {len(val_annotations)} 条记录")
294
+ unified_annotations = val_annotations
295
+ except Exception as e:
296
+ print(f"合并valid和val分割时出错: {e}")
297
+
298
  # 保存统一格式的注释
299
  if unified_annotations:
300
  # 对于valid分割,保存为val_unified.json