Example #1
0
def check_module(module_name, install_name=''):
    """
    check if the module exist, if not exist try to install by pip
    (you can provide the install name manually)
    :param module_name:
    :param install_name: default equals module name
    :return:
    """
    try:
        import_module(module_name)

    except ImportError:
        color.print_warn(module_name, 'Not Exists')

        pip_name = ''
        if ispython3():
            pip_name = 'pip3'
        elif ispython2():
            pip_name = 'pip'

        color.print_info(
            'Now, try to install through {}, wait please...:)'.format(
                pip_name))

        if install_name in ('', None):
            install_name = module_name

        info_lines, err_lines = exec_cmd('{0} install {1}'.format(
            pip_name, install_name))
        print('\n'.join(info_lines))
        if len(err_lines) != 0:
            print(''.join(err_lines))

    else:
        pass
Example #2
0
def main(command, unit='s'):
    with timeme(unit=unit) as t:
        info_lines, err_lines = exec_cmd(command)

    color.print_info('\n'.join(info_lines))
    color.print_err('\n'.join(err_lines))
    color.print_info(t)
Example #3
0
def main(command, unit='s'):
    with timeme(unit=unit) as t:
        info_lines, err_lines = exec_cmd(command)

    color.print_info('\n'.join(info_lines))
    color.print_err('\n'.join(err_lines))
    color.print_info(t)
Example #4
0
    def getPage(self, pageNum):

        # 构建URL
        url = self.baseURL + self.seeLZ_str + '&pn=' + str(pageNum)

        try:
            request = urllib.request.Request(url, headers=headers)
            response = urllib.request.urlopen(request, timeout=600)

            content = None
            while True:
                try:
                    content = response.read()
                except http.client.IncompleteRead as ex:
                    color.print_warn(ex)
                    color.print_info('retry...')
                else:
                    break

            # 返回UTF-8格式编码内容
            return content.decode('utf-8')

        # 无法连接,报错
        except urllib.error.URLError as e:
            if hasattr(e, "reason"):
                color.print_err(
                    "Failed to connect to BaiDuTieBa, Error Reason", e.reason)
                return None
Example #5
0
    def install_proxy_opener(dbname=None,
                             test_url=None, region=None, timeout=4, allow_delete=True):

        proxy_instance = proxy_ip(dbname=dbname)

        ip_set = proxy_instance.get_ip_port(region=region)
        # print(ip_set)
        for ip, port in ip_set:

            proxy = {'http': '{0}:{1}'.format(ip, port)}
            color.print_info('\ntry ')

            if not proxy_instance.isAlive(ip, port,
                                          test_url=test_url,
                                          allow_delete=allow_delete,
                                          timeout=timeout):

                proxy_instance.delete_db(ip, port)
                color.print_warn('not work, delete in db')

            else:
                # 使用这个方式是全局方法。
                proxy_support = urllib.request.ProxyHandler(proxy)
                opener = urllib.request.build_opener(proxy_support)
                urllib.request.install_opener(opener)

                # Then, you can use method urllib.request.urlopen()
                return ip, port

        return None
Example #6
0
def main(path, n, encoding=None, no_more=False):
    try:
        with open(path, 'rb') as f:
            res_list = fileecho.head(f, n)
            res = b'\n'.join(res_list)
            detect_result = chardet.detect(res)

            if encoding is not None:
                codec = encoding
            elif detect_result['confidence'] > 0.7:
                codec = detect_result['encoding']
            else:
                color.print_warn('Not Known encoding, may be %s.\n'
                                 'Please point it explictly' % detect_result['encoding'])
                return

            if no_more:
                color.print_info(res.decode(codec, errors='ignore'))
            else:
                more(res.decode(codec, errors='ignore'), print_color=True)

    except FileNotFoundError:
        color.print_err('%s not found' % path)
    except PermissionError:
        color.print_err('Permission denied: %s' % path)
Example #7
0
def recognise_tesseract(path, args=None):
    try:
        result = rg.tesseract(path, args)
    except Exception as ex:
        color.print_err(ex)
    else:
        color.print_info(result, len(result))
Example #8
0
def main(path, n, encoding=None, no_more=False):
    try:
        with open(path, 'rb') as f:
            res_list = fileecho.tail(f, n)
            res = b'\n'.join(res_list)
            detect_result = chardet.detect(res)

            if encoding is not None:
                codec = encoding
            elif detect_result['confidence'] > 0.7:
                codec = detect_result['encoding']
            else:
                color.print_warn('Not Known encoding, may be %s.\n'
                                 'Please point it explictly' %
                                 detect_result['encoding'])
                return

            if no_more:
                color.print_info(res.decode(codec, errors='ignore'))
            else:
                more(res.decode(codec, errors='ignore'), print_color=True)

    except FileNotFoundError:
        color.print_err('%s not found' % path)
    except PermissionError:
        color.print_err('Permission denied: %s' % path)
Example #9
0
def recognise_tesseract(path, args=None):
    try:
        result = rg.tesseract(path, args)
    except Exception as ex:
        color.print_err(ex)
    else:
        color.print_info(result, len(result))
