Advertisement
Guest User

map_downlaod

a guest
Jul 26th, 2021
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.18 KB | None | 0 0
  1. import os
  2. import time
  3. import hashlib
  4. from random import *
  5. import urllib.request
  6. import re
  7. from multiprocessing.pool import ThreadPool
  8.  
  9.  
  10.  
  11.  
  12. #timeout - время между загрузками картинок (некоторый сайты сразу кидают в
  13. # блок, если загружать ворохом)
  14. def download(ss,timeout=50,threads=10):
  15.     #Первый ряд загружается по одному изображению, пока не упрётся в 404,
  16.     #После чего в каждом столбце загружается первое изображение, и если оно выдаёт не 404,
  17.     #То через несколько потоков загружается вся строка (даже так загружалось почти 300 секунд),
  18.     # хотя 80 мб должны были загрузится за 40-80 секунд.
  19.     timeout*=0.001
  20.     m=f"data/map_data/{hashlib.sha1(ss.encode()).hexdigest()}"
  21.     for c in m.split("/"):
  22.         if not os.path.isdir(c):
  23.             os.mkdir(c)
  24.         os.chdir(c)
  25.     if not os.path.exists("name.txt"):
  26.         with open("name.txt",'w') as f:
  27.             f.write(ss)
  28.     ext=os.path.splitext(ss)[1]
  29.     path=os.getcwd()
  30.     lt=time.time()
  31.     st=lt
  32.  
  33.     def load_sloy(z):
  34.         nonlocal st,lt
  35.         loc=os.path.join(path,f'{z:03d}')
  36.         if not os.path.isdir(loc):
  37.             os.mkdir(loc)
  38.         os.chdir(loc)
  39.         if os.path.isfile('end'):
  40.             try:
  41.                 with open("end", 'r') as f:
  42.                     r=f.read()
  43.                     if r=='-':
  44.                         return False
  45.                     elif r=='+':
  46.                         return True
  47.  
  48.             except:
  49.                 return True
  50.         y=0
  51.         n=0
  52.         mx=-1
  53.         while True:
  54.             x=0
  55.             if mx==-1:
  56.                 while x!=mx:
  57.                     fname=f'{z}_{y}_{x}_{ext}'
  58.                     if not os.path.exists(fname):
  59.                         try:
  60.                             with urllib.request.urlopen(ss.format(z=z,x=x,y=y)) as f_net,\
  61.                                 open(fname,'wb') as f_file:
  62.                                 f_file.write(f_net.read())
  63.                                 time.sleep(timeout)
  64.                         except urllib.error.HTTPError as e:
  65.                             if e.code==404:
  66.                                 if x==0:
  67.                                     if y==0:
  68.                                         with open("end",'w') as f:
  69.                                             f.write("-")
  70.                                         return False
  71.                                     else:
  72.                                         print(f"Загружен слой {z}")
  73.                                         with open("end",'w') as f:
  74.                                             f.write("+")
  75.                                         return True
  76.                                 else:
  77.                                     mx=x
  78.                                     break
  79.                             else:
  80.                                 print(f"HTTP error {e.code}")
  81.                                 while input() not in ['q','exit','stop','end','close','й','']:
  82.                                     ...
  83.                         except Exception as e:
  84.                             raise e
  85.                     n+=1
  86.                     nt=time.time()
  87.                     if nt-lt>1:
  88.                         print(f" ... {nt-st:.1f}: {n} файлов")
  89.                         lt=nt
  90.                     x+=1
  91.             else:
  92.                 def download_url(x):
  93.                     fname=f'{z}_{y}_{x}_{ext}'
  94.                     if not os.path.exists(fname):
  95.                         try:
  96.                             with urllib.request.urlopen(ss.format(z=z, x=x, y=y)) as f_net, \
  97.                                     open(fname, 'wb') as f_file:
  98.                                 f_file.write(f_net.read())
  99.                                 time.sleep(timeout)
  100.                         except Exception as e:
  101.                             raise e
  102.  
  103.                 x=0
  104.                 fname = f'{z}_{y}_{x}_{ext}'
  105.                 if not os.path.exists(fname):
  106.                     try:
  107.                         with urllib.request.urlopen(ss.format(z=z, x=x, y=y)) as f_net, \
  108.                                 open(fname, 'wb') as f_file:
  109.                             f_file.write(f_net.read())
  110.                             time.sleep(timeout)
  111.                     except urllib.error.HTTPError as e:
  112.                         if e.code==404:
  113.                             print(f"Загружен слой {z}")
  114.                             with open("end",'w') as f:
  115.                                 f.write("+")
  116.                             return True
  117.                         else:
  118.                             print(f"HTTP error {e.code}")
  119.                         while input() not in ['q', 'exit', 'stop', 'end', 'close', 'й', '']:
  120.                             ...
  121.                     except Exception as e:
  122.                         raise e
  123.                 xx=list(range(1,mx))
  124.                 k=ThreadPool(threads)
  125.                 k.imap_unordered(download_url, xx)
  126.                 k.close()
  127.                 k.join()
  128.                 n += len(xx)
  129.                 nt = time.time()
  130.                 if nt-lt>1:
  131.                     print(f" ... {nt-st:.1f}: {n} файлов")
  132.                     lt = nt
  133.             y+=1
  134.  
  135.     z=0
  136.     while load_sloy(z):
  137.         z+=1
  138.     os.chdir(os.path.dirname(os.path.abspath(__file__)))
  139.     print(f"Рабочая папка: {os.getcwd()}")
  140.     ...
  141.  
  142.  
  143.  
  144. from PIL import Image
  145.  
  146. def skleiti(ss,ext='webp',quality=100):
  147.     m=f"data/map_data/{hashlib.sha1(ss.encode()).hexdigest()}"
  148.     for c in m.split("/"):
  149.         if not os.path.isdir(c):
  150.             os.mkdir(c)
  151.         os.chdir(c)
  152.  
  153.     lt=time.time()
  154.     st=lt
  155.     def load_sloy(z):
  156.         nonlocal lt
  157.         regex=re.compile(r"(\d+)_(\d+)_(\d+)_")
  158.         mx=0
  159.         my=0
  160.         nm=f"{z:03d}"
  161.         try:
  162.             with open(os.path.join(nm,"end"), 'r') as f:
  163.                 r = f.read()
  164.             if r=='-':
  165.                 return False
  166.         except:
  167.             print(f"Ошибка в слое {z}")
  168.             return False
  169.         ext_n=''
  170.         file_name=f"{nm}-{quality}.{ext}"
  171.         if os.path.exists(file_name):
  172.             print(f'[file_name] - уже есть')
  173.             return True
  174.         for c in os.listdir(nm):
  175.             for m in regex.finditer(c):
  176.                 y,x=int(m.group(2)),int(m.group(3))
  177.                 my=max(y,my)
  178.                 mx=max(x,mx)
  179.                 if not ext_n:
  180.                     ext_n=os.path.splitext(c)[1]
  181.  
  182.         mx+=1
  183.         my+=1
  184.         img = Image.new('RGB', (256*mx, 256*my))
  185.         n2=mx*my
  186.         n=0
  187.         for x in range(mx):
  188.             for y in range(my):
  189.                 il=Image.open(os.path.join(nm,f'{z}_{y}_{x}_{ext_n}'))
  190.                 img.paste(il, (256*x, 256*y))
  191.                 n+=1
  192.                 nt = time.time()
  193.                 if nt-lt>1:
  194.                     print(f" ... {nt-st:.1f}: Клею слой {z}, {n/n2:.1%}")
  195.                     lt = nt
  196.         print(f"Сохраняю слой слой {z} в {ext} (это может занять много времени)")
  197.         try:
  198.             img.save(file_name,quality=quality)
  199.         except:
  200.             os.remove(file_name)
  201.             img.save(file_name.replace(ext,'.jpg'),quality=quality)
  202.             print(f"Сохраняю слой слой {z} в jpg  (это может занять много времени)")
  203.         return True
  204.  
  205.     z = 0
  206.     while load_sloy(z):
  207.         z += 1
  208.  
  209. #http://maps.dadesign.ru/argus/
  210. #http://maps.dadesign.ru/draenor/
  211. #http://maps.dadesign.ru/shadowlands/
  212. #http://maps.dadesign.ru/outland/
  213. #http://maps.dadesign.ru/azeroth/data/7-0-0.jpg
  214.  
  215.  
  216. #   Загрузка
  217. # {z} - масштаб, {x}/{y} - координаты
  218. download(r"http://maps.dadesign.ru/azeroth/data/{z}-{x}-{y}.jpg")
  219.  
  220. #   Склеивать
  221. skleiti(r"http://maps.dadesign.ru/azeroth/data/{z}-{x}-{y}.jpg",ext='webp',quality=90)
  222.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement