def main(): parser = argparse.ArgumentParser('Temp Sensor Flask Server') parser.add_argument('--use_hostname', '-u', action='store_true', help='Use hostname instead of localhost/127.0.0.1') parser.add_argument('--port', '-p', type=int, help='Port to use', required=True) parser.add_argument( '--verbose', '-v', action='count', help= 'Print more verbose log info (may be specified multiple times to increase verbosity)' ) args = parser.parse_args() init_logging(args.verbose, names=None, log_path=None) flask_logger = logging.getLogger('flask.app') for handler in logging.getLogger().handlers: if handler.name == 'stderr': flask_logger.addHandler(handler) break if platform.system() == 'Windows': from ds_tools.flasks.socketio_server import SocketIOServer as Server else: from ds_tools.flasks.gunicorn_server import GunicornServer as Server host = socket.gethostname() if args.use_hostname else None server = Server(app, args.port, host) server.start_server()
def main(): args = parser().parse_args() init_logging(args.verbose, log_path=None, names=None) action = args.action if action == 'c2a': orig = AnimatedGif(args.path) updated = orig.color_to_alpha(args.color) disposal = _int_or_list(args.disposal) updated.save(args.output, duration=orig.info['duration'], transparency=0, disposal=disposal) elif action == 'split': AnimatedGif(args.path).save_frames(args.output_dir, prefix=args.prefix, format=args.format) elif action == 'combine': kwargs = dict( zip(('disposal', 'duration'), map(_int_or_list, (args.disposal, args.duration)))) AnimatedGif(args.paths).save(args.output, **kwargs) elif action == 'info': show_info(Path(args.path).resolve(), args.all or args.frames or False) else: raise ValueError(f'Unsupported {action=}')
def main(): args = parser().parse_args(req_subparser_value=True) init_logging(args.verbose, log_path=None) action = args.action if action == 'list': for i, monitor in enumerate(PlatformVcp.get_monitors()): print(f'{i}: {monitor}') if args.feature: current, max_val = monitor.get_feature_value(args.feature) supported = monitor.get_supported_values( args.feature) or '[not supported]' print( f' current=0x{current:02X}, max=0x{max_val:02X}, supported={supported}' ) elif args.capabilities: print(f' {monitor.capabilities}') elif action == 'get': monitor = PlatformVcp.get_monitor(args.monitor) feature = monitor.get_feature(args.feature) current, cur_name, max_val, max_name = monitor.get_feature_value_with_names( feature) print(f'monitors[{args.monitor}]: {monitor}[{feature}]:' f' current={maybe_named(current, cur_name)}' f', max={maybe_named(max_val, max_name)}') elif action == 'set': if not (monitors := PlatformVcp.get_monitors(args.monitor)): print(f'No monitors found for {args.monitor=}') for monitor in monitors: feature = monitor.get_feature(args.feature) monitor[feature] = value = monitor.normalize_feature_value( feature, args.value) print(f'monitors[{monitor.n}][{feature}] = 0x{value:02X}')
def main(): parser = argparse.ArgumentParser(description='BG Wiki Crawler for FFXI') parser.add_argument('--verbose', '-v', action='count', help='Print more verbose log info (may be specified multiple times to increase verbosity)') mgroup0 = parser.add_mutually_exclusive_group() mgroup0.add_argument('--endpoint', '-e', help='BG Wiki page to retrieve') mgroup0.add_argument('--list_descriptions', '-d', action='store_true', help='List all BLU spell descriptions') parser.add_argument('--limit', '-L', type=int, default=5, help='Limit on the number of links to retrieve') args = parser.parse_args() init_logging(args.verbose, log_path=None) crawler = WikiCrawler() if args.list_descriptions: links = crawler.get_links('index.php', params={'title':'Category:Blue_Magic'}) # Printer('json-pretty').pprint(links) # return tbl = Table(SimpleColumn('Spell', links), SimpleColumn('Description', 100)) for i, (spell, link) in enumerate(links.items()): if i == args.limit: break row = {'Spell': spell} try: row['Description'] = crawler.get_blu_spell_description(link) except Exception as e: log.error('Error retrieving {} from {}: {}'.format(spell, link, e)) tbl.print_row(row) elif args.endpoint: print(crawler.get_soup(args.endpoint))
def main(): args = parser().parse_args(req_subparser_value=True) from ds_tools.logging import init_logging init_logging(args.verbose, log_path=None) from pathlib import Path from pytube import YouTube yt = YouTube(args.url) if args.action == 'dl': from tempfile import TemporaryDirectory dest_dir = Path(args.save_dir).expanduser() if not dest_dir.exists(): dest_dir.mkdir(parents=True) with TemporaryDirectory() as tmp_dir: choices = yt.streams.order_by('resolution') vid_stream = choose_item(choices.fmt_streams, 'stream') # vid_stream = yt.streams.filter(file_extension=args.extension, res=args.resolution).order_by('resolution')[-1] log.info(f'Downloading video={vid_stream}') vid_path = Path(vid_stream.download(output_path=tmp_dir)) choices = yt.streams.filter(type='audio').order_by('abr') audio_stream = choose_item(choices, 'audio stream') # audio_stream = yt.streams.filter(type='audio').order_by('abr')[-1] log.info(f'Downloading audio={audio_stream}') audio_path = Path(audio_stream.download(output_path=tmp_dir)) dest_path = dest_dir.joinpath(vid_stream.default_filename) combine_via_ffmpeg(audio_path, vid_path, dest_path) log.info(f'Saved video to {dest_path}') elif args.action == 'list': print('Video:') for stream in yt.streams.filter(type='video').order_by('resolution'): print(f' {stream}') print('\nAudio:') for stream in yt.streams.filter(type='audio').order_by('abr'): print(f' {stream}') elif args.action == 'audio': dest_dir = Path(args.save_dir).expanduser() if not dest_dir.exists(): dest_dir.mkdir(parents=True) audio_stream = yt.streams.filter(type='audio').order_by('abr')[-1] log.info(f'Downloading audio={audio_stream}') audio_path = Path(audio_stream.download(output_path=dest_dir)) if args.extension: path = audio_path.with_suffix( args.extension if args.extension. startswith('.') else f'.{args.extension}') audio_path.rename(path) audio_path = path log.info(f'Saved video to {audio_path}') else: raise ValueError(f'Unknown action={args.action}')
def main(): args = parser().parse_args(req_subparser_value=False) from ds_tools.logging import init_logging init_logging(args.verbose, names=None, millis=True, set_levels={'PIL': 30}) if args.action == 'configure': configure(args) else: launch_gui(args)
def main(): args = parser().parse_args() init_logging(args.verbose, log_path=None) src_dir = Path(args.path).expanduser().resolve() zip_dir = src_dir.parent.joinpath('extracted_{}'.format( datetime.now().strftime('%Y-%m-%d'))) if args.old_mode: old_extract_albums(src_dir, zip_dir) else: extract_albums(src_dir, zip_dir) cleanup_names(src_dir)
def main(): args = parser().parse_args() init_logging(args.verbose, log_path=None) if args.debug: enable_http_debug_logging() cls = GoplayVideoStream if args.goplay else VideoStream video = cls(args.source, args.save_dir, args.name, args.format, args.local, args.ffmpeg_dl) if args.local or args.ffmpeg_dl: video.save_via_ffmpeg() else: video.download(args.parallel)
def main(): args = parser().parse_args(req_subparser_value=True) init_logging(args.verbose, log_path=None) f3data = F3Data(args.mode, args.size, args.chunk_size, args.buffering) action = args.action if action == 'write': if not f3data.write_files(args.path, args.start, args.end, args.rewrite): sys.exit(1) elif action == 'read': if not f3data.verify_files(args.path, args.chunk_size): sys.exit(1) else: raise ValueError(f'Unexpected {action=!r}')
def main(): args = parser().parse_args() init_logging(args.verbose, log_path=None) if len(args.path) < 2: raise ValueError('At least 2 input files are required') merger = PdfFileMerger() for path in args.path: log.info(f'Adding {path}') with open(path, 'rb') as f: merger.append(PdfFileReader(f)) log.info(f'Writing merged PDF: {args.output}') merger.write(args.output)
def main(): args = parser().parse_args(req_subparser_value=True) init_logging(args.verbose, log_path=None) image_args = (args.gray, args.normalize, args.max_width, args.max_height, args.compare_as) img_a = ComparableImage( Path(args.path_a).expanduser().resolve(), *image_args) img_b = ComparableImage( Path(args.path_b).expanduser().resolve(), *image_args) log.log(19, f'Comparing:\n{img_a}\nto\n{img_b}') methods = { 'taxicab_distance': 'lower values = more similar', # 'zero_norm': '0-1', 'mean_squared_error': 'lower values = more similar', 'mean_structural_similarity': '0-1; higher values = more similar', 'is_same_as': 'bool', 'is_similar_to': 'bool', } if args.same: methods.update({ 'euclidean_root_mse': '', 'min_max_root_mse': '', 'mean_root_mse': '', 'peak_signal_noise_ratio': 'higher values ~= higher quality if image A is an original version of image B', }) for method, description in methods.items(): result = getattr(img_a, method)(img_b) if isinstance(result, tuple): overall, per_pix = result log.info( f'{method:>26s}: {overall:17,.3f} - per pixel: {per_pix:10,.6f} ({description})' ) else: if method in ('is_same_as', 'is_similar_to'): log.info( f'{method:>26s}: {result!r:>17}{" " * 26} ({description})' ) else: log.info( f'{method:>26s}: {result:17,.3f}{" " * 26} ({description})' )
def main(): args = parser().parse_args() init_logging(args.verbose, log_path=None) parlor = Parlor(args.people, args.slices) parlor_thread = Thread(target=parlor.run) parlor_thread.start() people = [ Thread(target=run_person, args=(i, parlor)) for i in range(args.people) ] for p in people: p.start() for p in people: p.join() parlor_thread.join()
def main(): args = parser().parse_args() init_logging(args.verbose, log_path=None) data = ''.join(args.data) if not len(data) % 2 == 0: raise ValueError('Invalid data - length must be divisible by 2') bio = BytesIO() for i in range(0, len(data), 2): bio.write(bytes.fromhex(data[i:i + 2])) # bio.write(int(data[i: i + 2], 16).to_bytes()) for key, val in view_unpacked(bio.getvalue(), offset=args.offset, endian=args.endian).items(): print(f'{key}: {val}')
def main(): args, dynamic = parser().parse_with_dynamic_args('query') from ds_tools.logging import init_logging init_logging(args.verbose, log_path=None, names=None, millis=True) from music.files.patches import apply_mutagen_patches apply_mutagen_patches() from music.plex import LocalPlexServer plex = LocalPlexServer(args.server_url, args.username, args.server_path_root, args.config_path, args.music_library, args.dry_run) if args.action == 'sync': if args.sync_action == 'ratings': from music.plex.ratings import sync_ratings sync_ratings(plex, args.direction, args.path_filter) elif args.sync_action == 'playlists': sync_playlists(plex) else: raise ValueError(f'Invalid sync action={args.sync_action!r}') elif args.action == 'find': find_and_print(plex, args.format, args.obj_type, args.title, dynamic, args.escape, args.allow_inst, args.full_info) elif args.action == 'rate': from music.plex.ratings import find_and_rate find_and_rate(plex, args.rating, args.obj_type, args.title, dynamic, args.escape, args.allow_inst) elif args.action == 'rate_offset': from music.plex.ratings import adjust_track_ratings adjust_track_ratings(plex, args.min_rating, args.max_rating, args.offset) elif args.action == 'playlist': from music.plex.playlist import dump_playlists, compare_playlists, list_playlists if args.sub_action == 'dump': dump_playlists(plex, args.path, args.playlist) elif args.sub_action == 'compare': compare_playlists(plex, args.path, args.playlist, args.strict) elif args.sub_action == 'list': list_playlists(plex, args.path) else: log.error(f'Invalid playlist action={args.sub_action!r}') else: log.error(f'Invalid action={args.action!r}')
def main(): args = parser().parse_args() init_logging(args.verbose) if args.ignore_files: IGNORE_FILES.update(args.ignore_files) if args.ignore_dirs: IGNORE_DIRS.update(args.ignore_dirs) if args.action == 'backup': copy_util = BackupUtil(args.source, args.last_dirs, args.dest_dir, args.follow_links, args.dry_run) elif args.action == 'rebuild': copy_util = RebuildUtil(args.remote, args.destination, args.sources, args.follow_links, args.dry_run) else: raise ValueError(f'Unexpected {args.action=!r}') copy_util.process_files()
def test_log_path_name(self): this_file_name = get_expected_name() with tempfile.TemporaryDirectory() as tmp_dir: log_path = init_logging(filename_fmt='{prog}.log', file_dir=tmp_dir, names='test', streams=False) self.assertEqual( Path(log_path).name, '{}.log'.format(this_file_name)) self._cleanup_handlers('test')
def main(): args = parser().parse_args() init_logging(args.verbose, log_path=None) src_dir = Path(args.path).expanduser().resolve() ep_pat = re.compile(r'^(.+)[^a-zA-Z0-9]S(\d+)E(\d+)\D.*', re.IGNORECASE) for p in src_dir.iterdir(): if p.is_file(): m = ep_pat.match(p.name) if m: show, season, episode = m.groups() season = int(season) episode = int(episode) show_dir = src_dir.joinpath(show) ep_dir = show_dir.joinpath('S{:02d}E{:02d}'.format( season, episode)) if not ep_dir.exists(): ep_dir.mkdir(parents=True) new_path = ep_dir.joinpath(p.name) log.info('Moving {} -> {}'.format(p, new_path)) p.rename(new_path) for show_dir in src_dir.iterdir(): if show_dir.is_dir(): for ep_path in show_dir.iterdir(): if ep_path.is_dir(): original_contents = set(ep_path.iterdir()) process_episode(ep_path) new_contents = set( p for p in ep_path.iterdir() if p.is_file()).difference(original_contents) for p in new_contents: m = ep_pat.match(p.name) if m: show, season, episode = m.groups() season = int(season) season_dir = show_dir.joinpath( 'Season {}'.format(season)) new_path = season_dir.joinpath(p.name) log.info('Moving {} -> {}'.format(p, new_path)) p.rename(new_path)
def main(): args = parser().parse_args() init_logging(args.verbose, log_path=None) psarc = Path(args.psarc).expanduser().resolve() if not psarc.exists(): raise ValueError( f'Unable to find psarc binary - {psarc.as_posix()} does not exist') PakFile._psarc_loc = psarc.as_posix() nms = NoMansSky(psarc, Path(args.output).expanduser(), args.steamapps_dir, args.nms_dir) mbc = MbinCompiler(Path(args.mbin_compiler), Path(args.output)) if (action := args.action) == 'extract': if args.all: nms.extract_all_pak_files(args.debug) else: nms.extract_filtered_pak_files(EXCLUDE, args.debug)
def main(): args = parser().parse_args() init_logging(args.verbose, log_path=None) save_dir = Path( args.path or '~/AppData/Local/Myst/Saved/SaveGames').expanduser().resolve() backup_dir = Path(args.backups).expanduser().resolve( ) if args.backups else save_dir.parent.joinpath('SaveBackups') if save_dir.samefile(backup_dir): raise ValueError('The backup dir must be different from the save dir') if backup_dir.exists() and not backup_dir.is_dir(): raise ValueError( f'Invalid backup_dir={backup_dir.as_posix()} - it is not a directory' ) elif not backup_dir.exists(): log.debug(f'Creating backup_dir={backup_dir.as_posix()}') backup_dir.mkdir(parents=True) FSEventHandler(save_dir, backup_dir).run()
def main(): args = parser().parse_args(req_subparser_value=True) init_logging(args.verbose, log_path=None) action = args.action if action == 'simple': resize_simple(args.path, args.output, args.size or args.multiplier, args.filter, args.rename) elif action == 'updown': resize_up_down( args.path, args.output, args.size_1 or args.multiplier_1, args.size_2 or args.multiplier_2, args.filter_1, args.filter_2, args.rename, ) else: raise ValueError(f'Unexpected {action=!r}')
def main(): args = parser().parse_args() init_logging(args.verbose) source = Path(args.source).expanduser() if not source.is_file(): raise ValueError( f'Invalid {source=} file - does not exist or is not a file') dest_dir = Path(args.dest_dir).expanduser() if dest_dir.exists() and not dest_dir.is_dir(): raise ValueError(f'Invalid {dest_dir=} directory - is not a directory') elif not dest_dir.exists(): dest_dir.mkdir(parents=True) latest = get_latest_backup(dest_dir) if latest is None or args.always or sha512sum(source) != sha512sum(latest): backup_file(source, dest_dir, args.dry_run) else: log.info( f'Skipping backup of {source} - it has not changed compared to {latest=!s}' )
def test_log_path_uniq(self): this_file_name = get_expected_name() with tempfile.TemporaryDirectory() as tmp_dir: log_path_1 = init_logging(filename_fmt='{prog}{uniq}.log', file_dir=tmp_dir, names='test1', streams=False) log_path_2 = init_logging(filename_fmt='{prog}{uniq}.log', file_dir=tmp_dir, names='test2', streams=False) log_path_3 = init_logging(filename_fmt='{prog}{uniq}.log', file_dir=tmp_dir, names='test3', streams=False) self.assertEqual(Path(log_path_1).stem, this_file_name) self.assertEqual( Path(log_path_2).stem, '{}-0'.format(this_file_name)) self.assertEqual( Path(log_path_3).stem, '{}-1'.format(this_file_name)) self._cleanup_handlers('test1', 'test2', 'test3')
def main(): args = parser().parse_args() init_logging(args.verbose, log_path=None) cache = DBCache(None, db_path=args.path) if args.action == 'list': for key, orig in normalized_keys(cache): uprint(key) elif args.action == 'delete': prefix = '[DRY RUN] Would delete' if args.dry_run else 'Deleting' for key, orig in normalized_keys(cache): if any(fnmatch(key, pat) for pat in args.patterns): log.info('{}: {}'.format(prefix, key)) if not args.dry_run: del cache[orig] elif args.action == 'get': entry = cache[args.key] log.info(entry) else: raise ValueError('Unconfigured action: {}'.format(args.action))
def main(): args = parser().parse_args() init_logging(args.verbose, log_path=None) src_dir = Path(args.src_path).expanduser().resolve() dst_dir = Path(args.dst_path).expanduser().resolve() dst_shows = get_destinations(dst_dir) if args.show_dests: from ds_tools.output.table import Table rows = [{'Show': dst_show, 'Path': dst_path.as_posix()} for dst_show, dst_path in dst_shows.items()] Table.auto_print_rows(rows, sort_by='Show', sort_keys=False) else: src_moved_dir = src_dir.parent.joinpath(f'{src_dir.name}_moved') if not args.rm and not args.dry_run and not src_moved_dir.exists(): src_moved_dir.mkdir(parents=True) refresh = args.refresh and not args.dry_run copy_args = (src_dir, src_moved_dir, dst_shows, args.dry_run, args.rm, args.buf_size) while (copied := copy_shows(*copy_args)) and refresh: log.debug(f'Copied {copied} files. Checking for newly added files...')
def main(): args = parser().parse_args() init_logging(args.verbose, log_path=None) audio_dir = validate_dir(args.output, '--output/-o') wav_dir = validate_dir(args.wav_output, '--wav_output/-w') flac_dir = validate_dir(args.flac_output, '--flac_output/-f') mp3_dir = validate_dir(args.mp3_output, '--mp3_output/-m') mp3 = args.mp3 for path in args.path: dst_path = uexp_to_audio(Path(path).expanduser().resolve(), audio_dir) if dst_path is not None and dst_path.suffix in {'.mab', '.sab'}: wav_paths = xab_to_wav(dst_path, wav_dir) if wav_paths: log.info( f'Converted {dst_path.as_posix()} to {len(wav_paths)} WAV files' ) for wav_path in wav_paths: wav_to_flac(wav_path, flac_dir) if mp3: wav_to_mp3(wav_path, mp3_dir)
def main(): args = parser().parse_args() from ds_tools.logging import init_logging init_logging(args.verbose, log_path=None) action = args.action if action == 'list': show_tasks(args.path or '\\', args.recursive, args.format, args.summarize, args.triggers, args.raw_xml) elif action == 'table': table_tasks(args.path or '\\', args.recursive, args.times, args.hide_actions, args.with_trigger) elif action == 'create': from ds_tools.windows.scheduler import Scheduler Scheduler().create_exec_task(args.path, args.command, args.args, args.schedule, allow_update=args.update) else: raise ValueError(f'Unexpected {action=!r}')
def main(): args = parser().parse_args() init_logging(args.verbose, log_path=None) dry_run = args.dry_run src_dir = Path(args.source) dest_dir = Path(args.target) for file in src_dir.iterdir(): if file.suffix.lower() in ('.jpg', '.jpeg'): try: with file.open('rb') as f: jpg = process_file(f) date_taken = datetime.strptime( jpg['EXIF DateTimeOriginal'].values, '%Y:%m:%d %H:%M:%S') except Exception as e: log.error('Error processing {}: {}'.format(file, e)) else: day_str = date_taken.strftime('%Y-%m-%d') day_dir = dest_dir.joinpath(day_str) if not day_dir.exists(): if dry_run: log.info('[DRY RUN] Would create {}'.format(day_dir)) else: log.log(19, 'Creating {}'.format(day_dir)) day_dir.mkdir(parents=True) dest_file = day_dir.joinpath(file.name) if dest_file.exists(): log.error('Already exists: {}'.format(dest_file)) else: if dry_run: log.info('[DRY RUN] Would move {} -> {}'.format( file, dest_file)) else: log.log(19, 'Moving {} -> {}'.format(file, dest_file)) file.rename(dest_file) else: log.log(19, 'Skipping {}'.format(file))
def main(): init_logging(2, log_path=None, names=None) table1 = Table.from_data([{ 'a': 1, 'b': 2 }, { 'a': 3, 'b': 4 }], show_row_nums=True) table2 = Table.from_data([{ 'a': 1, 'b': 2 }, { 'a': 3, 'b': 4 }], show_row_nums=True) inpt = Input('test', size=(15, 1)) window = Window('Test One', [[table1, table2], [inpt]], size=(600, 600), element_justification='c') window.run()
self.text.update(text.path.as_posix() if isinstance(text, SongFile) else text) self.complete += 1 self.bar.update(self.complete) def __call__(self, iterable): for item in iterable: self.update() yield item if __name__ == '__main__': from argparse import ArgumentParser from ds_tools.logging import init_logging parser = ArgumentParser() parser.add_argument('image_path', nargs='*', help='Path to an image file') args = parser.parse_args() init_logging(12, log_path=None, names=None) spinner = Spinner( args.image_path[0] if args.image_path else None, # size=(200, 200) ) # popup.read(None) # noqa spinner.update() # import time # while True: # time.sleep(0.1) # spinner.update() spinner._popup.read(None) # noqa
f'Invalid {rating=} - value must be between 0 and 10, inclusive' ) self.rating = rating self.star_element.image = self._combined_stars() super().update(**kwargs) @property def ClickPosition( self ): # Used to trick PySimpleGUI into returning a value for this element (2/2) return self.rating def bind(self, bind_string, key_modifier): if rating_input := self.rating_input: rating_input.bind(bind_string, key_modifier) else: super().bind(bind_string, key_modifier) if __name__ == '__main__': from ..popups.base import BasePopup from ds_tools.logging import init_logging init_logging(10, names=None, millis=True, set_levels={'PIL': 30}) # BasePopup.test_popup([[Rating(i), Text(f'Rating: {i:>2d} {stars(i)}')] for i in range(11)]) BasePopup.test_popup([[Rating(i, show_value=True, change_cb=print)] for i in range(11)]) # BasePopup.test_popup([[Rating(i)] for i in range(11)])