Example #1
0
def ask_for_taco():
    receipt = Receipt()
    receipt.add_parent(Constants.TACO_PARENT_KEY).set_price(
        Constants.BASE_TACO_PRICE)

    shell_args = questionary.select('choose a shell',
                                    Constants.SHELLS,
                                    use_shortcuts=True).ask().split('+', 1)
    handle_additional_price_selection(
        receipt, shell_args, prefix_keys=(Constants.TACO_PARENT_KEY, ))

    meat_args = questionary.select('choose your meat',
                                   Constants.MEATS,
                                   use_shortcuts=True).ask().split('+', 1)
    handle_additional_price_selection(
        receipt, meat_args, prefix_keys=(Constants.TACO_PARENT_KEY, ))

    toppings = questionary.checkbox('choose your toppings',
                                    Constants.TOPPINGS,
                                    validate=topping_validator).ask()
    for topping in toppings:
        receipt.append(topping, prefix_keys=(Constants.TACO_PARENT_KEY, ))

    print('\n\n')
    total = 0
    for item in receipt.iter_items():
        if item.has_price:
            total += item.price
            print(
                f'{"  " * item.depth}{item.name} {f"(${item.price})" if item.has_price else ""}'
            )
        else:
            print(f'{"  " * item.depth}{item.name}')
    print(f'\nTOTAL: ${total}')
Example #2
0
def main():
    api_token = os.getenv("TODOIST_API_TOKEN")
    with console.status("[bold green]Initial Todoist API sync...") as _:
        api = TodoistAPI(api_token)
        api.sync()
    link = questionary.text("Link?").ask()
    item_type = questionary.select("Type?", choices=["book", "film"]).ask()
    if item_type == "book":
        author = questionary.text("Author?").ask()
        title = questionary.text("Title?").ask()
        notes = questionary.text("Notes?").ask()
        create_item_to_buy(api, f"{author} - '{title}'", ["buy", "books"],
                           link, notes)
    elif item_type == "film":
        title = questionary.text("Title?").ask()
        media_type = questionary.select("Type?",
                                        choices=["Blu-ray", "Digital",
                                                 "DVD"]).ask()
        if media_type == "Blu-ray":
            sub_type = questionary.select("Blu-ray type?",
                                          choices=["1080p", "4k"]).ask()
            media_type += f" {sub_type}"
        notes = questionary.text("Notes?").ask()
        create_item_to_buy(api, f"'{title}' ({media_type})", ["buy", "films"],
                           link, notes)
    return 0
Example #3
0
def load_extracted_data():
    """ Gets user choice on extracted data file and loads file for matrix calculation/prediction.

    """
    # Display menu
    data_extracted = questionary.select(
        "!! You will need to extract a new dataset before proceeding !!",
        choices=[
            'I have already extracted data', 'I need to extract new data',
            'Go back to main menu'
        ],
        style=blue).ask()
    # Load model
    if data_extracted == 'I have already extracted data':
        # Get extracted files as list
        extracted_data_files = []
        for idx, file_path in enumerate(
                glob.glob(paths.data_extracted_dir + "/*")):
            extracted_data_files.append(file_path)
        # Ask for user choice
        extracted_data_path = questionary.select(
            "Which extracted data file to use?",
            choices=extracted_data_files,
            style=blue).ask()
        print("\nLoading data file...")
        extracted_data = joblib.load(extracted_data_path)
        print("Data file loaded.\n")
        return extracted_data
    elif data_extracted == 'I need to extract new data':
        load_extract_menu()
    elif data_extracted == 'Go back to main menu':
        load_main_menu()
