def unpack_archive(self, replace=True): name = self.name tmp_file = tempfile.NamedTemporaryFile(suffix=os.path.splitext(name)[-1]) archive_file = self.file self.open() shutil.copyfileobj(archive_file, tmp_file.file) tmp_file.file.flush() archive = Archive(tmp_file.name) temp_dir = tempfile.mkdtemp() archive.extract(temp_dir) unpack_folder = self._generate_unpack_folder(name) try: for dir, dirs, files in os.walk(temp_dir): for _filename in files: abs_path = os.path.join(dir, _filename) storage_path = os.path.join(unpack_folder, os.path.relpath(abs_path, temp_dir)) is_exists = self.unpack_storage.exists(storage_path) if is_exists: if not replace: continue else: self.unpack_storage.delete(storage_path) with open(abs_path, 'rb') as f: self.unpack_storage.save(storage_path, File(f)) finally: shutil.rmtree(temp_dir)
def __unpack(self, archive_name) -> None: first = time.time() parent_dir = os.getcwd() frame_archive = Archive(archive_name) folder = frame_archive.name_woextension # You can also call this to remove a directory. if os.path.exists(frame_archive.name_woextension): for filename in os.listdir(folder): file_path = os.path.join(folder, filename) try: if os.path.isfile(file_path) or os.path.islink(file_path): os.unlink(file_path) elif os.path.isdir(file_path): shutil.rmtree(file_path) except Exception as e: print('Failed to delete %s. Reason: %s' % (file_path, e)) frame_archive.extract() os.chdir(parent_dir) os.remove("./%s" % frame_archive.file_name) print(f"{archive_name} unzipped and archived") frame_packet = sorted(os.listdir(f"{archive_name[:-4]}/Frames")) frame_packet = [ f"{archive_name[:-4]}/Frames/{x}" for x in frame_packet ] self.new_packets.append(frame_packet) print(f"{time.time() - first} to unpack")
class backend(models.Model): adana=("burası about sayfası için python kodu çalıştıran kod backend içinde") def badana(self): global kappa kappa=1 self.deneme="badana içine girdiğini gösteren kod" print(self.deneme) print(self.adana) api = SentinelAPI('flavves', 'şifre', 'https://scihub.copernicus.eu/dhus') footprint = geojson_to_wkt(read_geojson('media/map.geojson')) print(footprint) self.products = api.query(footprint,date=('20191219', date(2019, 12, 29)),platformname='Sentinel-2') products_df = api.to_dataframe(self.products) print("oluyor galiba") self.products_df_sorted = products_df.sort_values(['cloudcoverpercentage', 'ingestiondate'], ascending=[True, True]) self.products_df_sorted = self.products_df_sorted.head(1) self.df=self.products_df_sorted self.NotDefteriKaydi = self.df.values.tolist() self.str_denemesi=str(self.NotDefteriKaydi) self.Kaydetmeye_basla=list(self.str_denemesi.split(",")) self.yerler=[0,7,8,9,12,14,18,19,20] self.isimler=["Dosya adı:","Uydu adı","Dosya boyutu","Çekim tarihi","Orbit numarası","Bulut yüzdesi","vejetasyon yüzdesi","su yüzdesi","not vejetasyon yüzdesi"] self.i=0 with open("media/books/txt/deneme.txt", "w") as self.dosya: for self.sira in self.yerler: print(self.isimler[self.i]+":"+self.Kaydetmeye_basla[self.sira]) self.yaz=(self.isimler[self.i]+":"+self.Kaydetmeye_basla[self.sira]) self.i=self.i+1 self.dosya.write(self.yaz) self.dosya.write("\n") self.dosya.close() print(self.products_df_sorted) print("indirme başladı") #burasını blockladım çünkü 1 gb arşiv indiriyor #api.download_all(self.products_df_sorted.index) print("indirme bitti") self.veri_cekme=self.products_df_sorted.index self.veri_cekme1=self.veri_cekme[0] """ Bu işlem arşivden çıkarmak için gerekli arşivin adı indirdiğimiz verinin title adı oluyor """ self.arsiv_adi=api.get_product_odata(self.veri_cekme1) self.arsiv_adi=self.arsiv_adi["title"] self.arsiv_adi=str(self.arsiv_adi) print(self.arsiv_adi) self.a = Archive(self.arsiv_adi+'.zip') self.a.extract() self.img_data_klasor_ismi=os.listdir((self.arsiv_adi+".SAFE"+'/GRANULE')) self.img_data_klasor_ismi=self.img_data_klasor_ismi[0] self.img_data_klasor_ismi=str(self.img_data_klasor_ismi) self.dosya_yer_=(self.arsiv_adi+".SAFE"+'/GRANULE/'+self.img_data_klasor_ismi+'/IMG_DATA') self.resim_isim=os.listdir(self.dosya_yer_) print(self.dosya_yer_) """ şimdi ise resimleri rasterio ile bi kullanalım """ if self.resim_isim == "R10m" or "R20m" or "R60m": self.dosya_yer_=(self.arsiv_adi+".SAFE"+'/GRANULE/'+self.img_data_klasor_ismi+'/IMG_DATA/R60m') self.resim_isim=os.listdir(self.dosya_yer_) self.resim_isim[2] self.resim_isim[3] self.jp2ler = [self.resim_isim[2],self.resim_isim[3]] self.bands = [] #burası bizim jp2 dosyalarımızı okuyacak for self.jp2 in self.jp2ler: with rasterio.open(self.dosya_yer_+"/"+self.jp2) as self.f: self.bands.append(self.f.read(1)) #resimlerimizi ayrıştırdık özel bantlara self.band_red=self.bands[0] self.band_nir=self.bands[1] print("bant değerleri hesaplandı") print(self.bands[0],self.bands[1]) else: self.resim_isim[2] self.resim_isim[3] self.jp2ler = [self.resim_isim[2],self.resim_isim[3]] self.bands = [] #burası bizim jp2 dosyalarımızı okuyacak for self.jp2 in self.jp2ler: with rasterio.open(self.dosya_yer_+"/"+self.jp2) as f: self.bands.append(self.f.read(1)) #resimlerimizi ayrıştırdık özel bantlara self.band_red=self.bands[0] self.band_nir=self.bands[1] print("bant değerleri hesaplandı") print(self.bands[0],self.bands[1]) # Klasik NDVI denklemi ile hesaplama print("ndvı hesaplanıyor") np.seterr(divide='ignore', invalid='ignore') # Calculate NDVI. This is the equation at the top of this guide expressed in code self.ndvi = (self.band_nir.astype(float) - self.band_red.astype(float)) / (self.band_nir + self.band_red) #su için yapıyorum bu analizi ## ### self.ndvi=(self.band_red.astype(float) - self.band_nir.astype(float)) / (self.band_red + self.band_nir) ### ### np.nanmin(self.ndvi), np.nanmax(self.ndvi) print("ndvı değerler aralıkları") print(np.nanmin(self.ndvi), np.nanmax(self.ndvi)) # görüntümüze bakalım renklerine ayrılmış bir görüntümüz var # çizim yapacağız bunun için gerekli kütüphaneler ekleniyor # NDVI bilindiği üzere 1 ve -1 arasındaki değerlerde sınıflandırılır. # Biz de bu değerleri renklerle göstermek istiyoruz. # Bunun için alınan sayısal değerleri farklı renk spektrumlarına atayarak elimizde NDVI için renklendirilmiş bir görüntümüz olacaktır # # Bir orta nokta belirledik ve bu sola ve sağa olacak şekilde renklendiriyoru renk spekturumunu da aşağıda paylaşacağım class RenkNormalizasyonu(colors.Normalize): def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False): self.midpoint = midpoint colors.Normalize.__init__(self, vmin, vmax, clip) def __call__(self, value, clip=None): x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1] return np.ma.masked_array(np.interp(value, x, y), np.isnan(value)) self.min=np.nanmin(self.ndvi) self.max=np.nanmax(self.ndvi) self.mid=0.1 print("bitti mi şimdi bok biter") print(self.min,self.max) self.fig = plt.figure(figsize=(20,10)) self.ax = self.fig.add_subplot(111) self.cmap = plt.cm.RdYlGn self.cax = self.ax.imshow(self.ndvi, cmap=self.cmap, clim=(self.min, self.max), norm=RenkNormalizasyonu(midpoint=self.mid,vmin=self.min, vmax=self.max)) self.ax.axis('off') self.ax.set_title('NDVI görüntüsü', fontsize=18, fontweight='bold') self.cbar = self.fig.colorbar(self.cax, orientation='horizontal', shrink=0.65) #normalde byu alttaki gibi kaydetsin ama şimdilik benim yazdığım gibi yapsın olur mu cnm muck #self.fig_kaydet="resimler/"+self.resim_isim[2]+".tif" self.fig_kaydet="media/books/covers/denemeresmi.png" self.fig.savefig(self.fig_kaydet, dpi=200, bbox_inches='tight', pad_inches=0.7) self.fig_kaydet_tif="media/books/covers/denemeresmi.tif" self.fig.savefig(self.fig_kaydet_tif, dpi=200, bbox_inches='tight', pad_inches=0.7)
class Backup: """Handles complete backup flow. Check if file exists orhas been modified. Compresses, encrypts and uploads the file to th destination.""" db = None job = None compress = None encrypt = None def __init__(self, job, db): self.job = job self.db = db self.archive = Archive() self.crypt = Crypt() def backup(self): """Start backup process.""" if not isdir(self.job['path']): self._list_files( None, dirname(self.job['path']), [basename(self.job['path']), ] ) else: walk(self.job['path'], self._list_files, None) def _list_files(self, dir, basepath, files): """Callback for walker. Iterates over filelist, builds absolute path and checks wheather to skip or upload the file.""" for file in files: # absolute path path = join(basepath, file) # only work on files if isfile(path) or ( not isdir(path) and self.job.has_key('pre_command')): item = self.db.get_file(self.job['name'], path) # file is not in db if not item: self._backup_file(path) else: # file exists in db, but has a different mtime if isfile(path): mtime = getmtime(path) if int(item['mtime']) != int(mtime): self._backup_file(path) else: self._backup_file(path) def _execute_command(self, command): """Execute pre- or postcommand.""" if self.job.has_key(command): try: logging.info('[%s] Executing %s' % (self.job['name'], self.job[command])) system(self.job[command]) except: logging.warn('[%s] Command failed %s' % (self.job['name'], self.job[command])) def _backup_file(self, path): """Back ups specific file to desired storage device.""" print('[%s] Starting backup for %s' % (self.job['name'], path)) # precommand self._execute_command('pre_command') # get size, mtime file_info = self._file_info(path) # get storeage wrapper storage = self._get_account(self.job['destination']) dest = join(tempfile.gettempdir(), 'umaticssync') # is compression deired? bzip2 file if self.job.has_key('compress') and self.job['compress'] == 'true': logging.info('[%s] Compressing %s' % (self.job['name'], path)) self.archive.compress(path, dest) old_dest = dest compressed = 1 # is encryption desired? encrypt with user id if self.job.has_key('encrypt') and self.job['encrypt']: logging.info('[%s] Encrypting %s' % (self.job['name'], path)) self.crypt.encrypt(self.job['encrypt'], dest) dest = dest + '.gpg' remove(old_dest) encrypted = 1 # add file/increase revision info = self.db.add_file( self.job['name'], path, file_info['mtime'], file_info['size'], encrypted, compressed) # build key and upload, cleanup key = normpath('%s/%s.r%%s' % (self.job['name'], path)) logging.info('[%s] Uploading %s.r%s' % (self.job['name'], path, info['revision'])) storage.store_file(key % info['revision'], dest) remove(dest) # cleanup old revisions revision = int(info['revision']) - int(self.job['revisions']) if revision >= 0: print "del", key % revision storage.del_file(key % revision) # postcommand self._execute_command('post_command') def _file_info(self, path): """Returns size and mtime.""" return {'size': getsize(path), 'mtime': getmtime(path)} def _get_account(self, uri): """Return storage engine object based on the provided URI string.""" uri = urlsplit(uri) # s3 backend if uri[0] == 's3': a_key, s_key = uri[2][2:].split('@')[0].split(':') bucket = uri[2][2:].split('@')[1] from wrapper.S3Wrapper import S3Wrapper return S3Wrapper(a_key, s_key, bucket) # ftp server elif uri[0] == 'ftp': user, passwd = uri[2][2:].split('@')[0].split(':') host = uri[2][2:].split('@')[1] path = uri[2] from wrapper.FTPWrapper import FTPWrapper return FTPWrapper(host, user, passwd, path) # @todo: implement elif uri[0] == 'scp': pass # local storage backend elif uri[0] == 'file': path = uri[1] from wrapper.FileWrapper import FileWrapper return FileWrapper(path) def restore(self, revision): files = self.db.get_files(self.job['name']) if len(files) == 0: #logging.info('[%s] No files found for backup job') return False # get storage instance storage = self._get_account(self.job['destination']) # iterate thur files for file in files: try: # is given revision in allowed range? rev_diff = int(file['revision']) - int(self.job['revisions']) if int(revision) in range(rev_diff, file['revision'] + 1): rev = revision else: # fallback to latest file revision rev = file['revision'] except: rev = file['revision'] logging.info('[%s] Restoring %s.r%s' % (self.job['name'], file['path'], rev)) # get file key = normpath('%s/%s.r%s' % (self.job['name'], file['path'], rev)) dest = join(tempfile.gettempdir(), 'umaticssync') logging.info('[%s] Downloading %s' % (self.job['name'], file['path'])) storage.get_file(key, dest) if file['encrypted'] == 1: logging.info('[%s] Decrypting %s' % (self.job['name'], file['path'])) self.crypt.decrypt(self.job['encrypt'], dest, dest) if file['compressed'] == 1: logging.info('[%S] Extracting %s' % (self.job['name'], file['path'])) self.archive.extract(dest) else: rename(dest, file['path'])