Sneriko commited on
Commit
5525d1a
·
verified ·
1 Parent(s): 2c4fade

Upload folder using huggingface_hub

Browse files
data/images/gota_hovratt_seg_images_1.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9a637136606a5cee4444c740b93532cfc36d72940946dac134226e98fb6a33e3
3
+ size 31154588
data/images/gota_hovratt_seg_images_2.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2e0e7c2a833c71fee0c23cf516b1f24182d8944ebb3839e0aafcaa2a2488b594
3
+ size 32800277
data/page_xmls/gota_hovratt_seg_page_xmls_1.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5694aaa69919191f4a558dde5a39d2c909548105a0f7e1d64e5ca6a7e2366a33
3
+ size 396053
data/page_xmls/gota_hovratt_seg_page_xmls_2.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:83bd7462eae5efbb55673fd947ea7586fd7b4d4f84d950b1cb319eba9bd4334c
3
+ size 438574
gota_hovratt_seg.py ADDED
@@ -0,0 +1,483 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import os
3
+ import xml.etree.ElementTree as ET
4
+ from glob import glob
5
+ from pathlib import Path, PurePath
6
+
7
+ import cv2
8
+ import numpy as np
9
+ from datasets import (
10
+ BuilderConfig,
11
+ DatasetInfo,
12
+ Features,
13
+ GeneratorBasedBuilder,
14
+ Image,
15
+ Sequence,
16
+ Split,
17
+ SplitGenerator,
18
+ Value,
19
+ )
20
+ from PIL import Image as PILImage
21
+ from shapely.geometry import Polygon
22
+
23
+
24
+ class HTRDatasetConfig(BuilderConfig):
25
+ """Configuration for each dataset variant."""
26
+
27
+ def __init__(self, name, description, process_func, features, **kwargs):
28
+ super().__init__(name=name, description=description, **kwargs)
29
+ self.process_func = process_func
30
+ self.features = features
31
+
32
+
33
+ class HTRDataset(GeneratorBasedBuilder):
34
+ # Define feature structures for each dataset type
35
+ text_recognition_features = Features(
36
+ {
37
+ "image": Image(),
38
+ "transcription": Value("string"),
39
+ }
40
+ )
41
+
42
+ segmentation_features = Features(
43
+ {
44
+ "image_name": Value("string"),
45
+ "image": Image(),
46
+ "annotations": Sequence(
47
+ {
48
+ "polygon": Sequence(Sequence(Value("float32"))),
49
+ "transcription": Value("string"),
50
+ "class": Value("string"),
51
+ }
52
+ ),
53
+ }
54
+ )
55
+
56
+ BUILDER_CONFIGS = [
57
+ HTRDatasetConfig(
58
+ name="text_recognition",
59
+ description="textline dataset for text recognition of historical Swedish",
60
+ process_func="text_recognition",
61
+ features=text_recognition_features,
62
+ ),
63
+ HTRDatasetConfig(
64
+ name="inst_seg_lines_within_regions",
65
+ description="Cropped text region images with text line annotations",
66
+ process_func="inst_seg_lines_within_regions",
67
+ features=segmentation_features,
68
+ ),
69
+ HTRDatasetConfig(
70
+ name="inst_seg_regions_and_lines",
71
+ description="Original images with both region and line annotations",
72
+ process_func="inst_seg_regions_and_lines",
73
+ features=segmentation_features,
74
+ ),
75
+ HTRDatasetConfig(
76
+ name="inst_seg_lines",
77
+ description="Original images with text line annotations only",
78
+ process_func="inst_seg_lines",
79
+ features=segmentation_features,
80
+ ),
81
+ HTRDatasetConfig(
82
+ name="inst_seg_regions",
83
+ description="Original images with text region annotations only",
84
+ process_func="inst_seg_regions",
85
+ features=segmentation_features,
86
+ ),
87
+ ]
88
+
89
+ def _info(self):
90
+ return DatasetInfo(features=self.config.features)
91
+
92
+ def _split_generators(self, dl_manager):
93
+ # Define URLs for images and XMLs
94
+ """
95
+ images_url = [
96
+ f"https://huggingface.co/datasets/Riksarkivet/ra_enstaka_sidor/resolve/main/data/images/ra_enstaka_sidor_images_{i}.tar.gz"
97
+ for i in range(1, 3)
98
+ ]
99
+ xmls_url = [
100
+ f"https://huggingface.co/datasets/Riksarkivet/ra_enstaka_sidor/resolve/main/data/page_xmls/ra_enstaka_sidor_page_xmls_{i}.tar.gz"
101
+ for i in range(1, 3)
102
+ ]
103
+
104
+ """
105
+
106
+ images = dl_manager.download_and_extract(
107
+ [
108
+ f"https://huggingface.co/datasets/Riksarkivet/gota_hovratt_seg/resolve/main/data/images/gota_hovratt_seg_images_{i}.tar.gz"
109
+ for i in range(1, 3)
110
+ ]
111
+ )
112
+ xmls = dl_manager.download_and_extract(
113
+ [
114
+ f"https://huggingface.co/datasets/Riksarkivet/gota_hovratt_seg/resolve/main/data/page_xmls/gota_hovratt_seg_page_xmls_{i}.tar.gz"
115
+ for i in range(1, 3)
116
+ ]
117
+ )
118
+
119
+ # Download and extract images and XMLs
120
+ # images = dl_manager.download_and_extract(images_url)
121
+ # xmls = dl_manager.download_and_extract(xmls_url)
122
+
123
+ # Define supported image file extensions
124
+ image_extensions = [
125
+ "*.jpg",
126
+ "*.jpeg",
127
+ "*.png",
128
+ "*.gif",
129
+ "*.bmp",
130
+ "*.tif",
131
+ "*.tiff",
132
+ "*.JPG",
133
+ "*.JPEG",
134
+ "*.PNG",
135
+ "*.GIF",
136
+ "*.BMP",
137
+ "*.TIF",
138
+ "*.TIFF",
139
+ ]
140
+
141
+ # Collect and sort image and XML file paths
142
+ imgs_flat = self._collect_file_paths(images, image_extensions)
143
+ xmls_flat = self._collect_file_paths(xmls, ["*.xml"])
144
+
145
+ # Ensure the number of images matches the number of XML files
146
+ assert len(imgs_flat) == len(xmls_flat)
147
+
148
+ # Pair images and XML files
149
+ imgs_xmls = list(
150
+ zip(sorted(imgs_flat, key=lambda x: Path(x).stem), sorted(xmls_flat, key=lambda x: Path(x).stem))
151
+ )
152
+
153
+ return [
154
+ SplitGenerator(
155
+ name=Split.TRAIN,
156
+ gen_kwargs={"imgs_xmls": imgs_xmls},
157
+ )
158
+ ]
159
+
160
+ def _collect_file_paths(self, folders, extensions):
161
+ """Collects file paths recursively from specified folders."""
162
+ files_nested = [
163
+ glob(os.path.join(folder, "**", ext), recursive=True) for ext in extensions for folder in folders
164
+ ]
165
+ return [file for sublist in files_nested for file in sublist]
166
+
167
+ def _generate_examples(self, imgs_xmls):
168
+ process_func = getattr(self, self.config.process_func)
169
+ return process_func(imgs_xmls)
170
+
171
+ def text_recognition(self, imgs_xmls):
172
+ """Process for line dataset with cropped images and transcriptions."""
173
+ for img, xml in imgs_xmls:
174
+ img_filename, volume = self._extract_filename_and_volume(img, xml)
175
+ lines_data = self.parse_pagexml(xml)
176
+ image_array = cv2.imread(img)
177
+
178
+ for i, line in enumerate(lines_data):
179
+ line_id = str(i).zfill(4)
180
+ cropped_image = self.crop_line_image(image_array, line["coords"])
181
+ transcription = line["transcription"]
182
+
183
+ if not transcription:
184
+ print(f"Invalid transcription: {transcription}")
185
+ continue
186
+
187
+ unique_key = f"{volume}_{img_filename}_{line_id}"
188
+ yield unique_key, {"image": cropped_image, "transcription": transcription}
189
+
190
+ def inst_seg_lines_within_regions(self, imgs_xmls):
191
+ """Process for cropped images with text line annotations."""
192
+ for img_path, xml_path in imgs_xmls:
193
+ img_filename, volume = self._extract_filename_and_volume(img_path, xml_path)
194
+ image = PILImage.open(img_path)
195
+ root = self._parse_xml(xml_path)
196
+ namespaces = {"ns": "http://schema.primaresearch.org/PAGE/gts/pagecontent/2013-07-15"}
197
+
198
+ # Iterate through each TextRegion
199
+ for reg_ind, region in enumerate(root.findall(".//ns:TextRegion", namespaces=namespaces)):
200
+ reg_id = str(reg_ind).zfill(4)
201
+ region_polygon = self._get_polygon(region, namespaces)
202
+ min_x, min_y, max_x, max_y = self._get_bbox(region_polygon)
203
+ cropped_region_image = self.crop_image(image, region_polygon)
204
+
205
+ annotations = self._get_line_annotations_within_region(
206
+ region, namespaces, min_x, min_y, region_polygon
207
+ )
208
+
209
+ unique_key = f"{volume}_{img_filename}_{reg_id}"
210
+ try:
211
+ yield (
212
+ unique_key,
213
+ {
214
+ "image": {"bytes": self._image_to_bytes(cropped_region_image)},
215
+ "annotations": annotations,
216
+ "image_name": unique_key,
217
+ },
218
+ )
219
+ except:
220
+ print("still error")
221
+ continue
222
+
223
+ def inst_seg_regions_and_lines(self, imgs_xmls):
224
+ """Process for original images with both region and line annotations."""
225
+ for img_path, xml_path in imgs_xmls:
226
+ img_filename, volume = self._extract_filename_and_volume(img_path, xml_path)
227
+ image = PILImage.open(img_path)
228
+ root = self._parse_xml(xml_path)
229
+ annotations = self._get_region_and_line_annotations(root)
230
+
231
+ unique_key = f"{volume}_{img_filename}"
232
+ yield unique_key, {"image_name": unique_key, "image": image, "annotations": annotations}
233
+
234
+ def inst_seg_lines(self, imgs_xmls):
235
+ """Process for original images with text line annotations only."""
236
+ for img_path, xml_path in imgs_xmls:
237
+ img_filename, volume = self._extract_filename_and_volume(img_path, xml_path)
238
+ image = PILImage.open(img_path)
239
+ root = self._parse_xml(xml_path)
240
+
241
+ annotations = self._get_line_annotations(root)
242
+
243
+ unique_key = f"{volume}_{img_filename}"
244
+ yield unique_key, {"image_name": unique_key, "image": image, "annotations": annotations}
245
+
246
+ def inst_seg_regions(self, imgs_xmls):
247
+ """Process for original images with text region annotations only."""
248
+ for img_path, xml_path in imgs_xmls:
249
+ img_filename, volume = self._extract_filename_and_volume(img_path, xml_path)
250
+ image = PILImage.open(img_path)
251
+ root = self._parse_xml(xml_path)
252
+
253
+ annotations = self._get_region_annotations(root)
254
+
255
+ unique_key = f"{volume}_{img_filename}"
256
+ yield unique_key, {"image_name": unique_key, "image": image, "annotations": annotations}
257
+
258
+ def _extract_filename_and_volume(self, img, xml):
259
+ """Extracts the filename and volume from the image and XML paths."""
260
+ assert Path(img).stem == Path(xml).stem
261
+ img_filename = Path(img).stem
262
+ volume = PurePath(img).parts[-2]
263
+ return img_filename, volume
264
+
265
+ def _parse_xml(self, xml_path):
266
+ """Parses the XML file and returns the root element."""
267
+ try:
268
+ tree = ET.parse(xml_path)
269
+ return tree.getroot()
270
+ except ET.ParseError as e:
271
+ print(f"XML Parse Error: {e}")
272
+ return None
273
+
274
+ def _get_line_annotations_within_region(self, region, namespaces, min_x, min_y, region_polygon):
275
+ """Generates annotations for text lines within a region."""
276
+ annotations = []
277
+ for line in region.findall(".//ns:TextLine", namespaces=namespaces):
278
+ line_polygon = self._get_polygon(line, namespaces)
279
+ clipped_line_polygon = self.clip_polygon_to_region(line_polygon, region_polygon)
280
+
281
+ if len(clipped_line_polygon) < 3:
282
+ print(f"Invalid polygon detected for line: {line_polygon}, clipped: {clipped_line_polygon}")
283
+ continue
284
+
285
+ translated_polygon = [(x - min_x, y - min_y) for x, y in clipped_line_polygon]
286
+ transcription = "".join(line.itertext()).strip()
287
+
288
+ annotations.append(
289
+ {
290
+ "polygon": translated_polygon,
291
+ "transcription": transcription,
292
+ "class": "textline",
293
+ }
294
+ )
295
+ return annotations
296
+
297
+ def _get_region_and_line_annotations(self, root):
298
+ """Generates annotations for both text regions and lines."""
299
+ annotations = []
300
+
301
+ # Get region annotations
302
+ annotations.extend(self._get_region_annotations(root))
303
+
304
+ # Get line annotations
305
+ annotations.extend(self._get_line_annotations(root))
306
+
307
+ return annotations
308
+
309
+ def _get_line_annotations(self, root):
310
+ """Generates annotations for text lines only."""
311
+ namespaces = {"ns": "http://schema.primaresearch.org/PAGE/gts/pagecontent/2013-07-15"}
312
+ annotations = []
313
+ for region in root.findall(".//ns:TextRegion", namespaces=namespaces):
314
+ for line in region.findall(".//ns:TextLine", namespaces=namespaces):
315
+ line_polygon = self._get_polygon(line, namespaces)
316
+ transcription = "".join(line.itertext()).strip()
317
+ annotations.append(
318
+ {
319
+ "polygon": line_polygon,
320
+ "transcription": transcription,
321
+ "class": "textline",
322
+ }
323
+ )
324
+ return annotations
325
+
326
+ def _get_region_annotations(self, root):
327
+ """Generates annotations for text regions only."""
328
+ namespaces = {"ns": "http://schema.primaresearch.org/PAGE/gts/pagecontent/2013-07-15"}
329
+ annotations = []
330
+ for region in root.findall(".//ns:TextRegion", namespaces=namespaces):
331
+ region_polygon = self._get_polygon(region, namespaces)
332
+ annotations.append(
333
+ {
334
+ "polygon": region_polygon,
335
+ "transcription": "",
336
+ "class": "textregion",
337
+ }
338
+ )
339
+ return annotations
340
+
341
+ def _image_to_bytes(self, image):
342
+ """Converts a PIL image to bytes."""
343
+ with io.BytesIO() as output:
344
+ image.save(output, format="PNG")
345
+ return output.getvalue()
346
+
347
+ def crop_image(self, img_pil, coords):
348
+ coords = np.array(coords)
349
+ img = np.array(img_pil)
350
+ mask = np.zeros(img.shape[0:2], dtype=np.uint8)
351
+
352
+ try:
353
+ # Ensure the coordinates are within the bounds of the image
354
+ coords[:, 0] = np.clip(coords[:, 0], 0, img.shape[1] - 1)
355
+ coords[:, 1] = np.clip(coords[:, 1], 0, img.shape[0] - 1)
356
+
357
+ # Draw the mask
358
+ cv2.drawContours(mask, [coords], -1, (255, 255, 255), -1, cv2.LINE_AA)
359
+
360
+ # Apply mask to image
361
+ res = cv2.bitwise_and(img, img, mask=mask)
362
+ rect = cv2.boundingRect(coords)
363
+
364
+ # Ensure the bounding box is within the image dimensions
365
+ rect = (
366
+ max(0, rect[0]),
367
+ max(0, rect[1]),
368
+ min(rect[2], img.shape[1] - rect[0]),
369
+ min(rect[3], img.shape[0] - rect[1]),
370
+ )
371
+
372
+ wbg = np.ones_like(img, np.uint8) * 255
373
+ cv2.bitwise_not(wbg, wbg, mask=mask)
374
+
375
+ # Overlap the resulted cropped image on the white background
376
+ dst = wbg + res
377
+
378
+ # Use validated rect for cropping
379
+ cropped = dst[rect[1] : rect[1] + rect[3], rect[0] : rect[0] + rect[2]]
380
+
381
+ # Convert the NumPy array back to a PIL image
382
+ cropped_pil = PILImage.fromarray(cropped)
383
+
384
+ return cropped_pil
385
+
386
+ except Exception as e:
387
+ print(f"Error in cropping: {e}")
388
+ return img_pil # Return the original image if there's an error
389
+
390
+ def _create_mask(self, shape, coords):
391
+ """Creates a mask for the specified polygon coordinates."""
392
+ mask = np.zeros(shape, dtype=np.uint8)
393
+ cv2.drawContours(mask, [np.array(coords)], -1, (255, 255, 255), -1, cv2.LINE_AA)
394
+ return mask
395
+
396
+ def parse_pagexml(self, xml):
397
+ """Parses the PAGE XML and extracts line data."""
398
+ root = self._parse_xml(xml)
399
+ if not root:
400
+ return []
401
+
402
+ namespaces = {"ns": "http://schema.primaresearch.org/PAGE/gts/pagecontent/2013-07-15"}
403
+ lines_data = []
404
+ for region in root.findall(".//ns:TextRegion", namespaces):
405
+ for line in region.findall(".//ns:TextLine", namespaces):
406
+ try:
407
+ line_id = line.get("id")
408
+ coords = self._get_polygon(line, namespaces)
409
+ transcription = line.find("ns:TextEquiv/ns:Unicode", namespaces).text or ""
410
+ lines_data.append({"line_id": line_id, "coords": coords, "transcription": transcription})
411
+ except Exception as e:
412
+ print(f"Error parsing line: {e}")
413
+ return lines_data
414
+
415
+ def crop_line_image(self, img, coords):
416
+ """Crops a line image based on the provided coordinates."""
417
+ mask = self._create_mask(img.shape[:2], coords)
418
+
419
+ coords = np.array(coords)
420
+
421
+ # Apply mask to image
422
+ res = cv2.bitwise_and(img, img, mask=mask)
423
+ rect = cv2.boundingRect(coords)
424
+
425
+ # Create a white background and overlay the cropped image
426
+ wbg = np.ones_like(img, np.uint8) * 255
427
+ cv2.bitwise_not(wbg, wbg, mask=mask)
428
+ dst = wbg + res
429
+
430
+ cropped = dst[rect[1] : rect[1] + rect[3], rect[0] : rect[0] + rect[2]]
431
+
432
+ return self.cv2_to_pil(cropped)
433
+
434
+ def _get_polygon(self, element, namespaces):
435
+ """Extracts polygon points from a PAGE XML element."""
436
+ coords = element.find(".//ns:Coords", namespaces=namespaces).attrib["points"]
437
+ return [tuple(map(int, p.split(","))) for p in coords.split()]
438
+
439
+ def _get_bbox(self, polygon):
440
+ """Calculates the bounding box from polygon points."""
441
+ min_x = min(p[0] for p in polygon)
442
+ min_y = min(p[1] for p in polygon)
443
+ max_x = max(p[0] for p in polygon)
444
+ max_y = max(p[1] for p in polygon)
445
+ return min_x, min_y, max_x, max_y
446
+
447
+ def clip_polygon_to_region(self, line_polygon, region_polygon):
448
+ """
449
+ Clips a line polygon to ensure it's inside the region polygon using Shapely.
450
+ Returns the original line polygon if the intersection is empty.
451
+ """
452
+ # Convert lists of points to Shapely Polygons
453
+ line_poly = Polygon(line_polygon)
454
+ region_poly = Polygon(region_polygon)
455
+
456
+ # Compute the intersection of the line polygon with the region polygon
457
+ try:
458
+ intersection = line_poly.intersection(region_poly)
459
+ except Exception:
460
+ return line_polygon
461
+
462
+ # Return the intersection points as a list of tuples
463
+ if intersection.is_empty:
464
+ print(
465
+ f"No intersection found for line_polygon {line_polygon} within region_polygon {region_polygon}, returning original polygon."
466
+ )
467
+ return line_polygon
468
+ elif intersection.geom_type == "Polygon":
469
+ return list(intersection.exterior.coords)
470
+ elif intersection.geom_type == "MultiPolygon":
471
+ # If the result is a MultiPolygon, take the largest by area (or another heuristic)
472
+ largest_polygon = max(intersection, key=lambda p: p.area)
473
+ return list(largest_polygon.exterior.coords)
474
+ elif intersection.geom_type == "LineString":
475
+ return list(intersection.coords)
476
+ else:
477
+ print(f"Unexpected intersection type: {intersection.geom_type}")
478
+ return line_polygon
479
+
480
+ def cv2_to_pil(self, cv2_image):
481
+ """Converts an OpenCV image to a PIL Image."""
482
+ cv2_image_rgb = cv2.cvtColor(cv2_image, cv2.COLOR_BGR2RGB)
483
+ return PILImage.fromarray(cv2_image_rgb)