Example #4
0
    def read(self):
        """ Read mails, prompts interactive cli if target mail box is not specified """
        if self.args.address:
            selected_mailbox = MailTools.find_mailbox(self.args.address,
                                                      self.box)
        else:
            selected_mailbox = select("Select mailbox",
                                      choices=[{
                                          a: b
                                          for a, b in (("name", i.address),
                                                       ("value", i))
                                      } for i in self.box.mails],
                                      style=style,
                                      instruction=" ").ask()

        mails = selected_mailbox.get_mail_list()
        mail_list = [{a: b
                      for a, b in (("name", i.title), ("value", i))}
                     for i in mails]
        if mail_list:
            if self.args.last:
                selected_mail = mails[0]
            else:
                selected_mail = select("Select mail",
                                       choices=mail_list,
                                       style=style,
                                       instruction=" ").ask()
            MailTools.read_mail(selected_mail)
        else:
            print("No mails.")
Example #5
0
 def interact(self):
     choices = [
         questionary.Choice('Organize by module, only download files',
                            'module'),
         questionary.Choice(
             'Organize by module, download files, links and pages',
             'module_link'),
         questionary.Choice('As-is in file list', 'file'),
         questionary.Choice('As-is in file list, plus pages', 'file_link'),
         questionary.Choice('Custom',
                            'custom',
                            disabled='not supported yet')
     ]
     self.mode = questionary.select('Select default file organization mode',
                                    choices,
                                    default=find_choice(
                                        choices, self.mode)).unsafe_ask()
     choices = [
         questionary.Choice(
             "Delete local files if they disappears on Canvas", True),
         questionary.Choice("Always keep local files", False)
     ]
     self.delete_file = questionary.select(
         'How to handle deleted files on Canvas',
         choices,
         default=find_choice(choices, self.delete_file)).unsafe_ask()
Example #6
0
def _split(interactive, file, destination, size):

    if not file and not interactive:
        print('file not valid')
        return

    if not file and interactive:
        p = Path.cwd()
        files = []
        for f in p.iterdir():
            if f.is_file():
                files.append(f.name)
        file_to_split = questionary.select('which file do you want to split?',
                                           choices=files).ask()
        file = Path(file_to_split)

    if interactive:
        destination = questionary.text('name the destination folder').ask()
        support = questionary.select(
            'what chunk size do you desire?',
            choices=['floppy', 'iomega_zip', 'cd', 'dvd']).ask()
        if support == 'floppy':
            size = 1400000
        elif support == 'iomega_zip':
            size = 100000000
        elif support == 'cd':
            size = 700000000
        elif support == 'dvd':
            size = 4500000000

    f = Path(file)

    if f.exists():
        with open(f, 'rb') as file_stream:
            _chunk_file(file_stream, f.suffix, destination, size)
Example #7
0
def config(file):
    """Настройки"""
    if file:
        click.echo(CFG_PATH)
    else:
        config_data = defaultdict(lambda: "")
        config_data['redmine.host'] = questionary.text('Укажите URL').ask()
        auth_method = questionary.select('Выберите метод авторизации',
                                         ['Token', 'Login']).ask()

        if auth_method == 'Token':
            config_data['redmine.token'] = questionary.password(
                'Укажите Token').ask()
        elif auth_method == 'Login':
            config_data['redmine.username'] = questionary.text(
                'Укажите Логин').ask()
            config_data['redmine.password'] = questionary.password(
                'Укажите Пароль').ask()

        rd = get_rd(config_data)

        projects = get_projects(rd)
        projects_map = {str(v): v for v in projects}
        selected_project = questionary.select('Укажите ProjectID',
                                              list(projects_map.keys())).ask()
        config_data['project.id'] = projects_map[selected_project].id
        cf_fields = get_custom_fields(rd)
        cf_fields_map = {str(v): cf_id for cf_id, v in cf_fields.items()}
        cf_filter_selected = questionary.checkbox(
            'Какие настраиваемые поля использовать?',
            choices=list(cf_fields_map.keys())).ask()
        cf_filter_selected_release = questionary.checkbox(
            'Какие настраиваемые поля использовать для релиза?',
            choices=list(cf_fields_map.keys())).ask()

        config_data['release.filter_custom_fields'] = list(
            map(str, [cf_fields_map[cf] for cf in cf_filter_selected]))
        config_data['issue.filter_custom_fields'] = list(
            map(str, [cf_fields_map[cf] for cf in cf_filter_selected_release]))

        tracker = get_trackers_project(rd, config_data['project.id'])
        statuses = get_status_project(rd)
        status_map = {str(v): v for v in statuses}
        tracker_map = {str(v): v for v in tracker}

        selected_tracker = questionary.select('Выберите трекер с релизами',
                                              list(tracker_map.keys())).ask()
        selected_status = questionary.select(
            'Выберите статус опубликованого релиза',
            list(status_map.keys())).ask()

        config_data['release.tracker_id'] = tracker_map[selected_tracker].id
        config_data['release.done_status_id'] = status_map[selected_status].id

        if questionary.confirm('Сохранить').ask():
            cfg.update(config_data.items())
            cfg.sync()
            click.secho('Сохраннено', bold=True)