Example #10
0
    def install_proxy_opener(dbname=None,
                             test_url=None, region=None, timeout=4, allow_delete=True):

        proxy_instance = proxy_ip(dbname=dbname)

        ip_set = proxy_instance.get_ip_port(region=region)
        # print(ip_set)
        for ip, port in ip_set:

            proxy = {'http': '{0}:{1}'.format(ip, port)}
            color.print_info('\ntry ')

            if not proxy_instance.isAlive(ip, port,
                                          test_url=test_url,
                                          allow_delete=allow_delete,
                                          timeout=timeout):

                proxy_instance.delete_db(ip, port)
                color.print_warn('not work, delete in db')

            else:
                # 使用这个方式是全局方法。
                proxy_support = urllib.request.ProxyHandler(proxy)
                opener = urllib.request.build_opener(proxy_support)
                urllib.request.install_opener(opener)

                # Then, you can use method urllib.request.urlopen()
                return ip, port

        return None
Example #11
0
    def getPage(self, pageNum):

        # 构建URL
        url = self.baseURL + self.seeLZ_str + '&pn=' + str(pageNum)

        try:
            request = urllib.request.Request(url, headers=headers)
            response = urllib.request.urlopen(request, timeout=600)

            content = None
            while True:
                try:
                    content = response.read()
                except http.client.IncompleteRead as ex:
                    color.print_warn(ex)
                    color.print_info('retry...')
                else:
                    break

            # 返回UTF-8格式编码内容
            return content.decode('utf-8')

        # 无法连接,报错
        except urllib.error.URLError as e:
            if hasattr(e, "reason"):
                color.print_err(
                    "Failed to connect to BaiDuTieBa, Error Reason", e.reason)
                return None
Example #12
0
def display_cmd_prompt():
    user = getpass.getuser()
    hostname = socket.gethostname()
    cwd = os.getcwd()
    base_dir = os.path.basename(cwd)
    home_dir = os.path.expanduser('~')
    if cwd == home_dir:
        base_dir = '~'

    color.print_info('({0}:{1}){2}$'.format(user, hostname, base_dir), end='')

    sys.stdout.flush()
Example #13
0
def report_color(count, block_size, total_size):
    download_size = count * block_size
    percent = (download_size * 100 / total_size)

    pts = ('\rdownload ...' '\t{0:.3f} mb ').format(download_size / 10e5)
    pts2 = get_progress_bar(download_size,
                            total_size,
                            extra_str='{0:.2f}%'.format(percent))

    pts = ''.join([pts, pts2])
    sys.stdout.flush()
    color.print_info(pts, end='', flush=True)
Example #14
0
def report_color(count, block_size, total_size):
    download_size = count * block_size
    percent = (download_size * 100 / total_size)

    pts = ('\rdownload ...'
           '\t{0:.3f} mb ').format(download_size / 10e5)
    pts2 = get_progress_bar(download_size, total_size,
                            extra_str='{0:.2f}%'.format(percent))

    pts = ''.join([pts, pts2])
    sys.stdout.flush()
    color.print_info(pts, end='', flush=True)
Example #15
0
def cli():
    arguments = docopt(__doc__, version=minghu6.__version__)
    pattern = arguments['<pattern>']

    for fn in os.listdir(os.curdir):
        if fn == '.path2uuid.sqlite3':
            continue
        if fnmatch.fnmatch(fn, pattern) or fn == pattern:
            res = path2uuid(fn, d=arguments['-d'])

            if res is None:
                color.print_info('%s Do nothing' % fn)
            else:
                color.print_ok('convert %s to %s' % (fn, res))
Example #16
0
def display_cmd_prompt():
    user = getpass.getuser()
    hostname = socket.gethostname()
    cwd = os.getcwd()
    base_dir = os.path.basename(cwd)
    home_dir = os.path.expanduser('~')
    if cwd == home_dir:
        base_dir = '~'

    color.print_info('({0}:{1}){2}$'.format(user,
                                            hostname,
                                            base_dir), end='')

    sys.stdout.flush()
Example #17
0
def cli():
    arguments = docopt(__doc__, version=__version__)

    if not in_toplevel_of_repo():
        color.print_err('Not in toplevel of a git repo.')
        return

    if arguments['list']:
        n = int(arguments['-n'])

        result = max_file_hash_name(n)
        if result is not None:
            [color.print_info(item) for item in result]

    elif arguments['rm']:
        path_pattern = arguments['<path-pattern>']
        force = True if arguments['-f'] else False

        result = remove_from_history(path_pattern, force)
        color.print_ok(result)
        color.print_warn('run `untrack confirm` to confirm the op')

    elif arguments['reset']:
        try:
            reset()
        except ErrorReturnCode_1 as ex:
            color.print_err(ex)
        except RebundantResetException as ex:
            color.print_warn(ex)
        else:
            color.print_ok('reset.')

    elif arguments['confirm']:
        confirm_remove()
        color.print_ok('confirm remove.')
Example #18
0
def more(text, numlines=40, print_color=False):
    lines = text.splitlines()
    while lines:
        chunk = lines[:numlines]
        lines = lines[numlines:]
        for line in chunk:
            if print_color:
                color.print_info(line)
            else:
                print(line)

        if not lines: break
        if print_color:
            color.print_dark_pink('More?')
        else:
            print('More?', end='')
        if lines and input().upper() in ('N', 'NO', 'Q', 'QUIET'):
            break
