lukawskikacper commited on
Commit
d794b89
1 Parent(s): fbcca91

First version of the dataset

Browse files
README.md ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - en
4
+ pretty_name: Geo Coordinate Augmented Google-Landmarks
5
+ task_categories:
6
+ - image-classification
7
+ source_datasets:
8
+ - Google Landmarks V2
9
+ size_categories:
10
+ - < 50K
11
+ license: cc-by-4.0
12
+ ---
13
+
14
+
15
+ # Dataset Card for Geo Coordinate Augmented Google-Landmarks
16
+
17
+ Geo coordinates were added as data to a tar file's worth of images from the [Google Landmark V2](https://github.com/cvdfoundation/google-landmark). Not all of the
18
+ images could be geo-tagged due to lack of coordinates on the image's wikimedia page.
19
+
20
+ ## Dataset Details
21
+
22
+ ### Dataset Description
23
+
24
+ Geo coordinates were added as data to a tar file's worth of images from the [Google Landmark V2](https://github.com/cvdfoundation/google-landmark). There were many more images that could have
25
+ been downloaded but this dataset was found to be a good balance of data size and sample size.
26
+
27
+ The intended use for the dataset was to demonstrate using a geo-filter in Qdrant along with a image similarity search.
28
+
29
+ Not all of the images couuld be geo-tagged due to lack of coordinates on the image's wikimedia page.
30
+ We provide the raw geotagged file as a geojson document, train_attribution_geo.json.
31
+ We also provide a json file that includes the data above along with embedding vectors for the images, id_payload_vector.json.
32
+
33
+ Thingsvision was used as the library for creating the image embeddings with the following ThingVision model:
34
+
35
+ ```python
36
+ model_name = 'clip'
37
+ model_parameters = {
38
+ 'variant': 'ViT-B/32'
39
+ }
40
+ ```
41
+
42
+ The code directory contains the Python code used to geotag the images as well as generated the vectors. It can also be used to upload the embeddings to a Qdrant DB instance. This code is NOT for production and was
43
+ more focused on quickly and correctly get the coordinates and embed the images.
44
+
45
+ The license for this data and code match the license of the original Google Landmarks V2 Dataset: CC BY 4.0 license.
46
+
47
+ ## Uses
48
+
49
+ ### Direct Use
50
+
51
+ The primary use is case is image similarity search with geographic filtering.
code/db_upload.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from qdrant_client import QdrantClient
2
+ from qdrant_client.models import Distance, VectorParams
3
+
4
+
5
+ class DBUpload:
6
+
7
+ def __init__(self, vector_size: int, collection_name: str):
8
+
9
+ self.client = QdrantClient(host="localhost", port=6333)
10
+
11
+ self.vector_size = vector_size
12
+ self.collection_name = collection_name
13
+
14
+ self.client.recreate_collection(
15
+ collection_name=collection_name,
16
+ vectors_config=VectorParams(size=vector_size, distance=Distance.COSINE),
17
+ )
18
+
19
+ def upsert_vectors(self, ids, vectors, payloads):
20
+ self.client.upload_collection(
21
+ collection_name=self.collection_name,
22
+ ids=ids,
23
+ vectors=vectors,
24
+ payload=payloads
25
+ )
26
+
27
+ def query_vector(self, vector):
28
+ print(type(vector))
29
+ vector = vector[0]
30
+ search_result = self.client.search(
31
+ collection_name=self.collection_name,
32
+ query_vector=vector,
33
+ limit=5
34
+
35
+ )
36
+ return search_result
code/geojson2qdrnt.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+
3
+ import geojson
4
+
5
+ # This only accepts simple polygons NOT multipolygons
6
+ # This should actually have 2 methods
7
+ # 1 that returns the JSON needed a REST call
8
+ # 2 one that returns a valid GeoPolygon
9
+ # Maybe they are just static methods on the class and accept a JSON object as input
10
+
11
+
12
+
13
+ def geoJSON2coord_list(geojson_input: geojson):
14
+ coord_array = geojson_input["geometry"]["coordinates"][0]
15
+ result_array = []
16
+ for coord_pair in coord_array:
17
+ coord_obj = {"lon": coord_pair[0], "lat": coord_pair[1]}
18
+ result_array.append(coord_obj)
19
+ return result_array
20
+
21
+
22
+ def geoJSON_string2qjson(geojson_input: geojson):
23
+
24
+ coord_array = geoJSON2coord_list((geojson_input))
25
+ poly_filter = {"filter": {"must": [{"geo_polygon": {"exterior": {"points": coord_array}}}]}}
26
+ return json.dumps(poly_filter)
27
+ print("should be done")
28
+
29
+
30
+ def geoJSON_string2qgeom(geojson_input: geojson):
31
+ coord_array = geoJSON2coord_list((geojson_input))
32
+ print("not yet")
33
+
34
+ if __name__ == '__main__':
35
+ with open("../germany.geojson", "r", encoding='utf_8') as content:
36
+ print(geoJSON_string2qjson(json.load(content)))
37
+
38
+
39
+
40
+ # "geo_polygon": {
41
+ # "exterior": {
42
+ # "points": [
43
+ # { "lon": -70.0, "lat": -70.0 },
44
+ # { "lon": 60.0, "lat": -70.0 },
45
+ # { "lon": 60.0, "lat": 60.0 },
46
+ # { "lon": -70.0, "lat": 60.0 },
47
+ # { "lon": -70.0, "lat": -70.0 }
48
+ # ]
49
+ # },
50
+ # "interiors": [
51
+ # {
52
+ # "points": [
53
+ # { "lon": -65.0, "lat": -65.0 },
54
+ # { "lon": 0.0, "lat": -65.0 },
55
+ # { "lon": 0.0, "lat": 0.0 },
56
+ # { "lon": -65.0, "lat": 0.0 },
57
+ # { "lon": -65.0, "lat": -65.0 }
58
+ # ]
59
+ # }
60
+ # ]
61
+ # }
62
+
63
+
64
+ # models.FieldCondition(
65
+ # key="location",
66
+ # geo_polygon=models.GeoPolygon(
67
+ # exterior=models.GeoLineString(
68
+ # points=[
69
+ # models.GeoPoint(
70
+ # lon=-70.0,
71
+ # lat=-70.0,
72
+ # ),
73
+ # models.GeoPoint(
74
+ # lon=60.0,
75
+ # lat=-70.0,
76
+ # ),
77
+ # models.GeoPoint(
78
+ # lon=60.0,
79
+ # lat=60.0,
80
+ # ),
81
+ # models.GeoPoint(
82
+ # lon=-70.0,
83
+ # lat=60.0,
84
+ # ),
85
+ # models.GeoPoint(
86
+ # lon=-70.0,
87
+ # lat=-70.0,
88
+ # )
89
+ # ]
90
+ # ),
91
+ # interiors=[
92
+ # models.GeoLineString(
93
+ # points=[
94
+ # models.GeoPoint(
95
+ # lon=-65.0,
96
+ # lat=-65.0,
97
+ # ),
98
+ # models.GeoPoint(
99
+ # lon=0.0,
100
+ # lat=-65.0,
101
+ # ),
102
+ # models.GeoPoint(
103
+ # lon=0.0,
104
+ # lat=0.0,
105
+ # ),
106
+ # models.GeoPoint(
107
+ # lon=-65.0,
108
+ # lat=0.0,
109
+ # ),
110
+ # models.GeoPoint(
111
+ # lon=-65.0,
112
+ # lat=-65.0,
113
+ # )
114
+ # ]
115
+ # )
116
+ # ]
117
+ # )
118
+ # )
code/main.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ from bs4 import BeautifulSoup
3
+
4
+ from csv import DictReader
5
+ from pathlib import Path
6
+ import re
7
+ import uuid
8
+ import json
9
+
10
+ import db_upload
11
+ import make_embeddings_upload
12
+
13
+ #TODO this is definitely not efficient as it generates vectors for all the images, not just the ones with geo
14
+ # to fix we would somehow copy all the original images in the payloads_non_list into the directory we want to use in the vector making
15
+
16
+ #TODO there is also repeated code everywhere
17
+ # And hard coded values for too many things
18
+
19
+ image_path = Path("../images_000")
20
+
21
+ metadata_path = "../train_attribution.csv"
22
+ image_names = {}
23
+
24
+ for path in image_path.rglob('*.*'):
25
+ match = re.search('.*(\w{16})\.jpg$', str(path))
26
+ image_names[match.group(1)] = path
27
+
28
+ csvfile = open(metadata_path, "r", encoding='utf-8')
29
+ csvlines = DictReader(csvfile)
30
+
31
+ payloads_non_list = {}
32
+ i= 1
33
+ for line in csvlines:
34
+ if line['id'] in image_names:
35
+ try:
36
+ page = requests.get(line['url'])
37
+ html = BeautifulSoup(page.text, features="html.parser")
38
+ our_tag = html.find('a', {"data-style": "osm-intl"})
39
+ if our_tag is not None:
40
+ if "data-lat" in our_tag.attrs and "data-lon" in our_tag.attrs:
41
+ lat = float(our_tag.attrs["data-lat"])
42
+ lon = float(our_tag.attrs["data-lon"])
43
+
44
+ # We have our payload at this point
45
+ print("found one " + line['id'] + " : " + line['url'] + " coords: " + str(lat) + ", " + str(lon))
46
+ payloads_non_list[line['id']] = {"picture": line['id'], "filename": str(image_names[line['id']]), "url": line['url'], "location": {"lon": lon, "lat": lat}}
47
+ except:
48
+ print("Threw an exception on: " + line['id'])
49
+
50
+
51
+ csvfile.close()
52
+ # Write our payloads out to file
53
+
54
+ with open('../train_attribution_geo.json', 'w') as out_file:
55
+ json.dump(payloads_non_list, out_file, sort_keys=True, indent=4,
56
+ ensure_ascii=False)
57
+
58
+ # now create our vector
59
+ vectors_non_list = make_embeddings_upload.get_features()
60
+
61
+ ids, vectors, payloads = [], [], []
62
+ # Put them together - need to do this because of the sorting problem - need to get them to line up
63
+ for key, payload in payloads_non_list.items():
64
+ payloads.append(payload)
65
+ vectors.append(vectors_non_list[key])
66
+ ids.append(str(uuid.uuid3(uuid.NAMESPACE_DNS,payload["url"])))
67
+
68
+ # now insert into the collection
69
+ uploader = db_upload.DBUpload(512, "images")
70
+
71
+ uploader.upsert_vectors(ids, vectors, payloads)
72
+
73
+ print("finished")
74
+
75
+
76
+
77
+
code/make_embeddings_upload.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ from thingsvision import get_extractor
4
+ from thingsvision.utils.storing import save_features
5
+ from thingsvision.utils.data import ImageDataset, DataLoader
6
+
7
+ source = 'custom'
8
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
9
+ model_name = 'clip'
10
+ model_parameters = {
11
+ 'variant': 'ViT-B/32'
12
+ # This model creates 512 length vectors
13
+ }
14
+
15
+ # This model is more accurate but takes longer to run and not sure we need it for the demo
16
+ # model_name = 'OpenCLIP'
17
+ # model_parameters = {
18
+ # 'variant': 'ViT-H-14',
19
+ # 'dataset': 'laion2b_s32b_b79k'
20
+ # # This model create 1024 length vectors
21
+ # }
22
+
23
+ extractor = get_extractor(
24
+ model_name=model_name,
25
+ source=source,
26
+ device=device,
27
+ pretrained=True,
28
+ model_parameters=model_parameters,
29
+ )
30
+
31
+ root='../images_000/' # (e.g., './images/)
32
+ batch_size = 32
33
+
34
+ dataset = ImageDataset(
35
+ root=root,
36
+ out_path='../test_vectors',
37
+ backend=extractor.get_backend(), # backend framework of model
38
+ transforms=extractor.get_transformations(resize_dim=256, crop_dim=224) # set the input dimensionality to whichever values are required for your pretrained model
39
+ )
40
+
41
+ batches = DataLoader(
42
+ dataset=dataset,
43
+ batch_size=batch_size,
44
+ backend=extractor.get_backend() # backend framework of model
45
+ )
46
+
47
+
48
+ module_name = 'visual'
49
+
50
+ def get_features():
51
+ # we are creating 512 length vectors
52
+ features = extractor.extract_features(
53
+ batches=batches,
54
+ module_name=module_name,
55
+ flatten_acts=True,
56
+ output_type="ndarray", # or "tensor" (only applicable to PyTorch models of which CLIP is one!)
57
+ )
58
+
59
+ # WE ARE NOT DOING THIS append the file names to the front of the vector matrix. We turn the file names into a 40 x 1
60
+ # np array #full_data = np.hstack((np.array(dataset.file_names).reshape(-1,1), features))
61
+ # The model returns the vectors in alphbetical order for the filenames. Our other code just reads through the directory
62
+ # without a sort. Therefore this needs to be a dict so we can do lookups
63
+
64
+ # save_features(features, out_path='../test_vectors', file_format='txt') # file_format can be set to "npy", "txt", "mat", "pt", or "hdf5"
65
+
66
+ vectors = {}
67
+ for i in range(len(dataset.file_names)):
68
+ vectors[dataset.file_names[i][0:16]] = features[i]
69
+
70
+ return vectors
71
+
72
+
73
+ if __name__ == '__main__':
74
+ result = get_features()
75
+ print(str(len(result)))
76
+
code/payload2geojson.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # >>> Feature(geometry=my_point, id=27) # doctest: +ELLIPSIS
2
+ # {"geometry": {"coordinates": [-3.68..., 40.4...], "type": "Point"}, "id": 27, "properties": {}, "type": "Feature"}
3
+ import json
4
+ from decimal import Decimal
5
+
6
+ import geojson
7
+ from geojson import Feature, Point
8
+ from qdrant_client.conversions.conversion import payload_to_grpc
9
+
10
+ geojson_array = []
11
+
12
+
13
+ # Load the payload JSON
14
+ with open("D:\data\google-landmarks\geo-google-landmark-payload.json") as jf:
15
+ input_json = json.load(jf)
16
+
17
+ # Now iterate through and make an array of features
18
+ for id, payload in input_json.items():
19
+ lon = float(payload["location"]["lon"])
20
+ lat = float(payload["location"]["lat"])
21
+ my_point = Point((lon, lat))
22
+ geojson_array.append(Feature(geometry=my_point, id=payload["picture"], properties={"url": payload["url"]}))
23
+
24
+ with open("D:\data\google-landmarks\geo-google-landmark.geojson", "w") as output:
25
+ geojson.dump(geojson_array, fp=output)
26
+
27
+ print("finished")
code/requirements.txt ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ hpack~=4.0.0
2
+ hyperframe~=6.0.1
3
+ h2~=4.1.0
4
+ beautifulsoup4~=4.12.2
5
+ soupsieve~=2.5
6
+ h11~=0.14.0
7
+ Pillow~=10.0.1
8
+ pip~=21.3.1
9
+ wheel~=0.41.2
10
+ rsa~=4.9
11
+ pyasn1~=0.5.0
12
+ torch~=1.13.1
13
+ torchvision~=0.14.1
14
+ tqdm~=4.66.1
15
+ numpy~=1.25.2
16
+ clip~=1.0
17
+ ftfy~=6.1.1
18
+ regex~=2023.8.8
19
+ wcwidth~=0.2.7
20
+ gast~=0.4.0
21
+ h5py~=3.9.0
22
+ pytz~=2023.3.post1
23
+ scipy~=1.11.3
24
+ matplotlib~=3.8.0
25
+ tensorflow~=2.9.3
26
+ timm~=0.6.13
27
+ requests~=2.31.0
28
+ keras~=2.9.0
29
+ colorama~=0.4.5
30
+ exceptiongroup~=1.1.3
31
+ sniffio~=1.3.0
32
+ click~=8.1.3
33
+ httpcore~=0.18.0
34
+ idna~=3.4
35
+ certifi~=2023.7.22
36
+ pywin32~=306
37
+ six~=1.16.0
38
+ pandas~=2.1.1
39
+ wrapt~=1.14.1
40
+ numba~=0.58.0
41
+ llvmlite~=0.41.0
42
+ PyYAML~=6.0
43
+ setuptools~=68.2.2
44
+ Jinja2~=3.1.2
45
+ thingsvision~=2.4.1
46
+ imageio~=2.31.4
47
+ scikit-image~=0.21.0
48
+ astunparse~=1.6.3
49
+ tensorboard~=2.14.1
50
+ urllib3~=2.0.6
51
+ fsspec~=2023.9.2
52
+ cachetools~=5.3.1
53
+ packaging~=23.2
54
+ joblib~=1.3.2
55
+ MarkupSafe~=2.1.3
56
+ python-dateutil~=2.8.2
57
+ tifffile~=2023.9.26
58
+ networkx~=3.1
59
+ scikit-learn~=1.3.1
60
+ threadpoolctl~=3.2.0
61
+ anyio~=4.0.0
62
+ Markdown~=3.4.4
63
+ oauthlib~=3.2.2
64
+ pydantic~=2.4.2
65
+ werkzeug~=3.0.0
66
+ contourpy~=1.1.1
67
+ fonttools~=4.43.0
68
+ termcolor~=2.3.0
69
+ typeguard~=4.1.5
70
+ cycler~=0.12.0
71
+ pyparsing~=3.0.9
72
+ kiwisolver~=1.4.5
73
+ zipp~=3.17.0
74
+ torchtyping~=0.1.4
75
+ httpx~=0.25.0
76
+ portalocker~=2.8.2
77
+ filelock~=3.12.4
78
+ geojson~=3.0.1
79
+ flatbuffers~=1.12
id_payload_vector.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:699c647604a5831eab3be0b83bf00061798052084249dd798c922e1ffd5906a1
3
+ size 58657241
original_download.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6948e4c06fc0e828699519644f51c6eb570df7a58ae3484f529d2a25a3581585
3
+ size 1569291364
train_attribution_geo.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4fd75935c26bc1f5802705a1faaa283c9148261d01df6d2ed5fa093b9f1f5fc9
3
+ size 1121106