Example #8
0
def main(dry_run):
    action = q.select(
        "What do you want to do?",
        choices=[
            {
                "name": "init boilerplate",
                "value": INIT_BOILERPLATE
            },
            {
                "name": "create a new challenge",
                "value": NEW_CHALLENGE
            },
        ],
    ).ask()

    init_boilerplate = q.select(
        "Which boilerplate do you want to use?",
        choices=[
            q.Separator("---API---"),
            *APIS,
            q.Separator("---langs---"),
            *LANGS,
            q.Separator("---SPA---"),
            *SPAS,
        ],
    ).ask()

    api_choices = [q.Choice(x, checked=True)
                   for x in APIS] if init_boilerplate in APIS else APIS
    lang_choices = [q.Choice(x, checked=True)
                    for x in LANGS] if init_boilerplate in LANGS else LANGS
    spa_choices = [q.Choice(x, checked=True)
                   for x in SPAS] if init_boilerplate in SPAS else SPAS

    while action == NEW_CHALLENGE:
        allowed_boilerplates = q.checkbox(
            "Which boilerplates are candidates allowed to use?",
            choices=[
                q.Separator("---API---"),
                *api_choices,
                q.Separator("---langs---"),
                *lang_choices,
                q.Separator("---SPA---"),
                *spa_choices,
            ],
        ).ask()

        confirm_none = q.confirm(
            "No allowed boilerplates. Are you sure?",
            default=False,
        ).skip_if(len(allowed_boilerplates)).ask()

        if len(allowed_boilerplates) or confirm_none:
            break

    validate_bp_dir(init_boilerplate)
    sync_bp_dir(init_boilerplate, dry_run)
    def ask_select(self, text, choices, default=None):
        # workaround "TypeError: object of type 'NoneType' has no len()" when default is None
        choices = [str(choice) for choice in choices]
        if default:
            question = questionary.select(message=text,
                                          choices=choices,
                                          default=default)
        else:
            question = questionary.select(message=text, choices=choices)

        return question.ask()
Example #10
0
def remove():
    file_edit = questionary.select("[ ? ]Select the TODO list you want to edit:", file).ask()
    todo = open(file_edit, "r+")
    list1 = todo.readlines()
    todo.close()
    task = questionary.select("[ ? ]Select the task you want to remove:", list1).ask()
    list1.remove(task)
    list1 = ('\n').join(list1)
    todo = open(file_edit, 'w+')
    todo.write(list1)
    todo.close()
    os.system(f"sed '/^[[:space:]]*$/d' {file_edit} > /tmp/todo_swap && cat /tmp/todo_swap > {file_edit}")
Example #11
0
 def simple(self):
     """
     $ python -m sagas.tests.cli.questionary_tool simple
     :return:
     """
     questionary.select(
         "What do you want to do?",
         choices=[
             'Order a pizza',
             'Make a reservation',
             'Ask for opening hours'
         ]).ask()  # returns value of selection
Example #12
0
def ui_select_repository(header_text):
    print_heading(header_text)
    dev_path = Path.home().joinpath(DEV_DIR_NAME)
    sites = sorted(os.listdir(dev_path))
    site = questionary.select('Please select the site', choices=sites).ask()
    site_path = dev_path.joinpath(site)
    owners = sorted(os.listdir(site_path))
    owner = questionary.select('Please select the owner', choices=owners).ask()
    owner_path = site_path.joinpath(owner)
    repositories = sorted(os.listdir(owner_path))
    repo = questionary.select('Please select the repository',
                              choices=repositories).ask()
    return (owner, repo, owner_path.joinpath(repo))
