File size: 11,336 Bytes
a4ef2ef 98b2032 26ef508 98b2032 26ef508 98b2032 26ef508 98b2032 26ef508 98b2032 26ef508 98b2032 26ef508 98b2032 a4ef2ef 26ef508 6dde2d0 a4ef2ef 6dde2d0 a4ef2ef 6dde2d0 77ff214 a4ef2ef 77ff214 a4ef2ef fb23ddb a4ef2ef fb23ddb a4ef2ef 77ff214 fb23ddb 729e850 596d5d2 a4ef2ef 77ff214 596d5d2 a4ef2ef 6dde2d0 77ff214 6dde2d0 77ff214 6dde2d0 77ff214 6dde2d0 77ff214 6dde2d0 77ff214 6dde2d0 77ff214 6dde2d0 77ff214 a4ef2ef 729e850 77ff214 596d5d2 77ff214 596d5d2 77ff214 596d5d2 77ff214 a4ef2ef 77ff214 6dde2d0 596d5d2 6dde2d0 a4ef2ef |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 |
import gradio as gr
from PIL import Image
import tempfile
import os
from pathlib import Path
import shutil
import requests
import re
import time
from PIL import ImageEnhance
import concurrent.futures
import asyncio
import aiohttp
import io
class StreetViewDownloader:
def __init__(self):
self.headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
self.session = requests.Session()
def extract_panoid(self, url):
"""Extract panorama ID from Google Maps URL."""
pattern = r'!1s([A-Za-z0-9-_]+)!'
match = re.search(pattern, url)
if match:
return match.group(1)
raise ValueError("Could not find panorama ID in URL. Please make sure you're using a valid Street View URL.")
async def download_tile_async(self, session, panoid, x, y, adjusted_y, zoom, output_dir):
"""Download a single tile asynchronously."""
tile_url = f"https://streetviewpixels-pa.googleapis.com/v1/tile?cb_client=maps_sv.tactile&panoid={panoid}&x={x}&y={adjusted_y}&zoom={zoom}"
output_file = Path(output_dir) / f"tile_{x}_{y}.jpg"
try:
async with session.get(tile_url, headers=self.headers) as response:
if response.status == 200:
content = await response.read()
if len(content) > 1000:
output_file.write_bytes(content)
return (x, y)
except Exception as e:
print(f"Error downloading tile {x},{y}: {str(e)}")
return None
async def download_tiles_async(self, panoid, output_dir, zoom, cols, rows):
"""Download tiles asynchronously with custom parameters."""
Path(output_dir).mkdir(parents=True, exist_ok=True)
vertical_offset = rows // 4 # Dynamic vertical offset based on rows
async with aiohttp.ClientSession() as session:
tasks = []
for x in range(cols):
for y in range(rows):
adjusted_y = y - (rows // 2) + vertical_offset
task = self.download_tile_async(session, panoid, x, y, adjusted_y, zoom, output_dir)
tasks.append(task)
downloaded_tiles = []
for result in await asyncio.gather(*tasks):
if result:
downloaded_tiles.append(result)
return cols, rows, downloaded_tiles
def download_tiles(self, panoid, output_dir, zoom, cols, rows):
"""Synchronous wrapper for async download."""
return asyncio.run(self.download_tiles_async(panoid, output_dir, zoom, cols, rows))
def create_360_panorama(self, directory, cols, rows, downloaded_tiles, output_file):
"""Create an equirectangular 360° panorama from tiles with optimized processing."""
directory = Path(directory)
# Find a valid tile to get dimensions
valid_tile = None
for x, y in downloaded_tiles:
tile_path = directory / f"tile_{x}_{y}.jpg"
if tile_path.exists():
valid_tile = Image.open(tile_path)
break
if not valid_tile:
raise Exception("No valid tiles found in directory")
tile_width, tile_height = valid_tile.size
valid_tile.close()
panorama_width = tile_width * cols
panorama_height = tile_height * rows
panorama = Image.new('RGB', (panorama_width, panorama_height))
def process_tile(tile_info):
x, y = tile_info
tile_path = directory / f"tile_{x}_{y}.jpg"
if tile_path.exists():
with Image.open(tile_path) as tile:
if tile.getbbox():
return (x * tile_width, y * tile_height, tile.copy())
return None
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
tile_results = list(executor.map(process_tile, downloaded_tiles))
for result in tile_results:
if result:
x, y, tile = result
panorama.paste(tile, (x, y))
tile.close()
bbox = panorama.getbbox()
if bbox:
panorama = panorama.crop(bbox)
panorama = self.enhance_panorama(panorama)
panorama.save(output_file, 'JPEG', quality=95, optimize=True)
return panorama
def enhance_panorama(self, panorama):
"""Quick enhancement with minimal processing."""
enhancer = ImageEnhance.Contrast(panorama)
panorama = enhancer.enhance(1.1)
return panorama
def process_street_view(url, zoom, cols, rows, progress=gr.Progress()):
"""Process the Street View URL with custom parameters."""
try:
# Input validation
zoom = int(zoom)
cols = int(cols)
rows = int(rows)
if zoom < 0 or zoom > 5:
raise ValueError("Zoom level must be between 0 and 5")
if cols < 1 or rows < 1:
raise ValueError("Columns and rows must be positive numbers")
if cols * rows > 1000:
raise ValueError("Total number of tiles (cols * rows) cannot exceed 1000")
temp_dir = tempfile.mkdtemp()
progress(0.1, desc="Initializing...")
downloader = StreetViewDownloader()
panoid = downloader.extract_panoid(url)
progress(0.2, desc="Extracted panorama ID...")
tiles_dir = os.path.join(temp_dir, f"{panoid}_tiles")
output_file = os.path.join(temp_dir, f"{panoid}_360panorama.jpg")
progress(0.3, desc=f"Downloading {cols}x{rows} tiles at zoom level {zoom}...")
cols, rows, downloaded_tiles = downloader.download_tiles(panoid, tiles_dir, zoom, cols, rows)
progress(0.7, desc="Creating panorama...")
panorama = downloader.create_360_panorama(tiles_dir, cols, rows, downloaded_tiles, output_file)
progress(0.9, desc="Cleaning up...")
shutil.rmtree(tiles_dir)
progress(1.0, desc="Done!")
return output_file, panorama
except Exception as e:
print(f"Error: {str(e)}") # Debug print
return None, None
def create_gradio_interface():
# Example links with their respective parameters
example_links = [
["https://www.google.com/maps/@40.7579718,-73.9855442,3a,75y,36.7h,81.89t/data=!3m7!1e1!3m5!1sNYigM1H6Vz7eLR8fRmykuw!2e0!6shttps:%2F%2Fstreetviewpixels-pa.googleapis.com%2Fv1%2Fthumbnail%3Fpanoid%3DNYigM1H6Vz7eLR8fRmykuw%26cb_client%3Dmaps_sv.tactile.gps%26w%3D203%26h%3D100%26yaw%3D136.23409%26pitch%3D0%26thumbfov%3D100!7i16384!8i8192?coh=205409&entry=ttu&g_ep=EgoyMDI0MTAyMy4wIKXMDSoASAFQAw%3D%3D", "2", "16", "8"], # Times Square
["https://www.google.com/maps/@48.8560009,2.2981995,3a,75y,315.8h,98.33t/data=!3m7!1e1!3m5!1sgaXVhUqbqmZ006KVmB6TLw!2e0!6shttps:%2F%2Fstreetviewpixels-pa.googleapis.com%2Fv1%2Fthumbnail%3Fpanoid%3DgaXVhUqbqmZ006KVmB6TLw%26cb_client%3Dmaps_sv.tactile.gps%26w%3D203%26h%3D100%26yaw%3D294.00525%26pitch%3D0%26thumbfov%3D100!7i16384!8i8192?coh=205409&entry=ttu&g_ep=EgoyMDI0MTAyMy4wIKXMDSoASAFQAw%3D%3D", "3", "32", "16"], # Eiffel Tower
["https://www.google.com/maps/@27.1749733,78.0430361,2a,75y,276.92h,78.63t/data=!3m6!1e1!3m4!1sIinHqsOZDjMDKZ7STo_Kdw!2e0!7i13312!8i6656?coh=205409&entry=ttu&g_ep=EgoyMDI0MTAyMy4wIKXMDSoASAFQAw%3D%3D", "1", "8", "4"] # Taj Mahal
]
with gr.Blocks() as app:
gr.Markdown("# Street View Panorama Downloader")
gr.Markdown("Download panoramic images from Google Street View")
with gr.Row():
with gr.Column():
url_input = gr.Textbox(
label="Street View URL",
placeholder="Paste Google Street View URL here...",
info="Open Street View, copy the URL from your browser"
)
with gr.Row():
zoom_level = gr.Number(
label="Zoom Level (0-5)",
value=2,
minimum=0,
maximum=5,
step=1,
info="Higher zoom = more detail but slower download"
)
cols_input = gr.Number(
label="Columns",
value=16,
minimum=1,
maximum=128,
step=1,
info="Number of horizontal tiles"
)
rows_input = gr.Number(
label="Rows",
value=8,
minimum=1,
maximum=64,
step=1,
info="Number of vertical tiles"
)
submit_btn = gr.Button("Download and Process", variant="primary")
with gr.Row():
with gr.Column():
output_file = gr.File(label="Download Panorama")
with gr.Column():
output_image = gr.Image(label="Preview", type="pil")
# Examples section
gr.Examples(
examples=example_links,
inputs=[url_input, zoom_level, cols_input, rows_input],
outputs=[output_file, output_image],
fn=process_street_view,
cache_examples=True,
label="Example Locations"
)
submit_btn.click(
fn=process_street_view,
inputs=[url_input, zoom_level, cols_input, rows_input],
outputs=[output_file, output_image]
)
gr.Markdown("""
### Parameter Guide:
1. **Zoom Level (0-5):**
- 0: Lowest quality, fastest download (~4x4 tiles)
- 1: Low quality (~8x4 tiles)
- 2: Medium quality, recommended (~16x8 tiles)
- 3: High quality, slower (~32x16 tiles)
- 4: Very high quality, very slow (~64x32 tiles)
- 5: Maximum quality, extremely slow (~128x64 tiles)
2. **Columns:**
- Controls horizontal resolution
- More columns = wider image
- Recommended values:
- Fast: 8-16 columns
- Balanced: 16-32 columns
- High quality: 32-64 columns
3. **Rows:**
- Controls vertical resolution
- More rows = taller image
- Typically use half the number of columns
- Recommended values:
- Fast: 4-8 rows
- Balanced: 8-16 rows
- High quality: 16-32 rows
### Example Settings:
- Times Square: Balanced quality (zoom=2, cols=16, rows=8)
- Eiffel Tower: High quality (zoom=3, cols=32, rows=16)
- Taj Mahal: Fast preview (zoom=1, cols=8, rows=4)
""")
return app
if __name__ == "__main__":
app = create_gradio_interface()
app.launch(share=True) |