xingqiang commited on
Commit
bcb5616
·
verified ·
1 Parent(s): e81d809

Upload paligemma_dataset.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. paligemma_dataset.py +340 -0
paligemma_dataset.py ADDED
@@ -0,0 +1,340 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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}
17
+ }
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
+
34
+ def _info(self):
35
+ return datasets.DatasetInfo(
36
+ description=_DESCRIPTION,
37
+ features=datasets.Features({
38
+ "image": datasets.Image(),
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,
46
+ citation=_CITATION,
47
+ )
48
+
49
+ def _split_generators(self, dl_manager):
50
+ """Returns SplitGenerators."""
51
+ return [
52
+ datasets.SplitGenerator(
53
+ name=datasets.Split.TRAIN,
54
+ gen_kwargs={
55
+ "split": "train",
56
+ },
57
+ ),
58
+ datasets.SplitGenerator(
59
+ name=datasets.Split.VALIDATION,
60
+ gen_kwargs={
61
+ "split": "val",
62
+ },
63
+ ),
64
+ datasets.SplitGenerator(
65
+ name=datasets.Split.TEST,
66
+ gen_kwargs={
67
+ "split": "test",
68
+ },
69
+ ),
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
+ """将所有注释转换为统一格式"""
191
+ print("开始转换注释为统一格式...")
192
+
193
+ # 确保annotations目录存在
194
+ os.makedirs("annotations", exist_ok=True)
195
+
196
+ # 增加对valid分割的处理(有些文件使用valid而不是val)
197
+ for split in ["train", "val", "valid", "test"]:
198
+ print(f"处理 {split} 分割...")
199
+ unified_annotations = []
200
+
201
+ # 处理 JSON 注释
202
+ json_path = f"annotations/{split}.json"
203
+ print(f"检查 JSON 文件: {json_path}")
204
+ if os.path.exists(json_path):
205
+ print(f"找到 JSON 文件: {json_path}")
206
+ with open(json_path, encoding="utf-8") as f:
207
+ try:
208
+ annotations = json.load(f)
209
+ print(f"从 {json_path} 加载了 {len(annotations)} 条注释")
210
+ for ann in annotations:
211
+ unified_annotations.append({
212
+ "image_filename": ann["image_filename"],
213
+ "boxes": ann["boxes"],
214
+ "labels": ann["labels"],
215
+ "caption": ann["caption"],
216
+ "source": "original"
217
+ })
218
+ except json.JSONDecodeError:
219
+ print(f"错误: {json_path} 不是有效的 JSON 文件")
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()
241
+ if not line: # 跳过空行
242
+ print(f"跳过第 {line_num} 行: 空行")
243
+ continue
244
+
245
+ ann = json.loads(line)
246
+ image_filename = ann.get("image", "")
247
+
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}")
268
+ continue
269
+
270
+ # 转换为统一格式
271
+ if "annotations" in ann:
272
+ # 处理新格式
273
+ boxes = [[b["x"], b["y"], b["width"], b["height"]] for b in ann["annotations"]]
274
+ labels = [0 if b["class"] == "void" else 1 for b in ann["annotations"]]
275
+ caption = f"Image contains {len(boxes)} defects: " + \
276
+ ", ".join([b["class"] for b in ann["annotations"]])
277
+ else:
278
+ # 处理旧格式 (prefix/suffix)
279
+ boxes = []
280
+ labels = []
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,
307
+ "boxes": boxes,
308
+ "labels": labels,
309
+ "caption": caption,
310
+ "source": "p1v1"
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
333
+ save_split = "val" if split == "valid" else split
334
+ print(f"为 {save_split} 创建统一格式注释,共 {len(unified_annotations)} 条记录")
335
+ unified_path = f"annotations/{save_split}_unified.json"
336
+ with open(unified_path, "w", encoding="utf-8") as f:
337
+ json.dump(unified_annotations, f, ensure_ascii=False, indent=2)
338
+ print(f"已保存统一格式注释到: {unified_path}")
339
+ else:
340
+ print(f"警告: {split} 没有有效的注释,跳过创建统一格式文件")