Example #19
0
def build_version_infos():
    version_infos = []

    if iswin():
        possible_dir_name = [
            'Program Files (x86)',
            'Program Files',
            'ProgramData',
        ]
        possible_dir = []
        for driver in get_drivers():
            for each_dir in possible_dir_name:
                possible_dir.append(os.path.join(driver, os.sep, each_dir))

        possible_dir.append(os.path.abspath(os.curdir))

        for each_possible_dir in possible_dir:
            for java_path in find_wrapper(each_possible_dir, 'java'):
                try:
                    version_info = _build_version_info(java_path)
                except NotBelongToJDKError:
                    pass
                else:
                    color.print_info('')
                    version_infos.append(version_info)

    else:
        JAVA_PATTERN = '^.*/java/jdk[^/]*/bin/java$'
        for item in sh.locate('-A', '-r', JAVA_PATTERN):
            java_path = item.__str__().strip()

            try:
                version_info = _build_version_info(java_path)
            except NotBelongToJDKError:
                pass
            else:
                color.print_info('')
                version_infos.append(version_info)

    return version_infos
Example #20
0
def write_activate_file(virtual_env, java_home, java_tag, force=False):
    virtual_env = os.path.abspath(virtual_env)

    if os.path.lexists(virtual_env) and not force:
        color.print_warn('project diretory %s exists already\n'
                         'you can use -f argument to continue.' % virtual_env)
        return

    ensure_dir_exists(virtual_env)

    activate_dir = os.path.join(virtual_env, 'bin')
    ensure_dir_exists(os.path.join(activate_dir))

    if iswin():
        activate_path = os.path.join(activate_dir, 'activate.bat')
        deactivate_path = os.path.join(activate_dir, 'deactivate.bat')

        with open(activate_path,
                  'w') as fw_activate, open(deactivate_path,
                                            'w') as fw_deactivate:
            fw_activate.write(
                create_activate_s(virtual_env, java_home, java_tag))

            from jvirtualenv.template.deactivate_template_bat import template
            fw_deactivate.write(template)

        color.print_info('create active file {0}'.format(activate_path))
        color.print_info('run "{0}" to activate it'.format(activate_path))
        color.print_info('run "{0}" to deactivate it'.format(deactivate_path))

    else:
        activate_path = os.path.join(activate_dir, 'activate')

        with open(activate_path, 'w') as fw:
            fw.write(create_activate_s(virtual_env, java_home, java_tag))

        color.print_info('create active file {0}'.format(activate_path))
        color.print_info('run `source {0}` to activate it'.format(
            path_to(os.curdir, activate_path)))
Example #21
0
def convert(fn, output, size: str = None, rate: (int, float) = None, fps: (int, float) = None):
    if not assert_output_has_ext(output):
        color.print_err('Failed.')
        return
    
    fn_tmp = path2uuid(fn, quiet=True)
    output_tmp = path2uuid(output, quiet=True, rename=False)
    try:
        json_obj = load_video_info_json(fn_tmp)
        video_site, audio_site = get_video_audio_info_site_injson(json_obj)
        color.print_info('start convert %s to %s' % (fn, output))
        cmd_list = ['ffmpeg', '-i', fn_tmp]
        need_convert = False
        if rate is not None and rate != 1:
            source_origin_fps = load_fps_from_json(json_obj)
            source_fps = source_origin_fps * float(rate)
            cmd_list.insert(1, '-r')
            cmd_list.insert(2, str(source_fps))
            need_convert = True
        
        if size is not None:
            width = json_obj['streams'][video_site]['width']
            height = json_obj['streams'][video_site]['height']
            origin_size = '%sx%s' % (width, height)
            if origin_size != size:
                color.print_info('convert size from %s to %s' % (origin_size,
                                                                 size))
                cmd_list.append('-s')
                cmd_list.append(size)
                need_convert = True
        
        if fps is not None:
            origin_fps = round(load_fps_from_json(json_obj), 3)
            if round(fps, 3) != origin_fps:
                cmd_list.append('-r')
                cmd_list.append(str(fps))
                color.print_info('convert fps from %f to %f' % (origin_fps,
                                                                fps))
                need_convert = True
        
        _, ext_i = os.path.splitext(fn)
        _, ext_out = os.path.splitext(output)
        if ext_i != ext_out:
            need_convert = True
        
        if need_convert:
            cmd_list.append(output_tmp)
            for line in CommandRunner.run(' '.join(cmd_list)):
                print(line)
        else:
            os.rename(fn_tmp, output_tmp)
        
        path2uuid(output_tmp, d=True)
    except Exception as ex:
        path2uuid(output_tmp, d=True, rename=False)
        raise
    finally:
        path2uuid(fn_tmp, d=True)