Example #13
0
    def new(self):
        validator = UniqueID("Instance", self.instances)
        id = prompt("Instance ID: ", validator=validator)
        url = prompt("Instance URL: ")

        type = questionary.select("Instance type:",
                                  choices=[JIRA_CLOUD, JIRA_SERVER]).ask()

        credentials = questionary.select("Credentials:",
                                         choices=self.credentials.ids()).ask()
        credentials = self.credentials.find_by_id(credentials)

        i = Instance(id, url, type, credentials)
        self.instances.save(i)
Example #14
0
def get_browser_version(browser):
    "Get the browser version"
    if browser == "chrome":
        browser_version=questionary.select("Select the browser version",
                                            choices=conf.chrome_versions).ask()

    elif browser == "firefox":
        browser_version=questionary.select("Select the browser version",
                                            choices=conf.firefox_versions).ask()

    elif browser == "safari":
        browser_version = questionary.select("Select the browser version",
                                              choices=conf.safari_versions).ask()

    return browser_version
    def _get_labels_paper(self, index, stat_str=None, ask_stop=False):
        """Ask the user for a label for a particular paper.

        Arguments
        ---------
        index: int
            Paper ID in the dataset.
        stat_str: str
            Display this (statistic) string under the paper.
        ask_stop: bool
            Ask for confirmation when stopping.
        """
        # CLI paper format
        self.as_data.print_record(index)
        if stat_str is not None:
            print(stat_str + "\n")

        action = questionary.select(
            'Include or Exclude?',
            choices=[
                'Exclude', 'Include',
                questionary.Separator(), 'Back to main menu'
            ],
            default='Exclude',
        ).ask()

        if action == "Include":
            label = 1
        elif action == "Exclude":
            label = 0
        else:
            label = None

        return label
    def main_menu(self, logger, *args, **kwargs):
        "Get initial papers for modelling."
        while True:
            n_included = np.sum(self.y[self.train_idx] == 1)
            n_excluded = np.sum(self.y[self.train_idx] == 0)
            action = questionary.select(
                'What do you want to do next?',
                choices=[
                    "Find papers by keywords", "Find papers by ID",
                    questionary.Separator(),
                    f"Continue review ({n_included} included, "
                    f"{n_excluded} excluded)", "Export",
                    questionary.Separator(), "Stop"
                ]).ask()

            if action is None or action.startswith("Stop"):
                stop = questionary.confirm("Are you sure you want to stop?",
                                           default=False).ask()
                if stop:
                    raise KeyboardInterrupt
            elif action.endswith("by keywords"):
                self._papers_from_finder(logger)
            elif action.endswith("by ID"):
                self._papers_from_id(logger)
            elif action.startswith("Export"):
                self._export()
            elif action.startswith("Continue review"):
                try:
                    self._do_review(logger, *args, **kwargs)
                except KeyboardInterrupt:
                    pass
Example #17
0
def cli_node_attach(name, system_folders):
    """Attach the logs from the docker container to the terminal."""

    client = docker.from_env()
    check_if_docker_deamon_is_running(client)

    running_nodes = client.containers.list(
        filters={"label": f"{APPNAME}-type=node"})
    running_node_names = [node.name for node in running_nodes]

    if not name:
        name = q.select("Select the node you wish to inspect:",
                        choices=running_node_names).ask()
    else:
        post_fix = "system" if system_folders else "user"
        name = f"{APPNAME}-{name}-{post_fix}"

    if name in running_node_names:
        container = client.containers.get(name)
        logs = container.attach(stream=True, logs=True)
        Thread(target=print_log_worker, args=(logs, ), daemon=True).start()
        while True:
            try:
                time.sleep(1)
            except KeyboardInterrupt:
                info("Closing log file. Keyboard Interrupt.")
                exit(0)
    else:
        error(f"{Fore.RED}{name}{Style.RESET_ALL} was not running!?")
