Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- import time
- import hashlib
- from random import *
- import urllib.request
- import re
- from multiprocessing.pool import ThreadPool
- #timeout - время между загрузками картинок (некоторый сайты сразу кидают в
- # блок, если загружать ворохом)
- def download(ss,timeout=50,threads=10):
- #Первый ряд загружается по одному изображению, пока не упрётся в 404,
- #После чего в каждом столбце загружается первое изображение, и если оно выдаёт не 404,
- #То через несколько потоков загружается вся строка (даже так загружалось почти 300 секунд),
- # хотя 80 мб должны были загрузится за 40-80 секунд.
- timeout*=0.001
- m=f"data/map_data/{hashlib.sha1(ss.encode()).hexdigest()}"
- for c in m.split("/"):
- if not os.path.isdir(c):
- os.mkdir(c)
- os.chdir(c)
- if not os.path.exists("name.txt"):
- with open("name.txt",'w') as f:
- f.write(ss)
- ext=os.path.splitext(ss)[1]
- path=os.getcwd()
- lt=time.time()
- st=lt
- def load_sloy(z):
- nonlocal st,lt
- loc=os.path.join(path,f'{z:03d}')
- if not os.path.isdir(loc):
- os.mkdir(loc)
- os.chdir(loc)
- if os.path.isfile('end'):
- try:
- with open("end", 'r') as f:
- r=f.read()
- if r=='-':
- return False
- elif r=='+':
- return True
- except:
- return True
- y=0
- n=0
- mx=-1
- while True:
- x=0
- if mx==-1:
- while x!=mx:
- fname=f'{z}_{y}_{x}_{ext}'
- if not os.path.exists(fname):
- try:
- with urllib.request.urlopen(ss.format(z=z,x=x,y=y)) as f_net,\
- open(fname,'wb') as f_file:
- f_file.write(f_net.read())
- time.sleep(timeout)
- except urllib.error.HTTPError as e:
- if e.code==404:
- if x==0:
- if y==0:
- with open("end",'w') as f:
- f.write("-")
- return False
- else:
- print(f"Загружен слой {z}")
- with open("end",'w') as f:
- f.write("+")
- return True
- else:
- mx=x
- break
- else:
- print(f"HTTP error {e.code}")
- while input() not in ['q','exit','stop','end','close','й','']:
- ...
- except Exception as e:
- raise e
- n+=1
- nt=time.time()
- if nt-lt>1:
- print(f" ... {nt-st:.1f}: {n} файлов")
- lt=nt
- x+=1
- else:
- def download_url(x):
- fname=f'{z}_{y}_{x}_{ext}'
- if not os.path.exists(fname):
- try:
- with urllib.request.urlopen(ss.format(z=z, x=x, y=y)) as f_net, \
- open(fname, 'wb') as f_file:
- f_file.write(f_net.read())
- time.sleep(timeout)
- except Exception as e:
- raise e
- x=0
- fname = f'{z}_{y}_{x}_{ext}'
- if not os.path.exists(fname):
- try:
- with urllib.request.urlopen(ss.format(z=z, x=x, y=y)) as f_net, \
- open(fname, 'wb') as f_file:
- f_file.write(f_net.read())
- time.sleep(timeout)
- except urllib.error.HTTPError as e:
- if e.code==404:
- print(f"Загружен слой {z}")
- with open("end",'w') as f:
- f.write("+")
- return True
- else:
- print(f"HTTP error {e.code}")
- while input() not in ['q', 'exit', 'stop', 'end', 'close', 'й', '']:
- ...
- except Exception as e:
- raise e
- xx=list(range(1,mx))
- k=ThreadPool(threads)
- k.imap_unordered(download_url, xx)
- k.close()
- k.join()
- n += len(xx)
- nt = time.time()
- if nt-lt>1:
- print(f" ... {nt-st:.1f}: {n} файлов")
- lt = nt
- y+=1
- z=0
- while load_sloy(z):
- z+=1
- os.chdir(os.path.dirname(os.path.abspath(__file__)))
- print(f"Рабочая папка: {os.getcwd()}")
- ...
- from PIL import Image
- def skleiti(ss,ext='webp',quality=100):
- m=f"data/map_data/{hashlib.sha1(ss.encode()).hexdigest()}"
- for c in m.split("/"):
- if not os.path.isdir(c):
- os.mkdir(c)
- os.chdir(c)
- lt=time.time()
- st=lt
- def load_sloy(z):
- nonlocal lt
- regex=re.compile(r"(\d+)_(\d+)_(\d+)_")
- mx=0
- my=0
- nm=f"{z:03d}"
- try:
- with open(os.path.join(nm,"end"), 'r') as f:
- r = f.read()
- if r=='-':
- return False
- except:
- print(f"Ошибка в слое {z}")
- return False
- ext_n=''
- file_name=f"{nm}-{quality}.{ext}"
- if os.path.exists(file_name):
- print(f'[file_name] - уже есть')
- return True
- for c in os.listdir(nm):
- for m in regex.finditer(c):
- y,x=int(m.group(2)),int(m.group(3))
- my=max(y,my)
- mx=max(x,mx)
- if not ext_n:
- ext_n=os.path.splitext(c)[1]
- mx+=1
- my+=1
- img = Image.new('RGB', (256*mx, 256*my))
- n2=mx*my
- n=0
- for x in range(mx):
- for y in range(my):
- il=Image.open(os.path.join(nm,f'{z}_{y}_{x}_{ext_n}'))
- img.paste(il, (256*x, 256*y))
- n+=1
- nt = time.time()
- if nt-lt>1:
- print(f" ... {nt-st:.1f}: Клею слой {z}, {n/n2:.1%}")
- lt = nt
- print(f"Сохраняю слой слой {z} в {ext} (это может занять много времени)")
- try:
- img.save(file_name,quality=quality)
- except:
- os.remove(file_name)
- img.save(file_name.replace(ext,'.jpg'),quality=quality)
- print(f"Сохраняю слой слой {z} в jpg (это может занять много времени)")
- return True
- z = 0
- while load_sloy(z):
- z += 1
- #http://maps.dadesign.ru/argus/
- #http://maps.dadesign.ru/draenor/
- #http://maps.dadesign.ru/shadowlands/
- #http://maps.dadesign.ru/outland/
- #http://maps.dadesign.ru/azeroth/data/7-0-0.jpg
- # Загрузка
- # {z} - масштаб, {x}/{y} - координаты
- download(r"http://maps.dadesign.ru/azeroth/data/{z}-{x}-{y}.jpg")
- # Склеивать
- skleiti(r"http://maps.dadesign.ru/azeroth/data/{z}-{x}-{y}.jpg",ext='webp',quality=90)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement