def start_ftp_session(): print('In start_ftp_session...') ftp = FTP() try: ret = ftp.connect(host=settings.ftp_server, port=settings.ftp_port) print(f'Connected: {ret}') except ftplib.all_errors as e: print(f'Error connecting to {settings.ftp_server}: {e}') sys.exit() else: try: ret = ftp.login(user=settings.ftp_user, passwd=settings.ftp_pass) except ftplib.all_errors as e: print(f'Error logging in to {settings.ftp_server}: {e}') sys.exit() if sys.platform == 'ios': un = os.uname() dir_prefix = un.nodename else: dir_prefix = 'batch' sub_dir = make_targetdir_string(dir_prefix) target_dir = os.path.join(settings.ftp_basedir, sub_dir) make_ftp_targetdir(ftp, target_dir) console.set_idle_timer_disabled(True) #Don't let device go to sleep return ({'FTP': ftp, 'TargetDir': target_dir}) #return tuple
def send(self, file_list): if pythonista: console.set_idle_timer_disabled(True) print('Archiving files.....') self.comment_dict['sender'] = self.system comment_str = json.dumps(self.comment_dict) archiver(file_list, True, self.send_path, comment_str) self.start_server() if self.system == 'Windows': os.system('pause')
def __init__(self, obj, delay = .1): import console, time # trying for saftey ui.cancel_delays() # no sleeping... console.set_idle_timer_disabled(True) self.obj = obj self.delay = delay self.busy = False # record the start time self.start = time.time() ui.delay(self.auto_scroll, 2)
def main(): # Process any supplied arguments log_level = 'INFO' update_config = False for argument in sys.argv: if argument.lower() == '-v': log_level = 'FINE' elif argument.lower() == '-vv': log_level = 'DEBUG' elif argument.lower() == '-c': update_config = True # configure logging log_format = "%(message)s" logging.addLevelName(FINE, 'FINE') for handler in logging.getLogger().handlers: logging.getLogger().removeHandler(handler) logging.basicConfig(format=log_format, level=log_level) # disable dimming the screen console.set_idle_timer_disabled(True) # Load the current sync status file file_details = load_sync_state() # Load the initial configuration config = setup_configuration() # set up user configuration options setup_user_configuration(update_config, config) logging.info('Begin Dropbox sync') #configure dropbox sess = dropbox.session.DropboxSession(config['APP_KEY'], config['APP_SECRET'], config['ACCESS_TYPE']) configure_token(sess, config) client = dropbox.client.DropboxClient(sess) logging.info('linked account: %s', client.account_info()['display_name']) process_folder(config, client, '/', file_details) # Write sync state file write_sync_state(file_details) # re-enable dimming the screen console.set_idle_timer_disabled(False)
def touch_ended(self, touch): if not self.panning: self.running = self.running == False if self.running: self.update_interval = 1 l.text_color = 'black' console.set_idle_timer_disabled(True) else: self.update_interval = 0 l.text_color = 'darkgrey' console.set_idle_timer_disabled(False) self.panning = False self.prev_y = 0
def send(self, file_list): if pythonista: console.set_idle_timer_disabled(True) print('Archiving files.....') system = platform.system() if pythonista: sender = 'Pythonista' else: sender = system self.comment_dict['sender'] = sender comment_str = json.dumps(self.comment_dict) archiver(file_list, True, self.send_path, comment_str) self.start_server()
def touch_ended(self, touch): l = self.superview if not self.panning: self.running = self.running == False if self.running: self.update_interval = 1 l.text_color = theme.front console.set_idle_timer_disabled(True) else: self.update_interval = 0 l.text_color = theme.secondary console.set_idle_timer_disabled(False) self.panning = False self.prev_y = 0
def update(self): l.text = str(self.current_time) if self.current_time == 0: self.update_interval = 0 self.running = False self.seconds = 60 l.text_color = 'darkgrey' console.set_idle_timer_disabled(False) return self.seconds -= 1 self.set_needs_display() if self.seconds == 0: self.seconds = 60 self.current_time -= 1
def downbutton_tapped(sender): global after_id, image_url, video_url, media_code, down_dir, down_count, down_mode, start_time, down_size view.downbutton.enabled = False console.set_idle_timer_disabled(True) view.status.text = '正在与Instagram服务器通讯...' query_num = ceil(user_postcount / 500) query_count = 0 after_id = '' image_url = [] video_url = [] media_code = [] view.status.text = '向服务器请求ShortCode...' while query_count < query_num: if not get_media_code(): time.sleep(3) else: query_count += 1 view.status.text = '获取ShortCode完成!' time.sleep(1) view.status.text = '遍历贴文抓取下载地址...' while media_code: pool = Pool(40) pool.map(get_media_url, media_code) pool.close() pool.join() view.status.text = '下载地址抓取完成!' time.sleep(1) view.status.text = '准备下载...' down_dir = make_download_dir() down_count = 0 down_size = 0 start_time = time.time() while image_url: down_mode = 'image' pool = Pool(30) pool.map(download, image_url) pool.close() pool.join() while view.videobutton.value and video_url: down_mode = 'video' pool = Pool(30) pool.map(download, video_url) pool.close() pool.join() console.set_idle_timer_disabled(False) view.downbutton.enabled = True end_time = time.time() view.status.text = '下载完成!耗时{:.0f}秒,平均{:.1f}M/S。\n共下载{}项,总大小{:.1f}MB。\n保存在目录instagram/{}内。'.format( end_time - start_time, down_size / (end_time - start_time), down_count, down_size, user_name)
def main(): # Process any supplied arguments log_level = 'INFO' update_config = False for argument in sys.argv: if argument.lower() == '-v': log_level = 'FINE' elif argument.lower() == '-vv': log_level = 'DEBUG' elif argument.lower() == '-c': update_config = True # configure logging log_format = "%(message)s" logging.addLevelName(FINE, 'FINE') for handler in logging.getLogger().handlers: logging.getLogger().removeHandler(handler) logging.basicConfig(format=log_format, level=log_level) # disable dimming the screen console.set_idle_timer_disabled(True) # Load the current sync status file file_details = load_sync_state() # Load the initial configuration config = setup_configuration() # set up user configuration options setup_user_configuration(update_config, config) logging.info('Begin Dropbox sync') #configure dropbox client = get_dropbox_client(config) logging.info('linked account: %s', client.account_info()['display_name']) os.chdir(PYTHONISTA_DOC_DIR ) # Switch to Pythonista doc root if not there already process_folder(config, client, '/', file_details) # Write sync state file write_sync_state(file_details) # re-enable dimming the screen console.set_idle_timer_disabled(False)
def main(): # Process any supplied arguments log_level = 'INFO' update_config = False for argument in sys.argv: if argument.lower() == '-v': log_level = 'FINE' elif argument.lower() == '-vv': log_level = 'DEBUG' elif argument.lower() == '-c': update_config = True # configure logging log_format = "%(message)s" logging.addLevelName(FINE, 'FINE') for handler in logging.getLogger().handlers: logging.getLogger().removeHandler(handler) logging.basicConfig(format=log_format, level=log_level) # disable dimming the screen console.set_idle_timer_disabled(True) # Load the current sync status file file_details = load_sync_state() # Load the initial configuration config = setup_configuration() # set up user configuration options setup_user_configuration(update_config, config) logging.info('Begin Dropbox sync') #configure dropbox client = get_dropbox_client(config) logging.info('linked account: %s', client.account_info()['display_name']) os.chdir(PYTHONISTA_DOC_DIR) # Switch to Pythonista doc root if not there already process_folder(config, client, '/', file_details) # Write sync state file write_sync_state(file_details) # re-enable dimming the screen console.set_idle_timer_disabled(False)
def draw(self): if state.path: self.name = os.path.basename(state.path) else: self.name = 'MIDI player' if not state.playing: self['play'].enabled = True self['stop'].enabled = False self['next'].enabled = False console.set_idle_timer_disabled(False) else: self['play'].enabled = False self['stop'].enabled = True self['next'].enabled = True console.set_idle_timer_disabled(True)
def receive(self, wait_time, show_text=True): if pythonista: console.set_idle_timer_disabled(True) main_dir = self.main_dir if os.path.isfile(self.receive_path): os.remove(self.receive_path) try: while True: if show_text: print('Detecting Server.....') result = port_scan.scan() if result: IP = result[0] break if show_text: print('waiting for {}s'.format(wait_time)) time.sleep(wait_time) except KeyboardInterrupt: raise KeyboardInterrupt d = datetime.datetime.today().strftime("%Y-%m-%d %H-%M-%S") to_extract_path = to_abs_path(main_dir, d) print('Detected!!\nServer IP is ' + IP) rel_path = os.path.relpath(self.send_path, to_abs_path()) rel_path = rel_path.replace("\\", "/") # for windows target_url = 'http://{}:{}/{}'.format(IP, port, rel_path) downloader(target_url, self.receive_path) if os.path.exists(self.receive_path): if pythonista: console.hud_alert('Transfer Completed!!') if not os.path.isdir(to_extract_path): os.makedirs(to_extract_path) zip = zipfile.ZipFile(self.receive_path) receive_comment_dict = json.loads(zip.comment.decode('utf-8')) print('\nExtracting.....') sender = receive_comment_dict['sender'] for _ in zip.infolist(): decoding = 'shift-jis' if sender == 'Windows' else 'utf-8' _.filename = _.filename.encode('utf-8').decode( decoding, 'replace') try: zip.extract(_, to_extract_path) except: new_filename = [] sep = '//' if sender == 'Windows' else '/' for split in _.filename.split(sep): _split = re.sub(r'[\\|/|:|?|"|<|>|\|]', '-', split).strip() new_filename.append(_split) new_filename = sep.join(new_filename) _.filename = new_filename try: zip.extract(_, to_extract_path) except Exception as e: print('Error {}'.format(_.filename)) print(e) else: print('Renamed {}'.format(_.filename)) zip.close() os.remove(self.receive_path) if 'share_text' in receive_comment_dict: share_text = receive_comment_dict['share_text'] if pythonista: clipboard.set(share_text) console.hud_alert('Copied to clipboard') elif self.system == 'Windows': os.system('echo {}|clip'.format(share_text)) print('Copied to clipboard') print('Share text \n"\n{}\n"'.format(share_text)) else: print('Share text \n"\n{}\n"'.format(share_text)) removeEmptyFolders(to_extract_path, True) elif pythonista and receive_comment_dict['sender'] == 'Pythonista': msg = "Sender is Pythonista\nMove to original path?" if console.alert("Transfer", msg, "No", "Yes", hide_cancel_button=True) == 2: print('-----Detailed Log-----\n') file_list = [ (to_abs_path(os.path.relpath(x, to_extract_path)), x) for x in return_all_file(to_extract_path) ] total_file_list = [] # file not dir # print(file_list replace_list = [] for original_path, transfer_path in file_list: if os.path.isfile(original_path): replace_list.append([original_path, transfer_path]) if os.path.isdir(transfer_path): if not os.path.isdir(original_path): os.makedirs(original_path) fmt = 'dir {} was creadted' print( fmt.format( os.path.relpath( original_path, to_abs_path()))) else: if not os.path.isfile(original_path): shutil.move(transfer_path, original_path) fmt = 'moved {} to {}' print( fmt.format( os.path.relpath( transfer_path, to_abs_path()), os.path.relpath( original_path, to_abs_path()))) total_file_list.append(original_path) if replace_list and console.alert( "Transfer", "Following files will be replaced.\n{}".format( '\n'.join([ os.path.relpath(x, to_abs_path()) for x, y in replace_list ])), "No", "OK", hide_cancel_button=True) == 2: for original_path, transfer_path in replace_list: os.remove(original_path) print('{} was removed'.format( os.path.relpath(original_path, to_abs_path()))) shutil.move(transfer_path, original_path) fmt = 'moved {} to {}' print( fmt.format( os.path.relpath(transfer_path, to_abs_path()), os.path.relpath(original_path, to_abs_path()))) total_file_list.append(original_path) removeEmptyFolders(to_extract_path, True) if len(total_file_list) == 1: ab_file_path = total_file_list[0] re_file_path = os.path.relpath(ab_file_path, to_abs_path()) msg = 'Do you want to open {}?'.format(re_file_path) if console.alert("Transfer", msg, "No", "Yes", hide_cancel_button=True) == 2: editor.open_file(ab_file_path, True) else: msg = 'Sender is {sender}'.format(**receive_comment_dict) if pythonista: console.hud_alert(msg) else: print(msg) if 'share_text' not in receive_comment_dict: if self.system == 'Windows': os.system('explorer.exe {}'.format(to_extract_path)) elif self.system == 'Linux': os.system('nautilus "{}"'.format(to_extract_path)) print('Done!!') if self.system == 'Windows': os.system('pause') else: console.alert("Transfer", "{} is not found".format(self.receive_path), "OK", hide_cancel_button=True)
def stop(self): console.set_idle_timer_disabled(False) if self.tindeq.ready: self.tindeq.end_logging_weight() self.tindeq.sleep() cb.reset()
def main(): global splash if appex.is_running_extension(): # copy input file to sandbox folder dest_path_short = '~/Documents/inbox' dest_path = os.path.expanduser(dest_path_short) if not os.path.isdir(dest_path): print('Create ' + dest_path_short) os.mkdir(dest_path) file = appex.get_file_path() print('Input path: %s' % file) if (file == None): console.alert("Error", "Unable to process the input data. Import failed.", "Ok", hide_cancel_button=True) appex.finish() return filename = os.path.join(dest_path, os.path.basename(file)) filename = getuniquename(filename, '') shutil.copy(file, filename) print('Saved in %s' % dest_path_short) if not os.path.exists(filename): print(' > Error file %s not found !' % os.path.basename(filename)) # prompt for a new adventure name s = os.path.basename(file).replace(".thz", "") name = console.input_alert("Import Adventure", "Please enter the imported adventure name", s, "OK") name = name.replace("/", "") name = name.replace(".", "") name = name.replace(" ", "") res = False if name != "": if not os.path.exists(name): try: os.mkdir(name) res = True except: console.alert("Please enter a valid or non-existing name") if not res: appex.finish() return # unzip the file decompress_zipfile(filename, "./" + name) os.remove(filename) # check decompressed file integrity : does it include game files ? res = True if not os.path.exists("./" + name + "/Definition.txt"): res = False if res: console.alert("Adventure successfully imported!", "", "Ok", hide_cancel_button=True) else: recurseDeleteFolder(name) console.alert( "File corrupted!", "The adventure you tried to import is corrupted, import failed.", "Ok", hide_cancel_button=True) appex.finish() # launch game console.set_idle_timer_disabled(True) # Get the GPS info. location.start_updates() # Compass motion.start_updates() launchTitleScreen()
def will_close(self): console.set_idle_timer_disabled(False)
if direction.selected_index == 0: return westBound else: direction.selected_index = 1 return eastBound except NameError: #return data set depending on direction toggle in UI if direction.selected_index == 0: return westBound else: direction.selected_index = 1 return eastBound #Turn screen timout off so phone doesn't sleep console.set_idle_timer_disabled("disable") #Buildling out view info. v = ui.View(frame=(0, 0, 300, 110)) #Setup 3 labels for each station to write S1 = ui.Label(frame=(100, 5, 195, 20), flex='lwh', font=('<System>', 16), alignment=ui.ALIGN_LEFT, name='result_label') S2 = ui.Label(frame=(100, 25, 195, 20), flex='lwh', font=('<System>', 16), alignment=ui.ALIGN_LEFT, name='result_label') S3 = ui.Label(frame=(100, 45, 195, 20), flex='lwh', font=('<System>', 16), alignment=ui.ALIGN_LEFT, name='result_label') eventLog = ui.Label(frame=(100, 65, 195, 20), flex='lwh', font=('<System>', 16), alignment=ui.ALIGN_LEFT, name='result_label') v.add_subview(S1) v.add_subview(S2) v.add_subview(S3) v.add_subview(eventLog)
def main(): # Process any supplied arguments log_level = 'INFO' update_config = False for argument in sys.argv: if argument.lower() == '-v': log_level = 'FINE' elif argument.lower() == '-vv': log_level = 'DEBUG' elif argument.lower() == '-c': update_config = True # configure logging log_format = "%(message)s" logging.addLevelName(FINE, 'FINE') for handler in logging.getLogger().handlers: logging.getLogger().removeHandler(handler) logging.basicConfig(format=log_format, level=log_level) # disable dimming the screen if ispythonista: console.set_idle_timer_disabled(True) # Load the initial configuration config = setup_configuration() ans = True while ans: print(""" 1. Show available vouchers 2. Show last generated voucher 3. Generate a voucher 4. Change settings 5. Exit/Quit """) ans = raw_input("What would you like to do? ") if ans == "1": print("") print("------------------------------------------") print("") print(" Vouchers - not activated yet :") print("------------------------------------------") print_vouchers(config=config) elif ans == "2": print("") print("------------------------------------------") print("") print(" Show last generated voucher :") print("------------------------------------------") print_last_voucher(config=config) elif ans == "3": print("") print("------------------------------------------") print("") print(" Generating a voucher :") print("------------------------------------------") generate_voucher(config=config) elif ans == "4": print("") print("------------------------------------------") print("") print(" Changing settings :") print("------------------------------------------") config = change_settings(config=config) elif ans == "5": print("\n Goodbye") ans = False elif ans != "": print("\n Not Valid Choice Try again") # re-enable dimming the screen if ispythonista: console.set_idle_timer_disabled(False)
def teardown(ftp): ftp.quit() console.set_idle_timer_disabled( False) #Let device go back to its idle timer return
def main(assets, keep_meta, geo_tag, dest_dir, size): minumum_size = True resizePercent = 0 # This is time in seconds to allow for dropbox to process each photo. Older iOS devices will require more time. upload_pause = 3 if size == 'fifty': scale = float(50) / 100 elif size == 'custom': scale = v2['scale_text'] # Numbers only for textbox entries scale.keyboard_type = ui.KEYBOARD_NUMBER_PAD # Display ui locked in portrait orientation and wait till user selects something from it. v2.present(orientations = ['portrait']) v2.wait_modal() scale = float(scale.text) / 100 # No minumums here...reduce all photos no matter what their size. minumum_size = False # If user pressed the close button then cancel script if not ok: sys.exit('Script Cancelled') elif size == 'none': scale = 1 # Disable idle timer to cover working with a large batch of photos console.set_idle_timer_disabled(True) start = time.clock() # Create an instance of Dropbox client drop_client = get_client() for asset in assets: print '\nProcessing photo...' # Get date & time photo was taken the_year, the_date, the_time = get_date_time(asset.creation_date) file_name = '' # Formulate file name for photo old_filename = str(ObjCInstance(asset).filename()) if the_date: folder_name = '{}/{}'.format(the_year, the_date) new_filename = '{}.{}'.format(the_time, old_filename) else: folder_name = 'NoDates' new_filename = old_filename keep_meta = False new_filename = '{}/{}/{}'.format(dest_dir, folder_name, new_filename) if folder_name == 'NoDates': no_exif.append(new_filename) file_name = '{}.{}'.format(the_time, file_name) # Get dimensions for resize based on size of original photo new_w, new_h, w, h, resizeOk = get_dimensions(asset, scale, new_filename, minumum_size) fmt = '\nOriginal Name: {}\nNew Name: {}' print fmt.format(old_filename, new_filename) fmt = '\nOriginal Size: {}x{}\nNew Size: {}x{}' print fmt.format(w, h, new_w, new_h) addToMsg = 'with' if keep_meta else 'without' if resizeOk: msg = '\nCreating resized copy of original photo {} the metadata from original.' else: msg = '\nCreating copy of original photo {} the metadata from original.' print msg.format(addToMsg) # Fetch asset's image data & return it as a io.BytesIO object and then as a byte string img = asset.get_image_data(original = False).getvalue() # Write string image of original photo to Pythonista script dir with open('with_meta.jpg', 'wb') as out_file: out_file.write(img) # Open image, resize it, and write new image to scripts dir img = Image.open('with_meta.jpg') # Retrieve a number that represents the orientation of photo orientation = str(ObjCInstance(asset).orientation()) # Landscape if orientation == '1' or orientation == '3': img = img.resize((new_w, new_h),Image.ANTIALIAS) # Occasionally metadata will say the photo orientation is 1 even though the width is less than the height of photo. if new_w < new_h: oriented = 'portrait' else: oriented = 'landscape' # Portrait elif orientation == '6' or orientation == '8': img = img.resize((new_h, new_w), Image.ANTIALIAS) oriented = 'portrait' # Unavailable else: img = img.resize((new_w, new_h),Image.ANTIALIAS) oriented = 'unknown' print '\nThe orientation for photo is {}.'.format(oriented) if geo_tag: # Get geo-tagging info the_location = get_location(asset.location) if the_location: print '\nGeo-tagging photo...' the_time = the_time.replace('.',':') the_location = '{} @ {} in {}'.format(the_date, the_time, the_location) ''' Get degrees needed to rotate photo for it's proper orientation. See www.impulsesdventue.com/photoexif orientation.html for more details. ''' degrees = get_degrees_to_rotate(orientation) # Rotate photo so tag is on bottom of photo regardless of orientation img = img.rotate(degrees).convert('RGBA') # Tuple w, h = img.size draw = ImageDraw.Draw(img) # Font for geo-tag will be 28 pt Helvetica fontsize = 28 font = ImageFont.truetype('Helvetica', fontsize) y = h - 35 # Put red text @ bottom left of photo draw.text((25, y), the_location,(255, 0, 0), font = font) # Rotate photo back to original position img = img.rotate(-degrees) else: print '\nNo gps metadata for photo.' no_gps.append(new_filename) else: print '\nPhoto will not be geo_tagged. Flag is set to false.' # Save new image img.save('without_meta.jpg') if keep_meta: ''' Copy metadata from 'with_meta.jpg' to 'without_meta.jpg and call this reprocessed image file 'meta_resized.jpg'. ''' copy_meta('with_meta.jpg', 'without_meta.jpg', new_w, new_h) jpg_file = 'meta_resized.jpg' else: # Use resized photo that has not had metadata added back into it jpg_file = 'without_meta.jpg' print '\nUploading photo to Dropbox...' ''' Upload resized photo with or without original metadata to Dropbox...use 'with' statement to open file so file closes automatically at end of 'with'. ''' with open(jpg_file,'r') as img: response = drop_client.put_file(new_filename, img) # Give Dropbox server time to process...pause time is user defined. time.sleep(upload_pause) response = jpg_file = the_location = img = the_date = the_time = the_year = new_filename = old_filename = '' print '\nUpload successful.' finish = time.clock() print '{} photos processed in {}'.format(count, timer(start, finish, count, upload_pause)) if no_exif: print '\nPhotos with no DateTimeOriginal tag in their metadata and will need categorizing manually:' print '\n'.join(no_exif) if no_resize: print '\nPhotos that did not get resized because either you chose not to resize, or they were smaller than the minumum size of 1600x1200:' print '\n'.join(no_resize) if no_gps: print '\nPhotos that did not get geo-tagged because there was no gps info in the photo\'s metadata:' print '\n'.join(no_gps) # Re-enable idle timer console.set_idle_timer_disabled(False)
def __init__(self): self.isInit = False console.set_idle_timer_disabled(True) super(PFD, self).__init__()
def receive(self, wait_time, show_text=True): if pythonista: console.set_idle_timer_disabled(True) main_dir = self.main_dir if os.path.isfile(self.receive_path): os.remove(self.receive_path) try: while True: if show_text: print('Detecting Server.....') result = port_scan.scan() if result: IP = result break if show_text: print('waiting for {}s'.format(wait_time)) time.sleep(wait_time) except KeyboardInterrupt: raise KeyboardInterrupt d = datetime.datetime.today().strftime("%Y-%m-%d %H-%M-%S") to_extract_path = to_abs_path(main_dir, d) print('Detected!!\nServer IP is ' + IP) target_url = 'http://{}:{}/{}'.format( IP, port, os.path.relpath(self.send_path, to_abs_path()).replace("\\", "/")) #for windows downloader(target_url, self.receive_path) if os.path.exists(self.receive_path): if pythonista: console.hud_alert('Transfer Completed!!') if not os.path.isdir(to_extract_path): os.makedirs(to_extract_path) zip = zipfile.ZipFile(self.receive_path) receive_comment_dict = json.loads(zip.comment) print('\nExtracting.....') zip.extractall(to_extract_path) zip.close() os.remove(self.receive_path) if 'share_text' in receive_comment_dict: share_text = receive_comment_dict['share_text'] if pythonista: clipboard.set(share_text) console.hud_alert('Copied to clipboard') else: print('Share text \n"\n{}\n"'.format(share_text)) removeEmptyFolders(to_extract_path, True) elif receive_comment_dict['sender'] == 'Pythonista' and pythonista: if console.alert( "Transfer", "Sender is Pythonista\nMove to original path?", "No", "Yes", hide_cancel_button=True) == 2: print('-----Detailed Log-----\n') file_list = [ (to_abs_path(os.path.relpath(x, to_extract_path)), x) for x in return_all_file(to_extract_path) ] total_file_list = [] #file not dir #print file_list replace_list = [] for original_path, transfer_path in file_list: if os.path.isfile(original_path): replace_list.append([original_path, transfer_path]) if os.path.isdir(transfer_path): if not os.path.isdir(original_path): os.makedirs(original_path) print('dir {} was creadted'.format( os.path.relpath(original_path, to_abs_path()))) else: if not os.path.isfile(original_path): shutil.move(transfer_path, original_path) print('moved {} to {}'.format( os.path.relpath(transfer_path, to_abs_path()), os.path.relpath(original_path, to_abs_path()))) total_file_list.append(original_path) if not len(replace_list) == 0 and console.alert( "Transfer", "Following files will be replaced.\n{}".format( '\n'.join([ os.path.relpath(x, to_abs_path()) for x, y in replace_list ])), "No", "OK", hide_cancel_button=True) == 2: for original_path, transfer_path in replace_list: os.remove(original_path) print('{} was removed'.format( os.path.relpath(original_path, to_abs_path()))) shutil.move(transfer_path, original_path) print('moved {} to {}'.format( os.path.relpath(transfer_path, to_abs_path()), os.path.relpath(original_path, to_abs_path()))) total_file_list.append(original_path) removeEmptyFolders(to_extract_path, True) if len(total_file_list) == 1: ab_file_path = total_file_list[0] re_file_path = os.path.relpath(ab_file_path, to_abs_path()) if console.alert( "Transfer", 'Do you want to open {}?'.format(re_file_path), "No", "Yes", hide_cancel_button=True) == 2: editor.open_file(ab_file_path, True) else: if pythonista: console.hud_alert('Sender is {}'.format( receive_comment_dict['sender'])) else: print('Sender is {}'.format( receive_comment_dict['sender'])) print('Done!!') else: console.alert("Transfer", "{} is not found".format(self.receive_path), "OK", hide_cancel_button=True)
def setup(self): """ Add components to screen, start searcing for tindeq """ console.set_idle_timer_disabled(True) self.start_time = -5 self.active = False # status of repeater test self._state = IdleRepeaterState # parameters for test self.countdown_time = 5 self.work_interval = 7 self.rest_interval = 3 self.num_intervals = 30 self.num_sets_remaining = 1 self.zeropoint = 0 # test y/n? self.mode = 'test' # root node to hold all graphical elements self.root = Node(parent=self) # reels for interval timer self.reels = [] for i in range(2): reel = ReelNode(10) self.root.add_child(reel) self.reels.append(reel) # start counter at work interval self.reels[0].set_value(self.work_interval) # add decimal place for second self.dot = LabelNode('.', font=('Avenir Next', digit_h)) self.root.add_child(self.dot) # and a light shaded overlay to highlight actual digits self.overlay = SpriteNode(size=(max(self.size / 3), digit_h + 10)) self.overlay.shader = Shader(shader_src) self.root.add_child(self.overlay) # add a msgbox; will show status and current load self.background_color = "red" msg_font = ('Avenir Next', 30) self.msgbox = LabelNode('scanning for device', msg_font, color='white') self.cyclebox = LabelNode('', msg_font, color='white') self.root.add_child(self.msgbox) self.root.add_child(self.cyclebox) self.plot = Plot(parent=self.root, xsize=0.35, ysize=0.2, position=(0, 0), nticks=5) # add progressor, with this scene as parent self.tindeq = TindeqProgressor(self) # start scanning for peripherals cb.set_central_delegate(self.tindeq) cb.scan_for_peripherals() self.did_change_size() # buffers for data! self.times = [] self.data = []
def main(choose, keepMeta, geoTag, dest_dir, size): minumum_size = True resizePercent = 0 if size == 'fifty': scale = float(50) / 100 elif size == 'custom': msg = 'Enter desired reduction percent for selected photo(s): ' try: scale = float(console.input_alert(msg, 'Numbers only', '35')) / 100 # No minumums here...reduce all photos no matter what their size. minumum_size = False except KeyboardInterrupt: sys.exit('Script cancelled.') elif size == 'none': scale = 1 #john = dialogs.form_dialog(title = 'Photo Options',fields=[{'type':'switch','title':'Geotag'}, {'type':'switch','title':'Keep Metadata'}]) # Disable idle timer to cover working with a large batch of photos console.set_idle_timer_disabled(True) start = time.clock() # Create an instance of Dropbox client drop_client = get_client() ans = '' ''' When metadata is returned with photo the photo is a tuple, with one the image, and the other the media metadata. ''' for count, photo in enumerate(choose): # Raw data string and Metadata img, meta = photo #print meta #sys.exit() print '\nProcessing photo...' # Get date & time photo was taken theYear, theDate, theTime = GetDateTime(meta) # Formulate file name for photo old_filename = str(meta.get('filename')) if theDate: folder_name = '{}/{}'.format(theYear, theDate) new_filename = '{}.{}'.format(theTime, old_filename) else: folder_name = 'NoDates' new_filename = old_filename keepMeta = False new_filename = '{}/{}/{}'.format(dest_dir, folder_name, new_filename) if folder_name == 'NoDates': no_exif.append(new_filename) # Get dimensions for resize based on size of original photo new_w, new_h, w, h, resizeOk = GetDimensions(meta, scale, new_filename, minumum_size) fmt = '\nOriginal Name: {}\nNew Name: {}' print fmt.format(old_filename, new_filename) fmt = '\nOriginal Size: {}x{}\nNew Size: {}x{}' print fmt.format(w, h, new_w, new_h) addToMsg = 'with' if keepMeta else 'without' if resizeOk: msg = '\nCreating resized copy of original photo {} the metadata from original.' else: msg = '\nCreating copy of original photo {} the metadata from original.' print msg.format(addToMsg) # Write string image of original photo to Pythonista script dir with open('with_meta.jpg', 'wb') as out_file: out_file.write(img) # Open image, resize it, and write new image to scripts dir img = Image.open('with_meta.jpg') img = img.resize((new_w, new_h), Image.ANTIALIAS) if geoTag: # Get geo-tagging info theLocation = GetLocation(meta) if theLocation: print '\nGeo-tagging photo...' # Find out if photo is oriented for landscape or portrait orientation = meta.get('Orientation') # ccc: add a default? ''' Get degrees needed to rotate photo for it's proper orientation. See www.impulsesdventue.com/photo exif-orientation.html for more details. ''' degrees, oriented = GetDegreesToRotate(orientation) print '\nThe orientation for photo is {}.'.format(oriented) theTime = theTime.replace('.', ':') theLocation = '{} @ {} in {}'.format(theDate, theTime, theLocation) # Rotate so tag is on bottom of photo regardless of orientation img = img.rotate(degrees).convert('RGBA') # Tuple w, h = img.size draw = ImageDraw.Draw(img) # Font for geo-tag will be 28 pt Helvetica #fontsize = 56 if w > 1300 else 28 fontsize = 28 font = ImageFont.truetype('Helvetica', fontsize) # Determine y axis for geotag #if h < 1000: #y = h - 35 #else: #y = h - 75 y = h - 35 # Put red text @ bottom left of photo draw.text((25, y), theLocation, (255, 0, 0), font=font) # Rotate back to original position img = img.rotate(-degrees) else: print '\nNo gps metadata for photo.' no_gps.append(new_filename) else: print '\nPhoto will not be geotagged. Flag is set to false.' meta = '' #img = img.resize((new_w, new_h),Image.ANTIALIAS) # Save new image img.save('without_meta.jpg') if keepMeta: ''' Copy metadata from 'with_meta.jpg' to 'without_meta.jpg and call this reprocessed image file 'meta_resized.jpg'. ''' CopyMeta('with_meta.jpg', 'without_meta.jpg', new_w, new_h) jpgFile = 'meta_resized.jpg' else: # Use resized photo that has not had metadata added back into it jpgFile = 'without_meta.jpg' print '\nUploading photo to Dropbox...' ''' Upload resized photo with or without original metadata to Dropbox...use with statement to open file so file closes automatically at end of with. ''' with open(jpgFile, 'r') as img: response = drop_client.put_file(new_filename, img) # Give Dropbox server time to process time.sleep(5) response = jpgFile = theLocation = img = theDate = theTime = theYear = new_filename = old_filename = '' print '\nUpload successful.' finish = time.clock() print '{} photos processed in {}'.format(count + 1, Timer(start, finish, count + 1)) if no_exif: print '\nPhotos with no DateTimeOriginal tag in their metadata and will need categorizing manually:' print '\n'.join(no_exif) if no_resize: print '\nPhotos that did not get resized because either you chose not to resize, or they were smaller than the minumum size of 1600x1200:' print '\n'.join(no_resize) if no_gps: print '\nPhotos that did not get geo-tagged because there was no gps info in the photo\'s metadata:' print '\n'.join(no_gps)
import speech import time import sound import threading from flask import Flask, render_template import logging import console log = logging.getLogger('werkzeug') log.setLevel(logging.ERROR) console.set_idle_timer_disabled(1) app = Flask(__name__) command = '' index = 0 motor_key_words = [ 'Turn left', 'Turn right', 'forward', 'backward', 'Stop', 'Start' ] camera_key_words = ['Can you see', 'picture', 'video'] def listen(): global command global index recorder = sound.Recorder('speech.m4a') while 'exit' not in command: speech.say('listening') print('listening') recorder.record() time.sleep(3) recorder.stop() try: text = speech.recognize('speech.m4a')
pickle.dump(state, fyle) fyle.close() if __name__ == '__main__': token_filename = 'dropbox_sync.token' app_key = 'xxxxxx' app_secret = 'xxxxxx' console.show_activity() print(""" **************************************** * Dropbox File Syncronization * ****************************************""") console.set_idle_timer_disabled(True) _, client = dropboxsetup.init(token_filename, app_key, app_secret) print('\nLoading local state') # lets see if we can unpickle try: state = loadstate() except: print('\nCannot find state file. ***Making new local state***') # Aaaah, we have nothing, probably first run state = dropbox_state() print('\nDownloading everything from Dropbox') # no way to check what we have locally is newer, gratuitous dl state.download_all(client)
def main(assets, keep_meta, geo_tag, dest_dir, size): minumum_size = True resizePercent = 0 # This is time in seconds to allow for dropbox to process each photo. Older iOS devices will require more time. upload_pause = 3 if size == 'fifty': scale = float(50) / 100 elif size == 'custom': scale = tf2 # Numbers only for textbox entries scale.keyboard_type = ui.KEYBOARD_NUMBER_PAD # Display ui locked in portrait orientation and wait till user selects something from it. v2.present(orientations=['portrait']) v2.wait_modal() scale = float(scale.text) / 100 # No minumums here...reduce all photos no matter what their size. minumum_size = False # If user pressed the close button then cancel script if not ok: console.hud_alert('Script Cancelled') sys.exit() elif size == 'none': scale = 1 # Disable idle timer to cover working with a large batch of photos console.set_idle_timer_disabled(True) start = time.clock() # Create an instance of Dropbox client drop_client = get_client() for asset in assets: print('\nProcessing photo...') ''' Get date & time photo was created on YOUR iOS device. Note that in some cases the creation date may not be the date the photo was taken (ie you got it via text, email, Facebook, etc), but rather the date the photo was saved to the camera roll on your device. ''' the_year, the_date, the_time = get_date_time(asset.creation_date) file_name = '' # Formulate file name for photo old_filename = str(ObjCInstance(asset).filename()) if the_date: folder_name = '{}/{}'.format(the_year, the_date) new_filename = '{}.{}'.format(the_time, old_filename) else: folder_name = 'NoDates' new_filename = old_filename keep_meta = False new_filename = '{}/{}/{}'.format(dest_dir, folder_name, new_filename) if folder_name == 'NoDates': no_exif.append(new_filename) file_name = '{}.{}'.format(the_time, file_name) # Get dimensions for resize based on size of original photo new_w, new_h, w, h, resizeOk = get_dimensions(asset, scale, new_filename, minumum_size) fmt = '\nOriginal Name: {}\nNew Name: {}' print(fmt.format(old_filename, new_filename)) fmt = '\nOriginal Size: {}x{}\nNew Size: {}x{}' print(fmt.format(w, h, new_w, new_h)) addToMsg = 'with' if keep_meta else 'without' if resizeOk: msg = '\nCreating resized copy of original photo {} the metadata from original.' else: msg = '\nCreating copy of original photo {} the metadata from original.' print(msg.format(addToMsg)) # Fetch asset's image data & return it as a io.BytesIO object and then as a byte string img = asset.get_image_data(original=False).getvalue() # Write string image of original photo to Pythonista script dir with open('with_meta.jpg', 'wb') as out_file: out_file.write(img) # Open image, resize it, and write new image to scripts dir img = Image.open('with_meta.jpg') # Retrieve a number that represents the orientation of photo orientation = str(ObjCInstance(asset).orientation()) # Landscape if orientation in ('1', '3'): img = img.resize((new_w, new_h), Image.ANTIALIAS) # Occasionally metadata will say the photo orientation is 1 even though the width is less than the height of photo. oriented = 'portrait' if new_w < new_h else 'landscape' # Portrait elif orientation in ('6', '8'): img = img.resize((new_h, new_w), Image.ANTIALIAS) oriented = 'portrait' # Unavailable else: img = img.resize((new_w, new_h), Image.ANTIALIAS) oriented = 'unknown' print('\nThe orientation for photo is {}.'.format(oriented)) if geo_tag: # Get geo-tagging info the_location = get_location(asset.location) if the_location: print('\nGeo-tagging photo...') the_time = the_time.replace('.', ':') the_location = '{} @ {} in {}'.format(the_date, the_time, the_location) ''' Get degrees needed to rotate photo for it's proper orientation. See www.impulsesdventue.com/photoexif orientation.html for more details. ''' degrees = get_degrees_to_rotate(orientation) # Rotate photo so tag is on bottom of photo regardless of orientation img = img.rotate(degrees).convert('RGBA') # Tuple w, h = img.size draw = ImageDraw.Draw(img) # Font for geo-tag will be 28 pt Helvetica fontsize = 28 font = ImageFont.truetype('Helvetica', fontsize) y = h - 35 # Put red text @ bottom left of photo draw.text((25, y), the_location, (255, 0, 0), font=font) # Rotate photo back to original position img = img.rotate(-degrees) else: print('\nNo gps metadata for photo.') no_gps.append(new_filename) else: print('\nPhoto will not be geo_tagged. Flag is set to false.') # Save new image img.save('without_meta.jpg') if keep_meta: ''' Copy metadata from 'with_meta.jpg' to 'without_meta.jpg and call this reprocessed image file 'meta_resized.jpg'. ''' copy_meta('with_meta.jpg', 'without_meta.jpg', new_w, new_h) jpg_file = 'meta_resized.jpg' else: # Use resized photo that has not had metadata added back into it jpg_file = 'without_meta.jpg' print('\nUploading photo to Dropbox...') ''' Upload resized photo with or without original metadata to Dropbox...use 'with' statement to open file so file closes automatically at end of 'with'. ''' with open(jpg_file, 'r') as img: response = drop_client.put_file(new_filename, img) # Give Dropbox server time to process...pause time is user defined. time.sleep(upload_pause) response = jpg_file = the_location = img = the_date = the_time = the_year = new_filename = old_filename = '' print('\nUpload successful.') finish = time.clock() print('{} photos processed in {}'.format( count, timer(start, finish, count, upload_pause))) if no_exif: print( '\nPhotos with no DateTimeOriginal tag in their metadata and will need categorizing manually:' ) print('\n'.join(no_exif)) if no_resize: print( '\nPhotos that did not get resized because either you chose not to resize, or they were smaller than the minumum size of 1600x1200:' ) print('\n'.join(no_resize)) if no_gps: print( '\nPhotos that did not get geo-tagged because there was no gps info in the photo\'s metadata:' ) print('\n'.join(no_gps)) # Re-enable idle timer console.set_idle_timer_disabled(False)