Spaces:
Sleeping
Sleeping
Andy Lee
commited on
Commit
·
95c127a
1
Parent(s):
f83d6df
fix: data collect
Browse files- config.py +1 -1
- data_collector.py +52 -378
- mapcrunch_controller.py +47 -39
config.py
CHANGED
|
@@ -26,7 +26,7 @@ SELECTORS = {
|
|
| 26 |
MAPCRUNCH_OPTIONS = {
|
| 27 |
"urban_only": True, # Show urban areas only
|
| 28 |
"exclude_indoor": True, # Exclude indoor views
|
| 29 |
-
"stealth_mode":
|
| 30 |
"tour_mode": False, # 360 degree tour
|
| 31 |
"auto_mode": False, # Automatic slideshow
|
| 32 |
"selected_countries": None, # None means all, or list like ['us', 'gb', 'jp']
|
|
|
|
| 26 |
MAPCRUNCH_OPTIONS = {
|
| 27 |
"urban_only": True, # Show urban areas only
|
| 28 |
"exclude_indoor": True, # Exclude indoor views
|
| 29 |
+
"stealth_mode": False, # Hide location info during gameplay
|
| 30 |
"tour_mode": False, # 360 degree tour
|
| 31 |
"auto_mode": False, # Automatic slideshow
|
| 32 |
"selected_countries": None, # None means all, or list like ['us', 'gb', 'jp']
|
data_collector.py
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
import json
|
| 3 |
import time
|
|
@@ -18,8 +20,6 @@ from config import (
|
|
| 18 |
|
| 19 |
|
| 20 |
class DataCollector:
|
| 21 |
-
"""Collect MapCrunch location identifiers, coordinates, and thumbnails"""
|
| 22 |
-
|
| 23 |
def __init__(self, headless: bool = False, options: Optional[Dict] = None):
|
| 24 |
self.controller = MapCrunchController(headless=headless)
|
| 25 |
self.data = []
|
|
@@ -27,7 +27,6 @@ class DataCollector:
|
|
| 27 |
self.setup_directories()
|
| 28 |
|
| 29 |
def setup_directories(self):
|
| 30 |
-
"""Create necessary directories for data storage"""
|
| 31 |
for path in DATA_PATHS.values():
|
| 32 |
if path.endswith("/"):
|
| 33 |
Path(path).mkdir(parents=True, exist_ok=True)
|
|
@@ -35,172 +34,95 @@ class DataCollector:
|
|
| 35 |
Path(path).parent.mkdir(parents=True, exist_ok=True)
|
| 36 |
|
| 37 |
def collect_samples(
|
| 38 |
-
self, num_samples: Optional[int] = None,
|
| 39 |
) -> List[Dict]:
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
num_samples = BENCHMARK_CONFIG["data_collection_samples"]
|
| 43 |
-
|
| 44 |
-
# Override indoor filter if specified
|
| 45 |
-
if filter_indoor is not None:
|
| 46 |
-
self.options["exclude_indoor"] = filter_indoor
|
| 47 |
-
|
| 48 |
print(f"🚀 Starting location data collection for {num_samples} samples...")
|
| 49 |
-
|
| 50 |
-
f"📍 Options: Urban={self.options.get('urban_only', False)}, Exclude Indoor={self.options.get('exclude_indoor', True)}"
|
| 51 |
-
)
|
| 52 |
-
|
| 53 |
-
# Setup MapCrunch options
|
| 54 |
-
if not self.controller.setup_collection_options(self.options):
|
| 55 |
-
print("⚠️ Could not configure all options, continuing anyway...")
|
| 56 |
-
|
| 57 |
-
# Setup clean environment for stealth mode if needed
|
| 58 |
-
if self.options.get("stealth_mode", True):
|
| 59 |
-
self.controller.setup_clean_environment()
|
| 60 |
|
| 61 |
successful_samples = 0
|
| 62 |
-
failed_samples = 0
|
| 63 |
-
consecutive_failures = 0
|
| 64 |
-
|
| 65 |
while successful_samples < num_samples:
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
# Get new random location
|
| 72 |
-
if not self.controller.click_go_button():
|
| 73 |
-
print("❌ Failed to get new location")
|
| 74 |
-
failed_samples += 1
|
| 75 |
-
consecutive_failures += 1
|
| 76 |
-
if consecutive_failures > 5:
|
| 77 |
-
print("❌ Too many consecutive failures, stopping")
|
| 78 |
-
break
|
| 79 |
-
continue
|
| 80 |
-
|
| 81 |
-
# Wait for page to load
|
| 82 |
-
time.sleep(DATA_COLLECTION_CONFIG.get("wait_after_go", 5))
|
| 83 |
-
|
| 84 |
-
# Collect location data with retries
|
| 85 |
-
location_data = None
|
| 86 |
-
retries = (
|
| 87 |
-
DATA_COLLECTION_CONFIG.get("max_retries", 3)
|
| 88 |
-
if DATA_COLLECTION_CONFIG.get("retry_on_failure", True)
|
| 89 |
-
else 1
|
| 90 |
-
)
|
| 91 |
-
|
| 92 |
-
for retry in range(retries):
|
| 93 |
-
location_data = self.collect_single_location()
|
| 94 |
-
if location_data:
|
| 95 |
-
break
|
| 96 |
-
if retry < retries - 1:
|
| 97 |
-
print(f" ⚠️ Retry {retry + 1}/{retries - 1}")
|
| 98 |
-
time.sleep(1)
|
| 99 |
-
|
| 100 |
-
if location_data:
|
| 101 |
-
self.data.append(location_data)
|
| 102 |
-
successful_samples += 1
|
| 103 |
-
consecutive_failures = 0
|
| 104 |
-
|
| 105 |
-
# Display collected info
|
| 106 |
-
address = location_data.get("address", "Unknown")
|
| 107 |
-
lat, lng = location_data.get("lat"), location_data.get("lng")
|
| 108 |
-
if lat and lng:
|
| 109 |
-
print(
|
| 110 |
-
f"✅ Location {successful_samples}: {address} ({lat:.4f}, {lng:.4f})"
|
| 111 |
-
)
|
| 112 |
-
else:
|
| 113 |
-
print(f"✅ Location {successful_samples}: {address}")
|
| 114 |
-
|
| 115 |
-
if location_data.get("thumbnail_path"):
|
| 116 |
-
print(
|
| 117 |
-
f" 📸 Thumbnail saved: {location_data['thumbnail_path']}"
|
| 118 |
-
)
|
| 119 |
-
else:
|
| 120 |
-
failed_samples += 1
|
| 121 |
-
consecutive_failures += 1
|
| 122 |
-
print("❌ Location collection failed")
|
| 123 |
-
|
| 124 |
-
# Brief pause between samples
|
| 125 |
-
time.sleep(0.5)
|
| 126 |
|
| 127 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
print(
|
| 129 |
-
f"
|
| 130 |
)
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
print(f"❌ Error collecting location: {e}")
|
| 134 |
-
failed_samples += 1
|
| 135 |
-
consecutive_failures += 1
|
| 136 |
-
continue
|
| 137 |
-
|
| 138 |
-
print("\n📊 Collection Summary:")
|
| 139 |
-
print(f"✅ Successful: {successful_samples}")
|
| 140 |
-
print(f"❌ Failed: {failed_samples}")
|
| 141 |
-
print(
|
| 142 |
-
f"📈 Success rate: {successful_samples / (successful_samples + failed_samples) * 100:.1f}%"
|
| 143 |
-
)
|
| 144 |
|
| 145 |
-
# Save collected data
|
| 146 |
self.save_data()
|
| 147 |
-
|
| 148 |
return self.data
|
| 149 |
|
| 150 |
def collect_single_location(self) -> Optional[Dict]:
|
| 151 |
-
"""
|
| 152 |
try:
|
| 153 |
sample_id = str(uuid.uuid4())
|
| 154 |
timestamp = datetime.now().isoformat()
|
| 155 |
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
# 1. 获取实时坐标 (这个方法依然正确)
|
| 159 |
current_coords = self.controller.driver.execute_script(
|
| 160 |
"if (window.panorama) { return { lat: window.panorama.getPosition().lat(), lng: window.panorama.getPosition().lng() }; } else { return null; }"
|
| 161 |
)
|
| 162 |
if not current_coords or current_coords.get("lat") is None:
|
| 163 |
return None
|
| 164 |
|
| 165 |
-
#
|
| 166 |
live_identifiers = self.controller.get_live_location_identifiers()
|
| 167 |
if not live_identifiers or "error" in live_identifiers:
|
| 168 |
-
print(
|
| 169 |
-
f"⚠️ Could not get live identifiers: {live_identifiers.get('error')}"
|
| 170 |
-
)
|
| 171 |
return None
|
| 172 |
|
| 173 |
# 3. 获取地址
|
| 174 |
address = self.controller.get_current_address()
|
| 175 |
|
| 176 |
-
# 4.
|
| 177 |
location_data = {
|
| 178 |
"id": sample_id,
|
| 179 |
"timestamp": timestamp,
|
| 180 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
"lat": current_coords.get("lat"),
|
| 182 |
"lng": current_coords.get("lng"),
|
| 183 |
"address": address or "Unknown",
|
| 184 |
"source": "panorama_object",
|
| 185 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 186 |
"url": live_identifiers.get("permLink"),
|
| 187 |
-
"
|
| 188 |
"pano_id": live_identifiers.get("panoId"),
|
| 189 |
-
"
|
| 190 |
"collection_options": self.options.copy(),
|
| 191 |
}
|
| 192 |
|
| 193 |
-
#
|
| 194 |
if DATA_COLLECTION_CONFIG.get("save_thumbnails", True):
|
| 195 |
thumbnail_path = self.save_thumbnail(sample_id)
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
screenshot_path = self.save_full_screenshot(sample_id)
|
| 202 |
-
if screenshot_path:
|
| 203 |
-
location_data["screenshot_path"] = screenshot_path
|
| 204 |
|
| 205 |
return location_data
|
| 206 |
|
|
@@ -208,213 +130,39 @@ class DataCollector:
|
|
| 208 |
print(f"❌ Error in collect_single_location: {e}")
|
| 209 |
return None
|
| 210 |
|
|
|
|
| 211 |
def save_thumbnail(self, sample_id: str) -> Optional[str]:
|
| 212 |
-
"""Save a thumbnail of the current Street View"""
|
| 213 |
try:
|
| 214 |
-
# Take screenshot
|
| 215 |
screenshot_bytes = self.controller.take_street_view_screenshot()
|
| 216 |
if not screenshot_bytes:
|
| 217 |
return None
|
| 218 |
-
|
| 219 |
-
# Convert to PIL Image
|
| 220 |
image = Image.open(BytesIO(screenshot_bytes))
|
| 221 |
-
|
| 222 |
-
# Resize to thumbnail size
|
| 223 |
thumbnail_size = DATA_COLLECTION_CONFIG.get("thumbnail_size", (320, 240))
|
| 224 |
image.thumbnail(thumbnail_size, Image.Resampling.LANCZOS)
|
| 225 |
-
|
| 226 |
-
# Save thumbnail
|
| 227 |
thumbnail_filename = f"{sample_id}.jpg"
|
| 228 |
thumbnail_path = os.path.join(DATA_PATHS["thumbnails"], thumbnail_filename)
|
| 229 |
-
|
| 230 |
-
# Convert to RGB if necessary (remove alpha channel)
|
| 231 |
if image.mode in ("RGBA", "LA"):
|
| 232 |
rgb_image = Image.new("RGB", image.size, (255, 255, 255))
|
| 233 |
-
rgb_image.paste(
|
| 234 |
-
image, mask=image.split()[-1] if image.mode == "RGBA" else None
|
| 235 |
-
)
|
| 236 |
image = rgb_image
|
| 237 |
-
|
| 238 |
-
image.save(thumbnail_path, "JPEG", quality=85, optimize=True)
|
| 239 |
-
|
| 240 |
return thumbnail_filename
|
| 241 |
-
|
| 242 |
-
except Exception as e:
|
| 243 |
-
print(f"⚠️ Error saving thumbnail: {e}")
|
| 244 |
-
return None
|
| 245 |
-
|
| 246 |
-
def save_full_screenshot(self, sample_id: str) -> Optional[str]:
|
| 247 |
-
"""Save full resolution screenshot (optional, storage intensive)"""
|
| 248 |
-
try:
|
| 249 |
-
screenshot_bytes = self.controller.take_street_view_screenshot()
|
| 250 |
-
if not screenshot_bytes:
|
| 251 |
-
return None
|
| 252 |
-
|
| 253 |
-
screenshot_filename = f"{sample_id}.png"
|
| 254 |
-
screenshot_path = os.path.join(
|
| 255 |
-
DATA_PATHS["screenshots"], screenshot_filename
|
| 256 |
-
)
|
| 257 |
-
|
| 258 |
-
with open(screenshot_path, "wb") as f:
|
| 259 |
-
f.write(screenshot_bytes)
|
| 260 |
-
|
| 261 |
-
return screenshot_filename
|
| 262 |
-
|
| 263 |
-
except Exception as e:
|
| 264 |
-
print(f"⚠️ Error saving screenshot: {e}")
|
| 265 |
return None
|
| 266 |
|
| 267 |
def save_data(self):
|
| 268 |
-
"""Save collected location data to JSON file"""
|
| 269 |
try:
|
| 270 |
-
# Calculate statistics
|
| 271 |
-
stats = {
|
| 272 |
-
"total_samples": len(self.data),
|
| 273 |
-
"with_coordinates": sum(
|
| 274 |
-
1 for d in self.data if d.get("lat") is not None
|
| 275 |
-
),
|
| 276 |
-
"with_address": sum(
|
| 277 |
-
1
|
| 278 |
-
for d in self.data
|
| 279 |
-
if d.get("address") and d["address"] != "Unknown"
|
| 280 |
-
),
|
| 281 |
-
"with_thumbnails": sum(
|
| 282 |
-
1 for d in self.data if d.get("has_thumbnail", False)
|
| 283 |
-
),
|
| 284 |
-
"unique_countries": len(
|
| 285 |
-
set(
|
| 286 |
-
d.get("address", "").split(", ")[-1]
|
| 287 |
-
for d in self.data
|
| 288 |
-
if d.get("address")
|
| 289 |
-
)
|
| 290 |
-
),
|
| 291 |
-
}
|
| 292 |
-
|
| 293 |
output_data = {
|
| 294 |
-
"metadata": {
|
| 295 |
-
"collection_date": datetime.now().isoformat(),
|
| 296 |
-
"total_samples": len(self.data),
|
| 297 |
-
"statistics": stats,
|
| 298 |
-
"collection_options": self.options,
|
| 299 |
-
"version": "3.0",
|
| 300 |
-
"description": "MapCrunch location data with thumbnails and metadata",
|
| 301 |
-
},
|
| 302 |
"samples": self.data,
|
| 303 |
}
|
| 304 |
-
|
| 305 |
with open(DATA_PATHS["golden_labels"], "w") as f:
|
| 306 |
json.dump(output_data, f, indent=2)
|
| 307 |
-
|
| 308 |
print(f"\n💾 Location data saved to {DATA_PATHS['golden_labels']}")
|
| 309 |
-
print("📊 Statistics:")
|
| 310 |
-
for key, value in stats.items():
|
| 311 |
-
print(f" {key}: {value}")
|
| 312 |
-
|
| 313 |
except Exception as e:
|
| 314 |
print(f"❌ Error saving data: {e}")
|
| 315 |
|
| 316 |
-
def load_existing_data(self) -> List[Dict]:
|
| 317 |
-
"""Load existing location data"""
|
| 318 |
-
try:
|
| 319 |
-
if os.path.exists(DATA_PATHS["golden_labels"]):
|
| 320 |
-
with open(DATA_PATHS["golden_labels"], "r") as f:
|
| 321 |
-
data = json.load(f)
|
| 322 |
-
return data.get("samples", [])
|
| 323 |
-
else:
|
| 324 |
-
return []
|
| 325 |
-
except Exception as e:
|
| 326 |
-
print(f"❌ Error loading existing data: {e}")
|
| 327 |
-
return []
|
| 328 |
-
|
| 329 |
-
def validate_sample(self, sample: Dict) -> bool:
|
| 330 |
-
"""Validate that a sample has required fields"""
|
| 331 |
-
required_fields = ["id", "coordinates"]
|
| 332 |
-
|
| 333 |
-
# Check required fields
|
| 334 |
-
if not all(field in sample for field in required_fields):
|
| 335 |
-
return False
|
| 336 |
-
|
| 337 |
-
# Check if coordinates are valid
|
| 338 |
-
coords = sample["coordinates"]
|
| 339 |
-
if coords.get("lat") is None or coords.get("lng") is None:
|
| 340 |
-
if coords.get("address") is None:
|
| 341 |
-
return False
|
| 342 |
-
|
| 343 |
-
return True
|
| 344 |
-
|
| 345 |
-
def clean_invalid_samples(self):
|
| 346 |
-
"""Remove invalid samples from dataset"""
|
| 347 |
-
existing_data = self.load_existing_data()
|
| 348 |
-
valid_samples = [
|
| 349 |
-
sample for sample in existing_data if self.validate_sample(sample)
|
| 350 |
-
]
|
| 351 |
-
|
| 352 |
-
print(
|
| 353 |
-
f"🧹 Cleaned dataset: {len(existing_data)} -> {len(valid_samples)} samples"
|
| 354 |
-
)
|
| 355 |
-
|
| 356 |
-
if len(valid_samples) != len(existing_data):
|
| 357 |
-
# Save cleaned data
|
| 358 |
-
self.data = valid_samples
|
| 359 |
-
self.save_data()
|
| 360 |
-
|
| 361 |
-
def filter_samples(self, filter_func=None, country=None, has_coordinates=None):
|
| 362 |
-
"""Filter existing samples based on criteria"""
|
| 363 |
-
samples = self.load_existing_data()
|
| 364 |
-
|
| 365 |
-
filtered = samples
|
| 366 |
-
|
| 367 |
-
# Filter by country
|
| 368 |
-
if country:
|
| 369 |
-
filtered = [
|
| 370 |
-
s for s in filtered if country.lower() in s.get("address", "").lower()
|
| 371 |
-
]
|
| 372 |
-
|
| 373 |
-
# Filter by coordinate availability
|
| 374 |
-
if has_coordinates is not None:
|
| 375 |
-
if has_coordinates:
|
| 376 |
-
filtered = [
|
| 377 |
-
s
|
| 378 |
-
for s in filtered
|
| 379 |
-
if s.get("lat") is not None and s.get("lng") is not None
|
| 380 |
-
]
|
| 381 |
-
else:
|
| 382 |
-
filtered = [
|
| 383 |
-
s for s in filtered if s.get("lat") is None or s.get("lng") is None
|
| 384 |
-
]
|
| 385 |
-
|
| 386 |
-
# Apply custom filter
|
| 387 |
-
if filter_func:
|
| 388 |
-
filtered = [s for s in filtered if filter_func(s)]
|
| 389 |
-
|
| 390 |
-
print(f"🔍 Filtered: {len(samples)} -> {len(filtered)} samples")
|
| 391 |
-
return filtered
|
| 392 |
-
|
| 393 |
-
def export_summary(self, output_file: str = "data_summary.txt"):
|
| 394 |
-
"""Export a human-readable summary of collected data"""
|
| 395 |
-
samples = self.load_existing_data()
|
| 396 |
-
|
| 397 |
-
with open(output_file, "w") as f:
|
| 398 |
-
f.write("MapCrunch Data Collection Summary\n")
|
| 399 |
-
f.write("=" * 50 + "\n\n")
|
| 400 |
-
|
| 401 |
-
for i, sample in enumerate(samples):
|
| 402 |
-
f.write(f"Sample {i + 1}:\n")
|
| 403 |
-
f.write(f" ID: {sample['id'][:8]}...\n")
|
| 404 |
-
f.write(f" Address: {sample.get('address', 'Unknown')}\n")
|
| 405 |
-
f.write(
|
| 406 |
-
f" Coordinates: {sample.get('lat', 'N/A')}, {sample.get('lng', 'N/A')}\n"
|
| 407 |
-
)
|
| 408 |
-
f.write(
|
| 409 |
-
f" Thumbnail: {'Yes' if sample.get('has_thumbnail') else 'No'}\n"
|
| 410 |
-
)
|
| 411 |
-
f.write(f" Collected: {sample.get('timestamp', 'Unknown')}\n")
|
| 412 |
-
f.write("-" * 30 + "\n")
|
| 413 |
-
|
| 414 |
-
print(f"📄 Summary exported to {output_file}")
|
| 415 |
-
|
| 416 |
def close(self):
|
| 417 |
-
"""Clean up resources"""
|
| 418 |
self.controller.close()
|
| 419 |
|
| 420 |
def __enter__(self):
|
|
@@ -422,77 +170,3 @@ class DataCollector:
|
|
| 422 |
|
| 423 |
def __exit__(self, exc_type, exc_val, exc_tb):
|
| 424 |
self.close()
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
def main():
|
| 428 |
-
"""Main function for data collection"""
|
| 429 |
-
import argparse
|
| 430 |
-
|
| 431 |
-
parser = argparse.ArgumentParser(
|
| 432 |
-
description="Collect MapCrunch location data for benchmark"
|
| 433 |
-
)
|
| 434 |
-
parser.add_argument(
|
| 435 |
-
"--samples", type=int, default=50, help="Number of locations to collect"
|
| 436 |
-
)
|
| 437 |
-
parser.add_argument(
|
| 438 |
-
"--headless", action="store_true", help="Run browser in headless mode"
|
| 439 |
-
)
|
| 440 |
-
parser.add_argument(
|
| 441 |
-
"--clean", action="store_true", help="Clean invalid samples from existing data"
|
| 442 |
-
)
|
| 443 |
-
parser.add_argument(
|
| 444 |
-
"--urban", action="store_true", help="Collect only urban locations"
|
| 445 |
-
)
|
| 446 |
-
parser.add_argument("--no-indoor", action="store_true", help="Exclude indoor views")
|
| 447 |
-
parser.add_argument(
|
| 448 |
-
"--countries",
|
| 449 |
-
nargs="+",
|
| 450 |
-
help="Specific countries to collect from (e.g., us gb jp)",
|
| 451 |
-
)
|
| 452 |
-
parser.add_argument(
|
| 453 |
-
"--export-summary", action="store_true", help="Export summary of collected data"
|
| 454 |
-
)
|
| 455 |
-
parser.add_argument(
|
| 456 |
-
"--filter-country", help="Filter samples by country when exporting"
|
| 457 |
-
)
|
| 458 |
-
|
| 459 |
-
args = parser.parse_args()
|
| 460 |
-
|
| 461 |
-
if args.clean:
|
| 462 |
-
print("🧹 Cleaning existing dataset...")
|
| 463 |
-
with DataCollector(headless=True) as collector:
|
| 464 |
-
collector.clean_invalid_samples()
|
| 465 |
-
return
|
| 466 |
-
|
| 467 |
-
if args.export_summary:
|
| 468 |
-
print("📄 Exporting data summary...")
|
| 469 |
-
with DataCollector(headless=True) as collector:
|
| 470 |
-
if args.filter_country:
|
| 471 |
-
samples = collector.filter_samples(country=args.filter_country)
|
| 472 |
-
collector.data = samples
|
| 473 |
-
collector.export_summary(f"data_summary_{args.filter_country}.txt")
|
| 474 |
-
else:
|
| 475 |
-
collector.export_summary()
|
| 476 |
-
return
|
| 477 |
-
|
| 478 |
-
# Configure collection options
|
| 479 |
-
options = MAPCRUNCH_OPTIONS.copy()
|
| 480 |
-
|
| 481 |
-
if args.urban:
|
| 482 |
-
options["urban_only"] = True
|
| 483 |
-
|
| 484 |
-
if args.no_indoor:
|
| 485 |
-
options["exclude_indoor"] = True
|
| 486 |
-
|
| 487 |
-
if args.countries:
|
| 488 |
-
options["selected_countries"] = args.countries
|
| 489 |
-
|
| 490 |
-
# Collect new location data
|
| 491 |
-
with DataCollector(headless=args.headless, options=options) as collector:
|
| 492 |
-
data = collector.collect_samples(args.samples)
|
| 493 |
-
print(f"\n🎉 Collection complete! Collected {len(data)} location samples.")
|
| 494 |
-
print("📊 Ready for benchmark testing with these locations.")
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
if __name__ == "__main__":
|
| 498 |
-
main()
|
|
|
|
| 1 |
+
# data_collector.py (Restored to original format)
|
| 2 |
+
|
| 3 |
import os
|
| 4 |
import json
|
| 5 |
import time
|
|
|
|
| 20 |
|
| 21 |
|
| 22 |
class DataCollector:
|
|
|
|
|
|
|
| 23 |
def __init__(self, headless: bool = False, options: Optional[Dict] = None):
|
| 24 |
self.controller = MapCrunchController(headless=headless)
|
| 25 |
self.data = []
|
|
|
|
| 27 |
self.setup_directories()
|
| 28 |
|
| 29 |
def setup_directories(self):
|
|
|
|
| 30 |
for path in DATA_PATHS.values():
|
| 31 |
if path.endswith("/"):
|
| 32 |
Path(path).mkdir(parents=True, exist_ok=True)
|
|
|
|
| 34 |
Path(path).parent.mkdir(parents=True, exist_ok=True)
|
| 35 |
|
| 36 |
def collect_samples(
|
| 37 |
+
self, num_samples: Optional[int] = None, **kwargs
|
| 38 |
) -> List[Dict]:
|
| 39 |
+
# ... (此函数不变) ...
|
| 40 |
+
num_samples = num_samples or BENCHMARK_CONFIG["data_collection_samples"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
print(f"🚀 Starting location data collection for {num_samples} samples...")
|
| 42 |
+
self.controller.setup_collection_options(self.options)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
|
| 44 |
successful_samples = 0
|
|
|
|
|
|
|
|
|
|
| 45 |
while successful_samples < num_samples:
|
| 46 |
+
print(f"\n📍 Collecting location {successful_samples + 1}/{num_samples}")
|
| 47 |
+
if not self.controller.click_go_button():
|
| 48 |
+
print("❌ Failed to get new location")
|
| 49 |
+
continue
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
+
location_data = self.collect_single_location()
|
| 52 |
+
if location_data:
|
| 53 |
+
self.data.append(location_data)
|
| 54 |
+
successful_samples += 1
|
| 55 |
+
lat, lng = location_data.get("lat"), location_data.get("lng")
|
| 56 |
print(
|
| 57 |
+
f"✅ Location {successful_samples}: {location_data['address']} ({lat:.4f}, {lng:.4f})"
|
| 58 |
)
|
| 59 |
+
else:
|
| 60 |
+
print("❌ Location collection failed")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
|
|
|
|
| 62 |
self.save_data()
|
|
|
|
| 63 |
return self.data
|
| 64 |
|
| 65 |
def collect_single_location(self) -> Optional[Dict]:
|
| 66 |
+
"""Collects a single location using the original, verbose data format."""
|
| 67 |
try:
|
| 68 |
sample_id = str(uuid.uuid4())
|
| 69 |
timestamp = datetime.now().isoformat()
|
| 70 |
|
| 71 |
+
# 1. 获取实时坐标
|
|
|
|
|
|
|
| 72 |
current_coords = self.controller.driver.execute_script(
|
| 73 |
"if (window.panorama) { return { lat: window.panorama.getPosition().lat(), lng: window.panorama.getPosition().lng() }; } else { return null; }"
|
| 74 |
)
|
| 75 |
if not current_coords or current_coords.get("lat") is None:
|
| 76 |
return None
|
| 77 |
|
| 78 |
+
# 2. 获取实时标识符
|
| 79 |
live_identifiers = self.controller.get_live_location_identifiers()
|
| 80 |
if not live_identifiers or "error" in live_identifiers:
|
|
|
|
|
|
|
|
|
|
| 81 |
return None
|
| 82 |
|
| 83 |
# 3. 获取地址
|
| 84 |
address = self.controller.get_current_address()
|
| 85 |
|
| 86 |
+
# 4. **构建您期望的、未精简的JSON结构**
|
| 87 |
location_data = {
|
| 88 |
"id": sample_id,
|
| 89 |
"timestamp": timestamp,
|
| 90 |
+
# 嵌套的 coordinates 字典
|
| 91 |
+
"coordinates": {
|
| 92 |
+
"lat": current_coords.get("lat"),
|
| 93 |
+
"lng": current_coords.get("lng"),
|
| 94 |
+
"source": "panorama_object",
|
| 95 |
+
},
|
| 96 |
+
# 顶层的 lat/lng
|
| 97 |
"lat": current_coords.get("lat"),
|
| 98 |
"lng": current_coords.get("lng"),
|
| 99 |
"address": address or "Unknown",
|
| 100 |
"source": "panorama_object",
|
| 101 |
+
# 嵌套的 identifiers 字典 (现在填充的是实时数据)
|
| 102 |
+
"identifiers": {
|
| 103 |
+
"initPanoId": live_identifiers.get("panoId"), # 实时PanoID
|
| 104 |
+
"permLink": live_identifiers.get("permLink"), # 实时链接
|
| 105 |
+
# 保留旧字段,但填充新数据或留空
|
| 106 |
+
"initString": live_identifiers.get("urlString"),
|
| 107 |
+
"locationString": address,
|
| 108 |
+
"url": live_identifiers.get("permLink"),
|
| 109 |
+
},
|
| 110 |
+
# 顶层的链接字段
|
| 111 |
"url": live_identifiers.get("permLink"),
|
| 112 |
+
"init_string": live_identifiers.get("urlString"),
|
| 113 |
"pano_id": live_identifiers.get("panoId"),
|
| 114 |
+
"perm_link": live_identifiers.get("permLink"),
|
| 115 |
"collection_options": self.options.copy(),
|
| 116 |
}
|
| 117 |
|
| 118 |
+
# 保存缩略图
|
| 119 |
if DATA_COLLECTION_CONFIG.get("save_thumbnails", True):
|
| 120 |
thumbnail_path = self.save_thumbnail(sample_id)
|
| 121 |
+
if thumbnail_path:
|
| 122 |
+
location_data["thumbnail_path"] = thumbnail_path
|
| 123 |
+
location_data["has_thumbnail"] = True
|
| 124 |
+
else:
|
| 125 |
+
location_data["has_thumbnail"] = False
|
|
|
|
|
|
|
|
|
|
| 126 |
|
| 127 |
return location_data
|
| 128 |
|
|
|
|
| 130 |
print(f"❌ Error in collect_single_location: {e}")
|
| 131 |
return None
|
| 132 |
|
| 133 |
+
# ... (save_thumbnail, save_data 等其他函数保持不变) ...
|
| 134 |
def save_thumbnail(self, sample_id: str) -> Optional[str]:
|
|
|
|
| 135 |
try:
|
|
|
|
| 136 |
screenshot_bytes = self.controller.take_street_view_screenshot()
|
| 137 |
if not screenshot_bytes:
|
| 138 |
return None
|
|
|
|
|
|
|
| 139 |
image = Image.open(BytesIO(screenshot_bytes))
|
|
|
|
|
|
|
| 140 |
thumbnail_size = DATA_COLLECTION_CONFIG.get("thumbnail_size", (320, 240))
|
| 141 |
image.thumbnail(thumbnail_size, Image.Resampling.LANCZOS)
|
|
|
|
|
|
|
| 142 |
thumbnail_filename = f"{sample_id}.jpg"
|
| 143 |
thumbnail_path = os.path.join(DATA_PATHS["thumbnails"], thumbnail_filename)
|
|
|
|
|
|
|
| 144 |
if image.mode in ("RGBA", "LA"):
|
| 145 |
rgb_image = Image.new("RGB", image.size, (255, 255, 255))
|
| 146 |
+
rgb_image.paste(image, mask=image.split()[-1])
|
|
|
|
|
|
|
| 147 |
image = rgb_image
|
| 148 |
+
image.save(thumbnail_path, "JPEG", quality=85)
|
|
|
|
|
|
|
| 149 |
return thumbnail_filename
|
| 150 |
+
except Exception:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
return None
|
| 152 |
|
| 153 |
def save_data(self):
|
|
|
|
| 154 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
output_data = {
|
| 156 |
+
"metadata": {"collection_date": datetime.now().isoformat()},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
"samples": self.data,
|
| 158 |
}
|
|
|
|
| 159 |
with open(DATA_PATHS["golden_labels"], "w") as f:
|
| 160 |
json.dump(output_data, f, indent=2)
|
|
|
|
| 161 |
print(f"\n💾 Location data saved to {DATA_PATHS['golden_labels']}")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
except Exception as e:
|
| 163 |
print(f"❌ Error saving data: {e}")
|
| 164 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
def close(self):
|
|
|
|
| 166 |
self.controller.close()
|
| 167 |
|
| 168 |
def __enter__(self):
|
|
|
|
| 170 |
|
| 171 |
def __exit__(self, exc_type, exc_val, exc_tb):
|
| 172 |
self.close()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
mapcrunch_controller.py
CHANGED
|
@@ -1,14 +1,22 @@
|
|
| 1 |
-
# mapcrunch_controller.py
|
| 2 |
|
| 3 |
from selenium import webdriver
|
| 4 |
from selenium.webdriver.common.by import By
|
| 5 |
from selenium.webdriver.support.ui import WebDriverWait
|
| 6 |
from selenium.webdriver.support import expected_conditions as EC
|
| 7 |
-
from selenium.
|
| 8 |
from selenium.webdriver.chrome.options import Options
|
|
|
|
| 9 |
import time
|
| 10 |
-
|
| 11 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
|
| 14 |
class MapCrunchController:
|
|
@@ -42,27 +50,43 @@ class MapCrunchController:
|
|
| 42 |
time.sleep(3)
|
| 43 |
|
| 44 |
def setup_clean_environment(self):
|
| 45 |
-
"""
|
|
|
|
|
|
|
| 46 |
try:
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
self.driver.execute_script("""
|
| 49 |
-
const elementsToHide = ['#menu', '#info-box', '#social', '#bottom-box'];
|
| 50 |
elementsToHide.forEach(sel => {
|
| 51 |
const el = document.querySelector(sel);
|
| 52 |
if (el) el.style.display = 'none';
|
| 53 |
});
|
|
|
|
|
|
|
| 54 |
""")
|
| 55 |
-
print("✅
|
|
|
|
| 56 |
except Exception as e:
|
| 57 |
-
print(f"⚠️
|
| 58 |
|
|
|
|
| 59 |
def setup_collection_options(self, options: Dict = None):
|
| 60 |
-
from config import MAPCRUNCH_OPTIONS
|
| 61 |
-
|
| 62 |
if options is None:
|
| 63 |
options = MAPCRUNCH_OPTIONS
|
| 64 |
try:
|
| 65 |
-
assert self.wait is not None
|
| 66 |
options_button = self.wait.until(
|
| 67 |
EC.element_to_be_clickable(
|
| 68 |
(By.CSS_SELECTOR, SELECTORS["options_button"])
|
|
@@ -70,29 +94,22 @@ class MapCrunchController:
|
|
| 70 |
)
|
| 71 |
options_button.click()
|
| 72 |
time.sleep(1)
|
| 73 |
-
|
| 74 |
-
assert self.driver is not None
|
| 75 |
-
# Urban
|
| 76 |
urban_checkbox = self.driver.find_element(
|
| 77 |
By.CSS_SELECTOR, SELECTORS["urban_checkbox"]
|
| 78 |
)
|
| 79 |
if options.get("urban_only", False) != urban_checkbox.is_selected():
|
| 80 |
urban_checkbox.click()
|
| 81 |
-
|
| 82 |
-
# Indoor
|
| 83 |
indoor_checkbox = self.driver.find_element(
|
| 84 |
By.CSS_SELECTOR, SELECTORS["indoor_checkbox"]
|
| 85 |
)
|
| 86 |
if options.get("exclude_indoor", True) == indoor_checkbox.is_selected():
|
| 87 |
indoor_checkbox.click()
|
| 88 |
-
|
| 89 |
-
# Stealth
|
| 90 |
stealth_checkbox = self.driver.find_element(
|
| 91 |
By.CSS_SELECTOR, SELECTORS["stealth_checkbox"]
|
| 92 |
)
|
| 93 |
if options.get("stealth_mode", True) != stealth_checkbox.is_selected():
|
| 94 |
stealth_checkbox.click()
|
| 95 |
-
|
| 96 |
options_button.click()
|
| 97 |
time.sleep(0.5)
|
| 98 |
print("✅ Collection options configured")
|
|
@@ -131,22 +148,21 @@ class MapCrunchController:
|
|
| 131 |
def click_go_button(self) -> bool:
|
| 132 |
"""Click the Go button to get new Street View location"""
|
| 133 |
try:
|
| 134 |
-
assert self.wait is not None
|
| 135 |
go_button = self.wait.until(
|
| 136 |
EC.element_to_be_clickable((By.CSS_SELECTOR, SELECTORS["go_button"]))
|
| 137 |
)
|
| 138 |
go_button.click()
|
| 139 |
-
#
|
| 140 |
time.sleep(DATA_COLLECTION_CONFIG.get("wait_after_go", 5))
|
| 141 |
return True
|
| 142 |
except Exception as e:
|
|
|
|
| 143 |
print(f"❌ Error clicking Go button: {e}")
|
| 144 |
return False
|
| 145 |
|
| 146 |
def get_current_address(self) -> Optional[str]:
|
| 147 |
-
|
| 148 |
try:
|
| 149 |
-
assert self.wait is not None
|
| 150 |
address_element = self.wait.until(
|
| 151 |
EC.visibility_of_element_located(
|
| 152 |
(By.CSS_SELECTOR, SELECTORS["address_element"])
|
|
@@ -188,22 +204,19 @@ class MapCrunchController:
|
|
| 188 |
return {}
|
| 189 |
|
| 190 |
def take_street_view_screenshot(self) -> Optional[bytes]:
|
| 191 |
-
|
| 192 |
try:
|
| 193 |
-
assert self.wait is not None
|
| 194 |
pano_element = self.wait.until(
|
| 195 |
EC.presence_of_element_located(
|
| 196 |
(By.CSS_SELECTOR, SELECTORS["pano_container"])
|
| 197 |
)
|
| 198 |
)
|
| 199 |
return pano_element.screenshot_as_png
|
| 200 |
-
except Exception
|
| 201 |
-
print(f"❌ Error taking screenshot: {e}")
|
| 202 |
return None
|
| 203 |
|
| 204 |
-
# **新增**: 获取实时页面标识符的方法
|
| 205 |
def get_live_location_identifiers(self) -> Dict:
|
| 206 |
-
|
| 207 |
try:
|
| 208 |
assert self.driver is not None
|
| 209 |
# 调用网站自己的JS函数来获取实时链接
|
|
@@ -223,19 +236,14 @@ class MapCrunchController:
|
|
| 223 |
print(f"❌ Error getting live identifiers: {e}")
|
| 224 |
return {}
|
| 225 |
|
| 226 |
-
# **修改**: 增强 load_location_from_data
|
| 227 |
def load_location_from_data(self, location_data: Dict) -> bool:
|
| 228 |
-
|
| 229 |
try:
|
| 230 |
-
assert self.driver is not None
|
| 231 |
-
|
| 232 |
-
# **优先使用 perm_link 或 url (现在应该已经是正确的了)**
|
| 233 |
url_to_load = location_data.get("perm_link") or location_data.get("url")
|
| 234 |
-
|
| 235 |
-
if url_to_load and "/p/" in url_to_load:
|
| 236 |
print(f"✅ Loading location via perm_link: {url_to_load}")
|
| 237 |
self.driver.get(url_to_load)
|
| 238 |
-
time.sleep(
|
| 239 |
return True
|
| 240 |
|
| 241 |
# **备用方案: 根据坐标和视角手动构建链接 (来自您建议的格式)**
|
|
@@ -256,12 +264,12 @@ class MapCrunchController:
|
|
| 256 |
"⚠️ No valid location identifier (perm_link, url, or coords) found in data."
|
| 257 |
)
|
| 258 |
return False
|
| 259 |
-
|
| 260 |
except Exception as e:
|
| 261 |
print(f"❌ Error loading location: {e}")
|
| 262 |
return False
|
| 263 |
|
| 264 |
def close(self):
|
|
|
|
| 265 |
if self.driver:
|
| 266 |
self.driver.quit()
|
| 267 |
|
|
|
|
| 1 |
+
# mapcrunch_controller.py (Fixed)
|
| 2 |
|
| 3 |
from selenium import webdriver
|
| 4 |
from selenium.webdriver.common.by import By
|
| 5 |
from selenium.webdriver.support.ui import WebDriverWait
|
| 6 |
from selenium.webdriver.support import expected_conditions as EC
|
| 7 |
+
from selenium.common.exceptions import TimeoutException
|
| 8 |
from selenium.webdriver.chrome.options import Options
|
| 9 |
+
from typing import Dict, Optional
|
| 10 |
import time
|
| 11 |
+
|
| 12 |
+
# 修正: 从 config.py 导入所有需要的变量
|
| 13 |
+
from config import (
|
| 14 |
+
MAPCRUNCH_URL,
|
| 15 |
+
SELECTORS,
|
| 16 |
+
DATA_COLLECTION_CONFIG,
|
| 17 |
+
MAPCRUNCH_OPTIONS,
|
| 18 |
+
SELENIUM_CONFIG,
|
| 19 |
+
)
|
| 20 |
|
| 21 |
|
| 22 |
class MapCrunchController:
|
|
|
|
| 50 |
time.sleep(3)
|
| 51 |
|
| 52 |
def setup_clean_environment(self):
|
| 53 |
+
"""
|
| 54 |
+
Forcefully enables stealth mode and hides UI elements for a clean benchmark environment.
|
| 55 |
+
"""
|
| 56 |
try:
|
| 57 |
+
# 1. 强制开启 Stealth 模式
|
| 58 |
+
# 这一步确保地址信息被网站自身的逻辑隐藏
|
| 59 |
+
stealth_checkbox = self.wait.until(
|
| 60 |
+
EC.presence_of_element_located(
|
| 61 |
+
(By.CSS_SELECTOR, SELECTORS["stealth_checkbox"])
|
| 62 |
+
)
|
| 63 |
+
)
|
| 64 |
+
if not stealth_checkbox.is_selected():
|
| 65 |
+
# 使用JS点击更可靠,可以避免元素被遮挡的问题
|
| 66 |
+
self.driver.execute_script("arguments[0].click();", stealth_checkbox)
|
| 67 |
+
print("✅ Stealth mode programmatically enabled for benchmark.")
|
| 68 |
+
|
| 69 |
+
# 2. 用 JS 隐藏其他视觉干扰元素
|
| 70 |
+
# 这一步确保截图区域干净
|
| 71 |
self.driver.execute_script("""
|
| 72 |
+
const elementsToHide = ['#menu', '#info-box', '#social', '#bottom-box', '#topbar'];
|
| 73 |
elementsToHide.forEach(sel => {
|
| 74 |
const el = document.querySelector(sel);
|
| 75 |
if (el) el.style.display = 'none';
|
| 76 |
});
|
| 77 |
+
const panoBox = document.querySelector('#pano-box');
|
| 78 |
+
if (panoBox) panoBox.style.height = '100vh';
|
| 79 |
""")
|
| 80 |
+
print("✅ Clean UI configured for benchmark.")
|
| 81 |
+
|
| 82 |
except Exception as e:
|
| 83 |
+
print(f"⚠️ Warning: Could not fully configure clean environment: {e}")
|
| 84 |
|
| 85 |
+
# setup_collection_options 函数保持不变...
|
| 86 |
def setup_collection_options(self, options: Dict = None):
|
|
|
|
|
|
|
| 87 |
if options is None:
|
| 88 |
options = MAPCRUNCH_OPTIONS
|
| 89 |
try:
|
|
|
|
| 90 |
options_button = self.wait.until(
|
| 91 |
EC.element_to_be_clickable(
|
| 92 |
(By.CSS_SELECTOR, SELECTORS["options_button"])
|
|
|
|
| 94 |
)
|
| 95 |
options_button.click()
|
| 96 |
time.sleep(1)
|
| 97 |
+
# ... (内部逻辑和之前一样)
|
|
|
|
|
|
|
| 98 |
urban_checkbox = self.driver.find_element(
|
| 99 |
By.CSS_SELECTOR, SELECTORS["urban_checkbox"]
|
| 100 |
)
|
| 101 |
if options.get("urban_only", False) != urban_checkbox.is_selected():
|
| 102 |
urban_checkbox.click()
|
|
|
|
|
|
|
| 103 |
indoor_checkbox = self.driver.find_element(
|
| 104 |
By.CSS_SELECTOR, SELECTORS["indoor_checkbox"]
|
| 105 |
)
|
| 106 |
if options.get("exclude_indoor", True) == indoor_checkbox.is_selected():
|
| 107 |
indoor_checkbox.click()
|
|
|
|
|
|
|
| 108 |
stealth_checkbox = self.driver.find_element(
|
| 109 |
By.CSS_SELECTOR, SELECTORS["stealth_checkbox"]
|
| 110 |
)
|
| 111 |
if options.get("stealth_mode", True) != stealth_checkbox.is_selected():
|
| 112 |
stealth_checkbox.click()
|
|
|
|
| 113 |
options_button.click()
|
| 114 |
time.sleep(0.5)
|
| 115 |
print("✅ Collection options configured")
|
|
|
|
| 148 |
def click_go_button(self) -> bool:
|
| 149 |
"""Click the Go button to get new Street View location"""
|
| 150 |
try:
|
|
|
|
| 151 |
go_button = self.wait.until(
|
| 152 |
EC.element_to_be_clickable((By.CSS_SELECTOR, SELECTORS["go_button"]))
|
| 153 |
)
|
| 154 |
go_button.click()
|
| 155 |
+
# 修正: DATA_COLLECTION_CONFIG 现在已被导入,可以正常使用
|
| 156 |
time.sleep(DATA_COLLECTION_CONFIG.get("wait_after_go", 5))
|
| 157 |
return True
|
| 158 |
except Exception as e:
|
| 159 |
+
# 修正: 打印出具体的错误信息
|
| 160 |
print(f"❌ Error clicking Go button: {e}")
|
| 161 |
return False
|
| 162 |
|
| 163 |
def get_current_address(self) -> Optional[str]:
|
| 164 |
+
# ... (此函数不变) ...
|
| 165 |
try:
|
|
|
|
| 166 |
address_element = self.wait.until(
|
| 167 |
EC.visibility_of_element_located(
|
| 168 |
(By.CSS_SELECTOR, SELECTORS["address_element"])
|
|
|
|
| 204 |
return {}
|
| 205 |
|
| 206 |
def take_street_view_screenshot(self) -> Optional[bytes]:
|
| 207 |
+
# ... (此函数不变) ...
|
| 208 |
try:
|
|
|
|
| 209 |
pano_element = self.wait.until(
|
| 210 |
EC.presence_of_element_located(
|
| 211 |
(By.CSS_SELECTOR, SELECTORS["pano_container"])
|
| 212 |
)
|
| 213 |
)
|
| 214 |
return pano_element.screenshot_as_png
|
| 215 |
+
except Exception:
|
|
|
|
| 216 |
return None
|
| 217 |
|
|
|
|
| 218 |
def get_live_location_identifiers(self) -> Dict:
|
| 219 |
+
# ... (此函数不变) ...
|
| 220 |
try:
|
| 221 |
assert self.driver is not None
|
| 222 |
# 调用网站自己的JS函数来获取实时链接
|
|
|
|
| 236 |
print(f"❌ Error getting live identifiers: {e}")
|
| 237 |
return {}
|
| 238 |
|
|
|
|
| 239 |
def load_location_from_data(self, location_data: Dict) -> bool:
|
| 240 |
+
# ... (此函数不变) ...
|
| 241 |
try:
|
|
|
|
|
|
|
|
|
|
| 242 |
url_to_load = location_data.get("perm_link") or location_data.get("url")
|
| 243 |
+
if url_to_load and ("/p/" in url_to_load or "/s/" in url_to_load):
|
|
|
|
| 244 |
print(f"✅ Loading location via perm_link: {url_to_load}")
|
| 245 |
self.driver.get(url_to_load)
|
| 246 |
+
time.sleep(4)
|
| 247 |
return True
|
| 248 |
|
| 249 |
# **备用方案: 根据坐标和视角手动构建链接 (来自您建议的格式)**
|
|
|
|
| 264 |
"⚠️ No valid location identifier (perm_link, url, or coords) found in data."
|
| 265 |
)
|
| 266 |
return False
|
|
|
|
| 267 |
except Exception as e:
|
| 268 |
print(f"❌ Error loading location: {e}")
|
| 269 |
return False
|
| 270 |
|
| 271 |
def close(self):
|
| 272 |
+
# ... (此函数不变) ...
|
| 273 |
if self.driver:
|
| 274 |
self.driver.quit()
|
| 275 |
|