Example #22
0
    def start(self):
        color.print_info('start analyse..., url {0:s}'.format(self.baseURL))

        content = self.getPage(0)

        pageNum = self.getPageNum(content)
        title = self.getTitle(content)
        self.openFile(title)

        # Write LZ ID and NAME
        pattern = re.compile('<div id="post_content_.*?>(.*?)</div>')
        items = re.finditer(pattern, content)
        item = next(items)
        id_pattern = r'(?<=post_content_)(\d)+(?=")'
        lz_id = re.search(id_pattern, item.group(0)).group(0)
        # print(lz_id)
        lz_name = BDTB.get_name_by_id(lz_id)

        splitLine = "=" * 80 + '\n'
        self.file.write(splitLine)
        self.file.write('LZ {0} {1}\n'.format(lz_id, lz_name))
        self.file.write(splitLine)

        if pageNum is None:
            color.print_err(
                "the URL {0:s} might be invalidated".format(self.baseURL))
            return
        try:
            color.print_info(
                "This tie {0:s} has {1:d} pages".format(title, pageNum))

            for i in range(1, int(pageNum) + 1):
                color.print_info("write to page {0:d}".format(i))
                page = self.getPage(i)
                content = self.getContent(page)
                self.writeData(content)
        # 出现写入异常
        except IOError as e:
            color.print_err(e)
        else:
            color.print_ok("Successful!")
        finally:
            self.closeFile()
Example #23
0
    def start(self):
        color.print_info('start analyse..., url {0:s}'.format(self.baseURL))

        content = self.getPage(0)

        pageNum = self.getPageNum(content)
        title = self.getTitle(content)
        self.openFile(title)

        # Write LZ ID and NAME
        pattern = re.compile('<div id="post_content_.*?>(.*?)</div>')
        items = re.finditer(pattern, content)
        item = next(items)
        id_pattern = r'(?<=post_content_)(\d)+(?=")'
        lz_id = re.search(id_pattern, item.group(0)).group(0)
        # print(lz_id)
        lz_name = BDTB.get_name_by_id(lz_id)

        splitLine = "=" * 80 + '\n'
        self.file.write(splitLine)
        self.file.write('LZ {0} {1}\n'.format(lz_id, lz_name))
        self.file.write(splitLine)

        if pageNum is None:
            color.print_err("the URL {0:s} might be invalidated".format(
                self.baseURL))
            return
        try:
            color.print_info("This tie {0:s} has {1:d} pages".format(
                title, pageNum))

            for i in range(1, int(pageNum) + 1):
                color.print_info("write to page {0:d}".format(i))
                page = self.getPage(i)
                content = self.getContent(page)
                self.writeData(content)
        # 出现写入异常
        except IOError as e:
            color.print_err(e)
        else:
            color.print_ok("Successful!")
        finally:
            self.closeFile()
