KKaay commited on
Commit
89f6699
·
verified ·
1 Parent(s): 76d1ead

Upload folder using huggingface_hub

Browse files
.flake8 ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ [flake8]
2
+ max-line-length = 100
.gitignore ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python-generated files
2
+ __pycache__/
3
+ *.py[oc]
4
+ build/
5
+ dist/
6
+ wheels/
7
+ *.egg-info
8
+
9
+ # Virtual environments
10
+ .venv
.python-version ADDED
@@ -0,0 +1 @@
 
 
1
+ 3.12
Img2GPS/Release_baseline_model.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
Img2GPS/Release_post_process.ipynb ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "id": "5638b0d1",
7
+ "metadata": {
8
+ "id": "5638b0d1"
9
+ },
10
+ "outputs": [],
11
+ "source": [
12
+ "!pip install exifread"
13
+ ]
14
+ },
15
+ {
16
+ "cell_type": "markdown",
17
+ "source": [
18
+ "# Extracting GPS Information from Images\n",
19
+ "\n",
20
+ "(You will need to modify this script based on how your dataset is stored in order to execute the code.).\n"
21
+ ],
22
+ "metadata": {
23
+ "id": "yT4UQMosNN02"
24
+ },
25
+ "id": "yT4UQMosNN02"
26
+ },
27
+ {
28
+ "cell_type": "code",
29
+ "source": [
30
+ "import os\n",
31
+ "\n",
32
+ "# train_or_test_or_validation could be either train, test, or validation.\n",
33
+ "train_or_test_or_validation = \"train\" # it could also be test or validation\n",
34
+ "PATH_TO_YOUR_DATA_FOLDER = \"{PATH TO YOUR DATA FOLDER}\"\n",
35
+ "directory_path = f\"{PATH_TO_YOUR_DATA_FOLDER}/{train_or_test_or_validation}\"\n",
36
+ "output_csv = \"metadata.csv\"\n",
37
+ "output_csv = os.path.join(directory_path, output_csv)"
38
+ ],
39
+ "metadata": {
40
+ "id": "7QcjgXtAQB5Q"
41
+ },
42
+ "id": "7QcjgXtAQB5Q",
43
+ "execution_count": null,
44
+ "outputs": []
45
+ },
46
+ {
47
+ "cell_type": "code",
48
+ "execution_count": null,
49
+ "id": "e1713e4e-a848-42e9-b8d8-d1273f1b9689",
50
+ "metadata": {
51
+ "id": "e1713e4e-a848-42e9-b8d8-d1273f1b9689"
52
+ },
53
+ "outputs": [],
54
+ "source": [
55
+ "import exifread, csv\n",
56
+ "\n",
57
+ "def get_exif_data(image_path):\n",
58
+ " with open(image_path, 'rb') as image_file:\n",
59
+ " tags = exifread.process_file(image_file)\n",
60
+ " return tags\n",
61
+ "\n",
62
+ "def export_exif_to_json(exif_data, output_file):\n",
63
+ " # Convert tags to a serializable format\n",
64
+ " exif_data_serializable = {str(tag): str(value) for tag, value in exif_data.items()}\n",
65
+ " with open(output_file, 'w') as json_file:\n",
66
+ " json.dump(exif_data_serializable, json_file, indent=4)"
67
+ ]
68
+ },
69
+ {
70
+ "cell_type": "code",
71
+ "execution_count": null,
72
+ "id": "80fb378d",
73
+ "metadata": {
74
+ "id": "80fb378d"
75
+ },
76
+ "outputs": [],
77
+ "source": [
78
+ "# Function to convert GPS coordinates in degrees, minutes, and seconds to decimal degrees\n",
79
+ "def convert_to_decimal_degrees(value):\n",
80
+ " d, m, s = value.values\n",
81
+ " return d.num / d.den + (m.num / m.den) / 60 + (s.num / s.den) / 3600"
82
+ ]
83
+ },
84
+ {
85
+ "cell_type": "markdown",
86
+ "source": [
87
+ "### You will need to create subfolders in {PATH_TO_YOUR_DATA_FOLDER} for each split (train/test/validation) or just (train/test). Next, place the corresponding images into each split after randomly shuffling them. Then, create a metadata.csv file for each split and place it in the corresponding directory. Note that the current code only works for jpeg images. If the exported images are in some other format, convert them to .jpg before running this code."
88
+ ],
89
+ "metadata": {
90
+ "id": "yaoJPVKrNq9N"
91
+ },
92
+ "id": "yaoJPVKrNq9N"
93
+ },
94
+ {
95
+ "cell_type": "code",
96
+ "execution_count": null,
97
+ "id": "be3c347d",
98
+ "metadata": {
99
+ "id": "be3c347d"
100
+ },
101
+ "outputs": [],
102
+ "source": [
103
+ "with open(output_csv, mode='w', newline='') as csv_file:\n",
104
+ " fieldnames = ['file_name', 'Latitude', 'Longitude']\n",
105
+ " writer = csv.DictWriter(csv_file, fieldnames=fieldnames)\n",
106
+ "\n",
107
+ " # Write the header row\n",
108
+ " writer.writeheader()\n",
109
+ " for filename in os.listdir(directory_path):\n",
110
+ " if os.path.isfile(os.path.join(directory_path, filename)):\n",
111
+ " exif_data = get_exif_data(os.path.join(directory_path, filename))\n",
112
+ " if exif_data:\n",
113
+ " gps_latitude = exif_data.get('GPS GPSLatitude', None)\n",
114
+ " gps_latitude_ref = exif_data.get('GPS GPSLatitudeRef', None)\n",
115
+ " gps_longitude = exif_data.get('GPS GPSLongitude', None)\n",
116
+ " gps_longitude_ref = exif_data.get('GPS GPSLongitudeRef', None)\n",
117
+ " if gps_latitude and gps_longitude:\n",
118
+ " # Convert latitude and longitude to decimal degrees\n",
119
+ " latitude = convert_to_decimal_degrees(gps_latitude)\n",
120
+ " longitude = convert_to_decimal_degrees(gps_longitude)\n",
121
+ "\n",
122
+ " # Adjust for N/S and E/W reference\n",
123
+ " if gps_latitude_ref.values[0] == 'S':\n",
124
+ " latitude = -latitude\n",
125
+ " if gps_longitude_ref.values[0] == 'W':\n",
126
+ " longitude = -longitude\n",
127
+ "\n",
128
+ " # Write the data to the CSV file\n",
129
+ " writer.writerow({'file_name': filename, 'Latitude': latitude, 'Longitude': longitude})"
130
+ ]
131
+ },
132
+ {
133
+ "cell_type": "markdown",
134
+ "source": [
135
+ "# Uploading and Reading a Dataset on Hugging Face"
136
+ ],
137
+ "metadata": {
138
+ "id": "WEkVLwUcQ7PV"
139
+ },
140
+ "id": "WEkVLwUcQ7PV"
141
+ },
142
+ {
143
+ "cell_type": "code",
144
+ "source": [
145
+ "!pip install datasets"
146
+ ],
147
+ "metadata": {
148
+ "id": "xtmhkAUSRBxp",
149
+ "outputId": "cab82646-49d6-431e-bb91-a5fee48296f6",
150
+ "colab": {
151
+ "base_uri": "https://localhost:8080/"
152
+ }
153
+ },
154
+ "id": "xtmhkAUSRBxp",
155
+ "execution_count": null,
156
+ "outputs": [
157
+ {
158
+ "output_type": "stream",
159
+ "name": "stdout",
160
+ "text": [
161
+ "Collecting datasets\n",
162
+ " Downloading datasets-3.1.0-py3-none-any.whl.metadata (20 kB)\n",
163
+ "Requirement already satisfied: filelock in /usr/local/lib/python3.10/dist-packages (from datasets) (3.16.1)\n",
164
+ "Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.10/dist-packages (from datasets) (1.26.4)\n",
165
+ "Requirement already satisfied: pyarrow>=15.0.0 in /usr/local/lib/python3.10/dist-packages (from datasets) (17.0.0)\n",
166
+ "Collecting dill<0.3.9,>=0.3.0 (from datasets)\n",
167
+ " Downloading dill-0.3.8-py3-none-any.whl.metadata (10 kB)\n",
168
+ "Requirement already satisfied: pandas in /usr/local/lib/python3.10/dist-packages (from datasets) (2.2.2)\n",
169
+ "Requirement already satisfied: requests>=2.32.2 in /usr/local/lib/python3.10/dist-packages (from datasets) (2.32.3)\n",
170
+ "Requirement already satisfied: tqdm>=4.66.3 in /usr/local/lib/python3.10/dist-packages (from datasets) (4.66.6)\n",
171
+ "Collecting xxhash (from datasets)\n",
172
+ " Downloading xxhash-3.5.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (12 kB)\n",
173
+ "Collecting multiprocess<0.70.17 (from datasets)\n",
174
+ " Downloading multiprocess-0.70.16-py310-none-any.whl.metadata (7.2 kB)\n",
175
+ "Collecting fsspec<=2024.9.0,>=2023.1.0 (from fsspec[http]<=2024.9.0,>=2023.1.0->datasets)\n",
176
+ " Downloading fsspec-2024.9.0-py3-none-any.whl.metadata (11 kB)\n",
177
+ "Requirement already satisfied: aiohttp in /usr/local/lib/python3.10/dist-packages (from datasets) (3.10.10)\n",
178
+ "Requirement already satisfied: huggingface-hub>=0.23.0 in /usr/local/lib/python3.10/dist-packages (from datasets) (0.26.2)\n",
179
+ "Requirement already satisfied: packaging in /usr/local/lib/python3.10/dist-packages (from datasets) (24.2)\n",
180
+ "Requirement already satisfied: pyyaml>=5.1 in /usr/local/lib/python3.10/dist-packages (from datasets) (6.0.2)\n",
181
+ "Requirement already satisfied: aiohappyeyeballs>=2.3.0 in /usr/local/lib/python3.10/dist-packages (from aiohttp->datasets) (2.4.3)\n",
182
+ "Requirement already satisfied: aiosignal>=1.1.2 in /usr/local/lib/python3.10/dist-packages (from aiohttp->datasets) (1.3.1)\n",
183
+ "Requirement already satisfied: attrs>=17.3.0 in /usr/local/lib/python3.10/dist-packages (from aiohttp->datasets) (24.2.0)\n",
184
+ "Requirement already satisfied: frozenlist>=1.1.1 in /usr/local/lib/python3.10/dist-packages (from aiohttp->datasets) (1.5.0)\n",
185
+ "Requirement already satisfied: multidict<7.0,>=4.5 in /usr/local/lib/python3.10/dist-packages (from aiohttp->datasets) (6.1.0)\n",
186
+ "Requirement already satisfied: yarl<2.0,>=1.12.0 in /usr/local/lib/python3.10/dist-packages (from aiohttp->datasets) (1.17.1)\n",
187
+ "Requirement already satisfied: async-timeout<5.0,>=4.0 in /usr/local/lib/python3.10/dist-packages (from aiohttp->datasets) (4.0.3)\n",
188
+ "Requirement already satisfied: typing-extensions>=3.7.4.3 in /usr/local/lib/python3.10/dist-packages (from huggingface-hub>=0.23.0->datasets) (4.12.2)\n",
189
+ "Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.10/dist-packages (from requests>=2.32.2->datasets) (3.4.0)\n",
190
+ "Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.10/dist-packages (from requests>=2.32.2->datasets) (3.10)\n",
191
+ "Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.10/dist-packages (from requests>=2.32.2->datasets) (2.2.3)\n",
192
+ "Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.10/dist-packages (from requests>=2.32.2->datasets) (2024.8.30)\n",
193
+ "Requirement already satisfied: python-dateutil>=2.8.2 in /usr/local/lib/python3.10/dist-packages (from pandas->datasets) (2.8.2)\n",
194
+ "Requirement already satisfied: pytz>=2020.1 in /usr/local/lib/python3.10/dist-packages (from pandas->datasets) (2024.2)\n",
195
+ "Requirement already satisfied: tzdata>=2022.7 in /usr/local/lib/python3.10/dist-packages (from pandas->datasets) (2024.2)\n",
196
+ "Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.10/dist-packages (from python-dateutil>=2.8.2->pandas->datasets) (1.16.0)\n",
197
+ "Requirement already satisfied: propcache>=0.2.0 in /usr/local/lib/python3.10/dist-packages (from yarl<2.0,>=1.12.0->aiohttp->datasets) (0.2.0)\n",
198
+ "Downloading datasets-3.1.0-py3-none-any.whl (480 kB)\n",
199
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m480.6/480.6 kB\u001b[0m \u001b[31m6.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
200
+ "\u001b[?25hDownloading dill-0.3.8-py3-none-any.whl (116 kB)\n",
201
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m116.3/116.3 kB\u001b[0m \u001b[31m8.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
202
+ "\u001b[?25hDownloading fsspec-2024.9.0-py3-none-any.whl (179 kB)\n",
203
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m179.3/179.3 kB\u001b[0m \u001b[31m10.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
204
+ "\u001b[?25hDownloading multiprocess-0.70.16-py310-none-any.whl (134 kB)\n",
205
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m134.8/134.8 kB\u001b[0m \u001b[31m11.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
206
+ "\u001b[?25hDownloading xxhash-3.5.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (194 kB)\n",
207
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m194.1/194.1 kB\u001b[0m \u001b[31m14.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
208
+ "\u001b[?25hInstalling collected packages: xxhash, fsspec, dill, multiprocess, datasets\n",
209
+ " Attempting uninstall: fsspec\n",
210
+ " Found existing installation: fsspec 2024.10.0\n",
211
+ " Uninstalling fsspec-2024.10.0:\n",
212
+ " Successfully uninstalled fsspec-2024.10.0\n",
213
+ "\u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n",
214
+ "gcsfs 2024.10.0 requires fsspec==2024.10.0, but you have fsspec 2024.9.0 which is incompatible.\u001b[0m\u001b[31m\n",
215
+ "\u001b[0mSuccessfully installed datasets-3.1.0 dill-0.3.8 fsspec-2024.9.0 multiprocess-0.70.16 xxhash-3.5.0\n"
216
+ ]
217
+ }
218
+ ]
219
+ }
220
+ ],
221
+ "metadata": {
222
+ "kernelspec": {
223
+ "display_name": "Python 3 (ipykernel)",
224
+ "language": "python",
225
+ "name": "python3"
226
+ },
227
+ "language_info": {
228
+ "codemirror_mode": {
229
+ "name": "ipython",
230
+ "version": 3
231
+ },
232
+ "file_extension": ".py",
233
+ "mimetype": "text/x-python",
234
+ "name": "python",
235
+ "nbconvert_exporter": "python",
236
+ "pygments_lexer": "ipython3",
237
+ "version": "3.10.4"
238
+ },
239
+ "colab": {
240
+ "provenance": []
241
+ }
242
+ },
243
+ "nbformat": 4,
244
+ "nbformat_minor": 5
245
+ }
Img2GPS/eval_project_a.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import importlib.util
5
+ import math
6
+ import os
7
+ import sys
8
+ import time
9
+ from typing import Any, Iterable, List, Tuple
10
+
11
+ import numpy as np
12
+ import pandas as pd
13
+ import torch
14
+
15
+
16
+ def _dynamic_import(module_path: str, module_name: str):
17
+ spec = importlib.util.spec_from_file_location(module_name, module_path)
18
+ module = importlib.util.module_from_spec(spec)
19
+ sys.modules[module_name] = module
20
+ spec.loader.exec_module(module)
21
+ return module
22
+
23
+
24
+ def _instantiate_model(model_module, weights_path_override: str | None = None) -> Any:
25
+ """
26
+ Instantiate the student's model in a way that avoids automatic weight loading
27
+ inside their constructor (so we can control loading ourselves).
28
+ """
29
+ # Prefer explicit class if available so we can pass a sentinel weights path
30
+ if hasattr(model_module, "Model"):
31
+ ModelCls = getattr(model_module, "Model")
32
+ try:
33
+ # Pass a non-existent path so student's loader skips default weights
34
+ sentinel = weights_path_override or "__no_weights__.pth"
35
+ return ModelCls(weights_path=sentinel)
36
+ except TypeError:
37
+ # Constructor may not accept weights_path
38
+ return ModelCls()
39
+ except Exception:
40
+ # Fall back to get_model
41
+ if hasattr(model_module, "get_model") and callable(model_module.get_model):
42
+ return model_module.get_model()
43
+ raise
44
+ # Otherwise, try factory
45
+ if hasattr(model_module, "get_model") and callable(model_module.get_model):
46
+ try:
47
+ return model_module.get_model()
48
+ except Exception:
49
+ # As a last resort, try common class names without args
50
+ for cls_name in ["IMG2GPS", "Model"]:
51
+ if hasattr(model_module, cls_name):
52
+ try:
53
+ return getattr(model_module, cls_name)()
54
+ except Exception:
55
+ continue
56
+ raise
57
+ # Direct class fallback
58
+ for cls_name in ["Model", "IMG2GPS"]:
59
+ if hasattr(model_module, cls_name):
60
+ cls = getattr(model_module, cls_name)
61
+ return cls()
62
+ raise AttributeError("Model module must expose 'get_model()' or a class named 'Model'/'IMG2GPS'.")
63
+
64
+
65
+ def _normalize_state_dict_keys(state_dict: dict) -> dict:
66
+ normalized = {}
67
+ for k, v in state_dict.items():
68
+ key = k
69
+ if key.startswith("module."):
70
+ key = key[len("module.") :]
71
+ if key.startswith("model."):
72
+ key = key[len("model.") :]
73
+ while key.startswith("backbone.backbone."):
74
+ key = key.replace("backbone.backbone.", "backbone.", 1)
75
+ normalized[key] = v
76
+ return normalized
77
+
78
+
79
+ def _load_state_into_target(target: Any, sd: dict) -> int:
80
+ """
81
+ Load only intersecting keys (and matching shapes) into the target module.
82
+ Returns number of parameters loaded.
83
+ """
84
+ if target is None or not hasattr(target, "state_dict") or not hasattr(target, "load_state_dict"):
85
+ return 0
86
+ target_sd = target.state_dict()
87
+ filtered = {}
88
+ for k, v in sd.items():
89
+ if k in target_sd and isinstance(v, torch.Tensor) and target_sd[k].shape == v.shape:
90
+ filtered[k] = v
91
+ if not filtered:
92
+ return 0
93
+ missing, unexpected = target.load_state_dict(filtered, strict=False)
94
+ # load_state_dict returns a NamedTuple in newer torch; handle tuple/list fallback
95
+ # We don't use missing/unexpected here beyond validation; count by filtered size.
96
+ return len(filtered)
97
+
98
+
99
+ def _load_checkpoint(model: Any, ckpt_path: str | None) -> Any:
100
+ if not ckpt_path:
101
+ if hasattr(model, "eval"):
102
+ model.eval()
103
+ return model
104
+ checkpoint = torch.load(ckpt_path, map_location="cpu")
105
+ # Accept either {"state_dict": ...} or plain state dict
106
+ if isinstance(checkpoint, dict) and "state_dict" in checkpoint:
107
+ sd = _normalize_state_dict_keys(checkpoint["state_dict"])
108
+ elif isinstance(checkpoint, dict):
109
+ sd = _normalize_state_dict_keys(checkpoint)
110
+ else:
111
+ raise RuntimeError("Checkpoint must be a state_dict or {'state_dict': ...} dictionary.")
112
+ # Try loading into inner model first (common wrapper), then wrapper
113
+ total_loaded = 0
114
+ inner = getattr(model, "model", None)
115
+ total_loaded += _load_state_into_target(inner, sd)
116
+ total_loaded += _load_state_into_target(model, sd)
117
+ if total_loaded == 0:
118
+ # Provide actionable debug info
119
+ sample_keys = list(sd.keys())[:10]
120
+ raise RuntimeError(
121
+ "Failed to load any parameters from checkpoint into model. "
122
+ f"Example checkpoint keys after normalization: {sample_keys}"
123
+ )
124
+ if hasattr(model, "eval"):
125
+ model.eval()
126
+ return model
127
+
128
+
129
+ def _predict_in_batches(model: Any, X: List[Any], batch_size: int = 32) -> Tuple[List[Any], float, float]:
130
+ preds: List[Any] = []
131
+ total_s = 0.0
132
+ total_examples = 0
133
+ has_predict = hasattr(model, "predict") and callable(getattr(model, "predict"))
134
+ for i in range(0, len(X), batch_size):
135
+ batch = X[i : i + batch_size]
136
+ start = time.perf_counter()
137
+ if has_predict:
138
+ batch_preds = model.predict(batch)
139
+ else:
140
+ with torch.no_grad():
141
+ outputs = model(batch) # type: ignore
142
+ if isinstance(outputs, torch.Tensor):
143
+ batch_preds = outputs.cpu().tolist()
144
+ else:
145
+ batch_preds = outputs
146
+ end = time.perf_counter()
147
+ infer_time = end - start
148
+ total_s += infer_time
149
+ total_examples += len(batch)
150
+ if isinstance(batch_preds, torch.Tensor):
151
+ batch_preds = batch_preds.cpu().tolist()
152
+ preds.extend(list(batch_preds))
153
+ avg_ms = (total_s / max(total_examples, 1)) * 1000.0
154
+ return preds, total_s, avg_ms
155
+
156
+
157
+ def _resolve_column(columns: List[str], aliases: List[str]) -> str:
158
+ for name in aliases:
159
+ if name in columns:
160
+ return name
161
+ raise KeyError(f"Could not find any of the columns {aliases} in {columns}")
162
+
163
+
164
+ def _load_raw_lat_lon(csv_path: str) -> List[List[float]]:
165
+ df = pd.read_csv(csv_path)
166
+ cols = df.columns.tolist()
167
+ lat_col = _resolve_column(cols, ["Latitude", "latitude", "lat"])
168
+ lon_col = _resolve_column(cols, ["Longitude", "longitude", "lon"])
169
+ labels: List[List[float]] = []
170
+ for _, row in df.iterrows():
171
+ labels.append([float(row[lat_col]), float(row[lon_col])])
172
+ return labels
173
+
174
+
175
+ def _ensure_pairs(arr: List[Any]) -> np.ndarray:
176
+ pairs: List[List[float]] = []
177
+ for item in arr:
178
+ if isinstance(item, torch.Tensor):
179
+ item = item.detach().cpu().numpy()
180
+ item_np = np.asarray(item, dtype=np.float64)
181
+ if item_np.shape == (2,):
182
+ pairs.append([float(item_np[0]), float(item_np[1])])
183
+ elif item_np.ndim == 1 and item_np.size == 2:
184
+ pairs.append([float(item_np[0]), float(item_np[1])])
185
+ else:
186
+ raise ValueError(f"Expected 2-length pair, got shape {item_np.shape}")
187
+ return np.asarray(pairs, dtype=np.float64)
188
+
189
+
190
+ def _haversine_m(a: Iterable[float], b: Iterable[float]) -> float:
191
+ lat1, lon1 = a
192
+ lat2, lon2 = b
193
+ radius = 6_371_000.0
194
+ phi1 = math.radians(lat1)
195
+ phi2 = math.radians(lat2)
196
+ dphi = math.radians(lat2 - lat1)
197
+ dlambda = math.radians(lon2 - lon1)
198
+ h = math.sin(dphi / 2) ** 2 + math.cos(phi1) * math.cos(phi2) * math.sin(dlambda / 2) ** 2
199
+ return 2 * radius * math.asin(math.sqrt(h))
200
+
201
+
202
+ def compute_metrics(preds: List[Any], targets_raw: List[Any]) -> dict:
203
+ preds_np = _ensure_pairs(preds)
204
+ t_np = _ensure_pairs(targets_raw)
205
+ n = min(len(preds_np), len(t_np))
206
+ preds_np = preds_np[:n]
207
+ t_np = t_np[:n]
208
+ diffs = preds_np - t_np
209
+ mae = float(np.abs(diffs).mean())
210
+ rmse = float(np.sqrt((diffs ** 2).mean()))
211
+ distances = [_haversine_m(p, t) for p, t in zip(preds_np, t_np)]
212
+ avg_distance_m = float(np.mean(distances)) if distances else float("nan")
213
+ return {"mae": mae, "rmse": rmse, "avg_distance_m": avg_distance_m, "num_examples": n}
214
+
215
+
216
+ def parse_args() -> argparse.Namespace:
217
+ p = argparse.ArgumentParser(description="Local evaluator for Project A (img2gps).")
218
+ p.add_argument("--model", required=True, help="Path to student's model.py")
219
+ p.add_argument("--preprocess", required=True, help="Path to student's preprocess.py")
220
+ p.add_argument("--weights", default=None, help="Optional path to model checkpoint (e.g., model.pt)")
221
+ p.add_argument("--csv", required=True, help="Path to validation CSV (e.g., ./val/metadata.csv)")
222
+ p.add_argument("--batch-size", type=int, default=32)
223
+ return p.parse_args()
224
+
225
+
226
+ def main() -> None:
227
+ args = parse_args()
228
+ model_mod = _dynamic_import(args.model, "student_model_a")
229
+ preproc_mod = _dynamic_import(args.preprocess, "student_preproc_a")
230
+ # Instantiate while preventing any default weight load from student's constructor
231
+ model = _instantiate_model(model_mod, weights_path_override="__no_weights__.pth")
232
+ model = _load_checkpoint(model, args.weights)
233
+
234
+ X, _ = preproc_mod.prepare_data(args.csv)
235
+ if isinstance(X, torch.Tensor):
236
+ inputs = list(X)
237
+ elif isinstance(X, np.ndarray):
238
+ inputs = list(X)
239
+ else:
240
+ inputs = list(X)
241
+
242
+ preds, total_s, avg_ms = _predict_in_batches(model, inputs, batch_size=args.batch_size)
243
+ targets_raw = _load_raw_lat_lon(args.csv)
244
+ metrics = compute_metrics(preds, targets_raw)
245
+
246
+ print(f"num_examples: {metrics['num_examples']}")
247
+ print(f"avg_infer_ms: {avg_ms:.3f}")
248
+ print(f"total_infer_s: {total_s:.3f}")
249
+ print(f"mae (deg): {metrics['mae']:.6f}")
250
+ print(f"rmse (deg): {metrics['rmse']:.6f}")
251
+ print(f"avg_distance_m: {metrics['avg_distance_m']:.3f}")
252
+
253
+
254
+ if __name__ == "__main__":
255
+ main()
256
+
257
+
Img2GPS/reference/IMG_7159.jpg ADDED

Git LFS Details

  • SHA256: 75eda1ef6178ae4a48c15bce12082679444f8a228885f6e9a02d798acc619940
  • Pointer size: 132 Bytes
  • Size of remote file: 2.48 MB
Img2GPS/reference/IMG_7163.jpg ADDED

Git LFS Details

  • SHA256: 0c729e840bd55e81dcb4a7b89b24fb4bfe4f4f5188f9096b486882cad101c52a
  • Pointer size: 132 Bytes
  • Size of remote file: 2.34 MB
Img2GPS/reference/IMG_7165.jpg ADDED

Git LFS Details

  • SHA256: 27f38bcd68233946c13b656fa5c60760559248461d20601f26bc9954e7036725
  • Pointer size: 132 Bytes
  • Size of remote file: 2.14 MB
Img2GPS/reference/IMG_7170.jpg ADDED

Git LFS Details

  • SHA256: 1bd4973d83f66246b74eec5f840f9f83f4dd9271be0275d1a6ed5b3e38bed00d
  • Pointer size: 132 Bytes
  • Size of remote file: 2.5 MB
Img2GPS/reference/IMG_7171.jpg ADDED

Git LFS Details

  • SHA256: f217b055276684246dcb3e8df9f054531e92ad26b481dd675140ead0ca11382b
  • Pointer size: 132 Bytes
  • Size of remote file: 2.69 MB
Img2GPS/reference/IMG_7175.jpg ADDED

Git LFS Details

  • SHA256: 1f6cca76bc602875f94c9992b6f2632c3b12a1a067ca6b725fc14c1730a89756
  • Pointer size: 132 Bytes
  • Size of remote file: 2.75 MB
Img2GPS/reference/IMG_7178.jpg ADDED

Git LFS Details

  • SHA256: a0422c23ae6b5a5d6f45ca80ef837d95e96d85e3b5fe8eb3816544c2fe63b233
  • Pointer size: 132 Bytes
  • Size of remote file: 2.46 MB
Img2GPS/reference/IMG_7179.jpg ADDED

Git LFS Details

  • SHA256: 50875579a1a5af129e0a48451c032be968ccacb64a0b404393720139bc5e0add
  • Pointer size: 132 Bytes
  • Size of remote file: 3.04 MB
Img2GPS/reference/IMG_7181.jpg ADDED

Git LFS Details

  • SHA256: b01d1fa3a9f27c635f0b8d9936add2074542096edcc22ef7302f75ca18a6c1c9
  • Pointer size: 132 Bytes
  • Size of remote file: 2.08 MB
Img2GPS/reference/IMG_7182.jpg ADDED

Git LFS Details

  • SHA256: c2805dcbbd8db5cd39a913f48c7ed14f419cc56d7881bfc51c335e8111adf8bc
  • Pointer size: 132 Bytes
  • Size of remote file: 2.55 MB
Img2GPS/reference/metadata.csv ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ file_name,Latitude,Longitude
2
+ IMG_7182.jpg,39.95240833333334,-75.19158055555556
3
+ IMG_7181.jpg,39.95240833333334,-75.19158055555556
4
+ IMG_7171.jpg,39.952308333333335,-75.191575
5
+ IMG_7179.jpg,39.952400000000004,-75.191575
6
+ IMG_7175.jpg,39.952325,-75.19158055555556
7
+ IMG_7178.jpg,39.952400000000004,-75.19158055555556
8
+ IMG_7163.jpg,39.9523,-75.19155
9
+ IMG_7159.jpg,39.9523,-75.19155
10
+ IMG_7170.jpg,39.952308333333335,-75.191575
11
+ IMG_7165.jpg,39.9523,-75.19155
README.md ADDED
File without changes
main.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ def main():
2
+ print("Hello from final!")
3
+
4
+
5
+ if __name__ == "__main__":
6
+ main()
model_template.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+ from typing import Any, Iterable, List
4
+
5
+
6
+ class Model(nn.Module):
7
+ """
8
+ Template model for the leaderboard.
9
+
10
+ Requirements:
11
+ - Must be instantiable with no arguments (called by the evaluator).
12
+ - Must implement `predict(batch)` which receives an iterable of inputs and
13
+ returns a list of predictions (labels).
14
+ - Must implement `eval()` to place the model in evaluation mode.
15
+ - If you use PyTorch, submit a state_dict to be loaded via `load_state_dict`
16
+ """
17
+
18
+ def __init__(self, *args, **kwargs) -> None:
19
+ super().__init__(*args, **kwargs)
20
+ # Initialize your model here
21
+
22
+ def eval(self) -> nn.Module:
23
+ # Optional: set your model to evaluation mode
24
+ return self
25
+
26
+ def predict(self, batch: Iterable[Any]) -> List[Any]:
27
+ """
28
+ Implement your inference here.
29
+ Inputs:
30
+ batch: Iterable of preprocessed inputs (as produced by your preprocess.py)
31
+ Returns:
32
+ A list of predictions with the same length as `batch`.
33
+ """
34
+ raise NotImplementedError("Implement predict(...) to return a list of labels.")
35
+
36
+
37
+ def get_model() -> Model:
38
+ """
39
+ Factory function required by the evaluator.
40
+ Returns an uninitialized model instance. The evaluator may optionally load
41
+ weights (if provided) before calling predict(...).
42
+ """
43
+ return Model()
44
+
45
+
pyproject.toml ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "final"
3
+ version = "0.1.0"
4
+ description = "Add your description here"
5
+ readme = "README.md"
6
+ requires-python = ">=3.12"
7
+ dependencies = [
8
+ "numpy",
9
+ "pandas",
10
+ "torch==2.9.1",
11
+ "torchvision",
12
+ "scikit-learn",
13
+ "opencv-python"
14
+ ]
uv.lock ADDED
The diff for this file is too large to render. See raw diff