Example #18
0
def cli_node_stop(name, system_folders, all_nodes):
    """Stop a running container. """

    client = docker.from_env()
    check_if_docker_deamon_is_running(client)

    running_nodes = client.containers.list(
        filters={"label": f"{APPNAME}-type=node"})

    if not running_nodes:
        warning("No nodes are currently running.")
        return

    running_node_names = [node.name for node in running_nodes]

    if all_nodes:
        for name in running_node_names:
            container = client.containers.get(name)
            container.kill()
            info(f"Stopped the {Fore.GREEN}{name}{Style.RESET_ALL} Node.")
    else:
        if not name:
            name = q.select("Select the node you wish to stop:",
                            choices=running_node_names).ask()
        else:

            post_fix = "system" if system_folders else "user"
            name = f"{APPNAME}-{name}-{post_fix}"

        if name in running_node_names:
            container = client.containers.get(name)
            container.kill()
            info(f"Stopped the {Fore.GREEN}{name}{Style.RESET_ALL} Node.")
        else:
            error(f"{Fore.RED}{name}{Style.RESET_ALL} is not running?")
Example #19
0
File: ism.py Project: Sch-Tomi/ism
    def run(self):
        selected_host = (questionary.select("Select a Host to connect",
                                            choices=self.hosts,
                                            style=custom_style_fancy,
                                            qmark="").ask())

        system('ssh %s' % selected_host)
Example #20
0
def browse_file_search():
    """

    """
    file_path = os.getcwd()

    while (not os.path.isfile(file_path)):
        # Display the existing folders/files and let the user choose
        list_files_directory = [".."]
        for file in os.listdir(file_path):
            if (os.path.isdir(os.path.join(file_path, file))):
                file = "[D -> " + file + "]"
            else:
                file = "[F -> " + file + "]"
            list_files_directory.append(file)

        # Order the list
        list_files_directory.sort()

        add_to_path = questionary.select("Select your file",
                                         choices=list_files_directory).ask()

        if (add_to_path != ".."):
            file_path = os.path.join(file_path, add_to_path[6:-1])
        else:
            file_path = os.path.join(file_path, "..")
        clear()

    return file_path
Example #21
0
File: pSub.py Project: sprnza/psub
def radio(ctx, psub, search_term):
    results = psub.search(search_term).get('artist', [])

    if len(results) > 0:
        chosen_artist = questionary.select(
            "Choose an Artist to start a Radio play, or 'Search Again' to search again",
            choices=[artist.get('name')
                     for artist in results] + ['Search Again']).ask()
    else:
        click.secho('No Artists found matching {}'.format(search_term),
                    fg='red',
                    color=True)
        chosen_artist = 'Search Again'

    if chosen_artist == 'Search Again':
        search_term = questionary.text("Enter a new search term").ask()

        if not search_term:
            sys.exit(0)

        ctx.invoke(radio, search_term=search_term)
    else:
        radio_artist = next(
            (art for art in results if art.get('name') == chosen_artist), None)

        if radio_artist is None:
            sys.exit(0)

        psub.show_banner('Playing Radio based on {}'.format(
            radio_artist.get('name')))
        psub.play_radio(radio_artist.get('id'))
Example #22
0
def _request_action_from_user(
    predictions: List[Dict[Text, Any]],
    sender_id: Text, endpoint: EndpointConfig
) -> (Text, bool):
    """Ask the user to correct an action prediction."""

    _print_history(sender_id, endpoint)

    choices = [{"name": "{:03.2f} {:40}".format(a.get("score"),
                                                a.get("action")),
                "value": a.get("action")}
               for a in predictions]

    choices = ([{"name": "<create new action>", "value": OTHER_ACTION}] +
               choices)
    question = questionary.select("What is the next action of the bot?",
                                  choices)

    action_name = _ask_or_abort(question, sender_id, endpoint)
    is_new_action = action_name == OTHER_ACTION

    if is_new_action:
        action_name = _request_free_text_action(sender_id, endpoint)
    print("Thanks! The bot will now run {}.\n".format(action_name))
    return action_name, is_new_action