Example #24
0
def merge(pattern_list, output, type, **other_kwargs):
    isprefix = other_kwargs.get('isprefix', False)
    if not assert_output_has_ext(output):
        color.print_err('Failed.')
        return
    base_dir = os.curdir
    merge_file_list = []
    merge_file_list2 = []
    if type in ('vedio', 'audio', 'gif'):
        for fn in os.listdir(base_dir):
            if os.path.isdir(fn):
                continue
            if fn == '.path2uuid.sqlite3':
                continue
            
            for pattern in pattern_list:
                if isprefix:
                    if fn.lower().startswith(pattern.lower()):
                        merge_file_list.append(fn)
                else:
                    if fnmatch.fnmatch(fn, pattern):
                        merge_file_list.append(fn)
    else:  # 'va', 'vs
        merge_file_list = pattern_list
    
    # common_prefix_pattern = r'^(\w)+\+$'
    if isprefix and len(pattern_list) == 1:
        def key(fn):
            base = os.path.splitext(os.path.basename(fn))[0]
            v = LooseVersion(base.split(pattern_list[0])[1])
            return v
    elif type in ('va', 'vs'):
        key = lambda x: 0
    else:
        key = lambda fn: fn
    
    merge_file_list = sorted(merge_file_list, key=key)
    
    color.print_info('The following file will be merged in order')
    for i, file_to_merge in enumerate(merge_file_list):
        color.print_info('%3d. %s' % (i, file_to_merge))
    
    if len(merge_file_list) <= 1:
        color.print_info('Do nothing.')
        return
    args = input('press enter to continue, q to quit')
    if args in ('q', 'Q'):
        return
    
    merge_file_tmp_list = list(map(lambda x: path2uuid(x, quiet=True), merge_file_list))
    merge_file_tmp_list2 = []
    
    if type == 'video':
        # check if the video can be merge
        FileInfo = namedtuple('FileInfo', ['width', 'height', 'fps'])
        merge_file_info_list = []
        for fn in merge_file_tmp_list:
            json_obj = load_video_info_json(fn)
            video_site, audio_site = get_video_audio_info_site_injson(json_obj)
            codec_name = json_obj['streams'][video_site]['codec_name']
            width = int(json_obj['streams'][video_site]['width'])
            height = int(json_obj['streams'][video_site]['height'])
            fps = round(load_fps_from_json(json_obj), 3)
            
            merge_file_info_list.append(FileInfo(width, height, fps))
        
        if not each_same(merge_file_info_list, key=lambda x: (x.width, x.height, x.fps)):
            color.print_err('width, height, fps should be same of all video')
            
            min_width = sorted(merge_file_info_list, key=lambda x: x.width)[0].width
            min_height = sorted(merge_file_info_list, key=lambda x: x.height)[0].height
            min_resolution = '%dx%d' % (min_width, min_height)
            min_fps = sorted(merge_file_info_list, key=lambda x: x.fps)[0].fps
            
            color.print_warn('all_to_resolution: %s' % min_resolution)
            color.print_warn('all_to_fps: %s' % min_fps)
            if askyesno('convert to fix?'):
                merge_file_tmp_list2 = list(map(lambda x: add_postfix(x, 'tmp'), merge_file_tmp_list))
                
                def tmp(fn_tuple):
                    convert(*fn_tuple, size=min_resolution, fps=min_fps)
                
                list(map(lambda x: tmp(x),
                         zip(merge_file_tmp_list, merge_file_tmp_list2)))
            
            else:
                return
    
    elif type == 'audio':
        pass
    elif type == 'va':
        pass
    elif type == 'gif':
        pass
    
    output_tmp = path2uuid(output, rename=False, quiet=True)
    if len(merge_file_tmp_list2) == 0:
        input_file_list = merge_file_tmp_list
    else:
        input_file_list = merge_file_tmp_list2  # only for merge video
    try:
        
        fw = open('.mylist', 'w')
        for fn in input_file_list:
            fw.write("file '%s' \n" % fn)
        
        fw.close()
        if type in ('video', 'audio'):
            merge_cmd = 'ffmpeg -f concat -i %s -c copy %s' % ('.mylist', output_tmp)
        elif type == 'va':
            merge_cmd = 'ffmpeg -i %s -i %s -vcodec copy -acodec copy %s ' \
                        % (input_file_list[0], input_file_list[1], output_tmp)
        
        elif type == 'vs':
            with open(input_file_list[1]) as f_subtitle:
                encoding = guess_charset(f_subtitle)['encoding']
            
            if encoding.lower() not in ('utf-8', 'ascii'):
                info, err = exec_cmd('%s -m minghu6.tools.text convert %s utf-8'
                                     % (sys.executable, input_file_list[1]))
                
                if len(err) > 1 or err[0] != '':  # exec failed
                    color.print_err('error codec of the subtitle %s (need utf-8)')
            
            merge_cmd = 'ffmpeg -i %s -vf subtitles=%s %s' \
                        % (input_file_list[0], input_file_list[1], output_tmp)
        
        elif type == 'gif':
            framerate = other_kwargs['framerate']
            merge_cmd = 'ffmpeg -f image2 -framerate %d -i %s %s' \
                        % (int(framerate), '.mylist', output_tmp)
        
        for line in CommandRunner.run(merge_cmd):
            print(line)
        
        path2uuid(output_tmp, d=True)
    except Exception:
        raise
    else:
        color.print_ok('Done.')
    finally:
        try:
            os.remove('.mylist')
        except:
            pass
        
        for fn in input_file_list:
            path2uuid(fn, d=True)
Example #25
0
def main_info(path):
    name = fileformat.fileformat(path)
    if name == fileformat.UNKNOWN_TYPE:
        color.print_err(name)
    else:
        color.print_info('%s<===>%s' % (name.normal_name, name.ext_name))
Example #26
0
def main_info(path):
    name = fileformat.fileformat(path)
    if name == fileformat.UNKNOWN_TYPE:
        color.print_err(name)
    else:
        color.print_info('%s<===>%s' % (name.normal_name, name.ext_name))
Example #27
0
def getenv(args):
    if len(args) > 0:
        color.print_info(os.getenv(args[0]))

    return SHELL_STATUS_RUN
Example #28
0
def info(fn, list_all=False):
    json_obj = load_video_info_json(fn)
    
    if not list_all:
        def video_info(json_obj):
            video_site, audio_site = get_video_audio_info_site_injson(json_obj)
            filename = json_obj['format']['filename']
            
            size = json_obj['format']['size']
            
            bit_rate = json_obj['format']['bit_rate']
            frame_rate = load_fps_from_json(json_obj)
            
            width = json_obj['streams'][video_site]['width']
            height = json_obj['streams'][video_site]['height']
            resolution = '%sx%s' % (width, height)
            ratio_tuple = simpleist_int_ratio(width, height)
            
            format_name = json_obj['format']['format_name']
            format_long_name = json_obj['format']['format_long_name']
            
            codec_name = json_obj['streams'][video_site]['codec_name']
            codec_long_name = json_obj['streams'][video_site]['codec_long_name']
            
            audio_codec_name = json_obj['streams'][audio_site]['codec_name']
            audio_tag_string = json_obj['streams'][audio_site]['codec_tag_string']
            audio_channels = json_obj['streams'][audio_site]['channels']
            
            color.print_info('filename:         %s' % filename)
            color.print_info('size:             %.1f Mb' % (int(size) / (1024 * 1024)))
            color.print_info('bit_rate:         %.2f Mb/s' % (int(bit_rate) / 1000 / 1000))
            color.print_info('resolution:       %s' % resolution + ' (%s:%s)' % ratio_tuple)
            color.print_info('frame_rate:       %.2f fps' % frame_rate)
            color.print_info('format_name:      %s' % format_name)
            color.print_info('format_long_name: %s' % format_long_name)
            color.print_info('codec_name:       %s' % codec_name)
            color.print_info('codec_long_name:  %s' % codec_long_name)
            color.print_info()
            color.print_info('audio_codec_name: %s' % audio_codec_name)
            color.print_info('audio_tag_string: %s' % audio_tag_string)
            color.print_info('audio_channels:   %s' % audio_channels)
        
        def audio_info(json_obj):
            video_site, audio_site = get_video_audio_info_site_injson(json_obj)
            
            filename = json_obj['format']['filename']
            size = json_obj['format']['size']
            
            format_name = json_obj['format']['format_name']
            format_long_name = json_obj['format']['format_long_name']
            
            codec_name = json_obj['streams'][audio_site]['codec_name']
            codec_long_name = json_obj['streams'][audio_site]['codec_long_name']
            
            bit_rate = json_obj['streams'][audio_site]['bit_rate']
            sample_rate = json_obj['streams'][audio_site]['sample_rate']
            
            color.print_info('filename:         %s' % filename)
            color.print_info('size:             %.1f Mb' % (int(size) / (1024 * 1024)))
            color.print_info('bit_rate:         %d Kb/s' % (int(bit_rate) / 1000))
            color.print_info('sample_rate:      %.1f KHz' % (int(sample_rate) / 1000))
            color.print_info('format_name:      %s' % format_name)
            color.print_info('format_long_name: %s' % format_long_name)
            color.print_info('codec_name:       %s' % codec_name)
            color.print_info('codec_long_name:  %s' % codec_long_name)
        
        try:
            video_info(json_obj)
        except:
            audio_info(json_obj)
    
    else:
        
        buf = io.StringIO()
        with redirect_stdout(buf):
            pprint(json_obj)
        
        color.print_info(buf.getvalue())
