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785333",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [],
|
| 9 |
+
"source": [
|
| 10 |
+
"import h5py\n",
|
| 11 |
+
"from tqdm import tqdm, trange\n",
|
| 12 |
+
"import rasterio\n",
|
| 13 |
+
"import matplotlib.pyplot as plt\n",
|
| 14 |
+
"import os\n",
|
| 15 |
+
"import numpy as np\n",
|
| 16 |
+
"import ipywidgets as widgets\n",
|
| 17 |
+
"import geopandas as gpd\n",
|
| 18 |
+
"from ipyleaflet import Map, GeoJSON\n",
|
| 19 |
+
"from ipywidgets import Output\n",
|
| 20 |
+
"import shutil\n",
|
| 21 |
+
"\n",
|
| 22 |
+
"import torch\n",
|
| 23 |
+
"import torch, open_clip\n",
|
| 24 |
+
"from huggingface_hub import hf_hub_download\n",
|
| 25 |
+
"\n",
|
| 26 |
+
"from sklearn.cluster import KMeans\n",
|
| 27 |
+
"\n",
|
| 28 |
+
"import torch\n",
|
| 29 |
+
"import torch.nn.functional as F\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"from torch import Tensor\n",
|
| 32 |
+
"from transformers import AutoTokenizer, AutoModel\n",
|
| 33 |
+
"from transformers import AutoModelForCausalLM\n",
|
| 34 |
+
"\n",
|
| 35 |
+
"import random\n",
|
| 36 |
+
"import h5py\n",
|
| 37 |
+
"import json\n",
|
| 38 |
+
"\n",
|
| 39 |
+
"import fiona\n",
|
| 40 |
+
"from fiona.crs import from_epsg\n",
|
| 41 |
+
"from shapely.geometry import box, mapping"
|
| 42 |
+
]
|
| 43 |
+
},
|
| 44 |
+
{
|
| 45 |
+
"cell_type": "code",
|
| 46 |
+
"execution_count": 2,
|
| 47 |
+
"id": "cf1ac5c8-9236-400c-b9fb-08ac4f257b5d",
|
| 48 |
+
"metadata": {},
|
| 49 |
+
"outputs": [],
|
| 50 |
+
"source": [
|
| 51 |
+
"# Set paths\n",
|
| 52 |
+
"imagery_path = './south_america_reproj_resize_cog'\n",
|
| 53 |
+
"embedding_path = './south_america_remoteclip_emb.h5'\n",
|
| 54 |
+
"extent_path = './south_america_extents.gpkg'\n",
|
| 55 |
+
"vocabulary_path = './remoteclip_to_qwen3embedding06b_vocabulary.h5'\n",
|
| 56 |
+
"oam_meta_path = './oam_meta.json'"
|
| 57 |
+
]
|
| 58 |
+
},
|
| 59 |
+
{
|
| 60 |
+
"cell_type": "markdown",
|
| 61 |
+
"id": "13900685-b4e4-4b04-adcf-73508b938a10",
|
| 62 |
+
"metadata": {},
|
| 63 |
+
"source": [
|
| 64 |
+
"# Functional"
|
| 65 |
+
]
|
| 66 |
+
},
|
| 67 |
+
{
|
| 68 |
+
"cell_type": "code",
|
| 69 |
+
"execution_count": 3,
|
| 70 |
+
"id": "3d7298cb-87fc-4246-8a85-a3f1b397aeaf",
|
| 71 |
+
"metadata": {},
|
| 72 |
+
"outputs": [
|
| 73 |
+
{
|
| 74 |
+
"name": "stderr",
|
| 75 |
+
"output_type": "stream",
|
| 76 |
+
"text": [
|
| 77 |
+
"100%|█████████████████████████████| 9640554/9640554 [01:05<00:00, 146702.48it/s]\n"
|
| 78 |
+
]
|
| 79 |
+
},
|
| 80 |
+
{
|
| 81 |
+
"name": "stdout",
|
| 82 |
+
"output_type": "stream",
|
| 83 |
+
"text": [
|
| 84 |
+
"Done!\n"
|
| 85 |
+
]
|
| 86 |
+
}
|
| 87 |
+
],
|
| 88 |
+
"source": [
|
| 89 |
+
"with open(oam_meta_path, 'r') as f:\n",
|
| 90 |
+
" oam_meta = json.load(f)\n",
|
| 91 |
+
"\n",
|
| 92 |
+
"with h5py.File(vocabulary_path, 'r') as f:\n",
|
| 93 |
+
" text_vocabulary = f['text'][:]\n",
|
| 94 |
+
" remoteclip_vocabulary = f['remoteclip'][:, :]\n",
|
| 95 |
+
" qwen3embedding06b_vocabulary = f['qwen3embedding06b'][:, :]\n",
|
| 96 |
+
"\n",
|
| 97 |
+
"\n",
|
| 98 |
+
"class EDS(object):\n",
|
| 99 |
+
" def __init__(self, imagery_path, extent_path, embedding_path, embedding_footprint_size):\n",
|
| 100 |
+
" self.imagery_path = imagery_path\n",
|
| 101 |
+
" self.extent_path = extent_path\n",
|
| 102 |
+
" self.embedding_path = embedding_path\n",
|
| 103 |
+
"\n",
|
| 104 |
+
" # Load h5 datasets\n",
|
| 105 |
+
" self.h5file = h5py.File(embedding_path, 'r')\n",
|
| 106 |
+
" self.embedding_ds = self.h5file['embedding']\n",
|
| 107 |
+
" self.fname_ds = self.h5file['fname']\n",
|
| 108 |
+
" self.meta_ds = self.h5file['meta']\n",
|
| 109 |
+
" self.embedding_footprint_size = embedding_footprint_size\n",
|
| 110 |
+
" \n",
|
| 111 |
+
" # Prepare file dict\n",
|
| 112 |
+
" self.file_dict = dict()\n",
|
| 113 |
+
" for i in trange(self.meta_ds.shape[0]):\n",
|
| 114 |
+
" file_num, epsg, x, y, coverage = self.meta_ds[i]\n",
|
| 115 |
+
" if file_num not in self.file_dict:\n",
|
| 116 |
+
" self.file_dict[file_num] = []\n",
|
| 117 |
+
" self.file_dict[file_num].append((i, file_num, epsg, x, y, coverage))\n",
|
| 118 |
+
" \n",
|
| 119 |
+
" # Prepare name dicts\n",
|
| 120 |
+
" self.fname_to_fnum = dict()\n",
|
| 121 |
+
" self.fnum_to_fname = dict()\n",
|
| 122 |
+
" self.fname_to_fpath = dict()\n",
|
| 123 |
+
" for fnum, fname in enumerate(self.fname_ds):\n",
|
| 124 |
+
" fname = fname.decode('UTF8')\n",
|
| 125 |
+
" self.fname_to_fnum[fname] = fnum\n",
|
| 126 |
+
" self.fnum_to_fname[fnum] = fname\n",
|
| 127 |
+
" self.fname_to_fpath[fname] = os.path.join(imagery_path, fname)\n",
|
| 128 |
+
"\n",
|
| 129 |
+
" self.gdf = gpd.read_file(extent_path)\n",
|
| 130 |
+
"\n",
|
| 131 |
+
" def get_embeddings_by_fname(self, fname):\n",
|
| 132 |
+
" xy_list = []\n",
|
| 133 |
+
" embedding_list = []\n",
|
| 134 |
+
" for i, file_num, epsg, x, y, coverage in self.file_dict[self.fname_to_fnum[fname]]:\n",
|
| 135 |
+
" xy_list.append((x, y))\n",
|
| 136 |
+
" \n",
|
| 137 |
+
" embedding_t = torch.from_numpy(self.embedding_ds[i])\n",
|
| 138 |
+
" embedding_t = embedding_t / embedding_t.norm(dim=-1, keepdim=True)\n",
|
| 139 |
+
" embedding_list.append(embedding_t)\n",
|
| 140 |
+
" return xy_list, embedding_list, epsg\n",
|
| 141 |
+
"\n",
|
| 142 |
+
" def get_tumbnail_and_convert_coordinates_by_fname(self, fname, xy_list=None):\n",
|
| 143 |
+
" hw_list = []\n",
|
| 144 |
+
" cog_path = self.fname_to_fpath[fname]\n",
|
| 145 |
+
" with rasterio.open(cog_path) as src:\n",
|
| 146 |
+
" oviews = src.overviews(1)\n",
|
| 147 |
+
" decimation = oviews[-1]\n",
|
| 148 |
+
" \n",
|
| 149 |
+
" read_b = lambda n: src.read(n, out_shape=(1, int(src.height // decimation), int(src.width // decimation)))\n",
|
| 150 |
+
" thumbnail = np.stack([read_b(1), read_b(2), read_b(3)], axis=-1)\n",
|
| 151 |
+
" thumbnail = thumbnail.astype(np.uint8)\n",
|
| 152 |
+
"\n",
|
| 153 |
+
" if xy_list is not None:\n",
|
| 154 |
+
" for x, y in xy_list:\n",
|
| 155 |
+
" ph, pw = src.index(x, y)\n",
|
| 156 |
+
" hw_list.append((ph, pw))\n",
|
| 157 |
+
" return thumbnail, hw_list, decimation\n",
|
| 158 |
+
" \n",
|
| 159 |
+
" def get_thumbnail_and_embeddings_by_fname(self, fname):\n",
|
| 160 |
+
" xy_list, embedding_list, epsg = self.get_embeddings_by_fname(fname)\n",
|
| 161 |
+
" thumbnail, hw_list, decimation = self.get_tumbnail_and_convert_coordinates_by_fname(fname, xy_list)\n",
|
| 162 |
+
" return thumbnail, decimation, embedding_list, xy_list, hw_list, epsg\n",
|
| 163 |
+
"\n",
|
| 164 |
+
" def __del__(self):\n",
|
| 165 |
+
" self.h5file.close()\n",
|
| 166 |
+
"\n",
|
| 167 |
+
"\n",
|
| 168 |
+
"embeddings_dataset = EDS(imagery_path, extent_path, embedding_path, embedding_footprint_size=112)\n",
|
| 169 |
+
"print('Done!')"
|
| 170 |
+
]
|
| 171 |
+
},
|
| 172 |
+
{
|
| 173 |
+
"cell_type": "code",
|
| 174 |
+
"execution_count": 4,
|
| 175 |
+
"id": "8e696710-89f9-4424-a60c-d3a509b03ef3",
|
| 176 |
+
"metadata": {},
|
| 177 |
+
"outputs": [
|
| 178 |
+
{
|
| 179 |
+
"name": "stdout",
|
| 180 |
+
"output_type": "stream",
|
| 181 |
+
"text": [
|
| 182 |
+
"['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']\n"
|
| 183 |
+
]
|
| 184 |
+
}
|
| 185 |
+
],
|
| 186 |
+
"source": [
|
| 187 |
+
"prop_cycle = plt.rcParams['axes.prop_cycle']\n",
|
| 188 |
+
"colors_cycle = prop_cycle.by_key()['color']\n",
|
| 189 |
+
"print(colors_cycle)\n",
|
| 190 |
+
"\n",
|
| 191 |
+
"def hex_to_rgb(hex_color_string):\n",
|
| 192 |
+
" \"\"\"\n",
|
| 193 |
+
" Converts a hexadecimal color string (e.g., \"#RRGGBB\" or \"RRGGBB\")\n",
|
| 194 |
+
" to an RGB tuple (R, G, B).\n",
|
| 195 |
+
" \"\"\"\n",
|
| 196 |
+
" hex_color_string = hex_color_string.lstrip('#') # Remove '#' if present\n",
|
| 197 |
+
" return tuple(int(hex_color_string[i:i+2], 16) for i in (0, 2, 4))\n",
|
| 198 |
+
"\n",
|
| 199 |
+
"\n",
|
| 200 |
+
"def random_rgb_color():\n",
|
| 201 |
+
" return (int(random.randint(0, 255)), int(random.randint(0, 255)), int(random.randint(0, 255)))\n",
|
| 202 |
+
"\n",
|
| 203 |
+
"def make_color_map_from_cluster_index(clusters):\n",
|
| 204 |
+
" cluster_index_list = sorted(list(set(clusters)))\n",
|
| 205 |
+
" color_map = dict()\n",
|
| 206 |
+
" if len(cluster_index_list) < 11:\n",
|
| 207 |
+
" for i in range(len(cluster_index_list)):\n",
|
| 208 |
+
" color_map[cluster_index_list[i]] = hex_to_rgb(colors_cycle[i])\n",
|
| 209 |
+
" else:\n",
|
| 210 |
+
" for i in range(len(cluster_index_list)):\n",
|
| 211 |
+
" color_map[cluster_index_list[i]] = random_rgb_color()\n",
|
| 212 |
+
" return color_map"
|
| 213 |
+
]
|
| 214 |
+
},
|
| 215 |
+
{
|
| 216 |
+
"cell_type": "code",
|
| 217 |
+
"execution_count": 5,
|
| 218 |
+
"id": "0ff2154f-2fd4-439a-a439-11f14306c417",
|
| 219 |
+
"metadata": {},
|
| 220 |
+
"outputs": [
|
| 221 |
+
{
|
| 222 |
+
"name": "stdout",
|
| 223 |
+
"output_type": "stream",
|
| 224 |
+
"text": [
|
| 225 |
+
"ViT-L-14 is downloaded to checkpoints/models--chendelong--RemoteCLIP/snapshots/bf1d8a3ccf2ddbf7c875705e46373bfe542bce38/RemoteCLIP-ViT-L-14.pt.\n"
|
| 226 |
+
]
|
| 227 |
+
}
|
| 228 |
+
],
|
| 229 |
+
"source": [
|
| 230 |
+
"class RemoteCLIPTextModel(object):\n",
|
| 231 |
+
" def __init__(self):\n",
|
| 232 |
+
" model_name = 'ViT-L-14'\n",
|
| 233 |
+
" self.tokenizer = open_clip.get_tokenizer(model_name)\n",
|
| 234 |
+
" \n",
|
| 235 |
+
" checkpoint_path = hf_hub_download(\"chendelong/RemoteCLIP\", f\"RemoteCLIP-{model_name}.pt\", cache_dir='checkpoints')\n",
|
| 236 |
+
" print(f'{model_name} is downloaded to {checkpoint_path}.')\n",
|
| 237 |
+
" \n",
|
| 238 |
+
" self.device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 239 |
+
" model, _, preprocess = open_clip.create_model_and_transforms(model_name)\n",
|
| 240 |
+
" ckpt = torch.load(checkpoint_path, map_location=\"cpu\")\n",
|
| 241 |
+
" message = model.load_state_dict(ckpt)\n",
|
| 242 |
+
" self.model = model.to(self.device).eval()\n",
|
| 243 |
+
"\n",
|
| 244 |
+
" def __call__(self, text_queries):\n",
|
| 245 |
+
" text = self.tokenizer(text_queries)\n",
|
| 246 |
+
" with torch.no_grad():\n",
|
| 247 |
+
" text_features = self.model.encode_text(text.to(self.device))\n",
|
| 248 |
+
" text_features /= text_features.norm(dim=-1, keepdim=True)[0, ...]\n",
|
| 249 |
+
"\n",
|
| 250 |
+
" return text_features.detach()\n",
|
| 251 |
+
"\n",
|
| 252 |
+
"remoteclip_text_model = RemoteCLIPTextModel()\n",
|
| 253 |
+
"\n",
|
| 254 |
+
"\n",
|
| 255 |
+
"class Qwen3E06BTextModel(object):\n",
|
| 256 |
+
" def __init__(self):\n",
|
| 257 |
+
"\n",
|
| 258 |
+
" self.tokenizer = AutoTokenizer.from_pretrained('Qwen/Qwen3-Embedding-0.6B', padding_side='left')\n",
|
| 259 |
+
" self.model = AutoModel.from_pretrained('Qwen/Qwen3-Embedding-0.6B')\n",
|
| 260 |
+
"\n",
|
| 261 |
+
" @staticmethod\n",
|
| 262 |
+
" def last_token_pool(last_hidden_states: Tensor,\n",
|
| 263 |
+
" attention_mask: Tensor) -> Tensor:\n",
|
| 264 |
+
" left_padding = (attention_mask[:, -1].sum() == attention_mask.shape[0])\n",
|
| 265 |
+
" if left_padding:\n",
|
| 266 |
+
" return last_hidden_states[:, -1]\n",
|
| 267 |
+
" else:\n",
|
| 268 |
+
" sequence_lengths = attention_mask.sum(dim=1) - 1\n",
|
| 269 |
+
" batch_size = last_hidden_states.shape[0]\n",
|
| 270 |
+
" return last_hidden_states[torch.arange(batch_size, device=last_hidden_states.device), sequence_lengths]\n",
|
| 271 |
+
"\n",
|
| 272 |
+
" def __call__(self, text_queries):\n",
|
| 273 |
+
" # Tokenize the input texts\n",
|
| 274 |
+
" batch_dict = self.tokenizer(\n",
|
| 275 |
+
" text_queries,\n",
|
| 276 |
+
" padding=True,\n",
|
| 277 |
+
" truncation=True,\n",
|
| 278 |
+
" max_length=8192,\n",
|
| 279 |
+
" return_tensors=\"pt\",\n",
|
| 280 |
+
" )\n",
|
| 281 |
+
" \n",
|
| 282 |
+
" with torch.no_grad(), torch.cuda.amp.autocast():\n",
|
| 283 |
+
" batch_dict.to(self.model.device)\n",
|
| 284 |
+
" outputs = self.model(**batch_dict)\n",
|
| 285 |
+
" embeddings = self.last_token_pool(outputs.last_hidden_state, batch_dict['attention_mask'])\n",
|
| 286 |
+
"\n",
|
| 287 |
+
" return embeddings.detach()\n",
|
| 288 |
+
"\n",
|
| 289 |
+
"qwen3embedding06b_text_model = Qwen3E06BTextModel()\n",
|
| 290 |
+
"\n",
|
| 291 |
+
"class VocabularyPair(object):\n",
|
| 292 |
+
" def __init__(self, remoteclip_text_model, qwen3embedding06b_text_model,\n",
|
| 293 |
+
" qwen3embedding06b_vocabulary, remoteclip_vocabulary,\n",
|
| 294 |
+
" text_vocabulary):\n",
|
| 295 |
+
" self.remoteclip_text_model = remoteclip_text_model\n",
|
| 296 |
+
" self.qwen3embedding06b_text_model = qwen3embedding06b_text_model\n",
|
| 297 |
+
" self.qwen3embedding06b_vocabulary = qwen3embedding06b_vocabulary\n",
|
| 298 |
+
" self.remoteclip_vocabulary = remoteclip_vocabulary\n",
|
| 299 |
+
" self.text_vocabulary = text_vocabulary\n",
|
| 300 |
+
" \n",
|
| 301 |
+
" def find_by_embedding_in_qwen3embedding06b_vocabulary(self, query_emb):\n",
|
| 302 |
+
" \n",
|
| 303 |
+
" query_emb = F.normalize(query_emb, p=2, dim=1)\n",
|
| 304 |
+
" score_value_list = list()\n",
|
| 305 |
+
" vocabulary_len = self.qwen3embedding06b_vocabulary.shape[0]\n",
|
| 306 |
+
" for n in range(vocabulary_len):\n",
|
| 307 |
+
" t_text = self.text_vocabulary[n].decode('UTF8')\n",
|
| 308 |
+
" t_emb = torch.unsqueeze(torch.from_numpy(self.qwen3embedding06b_vocabulary[n, :]), dim=0)\n",
|
| 309 |
+
" t_emb = F.normalize(t_emb, p=2, dim=1)\n",
|
| 310 |
+
" score = float((t_emb @ query_emb.T))\n",
|
| 311 |
+
" score_value_list.append((score, t_text))\n",
|
| 312 |
+
" return sorted(score_value_list, key=lambda x: -x[0])\n",
|
| 313 |
+
" \n",
|
| 314 |
+
" \n",
|
| 315 |
+
" def find_by_text_in_qwen3embedding06b_vocabulary(self, text):\n",
|
| 316 |
+
" query_emb = self.qwen3embedding06b_text_model([text, ])\n",
|
| 317 |
+
" return self.find_by_embedding_in_qwen3embedding06b_vocabulary(query_emb)\n",
|
| 318 |
+
"\n",
|
| 319 |
+
" \n",
|
| 320 |
+
" def find_by_embedding_in_remoteclip_vocabulary(self, query_emb):\n",
|
| 321 |
+
" query_emb = F.normalize(query_emb, p=2, dim=1)\n",
|
| 322 |
+
" \n",
|
| 323 |
+
" score_value_list = list()\n",
|
| 324 |
+
" vocabulary_len = self.remoteclip_vocabulary.shape[0]\n",
|
| 325 |
+
" for n in range(vocabulary_len):\n",
|
| 326 |
+
" t_text = self.text_vocabulary[n].decode('UTF8')\n",
|
| 327 |
+
" t_emb = torch.unsqueeze(torch.from_numpy(self.remoteclip_vocabulary[n, :]), dim=0)\n",
|
| 328 |
+
" t_emb = F.normalize(t_emb, p=2, dim=1)\n",
|
| 329 |
+
" score = float((t_emb @ query_emb.T))\n",
|
| 330 |
+
" score_value_list.append((score, t_text))\n",
|
| 331 |
+
" return sorted(score_value_list, key=lambda x: -x[0])\n",
|
| 332 |
+
" \n",
|
| 333 |
+
" def find_by_text_in_remoteclip_vocabulary(self, text):\n",
|
| 334 |
+
" \n",
|
| 335 |
+
" query_emb = remoteclip_text_model([text, ])\n",
|
| 336 |
+
" return self.find_by_embedding_in_remoteclip_vocabulary(query_emb)\n",
|
| 337 |
+
"\n",
|
| 338 |
+
"vocabulary_pair = VocabularyPair(remoteclip_text_model, qwen3embedding06b_text_model,\n",
|
| 339 |
+
" qwen3embedding06b_vocabulary, remoteclip_vocabulary,\n",
|
| 340 |
+
" text_vocabulary)"
|
| 341 |
+
]
|
| 342 |
+
},
|
| 343 |
+
{
|
| 344 |
+
"cell_type": "code",
|
| 345 |
+
"execution_count": 6,
|
| 346 |
+
"id": "dea2432e-d822-4c83-8400-c23da5b1261a",
|
| 347 |
+
"metadata": {},
|
| 348 |
+
"outputs": [
|
| 349 |
+
{
|
| 350 |
+
"name": "stderr",
|
| 351 |
+
"output_type": "stream",
|
| 352 |
+
"text": [
|
| 353 |
+
"`torch_dtype` is deprecated! Use `dtype` instead!\n"
|
| 354 |
+
]
|
| 355 |
+
},
|
| 356 |
+
{
|
| 357 |
+
"data": {
|
| 358 |
+
"application/vnd.jupyter.widget-view+json": {
|
| 359 |
+
"model_id": "2404f1f6027a4999bc62421c3ee9ddf5",
|
| 360 |
+
"version_major": 2,
|
| 361 |
+
"version_minor": 0
|
| 362 |
+
},
|
| 363 |
+
"text/plain": [
|
| 364 |
+
"Loading checkpoint shards: 0%| | 0/3 [00:00<?, ?it/s]"
|
| 365 |
+
]
|
| 366 |
+
},
|
| 367 |
+
"metadata": {},
|
| 368 |
+
"output_type": "display_data"
|
| 369 |
+
}
|
| 370 |
+
],
|
| 371 |
+
"source": [
|
| 372 |
+
"model_name = \"Qwen/Qwen3-4B-Instruct-2507\"\n",
|
| 373 |
+
"# load the tokenizer and the model\n",
|
| 374 |
+
"tokenizer = AutoTokenizer.from_pretrained(model_name)\n",
|
| 375 |
+
"model = AutoModelForCausalLM.from_pretrained(\n",
|
| 376 |
+
" model_name,\n",
|
| 377 |
+
" torch_dtype=\"auto\",\n",
|
| 378 |
+
" device_map=\"auto\"\n",
|
| 379 |
+
")\n",
|
| 380 |
+
"\n",
|
| 381 |
+
"def summarize(t):\n",
|
| 382 |
+
" prompt = f\"Summarize this words in a one word, which could be used as a map legend, this word should be noun and depict particular type of objects, just one word as output: '{t}'.\"\n",
|
| 383 |
+
" messages = [\n",
|
| 384 |
+
" {\"role\": \"user\", \"content\": prompt}\n",
|
| 385 |
+
" ]\n",
|
| 386 |
+
" text = tokenizer.apply_chat_template(\n",
|
| 387 |
+
" messages,\n",
|
| 388 |
+
" tokenize=False,\n",
|
| 389 |
+
" add_generation_prompt=True,\n",
|
| 390 |
+
" )\n",
|
| 391 |
+
" model_inputs = tokenizer([text], return_tensors=\"pt\").to(model.device)\n",
|
| 392 |
+
" \n",
|
| 393 |
+
" # conduct text completion\n",
|
| 394 |
+
" generated_ids = model.generate(\n",
|
| 395 |
+
" **model_inputs,\n",
|
| 396 |
+
" max_new_tokens=16384\n",
|
| 397 |
+
" )\n",
|
| 398 |
+
" output_ids = generated_ids[0][len(model_inputs.input_ids[0]):].tolist() \n",
|
| 399 |
+
" \n",
|
| 400 |
+
" content = tokenizer.decode(output_ids, skip_special_tokens=True)\n",
|
| 401 |
+
" return content"
|
| 402 |
+
]
|
| 403 |
+
},
|
| 404 |
+
{
|
| 405 |
+
"cell_type": "markdown",
|
| 406 |
+
"id": "13c5e790-44e1-4787-85cf-7aa7cb64dccd",
|
| 407 |
+
"metadata": {},
|
| 408 |
+
"source": [
|
| 409 |
+
"# Imgery selection"
|
| 410 |
+
]
|
| 411 |
+
},
|
| 412 |
+
{
|
| 413 |
+
"cell_type": "code",
|
| 414 |
+
"execution_count": 15,
|
| 415 |
+
"id": "094d667d-033f-4972-9e09-3f783e9c1740",
|
| 416 |
+
"metadata": {},
|
| 417 |
+
"outputs": [
|
| 418 |
+
{
|
| 419 |
+
"data": {
|
| 420 |
+
"application/vnd.jupyter.widget-view+json": {
|
| 421 |
+
"model_id": "5bf9daf3c1c746eaaaf964c04171d105",
|
| 422 |
+
"version_major": 2,
|
| 423 |
+
"version_minor": 0
|
| 424 |
+
},
|
| 425 |
+
"text/plain": [
|
| 426 |
+
"HBox(children=(Map(center=[-34, -58], controls=(ZoomControl(options=['position', 'zoom_in_text', 'zoom_in_titl…"
|
| 427 |
+
]
|
| 428 |
+
},
|
| 429 |
+
"metadata": {},
|
| 430 |
+
"output_type": "display_data"
|
| 431 |
+
}
|
| 432 |
+
],
|
| 433 |
+
"source": [
|
| 434 |
+
"center = [-34, -58]\n",
|
| 435 |
+
"init_feature = {'properties':{'path': '6758c05a6f633f00010ed810.tif'}}\n",
|
| 436 |
+
"\n",
|
| 437 |
+
"# Create map\n",
|
| 438 |
+
"m = Map(center=center, zoom=4)\n",
|
| 439 |
+
"\n",
|
| 440 |
+
"# Output widget to capture selection\n",
|
| 441 |
+
"selected_fnames = [None]\n",
|
| 442 |
+
"selected_thumbnail_and_embeddings = [None]\n",
|
| 443 |
+
"\n",
|
| 444 |
+
"out = Output()\n",
|
| 445 |
+
"def handle_click(event, feature, **kwargs):\n",
|
| 446 |
+
" fname = feature['properties']['path']\n",
|
| 447 |
+
" selected_fnames[0] = fname\n",
|
| 448 |
+
" \n",
|
| 449 |
+
" out.clear_output(wait=True)\n",
|
| 450 |
+
" with out:\n",
|
| 451 |
+
" thumbnail_and_embeddings = embeddings_dataset.get_thumbnail_and_embeddings_by_fname(fname)\n",
|
| 452 |
+
" selected_thumbnail_and_embeddings[0] = thumbnail_and_embeddings\n",
|
| 453 |
+
" \n",
|
| 454 |
+
" thumbnail, decimation, embedding_list, xy_list, hw_list, epsg = thumbnail_and_embeddings\n",
|
| 455 |
+
" fig, axes = plt.subplots(1, 1, figsize=(4, 4))\n",
|
| 456 |
+
" axes.set_title(\"Image overview\")\n",
|
| 457 |
+
" axes.imshow(thumbnail)\n",
|
| 458 |
+
" axes.axis('off')\n",
|
| 459 |
+
" plt.tight_layout()\n",
|
| 460 |
+
" plt.show()\n",
|
| 461 |
+
"\n",
|
| 462 |
+
"\n",
|
| 463 |
+
"geo_json_data = embeddings_dataset.gdf.__geo_interface__\n",
|
| 464 |
+
"geo_json = GeoJSON(data=geo_json_data, hover_style={'fillColor': 'red'}, name='GeoJSON')\n",
|
| 465 |
+
"geo_json.on_click(handle_click)\n",
|
| 466 |
+
"m.add_layer(geo_json)\n",
|
| 467 |
+
"\n",
|
| 468 |
+
"display(widgets.HBox([m, out]))\n",
|
| 469 |
+
"handle_click(None, init_feature)"
|
| 470 |
+
]
|
| 471 |
+
},
|
| 472 |
+
{
|
| 473 |
+
"cell_type": "markdown",
|
| 474 |
+
"id": "bc5f1f26-50af-4ad5-a213-7d0db4c63b03",
|
| 475 |
+
"metadata": {},
|
| 476 |
+
"source": [
|
| 477 |
+
"# Vibe Mapping using RemoteCLIP and Qwen"
|
| 478 |
+
]
|
| 479 |
+
},
|
| 480 |
+
{
|
| 481 |
+
"cell_type": "code",
|
| 482 |
+
"execution_count": null,
|
| 483 |
+
"id": "196ea894-e463-4f09-8641-f046ea2b9bda",
|
| 484 |
+
"metadata": {},
|
| 485 |
+
"outputs": [],
|
| 486 |
+
"source": [
|
| 487 |
+
"# Just raw embeddigns\n",
|
| 488 |
+
"thumbnail_and_embeddings = selected_thumbnail_and_embeddings[0]\n",
|
| 489 |
+
"thumbnail, decimation, embedding_list, xy_list, hw_list, epsg = thumbnail_and_embeddings\n",
|
| 490 |
+
"\n",
|
| 491 |
+
"kmeans = KMeans(n_clusters=6, random_state=42)\n",
|
| 492 |
+
"clusters = kmeans.fit_predict(torch.stack(embedding_list, dim=0).numpy())\n",
|
| 493 |
+
"cluster_centers = kmeans.cluster_centers_\n",
|
| 494 |
+
"clusters_num = cluster_centers.shape[0]\n",
|
| 495 |
+
"cluster_string_list = []\n",
|
| 496 |
+
"cluster_string_list_summerized = []\n",
|
| 497 |
+
"print('LLM Legend sumerisation')\n",
|
| 498 |
+
"for i in trange(clusters_num):\n",
|
| 499 |
+
" emb = cluster_centers[i, :]\n",
|
| 500 |
+
" matched_text = vocabulary_pair.find_by_embedding_in_remoteclip_vocabulary(torch.unsqueeze(torch.from_numpy(emb), dim=0))[:4]\n",
|
| 501 |
+
" legend_string = ', '.join([i[1] for i in matched_text])\n",
|
| 502 |
+
" cluster_string_list.append(legend_string)\n",
|
| 503 |
+
" cluster_string_list_summerized.append(summarize(legend_string))\n",
|
| 504 |
+
"\n",
|
| 505 |
+
"\n",
|
| 506 |
+
"color_map = make_color_map_from_cluster_index(clusters)\n",
|
| 507 |
+
"\n",
|
| 508 |
+
"thumbnail_embedding_image = np.zeros_like(thumbnail[:,:,:]).astype(np.float32)\n",
|
| 509 |
+
"cc = int((embeddings_dataset.embedding_footprint_size / 2) / decimation) + 1\n",
|
| 510 |
+
"for n in range(len(hw_list)):\n",
|
| 511 |
+
" ph, pw = hw_list[n]\n",
|
| 512 |
+
" cluster_index = clusters[n]\n",
|
| 513 |
+
" color_rgb = np.array(color_map[cluster_index])\n",
|
| 514 |
+
" tph, tpw = int(ph / decimation), int(pw / decimation)\n",
|
| 515 |
+
" thumbnail_embedding_image[tph-cc:tph+cc, tpw-cc:tpw+cc, :] = color_rgb\n",
|
| 516 |
+
"\n",
|
| 517 |
+
"fig, axes = plt.subplots(1, 3, figsize=(12, 4)) \n",
|
| 518 |
+
"axes[0].imshow(thumbnail)\n",
|
| 519 |
+
"axes[0].axis('off')\n",
|
| 520 |
+
"axes[1].imshow(thumbnail_embedding_image.astype(np.uint8))\n",
|
| 521 |
+
"axes[2].imshow(thumbnail_embedding_image.astype(np.uint8))\n",
|
| 522 |
+
"\n",
|
| 523 |
+
"color_map_values = [i for i in color_map.values()]\n",
|
| 524 |
+
"for n in range(len(color_map_values)):\n",
|
| 525 |
+
" color_rgb = np.array(color_map_values[n]) / 255\n",
|
| 526 |
+
" axes[2].text(5., 10.0 + (20 * n), f'{str(n)}. {cluster_string_list_summerized[n]}', color=(color_rgb[0], color_rgb[1], color_rgb[2]), fontsize=8,\n",
|
| 527 |
+
" bbox=dict(boxstyle=\"round,pad=0.3\", fc=\"white\", ec=\"white\", lw=0, alpha=1.0))\n",
|
| 528 |
+
"axes[1].axis('off')\n",
|
| 529 |
+
"\n",
|
| 530 |
+
"plt.tight_layout()\n",
|
| 531 |
+
"plt.show()"
|
| 532 |
+
]
|
| 533 |
+
},
|
| 534 |
+
{
|
| 535 |
+
"cell_type": "markdown",
|
| 536 |
+
"id": "d083b661-fceb-49bd-a431-d409f712d33f",
|
| 537 |
+
"metadata": {},
|
| 538 |
+
"source": [
|
| 539 |
+
"# Attribute and save map"
|
| 540 |
+
]
|
| 541 |
+
},
|
| 542 |
+
{
|
| 543 |
+
"cell_type": "code",
|
| 544 |
+
"execution_count": 17,
|
| 545 |
+
"id": "a2ee8340-9546-4a62-8d6c-c0972ac7660c",
|
| 546 |
+
"metadata": {},
|
| 547 |
+
"outputs": [
|
| 548 |
+
{
|
| 549 |
+
"name": "stdout",
|
| 550 |
+
"output_type": "stream",
|
| 551 |
+
"text": [
|
| 552 |
+
"Vocabulary output:\n",
|
| 553 |
+
"0 white patchwork buildings, white roofs, community is white, white community\n",
|
| 554 |
+
"1 quiet forest, lush vegetation, lush wood, lush bush\n",
|
| 555 |
+
"2 small brown boats, boats is small brown, brown boats, boats is brown\n",
|
| 556 |
+
"3 thick green forest, light lush green forest, deep green forest, clear green forest\n",
|
| 557 |
+
"4 boats is brown, small brown boats, brown boats, boats is small brown\n",
|
| 558 |
+
"5 huts, houses is several vacant, vacant places, community is white\n",
|
| 559 |
+
"OAM metadata:\n",
|
| 560 |
+
"\n",
|
| 561 |
+
"[{'_id': '6758c6da6f633f00010ed814', 'acquisition_end': '2022-11-10T17:00:00.000Z', 'acquisition_start': '2022-11-10T11:00:00.000Z', 'contact': 'Labgeo EMATER,labgeoemater@gmail.com', 'platform': 'aircraft', 'provider': 'EMATER-PARÁ', 'properties': {'license': 'CC BY-NC 4.0', 'sensor': 'Phantom 4 Pro ', 'thumbnail': 'https://oin-hotosm-temp.s3.us-east-1.amazonaws.com/6758c05a6f633f00010ed80f/0/6758c05a6f633f00010ed810.png', 'tms': 'https://tiles.openaerialmap.org/6758c05a6f633f00010ed80f/0/6758c05a6f633f00010ed810/{z}/{x}/{y}', 'wmts': 'https://tiles.openaerialmap.org/6758c05a6f633f00010ed80f/0/6758c05a6f633f00010ed810/wmts'}, 'title': 'Ortomosaico da área urbana do município de Afuá-Pará', 'user': {'_id': '675735e748d17e0001ca9dad', 'name': 'Labgeo EMATER'}, 'uuid': 'https://oin-hotosm-temp.s3.us-east-1.amazonaws.com/6758c05a6f633f00010ed80f/0/6758c05a6f633f00010ed810.tif', 'geojson': {'bbox': [-50.394345, -0.167373, -50.370556, -0.151723], 'coordinates': [[[[-50.394345, -0.151724], [-50.394344, -0.167373], [-50.370556, -0.167373], [-50.370556, -0.151723], [-50.394345, -0.151724]]]], 'type': 'MultiPolygon'}, 'footprint': 'POLYGON ((-50.394345 -0.167373, -50.370556 -0.167373, -50.370556 -0.151723, -50.394345 -0.151723, -50.394345 -0.167373))', 'gsd': 0.0402309168832342, 'file_size': 576548103, 'projection': '\\nPROJCRS[\"SIRGAS 2000 / UTM zone 22S\",\\n BASEGEOGCRS[\"SIRGAS 2000\",\\n DATUM[\"Sistema de Referencia Geocentrico para las AmericaS 2000\",\\n ELLIPSOID[\"GRS 1980\",6378137,298.257222101,\\n LENGTHUNIT[\"metre\",1]]],\\n PRIMEM[\"Greenwich\",0,\\n ANGLEUNIT[\"degree\",0.0174532925199433]],\\n ID[\"EPSG\",4674]],\\n CONVERSION[\"UTM zone 22S\",\\n METHOD[\"Transverse Mercator\",\\n ID[\"EPSG\",9807]],\\n PARAMETER[\"Latitude of natural origin\",0,\\n ANGLEUNIT[\"degree\",0.0174532925199433],\\n ID[\"EPSG\",8801]],\\n PARAMETER[\"Longitude of natural origin\",-51,\\n ANGLEUNIT[\"degree\",0.0174532925199433],\\n ID[\"EPSG\",8802]],\\n PARAMETER[\"Scale factor at natural origin\",0.9996,\\n SCALEUNIT[\"unity\",1],\\n ID[\"EPSG\",8805]],\\n PARAMETER[\"False easting\",500000,\\n LENGTHUNIT[\"metre\",1],\\n ID[\"EPSG\",8806]],\\n PARAMETER[\"False northing\",10000000,\\n LENGTHUNIT[\"metre\",1],\\n ID[\"EPSG\",8807]]],\\n CS[Cartesian,2],\\n AXIS[\"(E)\",east,\\n ORDER[1],\\n LENGTHUNIT[\"metre\",1]],\\n AXIS[\"(N)\",north,\\n ORDER[2],\\n LENGTHUNIT[\"metre\",1]],\\n USAGE[\\n SCOPE[\"Engineering survey, topographic mapping.\"],\\n AREA[\"Brazil - between 54°W and 48°W, northern and southern hemispheres, onshore and offshore. In remainder of South America - between 54°W and 48°W, southern hemisphere, onshore and offshore.\"],\\n BBOX[-54.18,-54,7.04,-47.99]],\\n ID[\"EPSG\",31982]]', 'meta_uri': 'https://oin-hotosm-temp.s3.us-east-1.amazonaws.com/6758c05a6f633f00010ed80f/0/6758c05a6f633f00010ed810_meta.json', 'uploaded_at': '2024-12-10T22:55:22.296Z', 'bbox': [-50.394345, -0.167373, -50.370556, -0.151723], '__v': 0}]\n"
|
| 562 |
+
]
|
| 563 |
+
},
|
| 564 |
+
{
|
| 565 |
+
"name": "stderr",
|
| 566 |
+
"output_type": "stream",
|
| 567 |
+
"text": [
|
| 568 |
+
"100%|████████████████████████████████████████| 833/833 [00:01<00:00, 476.33it/s]"
|
| 569 |
+
]
|
| 570 |
+
},
|
| 571 |
+
{
|
| 572 |
+
"name": "stdout",
|
| 573 |
+
"output_type": "stream",
|
| 574 |
+
"text": [
|
| 575 |
+
"Saved\n"
|
| 576 |
+
]
|
| 577 |
+
},
|
| 578 |
+
{
|
| 579 |
+
"name": "stderr",
|
| 580 |
+
"output_type": "stream",
|
| 581 |
+
"text": [
|
| 582 |
+
"\n"
|
| 583 |
+
]
|
| 584 |
+
}
|
| 585 |
+
],
|
| 586 |
+
"source": [
|
| 587 |
+
"print('Vocabulary output:')\n",
|
| 588 |
+
"_ = [print(n, i) for (n, i) in enumerate(cluster_string_list)]\n",
|
| 589 |
+
"\n",
|
| 590 |
+
"\n",
|
| 591 |
+
"print('OAM metadata:\\n')\n",
|
| 592 |
+
"fname = selected_fnames[0]\n",
|
| 593 |
+
"print([i for i in oam_meta if i['uuid'].endswith(fname)])\n",
|
| 594 |
+
"\n",
|
| 595 |
+
"square_size = 56\n",
|
| 596 |
+
"schema = {\n",
|
| 597 |
+
" 'geometry': 'Polygon',\n",
|
| 598 |
+
" 'properties': {'id': 'int', 'name': 'str'}\n",
|
| 599 |
+
"}\n",
|
| 600 |
+
"with fiona.open(fname + '.gpkg', 'w', driver='GPKG', crs=from_epsg(epsg), schema=schema, layer='squares') as layer:\n",
|
| 601 |
+
" for idx, (x, y) in tqdm(enumerate(xy_list), total=len(xy_list)):\n",
|
| 602 |
+
" # Create square around the point\n",
|
| 603 |
+
" half_size = square_size / 2\n",
|
| 604 |
+
" square = box(x - half_size, y - half_size, x + half_size, y + half_size)\n",
|
| 605 |
+
" cluster_index = clusters[idx]\n",
|
| 606 |
+
" legend = cluster_string_list_summerized[cluster_index]\n",
|
| 607 |
+
" # Write to file\n",
|
| 608 |
+
" layer.write({\n",
|
| 609 |
+
" 'geometry': mapping(square),\n",
|
| 610 |
+
" 'properties': {'id': idx, 'name': legend}\n",
|
| 611 |
+
" })\n",
|
| 612 |
+
" \n",
|
| 613 |
+
"shutil.copy(embeddings_dataset.fname_to_fpath[fname], fname)\n",
|
| 614 |
+
"print(\"Saved\")"
|
| 615 |
+
]
|
| 616 |
+
},
|
| 617 |
+
{
|
| 618 |
+
"cell_type": "code",
|
| 619 |
+
"execution_count": null,
|
| 620 |
+
"id": "7ffbb909-7e49-41b5-aad3-59cec0ba22ff",
|
| 621 |
+
"metadata": {},
|
| 622 |
+
"outputs": [],
|
| 623 |
+
"source": []
|
| 624 |
+
}
|
| 625 |
+
],
|
| 626 |
+
"metadata": {
|
| 627 |
+
"kernelspec": {
|
| 628 |
+
"display_name": "Python 3 (ipykernel)",
|
| 629 |
+
"language": "python",
|
| 630 |
+
"name": "python3"
|
| 631 |
+
},
|
| 632 |
+
"language_info": {
|
| 633 |
+
"codemirror_mode": {
|
| 634 |
+
"name": "ipython",
|
| 635 |
+
"version": 3
|
| 636 |
+
},
|
| 637 |
+
"file_extension": ".py",
|
| 638 |
+
"mimetype": "text/x-python",
|
| 639 |
+
"name": "python",
|
| 640 |
+
"nbconvert_exporter": "python",
|
| 641 |
+
"pygments_lexer": "ipython3",
|
| 642 |
+
"version": "3.10.12"
|
| 643 |
+
}
|
| 644 |
+
},
|
| 645 |
+
"nbformat": 4,
|
| 646 |
+
"nbformat_minor": 5
|
| 647 |
+
}
|