Example #23
0
    def handle_exception(self, e):
        print("\nException:", e)
        traceback.print_exc(file=sys.stdout)

        answer = questionary.select('Now what?',
                                    choices=[
                                        'Restart browser',
                                        'Debug with ipdb',
                                        'Debug with pdb',
                                        'Exit',
                                    ]).ask()

        if answer == 'Debug with ipdb':
            try:
                import ipdb
            except ImportError:
                print('Please run "pip install ipdb" to install ipdb')
                sys.exit(1)
            ipdb.post_mortem()
        elif answer == 'Debug with pdb':
            import pdb
            pdb.post_mortem()
        elif answer == 'Restart browser':
            self.worker.restart()
            return

        self.worker.close()
        sys.exit()
Example #24
0
    def _ask_tag(self) -> str:
        latest_tag = get_latest_tag_name()
        if not latest_tag:
            out.error("No Existing Tag. Set tag to v0.0.1")
            return "0.0.1"

        is_correct_tag = questionary.confirm(
            f"Is {latest_tag} the latest tag?",
            style=self.cz.style,
            default=False).ask()
        if not is_correct_tag:
            tags = get_tag_names()
            if not tags:
                out.error("No Existing Tag. Set tag to v0.0.1")
                return "0.0.1"

            latest_tag = questionary.select(
                "Please choose the latest tag: ",
                choices=get_tag_names(),
                style=self.cz.style,
            ).ask()

            if not latest_tag:
                out.error("Tag is required!")
                raise SystemExit()
        return latest_tag
def second_question_batch(path):
    # ask to rate books based on the class
    # RETURNS: PANDAS DF

    # initialize a dataframe for storing the results
    user_ratings = pd.DataFrame(columns=('book_id', 'user_rating'))

    # read in the correct csv file
    books_to_rate = pd.read_csv(path)

    # loop over the books in a premade dataset for a class
    for i in range(0, len(books_to_rate)):
        answer = questionary.select(
            '\n\n Rate the book "' + books_to_rate['book_title'].iloc[i] +
            '" by ' + books_to_rate['author_name'].iloc[i] + "\n\n",
            choices=[
                Separator(), '1', '2', '3', '4', '5', '6', '7', '8', '9', '10',
                'Not read',
                Separator()
            ]).ask()
        # add the results to a dataframe
        answer = answer if answer != 'Not read' else 0
        user_ratings.loc[i] = [books_to_rate['book_id'].iloc[i], answer]

    return (user_ratings)
Example #26
0
def _request_selection_from_intent_list(
    intent_list: List[Dict[Text, Text]],
    sender_id: Text,
    endpoint: EndpointConfig
) -> Text:
    question = questionary.select("What intent is it?", choices=intent_list)
    return _ask_or_abort(question, sender_id, endpoint)
Example #27
0
def reset_date_file(path, date):
    """Resets date file to the correct date to resume a simulation"""
    old_date_files = [f for f in os.listdir(f"{path}/scripts") if f.endswith(".date")]
    if len(old_date_files) > 1:
        logger.info("Multiple date files found!")
        old_date_file = questionary.select(
            "Which is the right one", choices=old_date_files
        ).ask()
    else:
        old_date_file = old_date_files[0]
    logger.info(f"Resetting {old_date_file}")
    with open(f"{path}/scripts/{old_date_file}", "r") as old_file:
        old_file_contents = old_file.read()
        broken_date, broken_run_number = old_file_contents.split(" ")
    logger.info(f"Broken date:          {broken_date}")
    logger.info(f"Broken run number:    {broken_run_number}")
    broken_year = int(broken_date.split("-")[0])
    overflow_runs = broken_year - date
    logger.info(f"Overflow runs:        {overflow_runs}")
    new_date = str(broken_date).replace(str(broken_year), str(date))
    new_run_number = int(broken_run_number) - overflow_runs
    logger.info(f"Fixed date:           {new_date}")
    logger.info(f"Fixed run number:     {new_run_number}")
    with open(f"{path}/scripts/{old_date_file}.new", "w") as new_file:
        new_file_contents = f"{new_date} {new_run_number}"
        new_file.write(new_file_contents)
    logger.info("Old date file contents:")
    logger.info(old_file_contents)
    logger.info("New date file contents:")
    logger.info(new_file_contents)
    replace_date_file = questionary.confirm("Replace old file by new file?").ask()
    if replace_date_file:
        os.rename(
            f"{path}/scripts/{old_date_file}.new", f"{path}/scripts/{old_date_file}"
        )
