def _confirm_form_validation(action_name, tracker, endpoint, sender_id): """Ask a user whether an input for a form should be validated. Previous to this call, the active form was chosen after it was rejected.""" requested_slot = tracker.get("slots", {}).get(REQUESTED_SLOT) validation_questions = questionary.confirm( "Should '{}' validate user input to fill " "the slot '{}'?".format(action_name, requested_slot)) validate_input = _ask_or_abort(validation_questions, sender_id, endpoint) if not validate_input: # notify form action to skip validation send_event(endpoint, sender_id, {"event": "form_validation", "validate": False}) elif not tracker.get('active_form', {}).get('validate'): # handle contradiction with learned behaviour warning_question = questionary.confirm( "ERROR: FormPolicy predicted no form validation " "based on previous training stories. " "Make sure to remove contradictory stories " "from training data. " "Otherwise predicting no form validation " "will not work as expected.") _ask_or_abort(warning_question, sender_id, endpoint) # notify form action to validate an input send_event(endpoint, sender_id, {"event": "form_validation", "validate": True})
def get_recent_ckpt(ckpt_dir): if not os.path.isdir(ckpt_dir): raise ValueError(f"Default checkpoint dir at {ckpt_dir} missing!") files = os.listdir(ckpt_dir) if 'best_loss.pt' in files: answer = questionary.confirm( "File best_loss.pt found. Use this file?").ask() if answer: return os.path.join(ckpt_dir, 'best_loss.pt') epoch_list = [x for x in files if 'epoch' in x] if len(epoch_list) > 0: answer = questionary.confirm( "Epoch files found. Use best epoch file?").ask() if answer: epoch_list.sort(key=lambda x: int(x.split('_')[1].split('.')[0]), reverse=True) return os.path.join(ckpt_dir, epoch_list[0]) iter_list = [x for x in files if 'iter' in x] iter_list.sort(key=lambda x: int(x.split('_')[1].split('.')[0]), reverse=True) return os.path.join(ckpt_dir, iter_list[0])
def review_oracle(dataset, *args, log_file=None, **kwargs): """CLI to the interactive mode.""" if log_file is None: while True: log_file = questionary.text( 'Please provide a file to store ' 'the results of your review:', validate=lambda val: splitext(val)[1] in LOGGER_EXTENSIONS, ).ask() if log_file is None: return if len(log_file) == 0: force_continue = questionary.confirm( 'Are you sure you want to continue without saving?', default=False ).ask() if force_continue: log_file = None break else: if os.path.isfile(log_file): action = questionary.select( f'File {log_file} exists, what do you want' ' to do?', default='Exit', choices=[ f'Continue review from {log_file}', f'Delete review in {log_file} and start a new' ' review', f'Choose another file name.', questionary.Separator(), f'Exit' ] ).ask() if action == "Exit" or action is None: return if action.startswith("Continue"): break if action.startswith("Choose another"): continue if action.startswith("Delete"): delete = questionary.confirm( f'Are you sure you want to delete ' f'{log_file}?', default=False, ).ask() if delete: os.remove(log_file) break else: continue break try: review(dataset, *args, mode='oracle', log_file=log_file, **kwargs) except KeyboardInterrupt: print('\nClosing down the automated systematic review.')
def accept_terms_or_quit(args: argparse.Namespace) -> None: """Prompt the user to accept the Rasa terms.""" import webbrowser import questionary from rasax.community.constants import RASA_TERMS_URL show_prompt = not hasattr(args, "no_prompt") or not args.no_prompt if not show_prompt: print( f"By adding the '--no_prompt' parameter you agreed to the Rasa " f"X license agreement ({RASA_TERMS_URL})" ) return rasa_cli_utils.print_success( "Before you can use Rasa X, you have to agree to its " "license agreement (you will only have to do this " "once)." ) should_open_in_browser = questionary.confirm( "Would you like to view the license agreement in your web browser?" ).ask() if should_open_in_browser: webbrowser.open(RASA_TERMS_URL) accepted_terms = questionary.confirm( "\nRasa X License Agreement\n" "===========================\n\n" "Do you agree to the Rasa X license agreement ({})?\n" "By typing 'y', you agree to the terms. " "If you are using this software for a company, by confirming, " "you acknowledge you have the authority to do so.\n" "If you do not agree, type 'n' to stop Rasa X." "".format(RASA_TERMS_URL), default=False, qmark="", ).ask() if accepted_terms: rasa_utils.write_global_config_value(CONFIG_FILE_TERMS_KEY, True) else: rasa_cli_utils.print_error_and_exit( "Sorry, without accepting the terms, you cannot use Rasa X. " "You can of course still use the (Apache 2 licensed) Rasa framework: " "https://github.com/RasaHQ/rasa", exit_code=0, )
def main(subtasks_path, task_type, work_type): with console.status('[bold green]Initial Todoist API sync...') as _: api_token = os.getenv('TODOIST_API_TOKEN') api = TodoistAPI(api_token) api.sync() (project_id, _) = ui_select_project(api, work_type) branch_ref = '' repo = '' if task_type != DevTaskType.NON_MERGE: branch_ref = ui_get_jira_or_branch_ref() if task_type != DevTaskType.NON_MERGE: (_, repo, _) = ui_select_repository('Select Repository for Work') root_task_id = ui_create_root_dev_task(api, project_id, branch_ref, task_type, work_type, repo) if subtasks_path: ui_create_subtasks_from_file(api, subtasks_path, root_task_id, project_id, task_type, work_type) else: create_subtasks = questionary.confirm( 'Would you like to create any subtasks').ask() if create_subtasks: ui_create_subtasks(api, root_task_id, project_id, task_type, work_type) if task_type != DevTaskType.NON_MERGE: create_pr_checklist_subtask(api, project_id, root_task_id, branch_ref, task_type, work_type) create_merge_subtasks(api, project_id, root_task_id, branch_ref, repo, 'main', task_type, work_type) if os.getenv('JIRA_BASE_URL'): create_jira_admin_task(api, project_id, root_task_id, branch_ref)
async def _validate_user_text(latest_message: Dict[Text, Any], endpoint: EndpointConfig, sender_id: Text ) -> bool: """Validate a user message input as free text. This assumes the user message is a text message (so NOT `/greet`).""" parse_data = latest_message.get("parse_data", {}) text = _as_md_message(parse_data) intent = parse_data.get("intent", {}).get("name") entities = parse_data.get("entities", []) if entities: message = ("Is the intent '{}' correct for '{}' and are " "all entities labeled correctly?" .format(intent, text)) else: message = ("Your NLU model classified '{}' with intent '{}'" " and there are no entities, is this correct?" .format(text, intent)) if intent is None: print("The NLU classification for '{}' returned '{}'" "".format(text, intent)) return False else: question = questionary.confirm(message) return await _ask_questions(question, sender_id, endpoint)
def bump(filename, build, prerelease, bump_type): """Bump the latest version of a CHANGELOG file.""" changelog = Changelog(filename) if not changelog.unreleased.has_changes: click.echo('CHANGELOG has no unreleased changes.') raise click.Abort if bump_type: # `build` token currently not supported by VersionInfo.next_version if bump_type == 'build': new_version = changelog.latest_version.bump_build(build) else: new_version = changelog.latest_version.next_version( bump_type, prerelease_token=prerelease) else: available_versions = changelog.get_next_versions(prerelease, build) # Ask user to select new version new_v_num: str = questionary.select( message= f'Please select a new version (currently v{changelog.latest_version})', choices=[v_num for v_num in available_versions.keys()]).ask() if new_v_num is None: raise click.Abort new_version = available_versions[new_v_num] # Confirm selected new version should_bump: bool = questionary.confirm( message=f'Bump Changelog to v{new_version}?').ask() # Bump or end if not should_bump: raise click.Abort changelog.bump(new_version) click.echo(f'Bumped to v{new_version}!')
def delMed(self): cont = True while cont: with open("medicine.dat", "rb") as file: data: List[List[Any]] = pickle.load(file) file.close() if len(data) == 0: print(self.emptyError) return IDS = [row[0] for row in data] delId = questionary.autocomplete( "Choose the I.D. for which you want to delete record: ", choices=IDS, validate=lambda val: val in IDS, ).ask() for row in data: if row[0] == delId: data.remove(row) break with open("medicine.dat", "wb") as fh: pickle.dump(data, fh) fh.close() cont: bool = questionary.confirm( "Do you wish to continue?:", default=False ).ask()
def _ask_overwrite(path: Text) -> None: import questionary overwrite = questionary.confirm("Directory '{}' is not empty. Continue?" "".format(os.path.abspath(path))).ask() if not overwrite: print_cancel()
def server_configuration_questionaire(dirs, instance_name): """Questionary to generate a config file for the node instance.""" config = q.prompt([ { "type": "text", "name": "description", "message": "Enter a human-readable description:" }, { "type": "text", "name": "ip", "message": "ip:", "default": "0.0.0.0" }, { "type": "text", "name": "port", "message": "Enter port to which the server listens:", "default": "5000" }, { "type": "text", "name": "api_path", "message": "Path of the api:", "default": "/api" }, { "type": "text", "name": "uri", "message": "Database URI:", "default": "sqlite:///default.sqlite" }, { "type": "select", "name": "allow_drop_all", "message": "Allowed to drop all tables: ", "choices": ["True", "False"] } ]) res = q.select("Which level of logging would you like?", choices=["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL", "NOTSET"] ).ask() constant_jwt_secret = q.confirm("Do you want a constant JWT secret?").ask() if constant_jwt_secret: config["jwt_secret_key"] = str(uuid.uuid1()) config["logging"] = { "level": res, "file": f"{instance_name}.log", "use_console": True, "backup_count":5, "max_size": 1024, "format": "%(asctime)s - %(name)-14s - %(levelname)-8s - %(message)s", "datefmt": "%Y-%m-%d %H:%M:%S" } return config
def _read_telemetry_consent(no_prompt: bool) -> bool: """Check if the user wants to enable telemetry or not. Args: no_prompt: If `True`, do not prompt the user for input (but inform about any decision taken). Returns: Boolean indicating if the user wants to enable telemetry. """ import questionary allow_telemetry = (questionary.confirm( "Rasa will track a minimal amount of anonymized usage information " "(like how often the 'train' button is used) to help us improve Rasa X. " "None of your training data or conversations will ever be sent to Rasa. " "Are you OK with Rasa collecting anonymized usage data?").skip_if( no_prompt, default=True).ask()) if not no_prompt: rasa_cli_utils.print_success( f"Your decision has been stored into '{GLOBAL_USER_CONFIG_PATH}'.") else: rasa_cli_utils.print_info( "By adding the '--no_prompt' parameter you agreed to allow Rasa to track " "and send anonymized usage information.") return allow_telemetry
def send_action(endpoint: EndpointConfig, sender_id: Text, action_name: Text, policy: Optional[Text] = None, confidence: Optional[float] = None, is_new_action: bool = False) -> Dict[Text, Any]: """Log an action to a conversation.""" payload = ActionExecuted(action_name, policy, confidence).as_dict() subpath = "/conversations/{}/execute".format(sender_id) try: r = endpoint.request(json=payload, method="post", subpath=subpath) return _response_as_json(r) except requests.exceptions.HTTPError: if is_new_action: warning_questions = questionary.confirm( "WARNING: You have created a new action: '{}', " "which was not successfully executed. " "If this action does not return any events, " "you do not need to do anything. " "If this is a custom action which returns events, " "you are recommended to implement this action " "in your action server and try again." "".format(action_name)) _ask_or_abort(warning_questions, sender_id, endpoint) payload = ActionExecuted(action_name).as_dict() return send_event(endpoint, sender_id, payload) else: logger.error("failed to execute action!") raise
def print_train_or_instructions(args: argparse.Namespace) -> None: """Train a model if the user wants to.""" import questionary import rasa print_success("Finished creating project structure.") should_train = (questionary.confirm( "Do you want to train an initial model? 💪🏽").skip_if( args.no_prompt, default=True).ask()) if should_train: print_success("Training an initial model...") training_result = rasa.train( DEFAULT_DOMAIN_PATH, DEFAULT_CONFIG_PATH, DEFAULT_DATA_PATH, DEFAULT_MODELS_PATH, ) args.model = training_result.model print_run_or_instructions(args) else: print_success( "No problem 👍🏼. You can also train a model later by going " "to the project directory and running 'rasa train'.")
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
def save(self, path: Path): # Prepare diff baseline if path.exists(): with path.open() as f: old = json.load(f) else: old = {} # Check diff diff = list(dictdiffer.diff(old, self._data)) if len(diff) == 0: log.debug("No changes, writing nothing.") return t = tabulate(diff, tablefmt="plain", headers=["type", "path", "change"]) log.info(f"Saving the following changes:\n{t}") if questionary.confirm(f"Write data to {path}?", default=True).ask(): if not DATA_DIR.exists(): log.warning(f"Creating {DATA_DIR}") DATA_DIR.mkdir(parents=True) with path.open("w") as f: json.dump(self._data, f, indent=4)
def _overwrite_endpoints_for_local_x(endpoints, rasa_x_token, rasa_x_url): import questionary endpoints.model = EndpointConfig( "{}/projects/default/models/tags/production".format(rasa_x_url), token=rasa_x_token, wait_time_between_pulls=2, ) overwrite_existing_tracker_store = False if endpoints.tracker_store and not _is_correct_tracker_store( endpoints.tracker_store): print_error( "Rasa X currently only supports a SQLite tracker store with path '{}' " "when running locally. You can deploy Rasa X with Docker " "(https://rasa.com/docs/rasa-x/deploy/) if you want to use " "other tracker store configurations.".format(DEFAULT_TRACKER_DB)) overwrite_existing_tracker_store = questionary.confirm( "Do you want to continue with the default SQLite tracker store?" ).ask() if not overwrite_existing_tracker_store: exit(0) if not endpoints.tracker_store or overwrite_existing_tracker_store: endpoints.tracker_store = EndpointConfig(type="sql", db=DEFAULT_TRACKER_DB)
def is_metrics_collection_enabled(args: argparse.Namespace) -> bool: """Make sure the user consents to any metrics collection.""" try: allow_metrics = read_global_config_value("metrics", unavailable_ok=False) return allow_metrics.get("enabled", False) except ValueError: pass # swallow the error and ask the user allow_metrics = (questionary.confirm( "Rasa will track a minimal amount of anonymized usage information " "(like how often you use the 'train' button) to help us improve Rasa X. " "None of your training data or conversations will ever be sent to Rasa. " "Are you OK with Rasa collecting anonymized usage data?").skip_if( args.no_prompt, default=True).ask()) print_success("Your decision has been stored into {}. " "".format(GLOBAL_USER_CONFIG_PATH)) if not args.no_prompt: date = datetime.datetime.now() write_global_config_value("metrics", { "enabled": allow_metrics, "date": date }) return allow_metrics
def _overwrite_endpoints_for_local_x(endpoints: AvailableEndpoints, rasa_x_token: Text, rasa_x_url: Text): from rasa.utils.endpoints import EndpointConfig import questionary endpoints.model = EndpointConfig( f"{rasa_x_url}/projects/default/models/tags/production", token=rasa_x_token, wait_time_between_pulls=2, ) overwrite_existing_event_broker = False if endpoints.event_broker and not _is_correct_event_broker( endpoints.event_broker): cli_utils.print_error( "Rasa X currently only supports a SQLite event broker with path '{}' " "when running locally. You can deploy Rasa X with Docker " "(https://rasa.com/docs/rasa-x/deploy/) if you want to use " "other event broker configurations.".format(DEFAULT_EVENTS_DB)) overwrite_existing_event_broker = questionary.confirm( "Do you want to continue with the default SQLite event broker?" ).ask() if not overwrite_existing_event_broker: exit(0) if not endpoints.tracker_store or overwrite_existing_event_broker: endpoints.event_broker = EndpointConfig(type="sql", db=DEFAULT_EVENTS_DB)
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 find_last_valid_year(path): """Determines the last year that ran by looking at the restart/echam folder""" expid = path.split("/")[-1] restart_folder = f"{path}/restart/echam" restart_files = sorted( [f for f in os.listdir(restart_folder) if "echam" in f]) # Remove the file without a specific date: if f"restart_{expid}_echam.nc" in restart_files: restart_files.remove(f"restart_{expid}_echam.nc") logger.info(f"Last 5 files in {expid} for restart/echam:") for restart_file in restart_files[-5:]: logger.info(f"* {restart_file}") last_year = (restart_files[-1].replace(f"restart_{expid}_", "").replace("_echam.nc", "").replace("1231", "")) correct_last_year_guess = questionary.confirm( f"I'm going to use {last_year} as the last valid year. Is that correct?" ).ask() if not correct_last_year_guess: last_year = questionary.text( "Whats the last year? (without 1231)").ask() year = int(last_year) + 1 logger.info( f"OK, the next job that will be run will be for the year {year}") return year
def _get_event_broker_endpoint( event_broker_endpoint: Optional[EndpointConfig], ) -> EndpointConfig: import questionary default_event_broker_endpoint = EndpointConfig(type="sql", dialect="sqlite", db=DEFAULT_EVENTS_DB) if not event_broker_endpoint: return default_event_broker_endpoint elif not _is_correct_event_broker(event_broker_endpoint): cli_utils.print_error( f"Rasa X currently only supports a SQLite event broker with path " f"'{DEFAULT_EVENTS_DB}' when running locally. You can deploy Rasa X " f"with Docker ({DOCS_BASE_URL_RASA_X}/installation-and-setup/" f"docker-compose-quick-install/) if you want to use other event broker " f"configurations.") continue_with_default_event_broker = questionary.confirm( "Do you want to continue with the default SQLite event broker?" ).ask() if not continue_with_default_event_broker: exit(0) return default_event_broker_endpoint else: return event_broker_endpoint
def cli_node_clean(): """ This command erases docker volumes""" client = docker.from_env() check_if_docker_deamon_is_running(client) # retrieve all volumes volumes = client.volumes.list() canditates = [] msg = "This would remove the following volumes: " for volume in volumes: if volume.name[-6:] == "tmpvol": canditates.append(volume) msg += volume.name + "," info(msg) confirm = q.confirm(f"Are you sure?") if confirm.ask(): for volume in canditates: try: volume.remove() # info(volume.name) except docker.errors.APIError as e: error(f"Failed to remove volume {Fore.RED}'{volume.name}'" f"{Style.RESET_ALL}. Is it still in use?") debug(e) exit(1) info("Done!")
def _get_event_broker_endpoint( event_broker_endpoint: Optional[EndpointConfig], ) -> EndpointConfig: import questionary default_event_broker_endpoint = EndpointConfig(type="sql", dialect="sqlite", db=DEFAULT_EVENTS_DB) if not event_broker_endpoint: return default_event_broker_endpoint elif not _is_correct_event_broker(event_broker_endpoint): cli_utils.print_error( "Rasa X currently only supports a SQLite event broker with path '{}' " "when running locally. You can deploy Rasa X with Docker " "(https://rasa.com/docs/rasa-x/deploy/) if you want to use " "other event broker configurations.".format(DEFAULT_EVENTS_DB)) continue_with_default_event_broker = questionary.confirm( "Do you want to continue with the default SQLite event broker?" ).ask() if not continue_with_default_event_broker: exit(0) return default_event_broker_endpoint else: return event_broker_endpoint
def __call__(self): values_to_add = {} # No config for commitizen exist if not self.config.path: config_path = self._ask_config_path() if "toml" in config_path: self.config = TomlConfig(data="", path=config_path) elif "json" in config_path: self.config = JsonConfig(data="{}", path=config_path) elif "yaml" in config_path: self.config = YAMLConfig(data="", path=config_path) self.config.init_empty_config_content() values_to_add["name"] = self._ask_name() tag = self._ask_tag() values_to_add["version"] = Version(tag).public values_to_add["tag_format"] = self._ask_tag_format(tag) self._update_config_file(values_to_add) if questionary.confirm( "Do you want to install pre-commit hook?").ask(): self._install_pre_commit_hook() out.write( "You can bump the version and create changelog running:\n") out.info("cz bump --changelog") out.success("The configuration are all set.") else: out.line(f"Config file {self.config.path} already exists")
def print_train_or_instructions(args: argparse.Namespace, path: Text) -> None: import questionary print_success("Finished creating project structure.") should_train = questionary.confirm( "Do you want to train an initial model? 💪🏽").skip_if(args.no_prompt, default=True) if should_train: print_success("Training an initial model...") config = os.path.join(path, DEFAULT_CONFIG_PATH) training_files = os.path.join(path, DEFAULT_DATA_PATH) domain = os.path.join(path, DEFAULT_DOMAIN_PATH) output = os.path.join(path, create_output_path()) args.model = rasa.train(domain, config, training_files, output) print_run_or_instructions(args, path) else: print_success( "No problem 👍🏼. You can also train a model later by going " "to the project directory and running 'rasa train'." "".format(path))
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}" )
def print_run_or_instructions(args: argparse.Namespace, path: Text) -> None: from rasa.core import constants import questionary should_run = questionary.confirm( "Do you want to speak to the trained bot on the command line? 🤖").ask( ) if should_run: # provide defaults for command line arguments attributes = [ "endpoints", "credentials", "cors", "auth_token", "jwt_secret", "jwt_method", "enable_api", ] for a in attributes: setattr(args, a, None) args.port = constants.DEFAULT_SERVER_PORT shell(args) else: print_success("Ok 👍🏼. If you want to speak to the bot later, " "change into the project directory and run 'rasa shell'." "".format(path))
def prepare_test_pyinstaller(venv): script_path, cwd = ['', ''] while 1: script_path, cwd = ask_script_cwd_path(venv, script_path, cwd) if script_path is None: break if not (script_path.is_file() and (str(script_path).endswith('.py') or str(script_path).endswith('.pyw'))): print('[Error] script path should be a *.py or *.pyw file') continue if not cwd.is_dir(): print('[Error] cwd path should be a dir') continue choice = questionary.select( 'Choose a action for python script:', choices=['Test', 'Build', 'Exit']).ask() if choice == 'Exit': break elif choice == 'Test': print(f'Testing python script at {cwd}:') print_sep() # python xxx.py venv.run(script_path, cwd) print_sep() elif choice == 'Build': # pyinstaller xxx.py if not venv.check_pyinstaller(): venv.ask_if_install_pyinstaller() cache_path = venv.venv_path / 'dist_cache' if not cache_path.is_dir(): cache_path.mkdir() args = ask_for_args(venv, script_path, cwd, cache_path) print_sep() print(f'Building python script at {cwd}:\n{list2cmdline(args)}') run(args, cwd=cwd) clean = questionary.confirm( "Clean the cache files?", default=False).ask() if clean: clean_folder(cache_path) is_quit = questionary.confirm("Quit?", default=True).ask() if is_quit: if venv.name: is_del_venv = questionary.confirm( f'Remove the `{venv.name}` venv?', default=False).ask() if is_del_venv: Venvs.rm_venv(venv.name) quit()
async def send_action( endpoint: EndpointConfig, sender_id: Text, action_name: Text, policy: Optional[Text] = None, confidence: Optional[float] = None, is_new_action: bool = False, ) -> Dict[Text, Any]: """Log an action to a conversation.""" payload = ActionExecuted(action_name, policy, confidence).as_dict() subpath = "/conversations/{}/execute".format(sender_id) try: return await endpoint.request(json=payload, method="post", subpath=subpath) except ClientError: if is_new_action: if action_name in NEW_TEMPLATES: warning_questions = questionary.confirm( "WARNING: You have created a new action: '{0}', " "with matching template: '{1}'. " "This action will not return its message in this session, " "but the new utterance will be saved to your domain file " "when you exit and save this session. " "You do not need to do anything further. " "".format(action_name, [*NEW_TEMPLATES[action_name]][0]) ) await _ask_questions(warning_questions, sender_id, endpoint) else: warning_questions = questionary.confirm( "WARNING: You have created a new action: '{}', " "which was not successfully executed. " "If this action does not return any events, " "you do not need to do anything. " "If this is a custom action which returns events, " "you are recommended to implement this action " "in your action server and try again." "".format(action_name) ) await _ask_questions(warning_questions, sender_id, endpoint) payload = ActionExecuted(action_name).as_dict() return await send_event(endpoint, sender_id, payload) else: logger.error("failed to execute action!") raise
def purchaseItem(): cont = True while cont: data = [] codes = {} with open('Items.csv', 'r') as fileObject: reader = csv.reader(fileObject) for line in reader: if len(line) != 0: data.append(line) if len(data) != 0: for row in data: index = data.index(row) ncode = row[0] c = {ncode: index} codes.update(c) if len(data) == 0: print('Data Set is currently empty') print('Add some data first!') return print('Current data:\n') print(tabulate(data, header_purchase, 'fancy_grid'), '\n') while True: codeInput = str( input( 'Enter the code of the item that you want to purchase: ')) if codeInput not in codes.keys(): print('Invalid Code\nTry Again!') else: pIndex = codes[codeInput] pRec = data[pIndex] break description = str(pRec[1]) price = float(pRec[2]) discount = float(pRec[3]) / 100 actualPrice = price - price * discount while True: qty = int(input('Enter the quantity: ')) if qty < 0: print("Quantity cannot be negative\nTry Again!") else: break totalPrice = actualPrice * qty newList = [ codeInput, description, price, discount, actualPrice, qty, totalPrice ] printedList = [] printedList.append(newList) print('\nBill:\n') print(tabulate(printedList, header_purchase, 'fancy_grid'), '\n') print(""" -Thank you for shopping with us! -NO RETURNS, NO REFUNDS! -IF Bill is not provided, then this purchase is on the house! """) cont = qr.confirm('Do you wish to continue?').ask()