Example #29
0
def main(path, pwd, check_username=False, username=None):
    if pwd is None:
        pwd = getpass.getpass('Input your master password: '******'<%s>' % username
    interactive_help = split_blankline(__doc__)[0]
    while True:
        input_result = input(base_prompt).strip()  # STRIP !!
        if 'q' == input_result:
            return

        try:
            op = input_result.split(' ')[0]
            if input_result.startswith('query') or op == '?':
                label = split_whitespace(input_result)[1]
                all_match = pwd_keeper.query_account(label)
                if all_match is None:
                    print('None')
                    possiable_labels = []
                    for each_label in pwd_keeper.get_labels():
                        each_label2 = each_label.lower()
                        label2 = label.lower()
                        if each_label2.startswith(label2) or \
                                each_label2.endswith(label2):
                            possiable_labels.append(each_label)

                    if len(possiable_labels) != 0:
                        print('Maybe: ', end='')
                        for each_label in possiable_labels:
                            color.print_info(each_label, end='')
                        color.print_info()

                else:
                    for item in all_match:
                        try:
                            color.print_info(
                                'usrename:{0} passowrd:{1}'.format(*item))
                        except UnicodeEncodeError:
                            username, password = item[0], \
                                                 item[1]
                            color.print_err('usrename:{0} passowrd:{1}'.format(
                                username, password))

                            color.print_err(
                                'Warning: Master Password {0} may be Error'.
                                format(desensitization_pwd(pwd)))

            elif op in ('add', '+'):
                _, label, username, password = split_whitespace(input_result)
                pwd_keeper.add_account(label, username, password)

            elif input_result.startswith('del-account'):
                _, label, username = split_whitespace(input_result)
                pwd_keeper.del_account(label, username)

            elif input_result.startswith('del-label'):
                _, label = split_whitespace(input_result)
                pwd_keeper.del_label(label)

            elif input_result.startswith('update-account'):
                _, label, username, password = split_whitespace(input_result)
                pwd_keeper.update_account(label, username, password)

            elif input_result.startswith('update-label'):
                _, old_label, new_label = split_whitespace(input_result)
                pwd_keeper.update_label(old_label, new_label)

            elif input_result.startswith(
                    'list') or input_result == 'ls' or input_result == 'l':
                [
                    color.print_info(label)
                    for label in pwd_keeper.get_labels() if pwd_keeper
                ]

            elif op == 'h':
                color.print_info(interactive_help)
            elif input_result == '':
                pass
            else:  # '?'
                color.print_err('\nInvalid Input')
                print(input_result)
                color.print_info(interactive_help)

        except Exception:
            color.print_err('\nInvalid Input:')
            print(input_result)
            color.print_info(interactive_help)
            print()
Example #30
0
def cli():
    arguments = docopt(__doc__, version=minghu6.__version__)

    path_list = arguments['<filename>']
    try:
        fr_list = []
        [fr_list.append(open(path, 'rb')) for path in path_list]

    except FileNotFoundError:
        color.print_err('%s not found' % path_list)
        return
    else:

        if arguments['charset']:
            fr = fr_list[0]
            result = fileecho.guess_charset(fr)
            encoding, confidence = result['encoding'], result['confidence']
            if encoding is None:
                color.print_err('unknown')
            else:
                color.print_info('{0}, {1:.2f}'.format(encoding, confidence))

            fr.close()

        elif arguments['convert']:
            fr = fr_list[0]
            path = path_list[0]
            to_charset = arguments['<to_charset>']
            from_charset = arguments['--from_charset']
            if from_charset is None:
                result = fileecho.guess_charset(fr)
                encoding, confidence = result['encoding'], result['confidence']
                if confidence is None:
                    color.print_err('unknown from_charset, '
                                    'you must point it explicity')
                    return
                elif confidence < 0.7:
                    color.print_warn('uncertained from_charset, '
                                     'maybe %s\n'
                                     'you must point it explicity' % encoding)
                    return
                else:
                    from_charset = encoding

                    # rename(name_old, name_new)
                    # name_a, name_b must same driver in windows
                    dir = os.path.dirname(os.path.abspath(path))
                    fwn = tempfile.mktemp(dir=dir)
                    with open(fwn, 'wb') as fw:
                        for line in fr:
                            fw.write(line.decode(from_charset, errors='ignore')
                                     .encode(to_charset, errors='ignore'))

                    fr.close()
                    if arguments['--output'] is None:
                        shutil.copy(fwn, path)
                    else:
                        shutil.copy(fwn, arguments['--output'])

                    os.remove(fwn)

        elif arguments['merge']:
            if arguments['--regex'] is not None:
                # color.print_info(arguments)
                merge_file_path_list = findlist(startdir=os.curdir,
                                                pattern=arguments['--regex'],
                                                regex_match=True, dosort=True)

            else:
                merge_file_path_list = arguments['<filename>']

            with open(arguments['--output'], 'wb') as outfile:
                for infile_path in merge_file_path_list:
                    with open(infile_path, 'rb') as infile:
                        outfile.write(infile.read())

                    outfile.write(b'\n')
                    color.print_ok('have merged file %s' % infile_path)
Example #31
0
 def audio_info(json_obj):
     video_site, audio_site = get_video_audio_info_site_injson(json_obj)
     
     filename = json_obj['format']['filename']
     size = json_obj['format']['size']
     
     format_name = json_obj['format']['format_name']
     format_long_name = json_obj['format']['format_long_name']
     
     codec_name = json_obj['streams'][audio_site]['codec_name']
     codec_long_name = json_obj['streams'][audio_site]['codec_long_name']
     
     bit_rate = json_obj['streams'][audio_site]['bit_rate']
     sample_rate = json_obj['streams'][audio_site]['sample_rate']
     
     color.print_info('filename:         %s' % filename)
     color.print_info('size:             %.1f Mb' % (int(size) / (1024 * 1024)))
     color.print_info('bit_rate:         %d Kb/s' % (int(bit_rate) / 1000))
     color.print_info('sample_rate:      %.1f KHz' % (int(sample_rate) / 1000))
     color.print_info('format_name:      %s' % format_name)
     color.print_info('format_long_name: %s' % format_long_name)
     color.print_info('codec_name:       %s' % codec_name)
     color.print_info('codec_long_name:  %s' % codec_long_name)
Example #32
0
def cli():
    arguments = docopt(__doc__, version=minghu6.__version__)

    path_list = arguments['<filename>']
    try:
        fr_list = []
        [fr_list.append(open(path, 'rb')) for path in path_list]

    except FileNotFoundError:
        color.print_err('%s not found' % path_list)
        return
    else:

        if arguments['charset']:
            fr = fr_list[0]
            result = fileecho.guess_charset(fr)
            encoding, confidence = result['encoding'], result['confidence']
            if encoding is None:
                color.print_err('unknown')
            else:
                color.print_info('{0}, {1:.2f}'.format(encoding, confidence))

            fr.close()

        elif arguments['convert']:
            fr = fr_list[0]
            output = os.path.abspath(arguments['--output'])
            to_charset = arguments['<to_charset>']
            from_charset = arguments['--from_charset']
            if from_charset is None:
                result = fileecho.guess_charset(fr)
                encoding, confidence = result['encoding'], result['confidence']
                if confidence is None:
                    color.print_err('unknown from_charset, '
                                    'you must point it explicity')
                    return
                elif confidence < 0.7:
                    color.print_warn('uncertained from_charset, '
                                     'maybe %s\n'
                                     'you must point it explicity' % encoding)
                    return
                else:
                    from_charset = encoding

                    # rename(name_old, name_new)
                    # name_a, name_b must same driver in windows
                    with open(output, 'wb') as fw:
                        for line in fr:
                            #print(line.decode(from_charset))
                            print(line.decode(from_charset).encode(from_charset, errors='ignore').decode(to_charset, errors='ignore'))
                            fw.write(line.decode(from_charset).encode(from_charset, errors='ignore').decode(to_charset, errors='ignore').encode(from_charset))

                    fr.close()

        elif arguments['merge']:
            if arguments['--regex'] is not None:
                print(arguments['--regex'])
                # color.print_info(arguments)
                merge_file_path_list = findlist(startdir=os.curdir,
                                                pattern=arguments['--regex'],
                                                regex_match=True, dosort=True)
                color.print_normal('merge file:')
                pprint(merge_file_path_list)

            else:
                merge_file_path_list = arguments['<filename>']

            with open(arguments['--output'], 'wb') as outfile:
                for infile_path in merge_file_path_list:
                    with open(infile_path, 'rb') as infile:
                        outfile.write(infile.read())

                    outfile.write(b'\n')
                    color.print_ok('have merged file %s' % infile_path)
Example #33
0
def getenv(args):
    if len(args) > 0:
        color.print_info(os.getenv(args[0]))

    return SHELL_STATUS_RUN
Example #34
0
def pretty_print_config(version_infos):
    color.print_info('-' * 80)
    for version_info in version_infos:
        color.print_info()
        color.print_info('tag: {}'.format(version_info['tag']))
        color.print_info('version: {}'.format(version_info['version']))
        color.print_info('bit: {}'.format(version_info['bit']))
        color.print_info('home: {}'.format(version_info['home']))
        color.print_info()
        color.print_info('-' * 80)

    if not version_infos:
        color.print_warn('empty')
Example #35
0
def main(path, pwd, check_username=False, username=None):
    if pwd is None:
        pwd = getpass.getpass('Input your master password: '******'<%s>' % username
    interactive_help = split_blankline(__doc__)[0]
    while True:
        input_result = input(base_prompt).strip()  # STRIP !!
        if 'q!' in input_result:
            return

        try:
            if input_result.startswith('query'):
                label = split_whitespace(input_result)[1]
                all_match = pwd_keeper.query_account(label)
                if all_match is None:
                    print('None')
                    possiable_labels = []
                    for each_label in pwd_keeper.get_labels():
                        each_label2 = each_label.lower()
                        label2 = label.lower()
                        if each_label2.startswith(label2) or \
                                each_label2.endswith(label2):
                            possiable_labels.append(each_label)

                    if len(possiable_labels) != 0:
                        print('Maybe: ', end='')
                        for each_label in possiable_labels:
                            color.print_info(each_label, end='')
                        color.print_info()

                else:
                    for item in all_match:
                        try:
                            color.print_info('usrename:{0} passowrd:{1}'.format(*item))
                        except UnicodeEncodeError:
                            username, password = item[0], \
                                                 item[1]
                            color.print_err('usrename:{0} passowrd:{1}'.
                                            format(username, password))

                            color.print_err('Warning: Master Password {0} may be Error'.format(
                                desensitization_pwd(pwd))
                            )

            elif input_result.startswith('add'):
                _, label, username, password = split_whitespace(input_result)
                pwd_keeper.add_account(label, username, password)

            elif input_result.startswith('del-account'):
                _, label, username = split_whitespace(input_result)
                pwd_keeper.del_account(label, username)

            elif input_result.startswith('del-label'):
                _, label = split_whitespace(input_result)
                pwd_keeper.del_label(label)

            elif input_result.startswith('update-account'):
                _, label, username, password = split_whitespace(input_result)
                pwd_keeper.update_account(label, username, password)

            elif input_result.startswith('update-label'):
                _, old_label, new_label = split_whitespace(input_result)
                pwd_keeper.update_label(old_label, new_label)

            elif input_result.startswith('list'):
                [color.print_info(label) for label in pwd_keeper.get_labels() if pwd_keeper]

            elif input_result.startswith('?'):
                color.print_info(interactive_help)
            elif input_result == '':
                pass
            else:  # '?'
                color.print_err('\nInvalid Input')
                print(input_result)
                color.print_info(interactive_help)

        except ValueError:
            color.print_err('\nInvalid Input:')
            print(input_result)
            color.print_info(interactive_help)
            print()
Example #36
0
 def video_info(json_obj):
     video_site, audio_site = get_video_audio_info_site_injson(json_obj)
     filename = json_obj['format']['filename']
     
     size = json_obj['format']['size']
     
     bit_rate = json_obj['format']['bit_rate']
     frame_rate = load_fps_from_json(json_obj)
     
     width = json_obj['streams'][video_site]['width']
     height = json_obj['streams'][video_site]['height']
     resolution = '%sx%s' % (width, height)
     ratio_tuple = simpleist_int_ratio(width, height)
     
     format_name = json_obj['format']['format_name']
     format_long_name = json_obj['format']['format_long_name']
     
     codec_name = json_obj['streams'][video_site]['codec_name']
     codec_long_name = json_obj['streams'][video_site]['codec_long_name']
     
     audio_codec_name = json_obj['streams'][audio_site]['codec_name']
     audio_tag_string = json_obj['streams'][audio_site]['codec_tag_string']
     audio_channels = json_obj['streams'][audio_site]['channels']
     
     color.print_info('filename:         %s' % filename)
     color.print_info('size:             %.1f Mb' % (int(size) / (1024 * 1024)))
     color.print_info('bit_rate:         %.2f Mb/s' % (int(bit_rate) / 1000 / 1000))
     color.print_info('resolution:       %s' % resolution + ' (%s:%s)' % ratio_tuple)
     color.print_info('frame_rate:       %.2f fps' % frame_rate)
     color.print_info('format_name:      %s' % format_name)
     color.print_info('format_long_name: %s' % format_long_name)
     color.print_info('codec_name:       %s' % codec_name)
     color.print_info('codec_long_name:  %s' % codec_long_name)
     color.print_info()
     color.print_info('audio_codec_name: %s' % audio_codec_name)
     color.print_info('audio_tag_string: %s' % audio_tag_string)
     color.print_info('audio_channels:   %s' % audio_channels)