Example #28
0
File: pSub.py Project: ppGodel/psub
def artist(ctx, psub, search_term, randomise):
    results = get_as_list(psub.search(search_term).get('artist', []))

    if len(results) > 0:
        chosen_artist = questionary.select(
            "Choose an Artist, or 'Search Again' to search again",
            choices=[artist.get('name')
                     for artist in results] + ['Search Again']).ask()
    else:
        click.secho('No artists found matching "{}"'.format(search_term),
                    fg='red',
                    color=True)
        chosen_artist = 'Search Again'

    if chosen_artist == 'Search Again':
        search_term = questionary.text("Enter a new search term").ask()

        if not search_term:
            sys.exit(0)

        ctx.invoke(artist, search_term=search_term, randomise=randomise)
    else:
        play_artist = next(
            (art for art in results if art.get('name') == chosen_artist), None)

        if play_artist is None:
            sys.exit(0)

        psub.show_banner('Playing {}tracks by {}'.format(
            'randomised ' if randomise else '', play_artist.get('name')))
        psub.play_artist(play_artist.get('id'), randomise)
Example #29
0
def search_movie():

    try:
        ia = imdb.IMDb()
        user_input = input("Search for a movie: ")
        print("\n", end="")
        movies = ia.search_movie(user_input)

        choices_list = []

        for i in movies:
            get_title = i['title']
            get_id = i.movieID
            try:
                get_year = i['year']
            except KeyError:
                pass
            p = ("{: <10}".format(str(get_id))+ get_title + " " + "(" + str(get_year) + ")")
            choices_list.append(p)

        movie_list = questionary.select("Oh! there's alot. What did you mean? ", choices=choices_list).ask()  
        get_id = movie_list.split()
        IMDB_ID = get_id[0]
        
        return IMDB_ID

    except KeyboardInterrupt:
        print("\nKeyboard Interrupted")
        quit()
    except AttributeError:
        quit()
    except ValueError:
        print("\nUnknown movie name.")
        quit()
Example #30
0
File: pSub.py Project: sprnza/psub
def album(ctx, psub, search_term, randomise):
    results = psub.search(search_term).get('album', [])

    if len(results) > 0:
        chosen_album = questionary.select(
            "Choose an Album, or 'Search Again' to search again",
            choices=[album.get('name')
                     for album in results] + ['Search Again']).ask()
    else:
        click.secho('No albums found matching "{}"'.format(search_term),
                    fg='red',
                    color=True)
        chosen_album = 'Search Again'

    if chosen_album == 'Search Again':
        search_term = questionary.text("Enter a new search term").ask()

        if not search_term:
            sys.exit(0)

        ctx.invoke(album, search_term=search_term, randomise=randomise)
    else:
        play_album = next(
            (alb for alb in results if alb.get('name') == chosen_album), None)

        if play_album is None:
            sys.exit(0)

        psub.show_banner('Playing {}tracks from {} '.format(
            'randomised ' if randomise else '', play_album.get('name')))
        psub.play_album(play_album.get('id'), randomise)
Example #31
0
def pick_one(msg, options, alpha_options=None):
    choices = OrderedDict()
    for i, option in enumerate(options):
        choice_text = text_type(option)
        choices[choice_text] = option
    if alpha_options is not None:
        for k, v in alpha_options.items():
            choices[v] = k

    answer = questionary.select(msg, choices.keys()).ask()

    return choices[answer]