artpods56 commited on
Commit
8821bf7
·
unverified ·
1 Parent(s): 8ce9ece

feat: implement SacredBuildingsDataset class for architectural style classification

Browse files
Files changed (1) hide show
  1. sacred_buildings_loader.py +166 -0
sacred_buildings_loader.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import csv
2
+ import json
3
+ import os
4
+
5
+ import datasets
6
+ from PIL import Image
7
+ import tarfile
8
+ from io import BytesIO
9
+
10
+ import logging
11
+ import datasets
12
+ from datasets.utils.logging import get_logger, tqdm
13
+
14
+ logger = get_logger(__name__) # <- same pattern used in HF scripts
15
+
16
+
17
+ _DESCRIPTION = "WikiChurches is a dataset for architectural style classification"
18
+ _HOMEPAGE = "https://huggingface.co/datasets/LZSI-2/Recognizing_the_styles_of_sacred_buildings"
19
+ _LICENSE = "cc-by-nc-4.0"
20
+ _CITATION = """@article{barz2021wikichurches,
21
+ title={WikiChurches: A Fine-Grained Dataset of Architectural Styles with Real-World Challenges},
22
+ author={Barz, Björn and Denzler, Joachim},
23
+ journal={arXiv preprint arXiv:2108.06959},
24
+ year={2021}
25
+ }"""
26
+
27
+ TAR_PARTS = 40
28
+
29
+ _TAR_URLS =[f"https://huggingface.co/datasets/LZSI-2/Recognizing_the_styles_of_sacred_buildings/resolve/main/images/images_part{part_id}.tar" for part_id in range(1, TAR_PARTS + 1)]
30
+
31
+ _URLS = {
32
+ "churches_json": "https://huggingface.co/datasets/LZSI-2/Recognizing_the_styles_of_sacred_buildings/resolve/main/churches.json",
33
+ "style_levels": "https://huggingface.co/datasets/LZSI-2/Recognizing_the_styles_of_sacred_buildings/resolve/main/style_levels.json",
34
+ "style_names": "https://huggingface.co/datasets/LZSI-2/Recognizing_the_styles_of_sacred_buildings/resolve/main/style_names.txt",
35
+ }
36
+
37
+
38
+
39
+
40
+ _DESCRIPTION = """WikiChurches is a dataset for architectural style classification"""
41
+ _HOMEPAGE = "https://github.com/yourusername/sacred_buildings"
42
+
43
+
44
+ class SacredBuildingsDataset(datasets.GeneratorBasedBuilder):
45
+ """Sacred Buildings Dataset with support for different hierarchy levels."""
46
+
47
+ VERSION = datasets.Version("0.0.1")
48
+
49
+ BUILDER_CONFIGS = [
50
+ datasets.BuilderConfig(
51
+ name="wc4",
52
+ version=VERSION,
53
+ description="Wiki Churches 4 main classes"
54
+ ),
55
+ datasets.BuilderConfig(
56
+ name="wc6",
57
+ version=VERSION,
58
+ description="Wiki Churches 6 largest classes"
59
+ ),
60
+ datasets.BuilderConfig(
61
+ name="wc14",
62
+ version=VERSION,
63
+ description="Wiki Churches 14 first-level classes"
64
+ ),
65
+ ]
66
+
67
+ DEFAULT_CONFIG_NAME = "wc4"
68
+
69
+ def _info(self):
70
+ features = datasets.Features({
71
+ "image": datasets.Image(),
72
+ "style": datasets.Value("string"),
73
+ "church_id": datasets.Value("string"),
74
+
75
+ })
76
+
77
+ return datasets.DatasetInfo(
78
+ description=_DESCRIPTION,
79
+ features=features,
80
+ homepage=_HOMEPAGE,
81
+ license=_LICENSE,
82
+ citation=_CITATION,
83
+ )
84
+
85
+
86
+ def _get_style_names(self, style_levels):
87
+ return style_levels.get(self.config.name, {})
88
+
89
+ def _split_generators(self, dl_manager):
90
+ """Returns SplitGenerators."""
91
+
92
+ downloaded_files = dl_manager.download(_TAR_URLS)
93
+ data_dir = dl_manager.download_and_extract(_URLS)
94
+
95
+
96
+ return [
97
+ datasets.SplitGenerator(
98
+ name=datasets.Split.TRAIN,
99
+ gen_kwargs={
100
+ "file_paths": downloaded_files,
101
+ "data_dir": data_dir,
102
+ },
103
+ ),
104
+ ]
105
+
106
+
107
+ def _trace_to_top_parent(self, style_id, hierarchy):
108
+ while style_id in hierarchy and hierarchy[style_id]["parent"]:
109
+ style_id = hierarchy[style_id]["parent"]
110
+ return style_id
111
+
112
+ def _generate_examples(self, file_paths, data_dir):
113
+ with open(data_dir["churches_json"], "r") as f:
114
+ churches_data = json.load(f)
115
+
116
+ with open(data_dir["style_levels"], "r") as f:
117
+ style_levels = json.load(f)
118
+
119
+
120
+ style_levels = json.load(open(data_dir["style_levels"], "r"))
121
+ if self.config.name == "wc4":
122
+ domain_styles = list(style_levels["statistics"]["styles_by_size"].keys())[:4]
123
+ elif self.config.name == "wc6":
124
+ domain_styles = list(style_levels["statistics"]["styles_by_size"].keys())[:6]
125
+
126
+
127
+
128
+
129
+ """Yields examples."""
130
+ # Load churches data
131
+ for filepath in file_paths:
132
+ logger.info(f"Processing {filepath.split('/')[-1]}")
133
+ with tarfile.open(filepath, "r") as tar:
134
+ for member in tqdm(tar.getmembers(),
135
+ desc=f"{os.path.basename(filepath)}"):
136
+ if member.isfile():
137
+
138
+ image_file = tar.extractfile(member)
139
+
140
+
141
+ church_id = member.name.split("_")[0]
142
+ image_name = member.name
143
+ if church_id not in churches_data:
144
+ continue
145
+
146
+ church_styles = churches_data[church_id]["styles"]
147
+
148
+ top_level_set = set()
149
+ for s_id in church_styles:
150
+ top_parent = self._trace_to_top_parent(s_id, style_levels["hierarchy"])
151
+ if top_parent in domain_styles:
152
+ top_level_set.add(top_parent)
153
+
154
+ if len(top_level_set) == 1:
155
+ label_name = top_level_set.pop()
156
+
157
+ with Image.open(image_file) as image:
158
+ image = image.convert("RGB")
159
+ yield image_name, {
160
+ "image": image,
161
+ "style": label_name,
162
+ "church_id": church_id,
163
+ }
164
+ else:
165
+ continue
166
+