id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
224,500
IDSIA/sacred
sacred/dependencies.py
convert_path_to_module_parts
def convert_path_to_module_parts(path): """Convert path to a python file into list of module names.""" module_parts = splitall(path) if module_parts[-1] in ['__init__.py', '__init__.pyc']: # remove trailing __init__.py module_parts = module_parts[:-1] else: # remove file extension module_parts[-1], _ = os.path.splitext(module_parts[-1]) return module_parts
python
def convert_path_to_module_parts(path): """Convert path to a python file into list of module names.""" module_parts = splitall(path) if module_parts[-1] in ['__init__.py', '__init__.pyc']: # remove trailing __init__.py module_parts = module_parts[:-1] else: # remove file extension module_parts[-1], _ = os.path.splitext(module_parts[-1]) return module_parts
[ "def", "convert_path_to_module_parts", "(", "path", ")", ":", "module_parts", "=", "splitall", "(", "path", ")", "if", "module_parts", "[", "-", "1", "]", "in", "[", "'__init__.py'", ",", "'__init__.pyc'", "]", ":", "# remove trailing __init__.py", "module_parts",...
Convert path to a python file into list of module names.
[ "Convert", "path", "to", "a", "python", "file", "into", "list", "of", "module", "names", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/dependencies.py#L299-L308
224,501
IDSIA/sacred
sacred/dependencies.py
is_local_source
def is_local_source(filename, modname, experiment_path): """Check if a module comes from the given experiment path. Check if a module, given by name and filename, is from (a subdirectory of ) the given experiment path. This is used to determine if the module is a local source file, or rather a package dependency. Parameters ---------- filename: str The absolute filename of the module in question. (Usually module.__file__) modname: str The full name of the module including parent namespaces. experiment_path: str The base path of the experiment. Returns ------- bool: True if the module was imported locally from (a subdir of) the experiment_path, and False otherwise. """ if not is_subdir(filename, experiment_path): return False rel_path = os.path.relpath(filename, experiment_path) path_parts = convert_path_to_module_parts(rel_path) mod_parts = modname.split('.') if path_parts == mod_parts: return True if len(path_parts) > len(mod_parts): return False abs_path_parts = convert_path_to_module_parts(os.path.abspath(filename)) return all([p == m for p, m in zip(reversed(abs_path_parts), reversed(mod_parts))])
python
def is_local_source(filename, modname, experiment_path): """Check if a module comes from the given experiment path. Check if a module, given by name and filename, is from (a subdirectory of ) the given experiment path. This is used to determine if the module is a local source file, or rather a package dependency. Parameters ---------- filename: str The absolute filename of the module in question. (Usually module.__file__) modname: str The full name of the module including parent namespaces. experiment_path: str The base path of the experiment. Returns ------- bool: True if the module was imported locally from (a subdir of) the experiment_path, and False otherwise. """ if not is_subdir(filename, experiment_path): return False rel_path = os.path.relpath(filename, experiment_path) path_parts = convert_path_to_module_parts(rel_path) mod_parts = modname.split('.') if path_parts == mod_parts: return True if len(path_parts) > len(mod_parts): return False abs_path_parts = convert_path_to_module_parts(os.path.abspath(filename)) return all([p == m for p, m in zip(reversed(abs_path_parts), reversed(mod_parts))])
[ "def", "is_local_source", "(", "filename", ",", "modname", ",", "experiment_path", ")", ":", "if", "not", "is_subdir", "(", "filename", ",", "experiment_path", ")", ":", "return", "False", "rel_path", "=", "os", ".", "path", ".", "relpath", "(", "filename", ...
Check if a module comes from the given experiment path. Check if a module, given by name and filename, is from (a subdirectory of ) the given experiment path. This is used to determine if the module is a local source file, or rather a package dependency. Parameters ---------- filename: str The absolute filename of the module in question. (Usually module.__file__) modname: str The full name of the module including parent namespaces. experiment_path: str The base path of the experiment. Returns ------- bool: True if the module was imported locally from (a subdir of) the experiment_path, and False otherwise.
[ "Check", "if", "a", "module", "comes", "from", "the", "given", "experiment", "path", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/dependencies.py#L311-L347
224,502
IDSIA/sacred
sacred/dependencies.py
gather_sources_and_dependencies
def gather_sources_and_dependencies(globs, base_dir=None): """Scan the given globals for modules and return them as dependencies.""" experiment_path, main = get_main_file(globs) base_dir = base_dir or experiment_path gather_sources = source_discovery_strategies[SETTINGS['DISCOVER_SOURCES']] sources = gather_sources(globs, base_dir) if main is not None: sources.add(main) gather_dependencies = dependency_discovery_strategies[ SETTINGS['DISCOVER_DEPENDENCIES']] dependencies = gather_dependencies(globs, base_dir) if opt.has_numpy: # Add numpy as a dependency because it might be used for randomness dependencies.add(PackageDependency.create(opt.np)) return main, sources, dependencies
python
def gather_sources_and_dependencies(globs, base_dir=None): """Scan the given globals for modules and return them as dependencies.""" experiment_path, main = get_main_file(globs) base_dir = base_dir or experiment_path gather_sources = source_discovery_strategies[SETTINGS['DISCOVER_SOURCES']] sources = gather_sources(globs, base_dir) if main is not None: sources.add(main) gather_dependencies = dependency_discovery_strategies[ SETTINGS['DISCOVER_DEPENDENCIES']] dependencies = gather_dependencies(globs, base_dir) if opt.has_numpy: # Add numpy as a dependency because it might be used for randomness dependencies.add(PackageDependency.create(opt.np)) return main, sources, dependencies
[ "def", "gather_sources_and_dependencies", "(", "globs", ",", "base_dir", "=", "None", ")", ":", "experiment_path", ",", "main", "=", "get_main_file", "(", "globs", ")", "base_dir", "=", "base_dir", "or", "experiment_path", "gather_sources", "=", "source_discovery_st...
Scan the given globals for modules and return them as dependencies.
[ "Scan", "the", "given", "globals", "for", "modules", "and", "return", "them", "as", "dependencies", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/dependencies.py#L481-L501
224,503
IDSIA/sacred
sacred/config/utils.py
assert_is_valid_key
def assert_is_valid_key(key): """ Raise KeyError if a given config key violates any requirements. The requirements are the following and can be individually deactivated in ``sacred.SETTINGS.CONFIG_KEYS``: * ENFORCE_MONGO_COMPATIBLE (default: True): make sure the keys don't contain a '.' or start with a '$' * ENFORCE_JSONPICKLE_COMPATIBLE (default: True): make sure the keys do not contain any reserved jsonpickle tags This is very important. Only deactivate if you know what you are doing. * ENFORCE_STRING (default: False): make sure all keys are string. * ENFORCE_VALID_PYTHON_IDENTIFIER (default: False): make sure all keys are valid python identifiers. Parameters ---------- key: The key that should be checked Raises ------ KeyError: if the key violates any requirements """ if SETTINGS.CONFIG.ENFORCE_KEYS_MONGO_COMPATIBLE and ( isinstance(key, basestring) and ('.' in key or key[0] == '$')): raise KeyError('Invalid key "{}". Config-keys cannot ' 'contain "." or start with "$"'.format(key)) if SETTINGS.CONFIG.ENFORCE_KEYS_JSONPICKLE_COMPATIBLE and \ isinstance(key, basestring) and ( key in jsonpickle.tags.RESERVED or key.startswith('json://')): raise KeyError('Invalid key "{}". Config-keys cannot be one of the' 'reserved jsonpickle tags: {}' .format(key, jsonpickle.tags.RESERVED)) if SETTINGS.CONFIG.ENFORCE_STRING_KEYS and ( not isinstance(key, basestring)): raise KeyError('Invalid key "{}". Config-keys have to be strings, ' 'but was {}'.format(key, type(key))) if SETTINGS.CONFIG.ENFORCE_VALID_PYTHON_IDENTIFIER_KEYS and ( isinstance(key, basestring) and not PYTHON_IDENTIFIER.match(key)): raise KeyError('Key "{}" is not a valid python identifier' .format(key)) if SETTINGS.CONFIG.ENFORCE_KEYS_NO_EQUALS and ( isinstance(key, basestring) and '=' in key): raise KeyError('Invalid key "{}". Config keys may not contain an' 'equals sign ("=").'.format('='))
python
def assert_is_valid_key(key): """ Raise KeyError if a given config key violates any requirements. The requirements are the following and can be individually deactivated in ``sacred.SETTINGS.CONFIG_KEYS``: * ENFORCE_MONGO_COMPATIBLE (default: True): make sure the keys don't contain a '.' or start with a '$' * ENFORCE_JSONPICKLE_COMPATIBLE (default: True): make sure the keys do not contain any reserved jsonpickle tags This is very important. Only deactivate if you know what you are doing. * ENFORCE_STRING (default: False): make sure all keys are string. * ENFORCE_VALID_PYTHON_IDENTIFIER (default: False): make sure all keys are valid python identifiers. Parameters ---------- key: The key that should be checked Raises ------ KeyError: if the key violates any requirements """ if SETTINGS.CONFIG.ENFORCE_KEYS_MONGO_COMPATIBLE and ( isinstance(key, basestring) and ('.' in key or key[0] == '$')): raise KeyError('Invalid key "{}". Config-keys cannot ' 'contain "." or start with "$"'.format(key)) if SETTINGS.CONFIG.ENFORCE_KEYS_JSONPICKLE_COMPATIBLE and \ isinstance(key, basestring) and ( key in jsonpickle.tags.RESERVED or key.startswith('json://')): raise KeyError('Invalid key "{}". Config-keys cannot be one of the' 'reserved jsonpickle tags: {}' .format(key, jsonpickle.tags.RESERVED)) if SETTINGS.CONFIG.ENFORCE_STRING_KEYS and ( not isinstance(key, basestring)): raise KeyError('Invalid key "{}". Config-keys have to be strings, ' 'but was {}'.format(key, type(key))) if SETTINGS.CONFIG.ENFORCE_VALID_PYTHON_IDENTIFIER_KEYS and ( isinstance(key, basestring) and not PYTHON_IDENTIFIER.match(key)): raise KeyError('Key "{}" is not a valid python identifier' .format(key)) if SETTINGS.CONFIG.ENFORCE_KEYS_NO_EQUALS and ( isinstance(key, basestring) and '=' in key): raise KeyError('Invalid key "{}". Config keys may not contain an' 'equals sign ("=").'.format('='))
[ "def", "assert_is_valid_key", "(", "key", ")", ":", "if", "SETTINGS", ".", "CONFIG", ".", "ENFORCE_KEYS_MONGO_COMPATIBLE", "and", "(", "isinstance", "(", "key", ",", "basestring", ")", "and", "(", "'.'", "in", "key", "or", "key", "[", "0", "]", "==", "'$...
Raise KeyError if a given config key violates any requirements. The requirements are the following and can be individually deactivated in ``sacred.SETTINGS.CONFIG_KEYS``: * ENFORCE_MONGO_COMPATIBLE (default: True): make sure the keys don't contain a '.' or start with a '$' * ENFORCE_JSONPICKLE_COMPATIBLE (default: True): make sure the keys do not contain any reserved jsonpickle tags This is very important. Only deactivate if you know what you are doing. * ENFORCE_STRING (default: False): make sure all keys are string. * ENFORCE_VALID_PYTHON_IDENTIFIER (default: False): make sure all keys are valid python identifiers. Parameters ---------- key: The key that should be checked Raises ------ KeyError: if the key violates any requirements
[ "Raise", "KeyError", "if", "a", "given", "config", "key", "violates", "any", "requirements", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/config/utils.py#L13-L65
224,504
IDSIA/sacred
sacred/observers/slack.py
SlackObserver.from_config
def from_config(cls, filename): """ Create a SlackObserver from a given configuration file. The file can be in any format supported by Sacred (.json, .pickle, [.yaml]). It has to specify a ``webhook_url`` and can optionally set ``bot_name``, ``icon``, ``completed_text``, ``interrupted_text``, and ``failed_text``. """ d = load_config_file(filename) obs = None if 'webhook_url' in d: obs = cls(d['webhook_url']) else: raise ValueError("Slack configuration file must contain " "an entry for 'webhook_url'!") for k in ['completed_text', 'interrupted_text', 'failed_text', 'bot_name', 'icon']: if k in d: setattr(obs, k, d[k]) return obs
python
def from_config(cls, filename): """ Create a SlackObserver from a given configuration file. The file can be in any format supported by Sacred (.json, .pickle, [.yaml]). It has to specify a ``webhook_url`` and can optionally set ``bot_name``, ``icon``, ``completed_text``, ``interrupted_text``, and ``failed_text``. """ d = load_config_file(filename) obs = None if 'webhook_url' in d: obs = cls(d['webhook_url']) else: raise ValueError("Slack configuration file must contain " "an entry for 'webhook_url'!") for k in ['completed_text', 'interrupted_text', 'failed_text', 'bot_name', 'icon']: if k in d: setattr(obs, k, d[k]) return obs
[ "def", "from_config", "(", "cls", ",", "filename", ")", ":", "d", "=", "load_config_file", "(", "filename", ")", "obs", "=", "None", "if", "'webhook_url'", "in", "d", ":", "obs", "=", "cls", "(", "d", "[", "'webhook_url'", "]", ")", "else", ":", "rai...
Create a SlackObserver from a given configuration file. The file can be in any format supported by Sacred (.json, .pickle, [.yaml]). It has to specify a ``webhook_url`` and can optionally set ``bot_name``, ``icon``, ``completed_text``, ``interrupted_text``, and ``failed_text``.
[ "Create", "a", "SlackObserver", "from", "a", "given", "configuration", "file", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/observers/slack.py#L44-L65
224,505
IDSIA/sacred
sacred/host_info.py
get_host_info
def get_host_info(): """Collect some information about the machine this experiment runs on. Returns ------- dict A dictionary with information about the CPU, the OS and the Python version of this machine. """ host_info = {} for k, v in host_info_gatherers.items(): try: host_info[k] = v() except IgnoreHostInfo: pass return host_info
python
def get_host_info(): """Collect some information about the machine this experiment runs on. Returns ------- dict A dictionary with information about the CPU, the OS and the Python version of this machine. """ host_info = {} for k, v in host_info_gatherers.items(): try: host_info[k] = v() except IgnoreHostInfo: pass return host_info
[ "def", "get_host_info", "(", ")", ":", "host_info", "=", "{", "}", "for", "k", ",", "v", "in", "host_info_gatherers", ".", "items", "(", ")", ":", "try", ":", "host_info", "[", "k", "]", "=", "v", "(", ")", "except", "IgnoreHostInfo", ":", "pass", ...
Collect some information about the machine this experiment runs on. Returns ------- dict A dictionary with information about the CPU, the OS and the Python version of this machine.
[ "Collect", "some", "information", "about", "the", "machine", "this", "experiment", "runs", "on", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/host_info.py#L27-L43
224,506
IDSIA/sacred
sacred/host_info.py
host_info_getter
def host_info_getter(func, name=None): """ The decorated function is added to the process of collecting the host_info. This just adds the decorated function to the global ``sacred.host_info.host_info_gatherers`` dictionary. The functions from that dictionary are used when collecting the host info using :py:func:`~sacred.host_info.get_host_info`. Parameters ---------- func : callable A function that can be called without arguments and returns some json-serializable information. name : str, optional The name of the corresponding entry in host_info. Defaults to the name of the function. Returns ------- The function itself. """ name = name or func.__name__ host_info_gatherers[name] = func return func
python
def host_info_getter(func, name=None): """ The decorated function is added to the process of collecting the host_info. This just adds the decorated function to the global ``sacred.host_info.host_info_gatherers`` dictionary. The functions from that dictionary are used when collecting the host info using :py:func:`~sacred.host_info.get_host_info`. Parameters ---------- func : callable A function that can be called without arguments and returns some json-serializable information. name : str, optional The name of the corresponding entry in host_info. Defaults to the name of the function. Returns ------- The function itself. """ name = name or func.__name__ host_info_gatherers[name] = func return func
[ "def", "host_info_getter", "(", "func", ",", "name", "=", "None", ")", ":", "name", "=", "name", "or", "func", ".", "__name__", "host_info_gatherers", "[", "name", "]", "=", "func", "return", "func" ]
The decorated function is added to the process of collecting the host_info. This just adds the decorated function to the global ``sacred.host_info.host_info_gatherers`` dictionary. The functions from that dictionary are used when collecting the host info using :py:func:`~sacred.host_info.get_host_info`. Parameters ---------- func : callable A function that can be called without arguments and returns some json-serializable information. name : str, optional The name of the corresponding entry in host_info. Defaults to the name of the function. Returns ------- The function itself.
[ "The", "decorated", "function", "is", "added", "to", "the", "process", "of", "collecting", "the", "host_info", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/host_info.py#L47-L72
224,507
IDSIA/sacred
sacred/metrics_logger.py
linearize_metrics
def linearize_metrics(logged_metrics): """ Group metrics by name. Takes a list of individual measurements, possibly belonging to different metrics and groups them by name. :param logged_metrics: A list of ScalarMetricLogEntries :return: Measured values grouped by the metric name: {"metric_name1": {"steps": [0,1,2], "values": [4, 5, 6], "timestamps": [datetime, datetime, datetime]}, "metric_name2": {...}} """ metrics_by_name = {} for metric_entry in logged_metrics: if metric_entry.name not in metrics_by_name: metrics_by_name[metric_entry.name] = { "steps": [], "values": [], "timestamps": [], "name": metric_entry.name } metrics_by_name[metric_entry.name]["steps"] \ .append(metric_entry.step) metrics_by_name[metric_entry.name]["values"] \ .append(metric_entry.value) metrics_by_name[metric_entry.name]["timestamps"] \ .append(metric_entry.timestamp) return metrics_by_name
python
def linearize_metrics(logged_metrics): """ Group metrics by name. Takes a list of individual measurements, possibly belonging to different metrics and groups them by name. :param logged_metrics: A list of ScalarMetricLogEntries :return: Measured values grouped by the metric name: {"metric_name1": {"steps": [0,1,2], "values": [4, 5, 6], "timestamps": [datetime, datetime, datetime]}, "metric_name2": {...}} """ metrics_by_name = {} for metric_entry in logged_metrics: if metric_entry.name not in metrics_by_name: metrics_by_name[metric_entry.name] = { "steps": [], "values": [], "timestamps": [], "name": metric_entry.name } metrics_by_name[metric_entry.name]["steps"] \ .append(metric_entry.step) metrics_by_name[metric_entry.name]["values"] \ .append(metric_entry.value) metrics_by_name[metric_entry.name]["timestamps"] \ .append(metric_entry.timestamp) return metrics_by_name
[ "def", "linearize_metrics", "(", "logged_metrics", ")", ":", "metrics_by_name", "=", "{", "}", "for", "metric_entry", "in", "logged_metrics", ":", "if", "metric_entry", ".", "name", "not", "in", "metrics_by_name", ":", "metrics_by_name", "[", "metric_entry", ".", ...
Group metrics by name. Takes a list of individual measurements, possibly belonging to different metrics and groups them by name. :param logged_metrics: A list of ScalarMetricLogEntries :return: Measured values grouped by the metric name: {"metric_name1": {"steps": [0,1,2], "values": [4, 5, 6], "timestamps": [datetime, datetime, datetime]}, "metric_name2": {...}}
[ "Group", "metrics", "by", "name", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/metrics_logger.py#L85-L113
224,508
IDSIA/sacred
sacred/metrics_logger.py
MetricsLogger.get_last_metrics
def get_last_metrics(self): """Read all measurement events since last call of the method. :return List[ScalarMetricLogEntry] """ read_up_to = self._logged_metrics.qsize() messages = [] for i in range(read_up_to): try: messages.append(self._logged_metrics.get_nowait()) except Empty: pass return messages
python
def get_last_metrics(self): """Read all measurement events since last call of the method. :return List[ScalarMetricLogEntry] """ read_up_to = self._logged_metrics.qsize() messages = [] for i in range(read_up_to): try: messages.append(self._logged_metrics.get_nowait()) except Empty: pass return messages
[ "def", "get_last_metrics", "(", "self", ")", ":", "read_up_to", "=", "self", ".", "_logged_metrics", ".", "qsize", "(", ")", "messages", "=", "[", "]", "for", "i", "in", "range", "(", "read_up_to", ")", ":", "try", ":", "messages", ".", "append", "(", ...
Read all measurement events since last call of the method. :return List[ScalarMetricLogEntry]
[ "Read", "all", "measurement", "events", "since", "last", "call", "of", "the", "method", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/metrics_logger.py#L57-L69
224,509
IDSIA/sacred
sacred/commandline_options.py
gather_command_line_options
def gather_command_line_options(filter_disabled=None): """Get a sorted list of all CommandLineOption subclasses.""" if filter_disabled is None: filter_disabled = not SETTINGS.COMMAND_LINE.SHOW_DISABLED_OPTIONS options = [opt for opt in get_inheritors(CommandLineOption) if not filter_disabled or opt._enabled] return sorted(options, key=lambda opt: opt.__name__)
python
def gather_command_line_options(filter_disabled=None): """Get a sorted list of all CommandLineOption subclasses.""" if filter_disabled is None: filter_disabled = not SETTINGS.COMMAND_LINE.SHOW_DISABLED_OPTIONS options = [opt for opt in get_inheritors(CommandLineOption) if not filter_disabled or opt._enabled] return sorted(options, key=lambda opt: opt.__name__)
[ "def", "gather_command_line_options", "(", "filter_disabled", "=", "None", ")", ":", "if", "filter_disabled", "is", "None", ":", "filter_disabled", "=", "not", "SETTINGS", ".", "COMMAND_LINE", ".", "SHOW_DISABLED_OPTIONS", "options", "=", "[", "opt", "for", "opt",...
Get a sorted list of all CommandLineOption subclasses.
[ "Get", "a", "sorted", "list", "of", "all", "CommandLineOption", "subclasses", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/commandline_options.py#L159-L165
224,510
IDSIA/sacred
sacred/commandline_options.py
LoglevelOption.apply
def apply(cls, args, run): """Adjust the loglevel of the root-logger of this run.""" # TODO: sacred.initialize.create_run already takes care of this try: lvl = int(args) except ValueError: lvl = args run.root_logger.setLevel(lvl)
python
def apply(cls, args, run): """Adjust the loglevel of the root-logger of this run.""" # TODO: sacred.initialize.create_run already takes care of this try: lvl = int(args) except ValueError: lvl = args run.root_logger.setLevel(lvl)
[ "def", "apply", "(", "cls", ",", "args", ",", "run", ")", ":", "# TODO: sacred.initialize.create_run already takes care of this", "try", ":", "lvl", "=", "int", "(", "args", ")", "except", "ValueError", ":", "lvl", "=", "args", "run", ".", "root_logger", ".", ...
Adjust the loglevel of the root-logger of this run.
[ "Adjust", "the", "loglevel", "of", "the", "root", "-", "logger", "of", "this", "run", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/commandline_options.py#L203-L211
224,511
IDSIA/sacred
sacred/commandline_options.py
PriorityOption.apply
def apply(cls, args, run): """Add priority info for this run.""" try: priority = float(args) except ValueError: raise ValueError("The PRIORITY argument must be a number! " "(but was '{}')".format(args)) run.meta_info['priority'] = priority
python
def apply(cls, args, run): """Add priority info for this run.""" try: priority = float(args) except ValueError: raise ValueError("The PRIORITY argument must be a number! " "(but was '{}')".format(args)) run.meta_info['priority'] = priority
[ "def", "apply", "(", "cls", ",", "args", ",", "run", ")", ":", "try", ":", "priority", "=", "float", "(", "args", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "\"The PRIORITY argument must be a number! \"", "\"(but was '{}')\"", ".", "format", ...
Add priority info for this run.
[ "Add", "priority", "info", "for", "this", "run", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/commandline_options.py#L273-L280
224,512
IDSIA/sacred
sacred/ingredient.py
Ingredient.capture
def capture(self, function=None, prefix=None): """ Decorator to turn a function into a captured function. The missing arguments of captured functions are automatically filled from the configuration if possible. See :ref:`captured_functions` for more information. If a ``prefix`` is specified, the search for suitable entries is performed in the corresponding subtree of the configuration. """ if function in self.captured_functions: return function captured_function = create_captured_function(function, prefix=prefix) self.captured_functions.append(captured_function) return captured_function
python
def capture(self, function=None, prefix=None): """ Decorator to turn a function into a captured function. The missing arguments of captured functions are automatically filled from the configuration if possible. See :ref:`captured_functions` for more information. If a ``prefix`` is specified, the search for suitable entries is performed in the corresponding subtree of the configuration. """ if function in self.captured_functions: return function captured_function = create_captured_function(function, prefix=prefix) self.captured_functions.append(captured_function) return captured_function
[ "def", "capture", "(", "self", ",", "function", "=", "None", ",", "prefix", "=", "None", ")", ":", "if", "function", "in", "self", ".", "captured_functions", ":", "return", "function", "captured_function", "=", "create_captured_function", "(", "function", ",",...
Decorator to turn a function into a captured function. The missing arguments of captured functions are automatically filled from the configuration if possible. See :ref:`captured_functions` for more information. If a ``prefix`` is specified, the search for suitable entries is performed in the corresponding subtree of the configuration.
[ "Decorator", "to", "turn", "a", "function", "into", "a", "captured", "function", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L80-L95
224,513
IDSIA/sacred
sacred/ingredient.py
Ingredient.pre_run_hook
def pre_run_hook(self, func, prefix=None): """ Decorator to add a pre-run hook to this ingredient. Pre-run hooks are captured functions that are run, just before the main function is executed. """ cf = self.capture(func, prefix=prefix) self.pre_run_hooks.append(cf) return cf
python
def pre_run_hook(self, func, prefix=None): """ Decorator to add a pre-run hook to this ingredient. Pre-run hooks are captured functions that are run, just before the main function is executed. """ cf = self.capture(func, prefix=prefix) self.pre_run_hooks.append(cf) return cf
[ "def", "pre_run_hook", "(", "self", ",", "func", ",", "prefix", "=", "None", ")", ":", "cf", "=", "self", ".", "capture", "(", "func", ",", "prefix", "=", "prefix", ")", "self", ".", "pre_run_hooks", ".", "append", "(", "cf", ")", "return", "cf" ]
Decorator to add a pre-run hook to this ingredient. Pre-run hooks are captured functions that are run, just before the main function is executed.
[ "Decorator", "to", "add", "a", "pre", "-", "run", "hook", "to", "this", "ingredient", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L98-L107
224,514
IDSIA/sacred
sacred/ingredient.py
Ingredient.post_run_hook
def post_run_hook(self, func, prefix=None): """ Decorator to add a post-run hook to this ingredient. Post-run hooks are captured functions that are run, just after the main function is executed. """ cf = self.capture(func, prefix=prefix) self.post_run_hooks.append(cf) return cf
python
def post_run_hook(self, func, prefix=None): """ Decorator to add a post-run hook to this ingredient. Post-run hooks are captured functions that are run, just after the main function is executed. """ cf = self.capture(func, prefix=prefix) self.post_run_hooks.append(cf) return cf
[ "def", "post_run_hook", "(", "self", ",", "func", ",", "prefix", "=", "None", ")", ":", "cf", "=", "self", ".", "capture", "(", "func", ",", "prefix", "=", "prefix", ")", "self", ".", "post_run_hooks", ".", "append", "(", "cf", ")", "return", "cf" ]
Decorator to add a post-run hook to this ingredient. Post-run hooks are captured functions that are run, just after the main function is executed.
[ "Decorator", "to", "add", "a", "post", "-", "run", "hook", "to", "this", "ingredient", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L110-L119
224,515
IDSIA/sacred
sacred/ingredient.py
Ingredient.command
def command(self, function=None, prefix=None, unobserved=False): """ Decorator to define a new command for this Ingredient or Experiment. The name of the command will be the name of the function. It can be called from the command-line or by using the run_command function. Commands are automatically also captured functions. The command can be given a prefix, to restrict its configuration space to a subtree. (see ``capture`` for more information) A command can be made unobserved (i.e. ignoring all observers) by passing the unobserved=True keyword argument. """ captured_f = self.capture(function, prefix=prefix) captured_f.unobserved = unobserved self.commands[function.__name__] = captured_f return captured_f
python
def command(self, function=None, prefix=None, unobserved=False): """ Decorator to define a new command for this Ingredient or Experiment. The name of the command will be the name of the function. It can be called from the command-line or by using the run_command function. Commands are automatically also captured functions. The command can be given a prefix, to restrict its configuration space to a subtree. (see ``capture`` for more information) A command can be made unobserved (i.e. ignoring all observers) by passing the unobserved=True keyword argument. """ captured_f = self.capture(function, prefix=prefix) captured_f.unobserved = unobserved self.commands[function.__name__] = captured_f return captured_f
[ "def", "command", "(", "self", ",", "function", "=", "None", ",", "prefix", "=", "None", ",", "unobserved", "=", "False", ")", ":", "captured_f", "=", "self", ".", "capture", "(", "function", ",", "prefix", "=", "prefix", ")", "captured_f", ".", "unobs...
Decorator to define a new command for this Ingredient or Experiment. The name of the command will be the name of the function. It can be called from the command-line or by using the run_command function. Commands are automatically also captured functions. The command can be given a prefix, to restrict its configuration space to a subtree. (see ``capture`` for more information) A command can be made unobserved (i.e. ignoring all observers) by passing the unobserved=True keyword argument.
[ "Decorator", "to", "define", "a", "new", "command", "for", "this", "Ingredient", "or", "Experiment", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L122-L140
224,516
IDSIA/sacred
sacred/ingredient.py
Ingredient.config
def config(self, function): """ Decorator to add a function to the configuration of the Experiment. The decorated function is turned into a :class:`~sacred.config_scope.ConfigScope` and added to the Ingredient/Experiment. When the experiment is run, this function will also be executed and all json-serializable local variables inside it will end up as entries in the configuration of the experiment. """ self.configurations.append(ConfigScope(function)) return self.configurations[-1]
python
def config(self, function): """ Decorator to add a function to the configuration of the Experiment. The decorated function is turned into a :class:`~sacred.config_scope.ConfigScope` and added to the Ingredient/Experiment. When the experiment is run, this function will also be executed and all json-serializable local variables inside it will end up as entries in the configuration of the experiment. """ self.configurations.append(ConfigScope(function)) return self.configurations[-1]
[ "def", "config", "(", "self", ",", "function", ")", ":", "self", ".", "configurations", ".", "append", "(", "ConfigScope", "(", "function", ")", ")", "return", "self", ".", "configurations", "[", "-", "1", "]" ]
Decorator to add a function to the configuration of the Experiment. The decorated function is turned into a :class:`~sacred.config_scope.ConfigScope` and added to the Ingredient/Experiment. When the experiment is run, this function will also be executed and all json-serializable local variables inside it will end up as entries in the configuration of the experiment.
[ "Decorator", "to", "add", "a", "function", "to", "the", "configuration", "of", "the", "Experiment", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L142-L155
224,517
IDSIA/sacred
sacred/ingredient.py
Ingredient.named_config
def named_config(self, func): """ Decorator to turn a function into a named configuration. See :ref:`named_configurations`. """ config_scope = ConfigScope(func) self._add_named_config(func.__name__, config_scope) return config_scope
python
def named_config(self, func): """ Decorator to turn a function into a named configuration. See :ref:`named_configurations`. """ config_scope = ConfigScope(func) self._add_named_config(func.__name__, config_scope) return config_scope
[ "def", "named_config", "(", "self", ",", "func", ")", ":", "config_scope", "=", "ConfigScope", "(", "func", ")", "self", ".", "_add_named_config", "(", "func", ".", "__name__", ",", "config_scope", ")", "return", "config_scope" ]
Decorator to turn a function into a named configuration. See :ref:`named_configurations`.
[ "Decorator", "to", "turn", "a", "function", "into", "a", "named", "configuration", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L157-L165
224,518
IDSIA/sacred
sacred/ingredient.py
Ingredient.config_hook
def config_hook(self, func): """ Decorator to add a config hook to this ingredient. Config hooks need to be a function that takes 3 parameters and returns a dictionary: (config, command_name, logger) --> dict Config hooks are run after the configuration of this Ingredient, but before any further ingredient-configurations are run. The dictionary returned by a config hook is used to update the config updates. Note that they are not restricted to the local namespace of the ingredient. """ argspec = inspect.getargspec(func) args = ['config', 'command_name', 'logger'] if not (argspec.args == args and argspec.varargs is None and argspec.keywords is None and argspec.defaults is None): raise ValueError('Wrong signature for config_hook. Expected: ' '(config, command_name, logger)') self.config_hooks.append(func) return self.config_hooks[-1]
python
def config_hook(self, func): """ Decorator to add a config hook to this ingredient. Config hooks need to be a function that takes 3 parameters and returns a dictionary: (config, command_name, logger) --> dict Config hooks are run after the configuration of this Ingredient, but before any further ingredient-configurations are run. The dictionary returned by a config hook is used to update the config updates. Note that they are not restricted to the local namespace of the ingredient. """ argspec = inspect.getargspec(func) args = ['config', 'command_name', 'logger'] if not (argspec.args == args and argspec.varargs is None and argspec.keywords is None and argspec.defaults is None): raise ValueError('Wrong signature for config_hook. Expected: ' '(config, command_name, logger)') self.config_hooks.append(func) return self.config_hooks[-1]
[ "def", "config_hook", "(", "self", ",", "func", ")", ":", "argspec", "=", "inspect", ".", "getargspec", "(", "func", ")", "args", "=", "[", "'config'", ",", "'command_name'", ",", "'logger'", "]", "if", "not", "(", "argspec", ".", "args", "==", "args",...
Decorator to add a config hook to this ingredient. Config hooks need to be a function that takes 3 parameters and returns a dictionary: (config, command_name, logger) --> dict Config hooks are run after the configuration of this Ingredient, but before any further ingredient-configurations are run. The dictionary returned by a config hook is used to update the config updates. Note that they are not restricted to the local namespace of the ingredient.
[ "Decorator", "to", "add", "a", "config", "hook", "to", "this", "ingredient", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L167-L189
224,519
IDSIA/sacred
sacred/ingredient.py
Ingredient.add_package_dependency
def add_package_dependency(self, package_name, version): """ Add a package to the list of dependencies. :param package_name: The name of the package dependency :type package_name: str :param version: The (minimum) version of the package :type version: str """ if not PEP440_VERSION_PATTERN.match(version): raise ValueError('Invalid Version: "{}"'.format(version)) self.dependencies.add(PackageDependency(package_name, version))
python
def add_package_dependency(self, package_name, version): """ Add a package to the list of dependencies. :param package_name: The name of the package dependency :type package_name: str :param version: The (minimum) version of the package :type version: str """ if not PEP440_VERSION_PATTERN.match(version): raise ValueError('Invalid Version: "{}"'.format(version)) self.dependencies.add(PackageDependency(package_name, version))
[ "def", "add_package_dependency", "(", "self", ",", "package_name", ",", "version", ")", ":", "if", "not", "PEP440_VERSION_PATTERN", ".", "match", "(", "version", ")", ":", "raise", "ValueError", "(", "'Invalid Version: \"{}\"'", ".", "format", "(", "version", ")...
Add a package to the list of dependencies. :param package_name: The name of the package dependency :type package_name: str :param version: The (minimum) version of the package :type version: str
[ "Add", "a", "package", "to", "the", "list", "of", "dependencies", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L272-L283
224,520
IDSIA/sacred
sacred/ingredient.py
Ingredient._gather
def _gather(self, func): """ Function needed and used by gathering functions through the decorator `gather_from_ingredients` in `Ingredient`. Don't use this function by itself outside of the decorator! By overwriting this function you can filter what is visible when gathering something (e.g. commands). See `Experiment._gather` for an example. """ for ingredient, _ in self.traverse_ingredients(): for item in func(ingredient): yield item
python
def _gather(self, func): """ Function needed and used by gathering functions through the decorator `gather_from_ingredients` in `Ingredient`. Don't use this function by itself outside of the decorator! By overwriting this function you can filter what is visible when gathering something (e.g. commands). See `Experiment._gather` for an example. """ for ingredient, _ in self.traverse_ingredients(): for item in func(ingredient): yield item
[ "def", "_gather", "(", "self", ",", "func", ")", ":", "for", "ingredient", ",", "_", "in", "self", ".", "traverse_ingredients", "(", ")", ":", "for", "item", "in", "func", "(", "ingredient", ")", ":", "yield", "item" ]
Function needed and used by gathering functions through the decorator `gather_from_ingredients` in `Ingredient`. Don't use this function by itself outside of the decorator! By overwriting this function you can filter what is visible when gathering something (e.g. commands). See `Experiment._gather` for an example.
[ "Function", "needed", "and", "used", "by", "gathering", "functions", "through", "the", "decorator", "gather_from_ingredients", "in", "Ingredient", ".", "Don", "t", "use", "this", "function", "by", "itself", "outside", "of", "the", "decorator!" ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L285-L297
224,521
IDSIA/sacred
sacred/ingredient.py
Ingredient.gather_commands
def gather_commands(self, ingredient): """Collect all commands from this ingredient and its sub-ingredients. Yields ------ cmd_name: str The full (dotted) name of the command. cmd: function The corresponding captured function. """ for command_name, command in ingredient.commands.items(): yield join_paths(ingredient.path, command_name), command
python
def gather_commands(self, ingredient): """Collect all commands from this ingredient and its sub-ingredients. Yields ------ cmd_name: str The full (dotted) name of the command. cmd: function The corresponding captured function. """ for command_name, command in ingredient.commands.items(): yield join_paths(ingredient.path, command_name), command
[ "def", "gather_commands", "(", "self", ",", "ingredient", ")", ":", "for", "command_name", ",", "command", "in", "ingredient", ".", "commands", ".", "items", "(", ")", ":", "yield", "join_paths", "(", "ingredient", ".", "path", ",", "command_name", ")", ",...
Collect all commands from this ingredient and its sub-ingredients. Yields ------ cmd_name: str The full (dotted) name of the command. cmd: function The corresponding captured function.
[ "Collect", "all", "commands", "from", "this", "ingredient", "and", "its", "sub", "-", "ingredients", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L300-L311
224,522
IDSIA/sacred
sacred/ingredient.py
Ingredient.gather_named_configs
def gather_named_configs(self, ingredient): """Collect all named configs from this ingredient and its sub-ingredients. Yields ------ config_name: str The full (dotted) name of the named config. config: ConfigScope or ConfigDict or basestring The corresponding named config. """ for config_name, config in ingredient.named_configs.items(): yield join_paths(ingredient.path, config_name), config
python
def gather_named_configs(self, ingredient): """Collect all named configs from this ingredient and its sub-ingredients. Yields ------ config_name: str The full (dotted) name of the named config. config: ConfigScope or ConfigDict or basestring The corresponding named config. """ for config_name, config in ingredient.named_configs.items(): yield join_paths(ingredient.path, config_name), config
[ "def", "gather_named_configs", "(", "self", ",", "ingredient", ")", ":", "for", "config_name", ",", "config", "in", "ingredient", ".", "named_configs", ".", "items", "(", ")", ":", "yield", "join_paths", "(", "ingredient", ".", "path", ",", "config_name", ")...
Collect all named configs from this ingredient and its sub-ingredients. Yields ------ config_name: str The full (dotted) name of the named config. config: ConfigScope or ConfigDict or basestring The corresponding named config.
[ "Collect", "all", "named", "configs", "from", "this", "ingredient", "and", "its", "sub", "-", "ingredients", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L314-L326
224,523
IDSIA/sacred
sacred/ingredient.py
Ingredient.get_experiment_info
def get_experiment_info(self): """Get a dictionary with information about this experiment. Contains: * *name*: the name * *sources*: a list of sources (filename, md5) * *dependencies*: a list of package dependencies (name, version) :return: experiment information :rtype: dict """ dependencies = set() sources = set() for ing, _ in self.traverse_ingredients(): dependencies |= ing.dependencies sources |= ing.sources for dep in dependencies: dep.fill_missing_version() mainfile = (self.mainfile.to_json(self.base_dir)[0] if self.mainfile else None) def name_lower(d): return d.name.lower() return dict( name=self.path, base_dir=self.base_dir, sources=[s.to_json(self.base_dir) for s in sorted(sources)], dependencies=[d.to_json() for d in sorted(dependencies, key=name_lower)], repositories=collect_repositories(sources), mainfile=mainfile )
python
def get_experiment_info(self): """Get a dictionary with information about this experiment. Contains: * *name*: the name * *sources*: a list of sources (filename, md5) * *dependencies*: a list of package dependencies (name, version) :return: experiment information :rtype: dict """ dependencies = set() sources = set() for ing, _ in self.traverse_ingredients(): dependencies |= ing.dependencies sources |= ing.sources for dep in dependencies: dep.fill_missing_version() mainfile = (self.mainfile.to_json(self.base_dir)[0] if self.mainfile else None) def name_lower(d): return d.name.lower() return dict( name=self.path, base_dir=self.base_dir, sources=[s.to_json(self.base_dir) for s in sorted(sources)], dependencies=[d.to_json() for d in sorted(dependencies, key=name_lower)], repositories=collect_repositories(sources), mainfile=mainfile )
[ "def", "get_experiment_info", "(", "self", ")", ":", "dependencies", "=", "set", "(", ")", "sources", "=", "set", "(", ")", "for", "ing", ",", "_", "in", "self", ".", "traverse_ingredients", "(", ")", ":", "dependencies", "|=", "ing", ".", "dependencies"...
Get a dictionary with information about this experiment. Contains: * *name*: the name * *sources*: a list of sources (filename, md5) * *dependencies*: a list of package dependencies (name, version) :return: experiment information :rtype: dict
[ "Get", "a", "dictionary", "with", "information", "about", "this", "experiment", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L328-L362
224,524
IDSIA/sacred
sacred/ingredient.py
Ingredient.traverse_ingredients
def traverse_ingredients(self): """Recursively traverse this ingredient and its sub-ingredients. Yields ------ ingredient: sacred.Ingredient The ingredient as traversed in preorder. depth: int The depth of the ingredient starting from 0. Raises ------ CircularDependencyError: If a circular structure among ingredients was detected. """ if self._is_traversing: raise CircularDependencyError(ingredients=[self]) else: self._is_traversing = True yield self, 0 with CircularDependencyError.track(self): for ingredient in self.ingredients: for ingred, depth in ingredient.traverse_ingredients(): yield ingred, depth + 1 self._is_traversing = False
python
def traverse_ingredients(self): """Recursively traverse this ingredient and its sub-ingredients. Yields ------ ingredient: sacred.Ingredient The ingredient as traversed in preorder. depth: int The depth of the ingredient starting from 0. Raises ------ CircularDependencyError: If a circular structure among ingredients was detected. """ if self._is_traversing: raise CircularDependencyError(ingredients=[self]) else: self._is_traversing = True yield self, 0 with CircularDependencyError.track(self): for ingredient in self.ingredients: for ingred, depth in ingredient.traverse_ingredients(): yield ingred, depth + 1 self._is_traversing = False
[ "def", "traverse_ingredients", "(", "self", ")", ":", "if", "self", ".", "_is_traversing", ":", "raise", "CircularDependencyError", "(", "ingredients", "=", "[", "self", "]", ")", "else", ":", "self", ".", "_is_traversing", "=", "True", "yield", "self", ",",...
Recursively traverse this ingredient and its sub-ingredients. Yields ------ ingredient: sacred.Ingredient The ingredient as traversed in preorder. depth: int The depth of the ingredient starting from 0. Raises ------ CircularDependencyError: If a circular structure among ingredients was detected.
[ "Recursively", "traverse", "this", "ingredient", "and", "its", "sub", "-", "ingredients", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L364-L388
224,525
simonw/datasette
datasette/utils.py
path_from_row_pks
def path_from_row_pks(row, pks, use_rowid, quote=True): """ Generate an optionally URL-quoted unique identifier for a row from its primary keys.""" if use_rowid: bits = [row['rowid']] else: bits = [ row[pk]["value"] if isinstance(row[pk], dict) else row[pk] for pk in pks ] if quote: bits = [urllib.parse.quote_plus(str(bit)) for bit in bits] else: bits = [str(bit) for bit in bits] return ','.join(bits)
python
def path_from_row_pks(row, pks, use_rowid, quote=True): """ Generate an optionally URL-quoted unique identifier for a row from its primary keys.""" if use_rowid: bits = [row['rowid']] else: bits = [ row[pk]["value"] if isinstance(row[pk], dict) else row[pk] for pk in pks ] if quote: bits = [urllib.parse.quote_plus(str(bit)) for bit in bits] else: bits = [str(bit) for bit in bits] return ','.join(bits)
[ "def", "path_from_row_pks", "(", "row", ",", "pks", ",", "use_rowid", ",", "quote", "=", "True", ")", ":", "if", "use_rowid", ":", "bits", "=", "[", "row", "[", "'rowid'", "]", "]", "else", ":", "bits", "=", "[", "row", "[", "pk", "]", "[", "\"va...
Generate an optionally URL-quoted unique identifier for a row from its primary keys.
[ "Generate", "an", "optionally", "URL", "-", "quoted", "unique", "identifier", "for", "a", "row", "from", "its", "primary", "keys", "." ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/utils.py#L75-L90
224,526
simonw/datasette
datasette/utils.py
detect_primary_keys
def detect_primary_keys(conn, table): " Figure out primary keys for a table. " table_info_rows = [ row for row in conn.execute( 'PRAGMA table_info("{}")'.format(table) ).fetchall() if row[-1] ] table_info_rows.sort(key=lambda row: row[-1]) return [str(r[1]) for r in table_info_rows]
python
def detect_primary_keys(conn, table): " Figure out primary keys for a table. " table_info_rows = [ row for row in conn.execute( 'PRAGMA table_info("{}")'.format(table) ).fetchall() if row[-1] ] table_info_rows.sort(key=lambda row: row[-1]) return [str(r[1]) for r in table_info_rows]
[ "def", "detect_primary_keys", "(", "conn", ",", "table", ")", ":", "table_info_rows", "=", "[", "row", "for", "row", "in", "conn", ".", "execute", "(", "'PRAGMA table_info(\"{}\")'", ".", "format", "(", "table", ")", ")", ".", "fetchall", "(", ")", "if", ...
Figure out primary keys for a table.
[ "Figure", "out", "primary", "keys", "for", "a", "table", "." ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/utils.py#L478-L488
224,527
simonw/datasette
datasette/utils.py
detect_fts
def detect_fts(conn, table): "Detect if table has a corresponding FTS virtual table and return it" rows = conn.execute(detect_fts_sql(table)).fetchall() if len(rows) == 0: return None else: return rows[0][0]
python
def detect_fts(conn, table): "Detect if table has a corresponding FTS virtual table and return it" rows = conn.execute(detect_fts_sql(table)).fetchall() if len(rows) == 0: return None else: return rows[0][0]
[ "def", "detect_fts", "(", "conn", ",", "table", ")", ":", "rows", "=", "conn", ".", "execute", "(", "detect_fts_sql", "(", "table", ")", ")", ".", "fetchall", "(", ")", "if", "len", "(", "rows", ")", "==", "0", ":", "return", "None", "else", ":", ...
Detect if table has a corresponding FTS virtual table and return it
[ "Detect", "if", "table", "has", "a", "corresponding", "FTS", "virtual", "table", "and", "return", "it" ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/utils.py#L545-L551
224,528
simonw/datasette
datasette/app.py
Datasette.metadata
def metadata(self, key=None, database=None, table=None, fallback=True): """ Looks up metadata, cascading backwards from specified level. Returns None if metadata value is not found. """ assert not (database is None and table is not None), \ "Cannot call metadata() with table= specified but not database=" databases = self._metadata.get("databases") or {} search_list = [] if database is not None: search_list.append(databases.get(database) or {}) if table is not None: table_metadata = ( (databases.get(database) or {}).get("tables") or {} ).get(table) or {} search_list.insert(0, table_metadata) search_list.append(self._metadata) if not fallback: # No fallback allowed, so just use the first one in the list search_list = search_list[:1] if key is not None: for item in search_list: if key in item: return item[key] return None else: # Return the merged list m = {} for item in search_list: m.update(item) return m
python
def metadata(self, key=None, database=None, table=None, fallback=True): """ Looks up metadata, cascading backwards from specified level. Returns None if metadata value is not found. """ assert not (database is None and table is not None), \ "Cannot call metadata() with table= specified but not database=" databases = self._metadata.get("databases") or {} search_list = [] if database is not None: search_list.append(databases.get(database) or {}) if table is not None: table_metadata = ( (databases.get(database) or {}).get("tables") or {} ).get(table) or {} search_list.insert(0, table_metadata) search_list.append(self._metadata) if not fallback: # No fallback allowed, so just use the first one in the list search_list = search_list[:1] if key is not None: for item in search_list: if key in item: return item[key] return None else: # Return the merged list m = {} for item in search_list: m.update(item) return m
[ "def", "metadata", "(", "self", ",", "key", "=", "None", ",", "database", "=", "None", ",", "table", "=", "None", ",", "fallback", "=", "True", ")", ":", "assert", "not", "(", "database", "is", "None", "and", "table", "is", "not", "None", ")", ",",...
Looks up metadata, cascading backwards from specified level. Returns None if metadata value is not found.
[ "Looks", "up", "metadata", "cascading", "backwards", "from", "specified", "level", ".", "Returns", "None", "if", "metadata", "value", "is", "not", "found", "." ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/app.py#L239-L269
224,529
simonw/datasette
datasette/app.py
Datasette.inspect
def inspect(self): " Inspect the database and return a dictionary of table metadata " if self._inspect: return self._inspect self._inspect = {} for filename in self.files: if filename is MEMORY: self._inspect[":memory:"] = { "hash": "000", "file": ":memory:", "size": 0, "views": {}, "tables": {}, } else: path = Path(filename) name = path.stem if name in self._inspect: raise Exception("Multiple files with same stem %s" % name) try: with sqlite3.connect( "file:{}?mode=ro".format(path), uri=True ) as conn: self.prepare_connection(conn) self._inspect[name] = { "hash": inspect_hash(path), "file": str(path), "size": path.stat().st_size, "views": inspect_views(conn), "tables": inspect_tables(conn, (self.metadata("databases") or {}).get(name, {})) } except sqlite3.OperationalError as e: if (e.args[0] == 'no such module: VirtualSpatialIndex'): raise click.UsageError( "It looks like you're trying to load a SpatiaLite" " database without first loading the SpatiaLite module." "\n\nRead more: https://datasette.readthedocs.io/en/latest/spatialite.html" ) else: raise return self._inspect
python
def inspect(self): " Inspect the database and return a dictionary of table metadata " if self._inspect: return self._inspect self._inspect = {} for filename in self.files: if filename is MEMORY: self._inspect[":memory:"] = { "hash": "000", "file": ":memory:", "size": 0, "views": {}, "tables": {}, } else: path = Path(filename) name = path.stem if name in self._inspect: raise Exception("Multiple files with same stem %s" % name) try: with sqlite3.connect( "file:{}?mode=ro".format(path), uri=True ) as conn: self.prepare_connection(conn) self._inspect[name] = { "hash": inspect_hash(path), "file": str(path), "size": path.stat().st_size, "views": inspect_views(conn), "tables": inspect_tables(conn, (self.metadata("databases") or {}).get(name, {})) } except sqlite3.OperationalError as e: if (e.args[0] == 'no such module: VirtualSpatialIndex'): raise click.UsageError( "It looks like you're trying to load a SpatiaLite" " database without first loading the SpatiaLite module." "\n\nRead more: https://datasette.readthedocs.io/en/latest/spatialite.html" ) else: raise return self._inspect
[ "def", "inspect", "(", "self", ")", ":", "if", "self", ".", "_inspect", ":", "return", "self", ".", "_inspect", "self", ".", "_inspect", "=", "{", "}", "for", "filename", "in", "self", ".", "files", ":", "if", "filename", "is", "MEMORY", ":", "self",...
Inspect the database and return a dictionary of table metadata
[ "Inspect", "the", "database", "and", "return", "a", "dictionary", "of", "table", "metadata" ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/app.py#L414-L455
224,530
simonw/datasette
datasette/app.py
Datasette.table_metadata
def table_metadata(self, database, table): "Fetch table-specific metadata." return (self.metadata("databases") or {}).get(database, {}).get( "tables", {} ).get( table, {} )
python
def table_metadata(self, database, table): "Fetch table-specific metadata." return (self.metadata("databases") or {}).get(database, {}).get( "tables", {} ).get( table, {} )
[ "def", "table_metadata", "(", "self", ",", "database", ",", "table", ")", ":", "return", "(", "self", ".", "metadata", "(", "\"databases\"", ")", "or", "{", "}", ")", ".", "get", "(", "database", ",", "{", "}", ")", ".", "get", "(", "\"tables\"", "...
Fetch table-specific metadata.
[ "Fetch", "table", "-", "specific", "metadata", "." ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/app.py#L521-L527
224,531
simonw/datasette
datasette/app.py
Datasette.execute
async def execute( self, db_name, sql, params=None, truncate=False, custom_time_limit=None, page_size=None, ): """Executes sql against db_name in a thread""" page_size = page_size or self.page_size def sql_operation_in_thread(conn): time_limit_ms = self.sql_time_limit_ms if custom_time_limit and custom_time_limit < time_limit_ms: time_limit_ms = custom_time_limit with sqlite_timelimit(conn, time_limit_ms): try: cursor = conn.cursor() cursor.execute(sql, params or {}) max_returned_rows = self.max_returned_rows if max_returned_rows == page_size: max_returned_rows += 1 if max_returned_rows and truncate: rows = cursor.fetchmany(max_returned_rows + 1) truncated = len(rows) > max_returned_rows rows = rows[:max_returned_rows] else: rows = cursor.fetchall() truncated = False except sqlite3.OperationalError as e: if e.args == ('interrupted',): raise InterruptedError(e) print( "ERROR: conn={}, sql = {}, params = {}: {}".format( conn, repr(sql), params, e ) ) raise if truncate: return Results(rows, truncated, cursor.description) else: return Results(rows, False, cursor.description) with trace("sql", (db_name, sql.strip(), params)): results = await self.execute_against_connection_in_thread( db_name, sql_operation_in_thread ) return results
python
async def execute( self, db_name, sql, params=None, truncate=False, custom_time_limit=None, page_size=None, ): """Executes sql against db_name in a thread""" page_size = page_size or self.page_size def sql_operation_in_thread(conn): time_limit_ms = self.sql_time_limit_ms if custom_time_limit and custom_time_limit < time_limit_ms: time_limit_ms = custom_time_limit with sqlite_timelimit(conn, time_limit_ms): try: cursor = conn.cursor() cursor.execute(sql, params or {}) max_returned_rows = self.max_returned_rows if max_returned_rows == page_size: max_returned_rows += 1 if max_returned_rows and truncate: rows = cursor.fetchmany(max_returned_rows + 1) truncated = len(rows) > max_returned_rows rows = rows[:max_returned_rows] else: rows = cursor.fetchall() truncated = False except sqlite3.OperationalError as e: if e.args == ('interrupted',): raise InterruptedError(e) print( "ERROR: conn={}, sql = {}, params = {}: {}".format( conn, repr(sql), params, e ) ) raise if truncate: return Results(rows, truncated, cursor.description) else: return Results(rows, False, cursor.description) with trace("sql", (db_name, sql.strip(), params)): results = await self.execute_against_connection_in_thread( db_name, sql_operation_in_thread ) return results
[ "async", "def", "execute", "(", "self", ",", "db_name", ",", "sql", ",", "params", "=", "None", ",", "truncate", "=", "False", ",", "custom_time_limit", "=", "None", ",", "page_size", "=", "None", ",", ")", ":", "page_size", "=", "page_size", "or", "se...
Executes sql against db_name in a thread
[ "Executes", "sql", "against", "db_name", "in", "a", "thread" ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/app.py#L580-L631
224,532
simonw/datasette
datasette/inspect.py
inspect_hash
def inspect_hash(path): " Calculate the hash of a database, efficiently. " m = hashlib.sha256() with path.open("rb") as fp: while True: data = fp.read(HASH_BLOCK_SIZE) if not data: break m.update(data) return m.hexdigest()
python
def inspect_hash(path): " Calculate the hash of a database, efficiently. " m = hashlib.sha256() with path.open("rb") as fp: while True: data = fp.read(HASH_BLOCK_SIZE) if not data: break m.update(data) return m.hexdigest()
[ "def", "inspect_hash", "(", "path", ")", ":", "m", "=", "hashlib", ".", "sha256", "(", ")", "with", "path", ".", "open", "(", "\"rb\"", ")", "as", "fp", ":", "while", "True", ":", "data", "=", "fp", ".", "read", "(", "HASH_BLOCK_SIZE", ")", "if", ...
Calculate the hash of a database, efficiently.
[ "Calculate", "the", "hash", "of", "a", "database", "efficiently", "." ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/inspect.py#L17-L27
224,533
simonw/datasette
datasette/inspect.py
inspect_tables
def inspect_tables(conn, database_metadata): " List tables and their row counts, excluding uninteresting tables. " tables = {} table_names = [ r["name"] for r in conn.execute( 'select * from sqlite_master where type="table"' ) ] for table in table_names: table_metadata = database_metadata.get("tables", {}).get( table, {} ) try: count = conn.execute( "select count(*) from {}".format(escape_sqlite(table)) ).fetchone()[0] except sqlite3.OperationalError: # This can happen when running against a FTS virtual table # e.g. "select count(*) from some_fts;" count = 0 column_names = table_columns(conn, table) tables[table] = { "name": table, "columns": column_names, "primary_keys": detect_primary_keys(conn, table), "count": count, "hidden": table_metadata.get("hidden") or False, "fts_table": detect_fts(conn, table), } foreign_keys = get_all_foreign_keys(conn) for table, info in foreign_keys.items(): tables[table]["foreign_keys"] = info # Mark tables 'hidden' if they relate to FTS virtual tables hidden_tables = [ r["name"] for r in conn.execute( """ select name from sqlite_master where rootpage = 0 and sql like '%VIRTUAL TABLE%USING FTS%' """ ) ] if detect_spatialite(conn): # Also hide Spatialite internal tables hidden_tables += [ "ElementaryGeometries", "SpatialIndex", "geometry_columns", "spatial_ref_sys", "spatialite_history", "sql_statements_log", "sqlite_sequence", "views_geometry_columns", "virts_geometry_columns", ] + [ r["name"] for r in conn.execute( """ select name from sqlite_master where name like "idx_%" and type = "table" """ ) ] for t in tables.keys(): for hidden_table in hidden_tables: if t == hidden_table or t.startswith(hidden_table): tables[t]["hidden"] = True continue return tables
python
def inspect_tables(conn, database_metadata): " List tables and their row counts, excluding uninteresting tables. " tables = {} table_names = [ r["name"] for r in conn.execute( 'select * from sqlite_master where type="table"' ) ] for table in table_names: table_metadata = database_metadata.get("tables", {}).get( table, {} ) try: count = conn.execute( "select count(*) from {}".format(escape_sqlite(table)) ).fetchone()[0] except sqlite3.OperationalError: # This can happen when running against a FTS virtual table # e.g. "select count(*) from some_fts;" count = 0 column_names = table_columns(conn, table) tables[table] = { "name": table, "columns": column_names, "primary_keys": detect_primary_keys(conn, table), "count": count, "hidden": table_metadata.get("hidden") or False, "fts_table": detect_fts(conn, table), } foreign_keys = get_all_foreign_keys(conn) for table, info in foreign_keys.items(): tables[table]["foreign_keys"] = info # Mark tables 'hidden' if they relate to FTS virtual tables hidden_tables = [ r["name"] for r in conn.execute( """ select name from sqlite_master where rootpage = 0 and sql like '%VIRTUAL TABLE%USING FTS%' """ ) ] if detect_spatialite(conn): # Also hide Spatialite internal tables hidden_tables += [ "ElementaryGeometries", "SpatialIndex", "geometry_columns", "spatial_ref_sys", "spatialite_history", "sql_statements_log", "sqlite_sequence", "views_geometry_columns", "virts_geometry_columns", ] + [ r["name"] for r in conn.execute( """ select name from sqlite_master where name like "idx_%" and type = "table" """ ) ] for t in tables.keys(): for hidden_table in hidden_tables: if t == hidden_table or t.startswith(hidden_table): tables[t]["hidden"] = True continue return tables
[ "def", "inspect_tables", "(", "conn", ",", "database_metadata", ")", ":", "tables", "=", "{", "}", "table_names", "=", "[", "r", "[", "\"name\"", "]", "for", "r", "in", "conn", ".", "execute", "(", "'select * from sqlite_master where type=\"table\"'", ")", "]"...
List tables and their row counts, excluding uninteresting tables.
[ "List", "tables", "and", "their", "row", "counts", "excluding", "uninteresting", "tables", "." ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/inspect.py#L35-L115
224,534
simonw/datasette
datasette/filters.py
Filters.convert_unit
def convert_unit(self, column, value): "If the user has provided a unit in the query, convert it into the column unit, if present." if column not in self.units: return value # Try to interpret the value as a unit value = self.ureg(value) if isinstance(value, numbers.Number): # It's just a bare number, assume it's the column unit return value column_unit = self.ureg(self.units[column]) return value.to(column_unit).magnitude
python
def convert_unit(self, column, value): "If the user has provided a unit in the query, convert it into the column unit, if present." if column not in self.units: return value # Try to interpret the value as a unit value = self.ureg(value) if isinstance(value, numbers.Number): # It's just a bare number, assume it's the column unit return value column_unit = self.ureg(self.units[column]) return value.to(column_unit).magnitude
[ "def", "convert_unit", "(", "self", ",", "column", ",", "value", ")", ":", "if", "column", "not", "in", "self", ".", "units", ":", "return", "value", "# Try to interpret the value as a unit", "value", "=", "self", ".", "ureg", "(", "value", ")", "if", "isi...
If the user has provided a unit in the query, convert it into the column unit, if present.
[ "If", "the", "user", "has", "provided", "a", "unit", "in", "the", "query", "convert", "it", "into", "the", "column", "unit", "if", "present", "." ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/filters.py#L156-L168
224,535
simonw/datasette
datasette/cli.py
skeleton
def skeleton(files, metadata, sqlite_extensions): "Generate a skeleton metadata.json file for specified SQLite databases" if os.path.exists(metadata): click.secho( "File {} already exists, will not over-write".format(metadata), bg="red", fg="white", bold=True, err=True, ) sys.exit(1) app = Datasette(files, sqlite_extensions=sqlite_extensions) databases = {} for database_name, info in app.inspect().items(): databases[database_name] = { "title": None, "description": None, "description_html": None, "license": None, "license_url": None, "source": None, "source_url": None, "queries": {}, "tables": { table_name: { "title": None, "description": None, "description_html": None, "license": None, "license_url": None, "source": None, "source_url": None, "units": {}, } for table_name in (info.get("tables") or {}) }, } open(metadata, "w").write( json.dumps( { "title": None, "description": None, "description_html": None, "license": None, "license_url": None, "source": None, "source_url": None, "databases": databases, }, indent=4, ) ) click.echo("Wrote skeleton to {}".format(metadata))
python
def skeleton(files, metadata, sqlite_extensions): "Generate a skeleton metadata.json file for specified SQLite databases" if os.path.exists(metadata): click.secho( "File {} already exists, will not over-write".format(metadata), bg="red", fg="white", bold=True, err=True, ) sys.exit(1) app = Datasette(files, sqlite_extensions=sqlite_extensions) databases = {} for database_name, info in app.inspect().items(): databases[database_name] = { "title": None, "description": None, "description_html": None, "license": None, "license_url": None, "source": None, "source_url": None, "queries": {}, "tables": { table_name: { "title": None, "description": None, "description_html": None, "license": None, "license_url": None, "source": None, "source_url": None, "units": {}, } for table_name in (info.get("tables") or {}) }, } open(metadata, "w").write( json.dumps( { "title": None, "description": None, "description_html": None, "license": None, "license_url": None, "source": None, "source_url": None, "databases": databases, }, indent=4, ) ) click.echo("Wrote skeleton to {}".format(metadata))
[ "def", "skeleton", "(", "files", ",", "metadata", ",", "sqlite_extensions", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "metadata", ")", ":", "click", ".", "secho", "(", "\"File {} already exists, will not over-write\"", ".", "format", "(", "metadat...
Generate a skeleton metadata.json file for specified SQLite databases
[ "Generate", "a", "skeleton", "metadata", ".", "json", "file", "for", "specified", "SQLite", "databases" ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/cli.py#L107-L159
224,536
simonw/datasette
datasette/cli.py
plugins
def plugins(all, plugins_dir): "List currently available plugins" app = Datasette([], plugins_dir=plugins_dir) click.echo(json.dumps(app.plugins(all), indent=4))
python
def plugins(all, plugins_dir): "List currently available plugins" app = Datasette([], plugins_dir=plugins_dir) click.echo(json.dumps(app.plugins(all), indent=4))
[ "def", "plugins", "(", "all", ",", "plugins_dir", ")", ":", "app", "=", "Datasette", "(", "[", "]", ",", "plugins_dir", "=", "plugins_dir", ")", "click", ".", "echo", "(", "json", ".", "dumps", "(", "app", ".", "plugins", "(", "all", ")", ",", "ind...
List currently available plugins
[ "List", "currently", "available", "plugins" ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/cli.py#L169-L172
224,537
simonw/datasette
datasette/cli.py
package
def package( files, tag, metadata, extra_options, branch, template_dir, plugins_dir, static, install, spatialite, version_note, **extra_metadata ): "Package specified SQLite files into a new datasette Docker container" if not shutil.which("docker"): click.secho( ' The package command requires "docker" to be installed and configured ', bg="red", fg="white", bold=True, err=True, ) sys.exit(1) with temporary_docker_directory( files, "datasette", metadata, extra_options, branch, template_dir, plugins_dir, static, install, spatialite, version_note, extra_metadata, ): args = ["docker", "build"] if tag: args.append("-t") args.append(tag) args.append(".") call(args)
python
def package( files, tag, metadata, extra_options, branch, template_dir, plugins_dir, static, install, spatialite, version_note, **extra_metadata ): "Package specified SQLite files into a new datasette Docker container" if not shutil.which("docker"): click.secho( ' The package command requires "docker" to be installed and configured ', bg="red", fg="white", bold=True, err=True, ) sys.exit(1) with temporary_docker_directory( files, "datasette", metadata, extra_options, branch, template_dir, plugins_dir, static, install, spatialite, version_note, extra_metadata, ): args = ["docker", "build"] if tag: args.append("-t") args.append(tag) args.append(".") call(args)
[ "def", "package", "(", "files", ",", "tag", ",", "metadata", ",", "extra_options", ",", "branch", ",", "template_dir", ",", "plugins_dir", ",", "static", ",", "install", ",", "spatialite", ",", "version_note", ",", "*", "*", "extra_metadata", ")", ":", "if...
Package specified SQLite files into a new datasette Docker container
[ "Package", "specified", "SQLite", "files", "into", "a", "new", "datasette", "Docker", "container" ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/cli.py#L222-L265
224,538
simonw/datasette
datasette/cli.py
serve
def serve( files, immutable, host, port, debug, reload, cors, sqlite_extensions, inspect_file, metadata, template_dir, plugins_dir, static, memory, config, version_note, help_config, ): """Serve up specified SQLite database files with a web UI""" if help_config: formatter = formatting.HelpFormatter() with formatter.section("Config options"): formatter.write_dl([ (option.name, '{} (default={})'.format( option.help, option.default )) for option in CONFIG_OPTIONS ]) click.echo(formatter.getvalue()) sys.exit(0) if reload: import hupper reloader = hupper.start_reloader("datasette.cli.serve") reloader.watch_files(files) if metadata: reloader.watch_files([metadata.name]) inspect_data = None if inspect_file: inspect_data = json.load(open(inspect_file)) metadata_data = None if metadata: metadata_data = json.loads(metadata.read()) click.echo("Serve! files={} (immutables={}) on port {}".format(files, immutable, port)) ds = Datasette( files, immutables=immutable, cache_headers=not debug and not reload, cors=cors, inspect_data=inspect_data, metadata=metadata_data, sqlite_extensions=sqlite_extensions, template_dir=template_dir, plugins_dir=plugins_dir, static_mounts=static, config=dict(config), memory=memory, version_note=version_note, ) # Force initial hashing/table counting ds.inspect() ds.app().run(host=host, port=port, debug=debug)
python
def serve( files, immutable, host, port, debug, reload, cors, sqlite_extensions, inspect_file, metadata, template_dir, plugins_dir, static, memory, config, version_note, help_config, ): """Serve up specified SQLite database files with a web UI""" if help_config: formatter = formatting.HelpFormatter() with formatter.section("Config options"): formatter.write_dl([ (option.name, '{} (default={})'.format( option.help, option.default )) for option in CONFIG_OPTIONS ]) click.echo(formatter.getvalue()) sys.exit(0) if reload: import hupper reloader = hupper.start_reloader("datasette.cli.serve") reloader.watch_files(files) if metadata: reloader.watch_files([metadata.name]) inspect_data = None if inspect_file: inspect_data = json.load(open(inspect_file)) metadata_data = None if metadata: metadata_data = json.loads(metadata.read()) click.echo("Serve! files={} (immutables={}) on port {}".format(files, immutable, port)) ds = Datasette( files, immutables=immutable, cache_headers=not debug and not reload, cors=cors, inspect_data=inspect_data, metadata=metadata_data, sqlite_extensions=sqlite_extensions, template_dir=template_dir, plugins_dir=plugins_dir, static_mounts=static, config=dict(config), memory=memory, version_note=version_note, ) # Force initial hashing/table counting ds.inspect() ds.app().run(host=host, port=port, debug=debug)
[ "def", "serve", "(", "files", ",", "immutable", ",", "host", ",", "port", ",", "debug", ",", "reload", ",", "cors", ",", "sqlite_extensions", ",", "inspect_file", ",", "metadata", ",", "template_dir", ",", "plugins_dir", ",", "static", ",", "memory", ",", ...
Serve up specified SQLite database files with a web UI
[ "Serve", "up", "specified", "SQLite", "database", "files", "with", "a", "web", "UI" ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/cli.py#L340-L405
224,539
ResidentMario/missingno
missingno/missingno.py
bar
def bar(df, figsize=(24, 10), fontsize=16, labels=None, log=False, color='dimgray', inline=False, filter=None, n=0, p=0, sort=None): """ A bar chart visualization of the nullity of the given DataFrame. :param df: The input DataFrame. :param log: Whether or not to display a logorithmic plot. Defaults to False (linear). :param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default). :param n: The cap on the number of columns to include in the filtered DataFrame. :param p: The cap on the percentage fill of the columns in the filtered DataFrame. :param sort: The sort to apply to the heatmap. Should be one of "ascending", "descending", or None (default). :param figsize: The size of the figure to display. :param fontsize: The figure's font size. This default to 16. :param labels: Whether or not to display the column names. Would need to be turned off on particularly large displays. Defaults to True. :param color: The color of the filled columns. Default to the RGB multiple `(0.25, 0.25, 0.25)`. :return: If `inline` is False, the underlying `matplotlib.figure` object. Else, nothing. """ nullity_counts = len(df) - df.isnull().sum() df = nullity_filter(df, filter=filter, n=n, p=p) df = nullity_sort(df, sort=sort) plt.figure(figsize=figsize) (nullity_counts / len(df)).plot(kind='bar', figsize=figsize, fontsize=fontsize, log=log, color=color) ax1 = plt.gca() axes = [ax1] # Start appending elements, starting with a modified bottom x axis. if labels or (labels is None and len(df.columns) <= 50): ax1.set_xticklabels(ax1.get_xticklabels(), rotation=45, ha='right', fontsize=fontsize) # Create the numerical ticks. ax2 = ax1.twinx() axes.append(ax2) if not log: ax1.set_ylim([0, 1]) ax2.set_yticks(ax1.get_yticks()) ax2.set_yticklabels([int(n*len(df)) for n in ax1.get_yticks()], fontsize=fontsize) else: # For some reason when a logarithmic plot is specified `ax1` always contains two more ticks than actually # appears in the plot. The fix is to ignore the first and last entries. Also note that when a log scale # is used, we have to make it match the `ax1` layout ourselves. ax2.set_yscale('log') ax2.set_ylim(ax1.get_ylim()) ax2.set_yticklabels([int(n*len(df)) for n in ax1.get_yticks()], fontsize=fontsize) else: ax1.set_xticks([]) # Create the third axis, which displays columnar totals above the rest of the plot. ax3 = ax1.twiny() axes.append(ax3) ax3.set_xticks(ax1.get_xticks()) ax3.set_xlim(ax1.get_xlim()) ax3.set_xticklabels(nullity_counts.values, fontsize=fontsize, rotation=45, ha='left') ax3.grid(False) for ax in axes: ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['bottom'].set_visible(False) ax.spines['left'].set_visible(False) ax.xaxis.set_ticks_position('none') ax.yaxis.set_ticks_position('none') if inline: plt.show() else: return ax1
python
def bar(df, figsize=(24, 10), fontsize=16, labels=None, log=False, color='dimgray', inline=False, filter=None, n=0, p=0, sort=None): """ A bar chart visualization of the nullity of the given DataFrame. :param df: The input DataFrame. :param log: Whether or not to display a logorithmic plot. Defaults to False (linear). :param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default). :param n: The cap on the number of columns to include in the filtered DataFrame. :param p: The cap on the percentage fill of the columns in the filtered DataFrame. :param sort: The sort to apply to the heatmap. Should be one of "ascending", "descending", or None (default). :param figsize: The size of the figure to display. :param fontsize: The figure's font size. This default to 16. :param labels: Whether or not to display the column names. Would need to be turned off on particularly large displays. Defaults to True. :param color: The color of the filled columns. Default to the RGB multiple `(0.25, 0.25, 0.25)`. :return: If `inline` is False, the underlying `matplotlib.figure` object. Else, nothing. """ nullity_counts = len(df) - df.isnull().sum() df = nullity_filter(df, filter=filter, n=n, p=p) df = nullity_sort(df, sort=sort) plt.figure(figsize=figsize) (nullity_counts / len(df)).plot(kind='bar', figsize=figsize, fontsize=fontsize, log=log, color=color) ax1 = plt.gca() axes = [ax1] # Start appending elements, starting with a modified bottom x axis. if labels or (labels is None and len(df.columns) <= 50): ax1.set_xticklabels(ax1.get_xticklabels(), rotation=45, ha='right', fontsize=fontsize) # Create the numerical ticks. ax2 = ax1.twinx() axes.append(ax2) if not log: ax1.set_ylim([0, 1]) ax2.set_yticks(ax1.get_yticks()) ax2.set_yticklabels([int(n*len(df)) for n in ax1.get_yticks()], fontsize=fontsize) else: # For some reason when a logarithmic plot is specified `ax1` always contains two more ticks than actually # appears in the plot. The fix is to ignore the first and last entries. Also note that when a log scale # is used, we have to make it match the `ax1` layout ourselves. ax2.set_yscale('log') ax2.set_ylim(ax1.get_ylim()) ax2.set_yticklabels([int(n*len(df)) for n in ax1.get_yticks()], fontsize=fontsize) else: ax1.set_xticks([]) # Create the third axis, which displays columnar totals above the rest of the plot. ax3 = ax1.twiny() axes.append(ax3) ax3.set_xticks(ax1.get_xticks()) ax3.set_xlim(ax1.get_xlim()) ax3.set_xticklabels(nullity_counts.values, fontsize=fontsize, rotation=45, ha='left') ax3.grid(False) for ax in axes: ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['bottom'].set_visible(False) ax.spines['left'].set_visible(False) ax.xaxis.set_ticks_position('none') ax.yaxis.set_ticks_position('none') if inline: plt.show() else: return ax1
[ "def", "bar", "(", "df", ",", "figsize", "=", "(", "24", ",", "10", ")", ",", "fontsize", "=", "16", ",", "labels", "=", "None", ",", "log", "=", "False", ",", "color", "=", "'dimgray'", ",", "inline", "=", "False", ",", "filter", "=", "None", ...
A bar chart visualization of the nullity of the given DataFrame. :param df: The input DataFrame. :param log: Whether or not to display a logorithmic plot. Defaults to False (linear). :param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default). :param n: The cap on the number of columns to include in the filtered DataFrame. :param p: The cap on the percentage fill of the columns in the filtered DataFrame. :param sort: The sort to apply to the heatmap. Should be one of "ascending", "descending", or None (default). :param figsize: The size of the figure to display. :param fontsize: The figure's font size. This default to 16. :param labels: Whether or not to display the column names. Would need to be turned off on particularly large displays. Defaults to True. :param color: The color of the filled columns. Default to the RGB multiple `(0.25, 0.25, 0.25)`. :return: If `inline` is False, the underlying `matplotlib.figure` object. Else, nothing.
[ "A", "bar", "chart", "visualization", "of", "the", "nullity", "of", "the", "given", "DataFrame", "." ]
1d67f91fbab0695a919c6bb72c796db57024e0ca
https://github.com/ResidentMario/missingno/blob/1d67f91fbab0695a919c6bb72c796db57024e0ca/missingno/missingno.py#L195-L263
224,540
ResidentMario/missingno
missingno/missingno.py
heatmap
def heatmap(df, inline=False, filter=None, n=0, p=0, sort=None, figsize=(20, 12), fontsize=16, labels=True, cmap='RdBu', vmin=-1, vmax=1, cbar=True ): """ Presents a `seaborn` heatmap visualization of nullity correlation in the given DataFrame. Note that this visualization has no special support for large datasets. For those, try the dendrogram instead. :param df: The DataFrame whose completeness is being heatmapped. :param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default). See `nullity_filter()` for more information. :param n: The cap on the number of columns to include in the filtered DataFrame. See `nullity_filter()` for more information. :param p: The cap on the percentage fill of the columns in the filtered DataFrame. See `nullity_filter()` for more information. :param sort: The sort to apply to the heatmap. Should be one of "ascending", "descending", or None. See `nullity_sort()` for more information. :param figsize: The size of the figure to display. This is a `matplotlib` parameter which defaults to (20, 12). :param fontsize: The figure's font size. :param labels: Whether or not to label each matrix entry with its correlation (default is True). :param cmap: What `matplotlib` colormap to use. Defaults to `RdBu`. :param vmin: The normalized colormap threshold. Defaults to -1, e.g. the bottom of the color scale. :param vmax: The normalized colormap threshold. Defaults to 1, e.g. the bottom of the color scale. :param inline: Whether or not the figure is inline. If it's not then instead of getting plotted, this method will return its figure. :return: If `inline` is False, the underlying `matplotlib.figure` object. Else, nothing. """ # Apply filters and sorts, set up the figure. df = nullity_filter(df, filter=filter, n=n, p=p) df = nullity_sort(df, sort=sort) plt.figure(figsize=figsize) gs = gridspec.GridSpec(1, 1) ax0 = plt.subplot(gs[0]) # Remove completely filled or completely empty variables. df = df.iloc[:,[i for i, n in enumerate(np.var(df.isnull(), axis='rows')) if n > 0]] # Create and mask the correlation matrix. Construct the base heatmap. corr_mat = df.isnull().corr() mask = np.zeros_like(corr_mat) mask[np.triu_indices_from(mask)] = True if labels: sns.heatmap(corr_mat, mask=mask, cmap=cmap, ax=ax0, cbar=cbar, annot=True, annot_kws={'size': fontsize - 2}, vmin=vmin, vmax=vmax) else: sns.heatmap(corr_mat, mask=mask, cmap=cmap, ax=ax0, cbar=cbar, vmin=vmin, vmax=vmax) # Apply visual corrections and modifications. ax0.xaxis.tick_bottom() ax0.set_xticklabels(ax0.xaxis.get_majorticklabels(), rotation=45, ha='right', fontsize=fontsize) ax0.set_yticklabels(ax0.yaxis.get_majorticklabels(), fontsize=fontsize, rotation=0) ax0.set_yticklabels(ax0.yaxis.get_majorticklabels(), rotation=0, fontsize=fontsize) ax0.xaxis.set_ticks_position('none') ax0.yaxis.set_ticks_position('none') ax0.patch.set_visible(False) for text in ax0.texts: t = float(text.get_text()) if 0.95 <= t < 1: text.set_text('<1') elif -1 < t <= -0.95: text.set_text('>-1') elif t == 1: text.set_text('1') elif t == -1: text.set_text('-1') elif -0.05 < t < 0.05: text.set_text('') else: text.set_text(round(t, 1)) if inline: plt.show() else: return ax0
python
def heatmap(df, inline=False, filter=None, n=0, p=0, sort=None, figsize=(20, 12), fontsize=16, labels=True, cmap='RdBu', vmin=-1, vmax=1, cbar=True ): """ Presents a `seaborn` heatmap visualization of nullity correlation in the given DataFrame. Note that this visualization has no special support for large datasets. For those, try the dendrogram instead. :param df: The DataFrame whose completeness is being heatmapped. :param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default). See `nullity_filter()` for more information. :param n: The cap on the number of columns to include in the filtered DataFrame. See `nullity_filter()` for more information. :param p: The cap on the percentage fill of the columns in the filtered DataFrame. See `nullity_filter()` for more information. :param sort: The sort to apply to the heatmap. Should be one of "ascending", "descending", or None. See `nullity_sort()` for more information. :param figsize: The size of the figure to display. This is a `matplotlib` parameter which defaults to (20, 12). :param fontsize: The figure's font size. :param labels: Whether or not to label each matrix entry with its correlation (default is True). :param cmap: What `matplotlib` colormap to use. Defaults to `RdBu`. :param vmin: The normalized colormap threshold. Defaults to -1, e.g. the bottom of the color scale. :param vmax: The normalized colormap threshold. Defaults to 1, e.g. the bottom of the color scale. :param inline: Whether or not the figure is inline. If it's not then instead of getting plotted, this method will return its figure. :return: If `inline` is False, the underlying `matplotlib.figure` object. Else, nothing. """ # Apply filters and sorts, set up the figure. df = nullity_filter(df, filter=filter, n=n, p=p) df = nullity_sort(df, sort=sort) plt.figure(figsize=figsize) gs = gridspec.GridSpec(1, 1) ax0 = plt.subplot(gs[0]) # Remove completely filled or completely empty variables. df = df.iloc[:,[i for i, n in enumerate(np.var(df.isnull(), axis='rows')) if n > 0]] # Create and mask the correlation matrix. Construct the base heatmap. corr_mat = df.isnull().corr() mask = np.zeros_like(corr_mat) mask[np.triu_indices_from(mask)] = True if labels: sns.heatmap(corr_mat, mask=mask, cmap=cmap, ax=ax0, cbar=cbar, annot=True, annot_kws={'size': fontsize - 2}, vmin=vmin, vmax=vmax) else: sns.heatmap(corr_mat, mask=mask, cmap=cmap, ax=ax0, cbar=cbar, vmin=vmin, vmax=vmax) # Apply visual corrections and modifications. ax0.xaxis.tick_bottom() ax0.set_xticklabels(ax0.xaxis.get_majorticklabels(), rotation=45, ha='right', fontsize=fontsize) ax0.set_yticklabels(ax0.yaxis.get_majorticklabels(), fontsize=fontsize, rotation=0) ax0.set_yticklabels(ax0.yaxis.get_majorticklabels(), rotation=0, fontsize=fontsize) ax0.xaxis.set_ticks_position('none') ax0.yaxis.set_ticks_position('none') ax0.patch.set_visible(False) for text in ax0.texts: t = float(text.get_text()) if 0.95 <= t < 1: text.set_text('<1') elif -1 < t <= -0.95: text.set_text('>-1') elif t == 1: text.set_text('1') elif t == -1: text.set_text('-1') elif -0.05 < t < 0.05: text.set_text('') else: text.set_text(round(t, 1)) if inline: plt.show() else: return ax0
[ "def", "heatmap", "(", "df", ",", "inline", "=", "False", ",", "filter", "=", "None", ",", "n", "=", "0", ",", "p", "=", "0", ",", "sort", "=", "None", ",", "figsize", "=", "(", "20", ",", "12", ")", ",", "fontsize", "=", "16", ",", "labels",...
Presents a `seaborn` heatmap visualization of nullity correlation in the given DataFrame. Note that this visualization has no special support for large datasets. For those, try the dendrogram instead. :param df: The DataFrame whose completeness is being heatmapped. :param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default). See `nullity_filter()` for more information. :param n: The cap on the number of columns to include in the filtered DataFrame. See `nullity_filter()` for more information. :param p: The cap on the percentage fill of the columns in the filtered DataFrame. See `nullity_filter()` for more information. :param sort: The sort to apply to the heatmap. Should be one of "ascending", "descending", or None. See `nullity_sort()` for more information. :param figsize: The size of the figure to display. This is a `matplotlib` parameter which defaults to (20, 12). :param fontsize: The figure's font size. :param labels: Whether or not to label each matrix entry with its correlation (default is True). :param cmap: What `matplotlib` colormap to use. Defaults to `RdBu`. :param vmin: The normalized colormap threshold. Defaults to -1, e.g. the bottom of the color scale. :param vmax: The normalized colormap threshold. Defaults to 1, e.g. the bottom of the color scale. :param inline: Whether or not the figure is inline. If it's not then instead of getting plotted, this method will return its figure. :return: If `inline` is False, the underlying `matplotlib.figure` object. Else, nothing.
[ "Presents", "a", "seaborn", "heatmap", "visualization", "of", "nullity", "correlation", "in", "the", "given", "DataFrame", ".", "Note", "that", "this", "visualization", "has", "no", "special", "support", "for", "large", "datasets", ".", "For", "those", "try", ...
1d67f91fbab0695a919c6bb72c796db57024e0ca
https://github.com/ResidentMario/missingno/blob/1d67f91fbab0695a919c6bb72c796db57024e0ca/missingno/missingno.py#L266-L346
224,541
ResidentMario/missingno
missingno/missingno.py
dendrogram
def dendrogram(df, method='average', filter=None, n=0, p=0, sort=None, orientation=None, figsize=None, fontsize=16, inline=False ): """ Fits a `scipy` hierarchical clustering algorithm to the given DataFrame's variables and visualizes the results as a `scipy` dendrogram. The default vertical display will fit up to 50 columns. If more than 50 columns are specified and orientation is left unspecified the dendrogram will automatically swap to a horizontal display to fit the additional variables. :param df: The DataFrame whose completeness is being dendrogrammed. :param method: The distance measure being used for clustering. This is a parameter that is passed to `scipy.hierarchy`. :param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default). :param n: The cap on the number of columns to include in the filtered DataFrame. :param p: The cap on the percentage fill of the columns in the filtered DataFrame. :param sort: The sort to apply to the heatmap. Should be one of "ascending", "descending", or None. :param figsize: The size of the figure to display. This is a `matplotlib` parameter which defaults to `(25, 10)`. :param fontsize: The figure's font size. :param orientation: The way the dendrogram is oriented. Defaults to top-down if there are less than or equal to 50 columns and left-right if there are more. :param inline: Whether or not the figure is inline. If it's not then instead of getting plotted, this method will return its figure. :return: If `inline` is False, the underlying `matplotlib.figure` object. Else, nothing. """ if not figsize: if len(df.columns) <= 50 or orientation == 'top' or orientation == 'bottom': figsize = (25, 10) else: figsize = (25, (25 + len(df.columns) - 50)*0.5) plt.figure(figsize=figsize) gs = gridspec.GridSpec(1, 1) ax0 = plt.subplot(gs[0]) df = nullity_filter(df, filter=filter, n=n, p=p) df = nullity_sort(df, sort=sort) # Link the hierarchical output matrix, figure out orientation, construct base dendrogram. x = np.transpose(df.isnull().astype(int).values) z = hierarchy.linkage(x, method) if not orientation: if len(df.columns) > 50: orientation = 'left' else: orientation = 'bottom' hierarchy.dendrogram(z, orientation=orientation, labels=df.columns.tolist(), distance_sort='descending', link_color_func=lambda c: 'black', leaf_font_size=fontsize, ax=ax0 ) # Remove extraneous default visual elements. ax0.set_aspect('auto') ax0.grid(b=False) if orientation == 'bottom': ax0.xaxis.tick_top() ax0.xaxis.set_ticks_position('none') ax0.yaxis.set_ticks_position('none') ax0.spines['top'].set_visible(False) ax0.spines['right'].set_visible(False) ax0.spines['bottom'].set_visible(False) ax0.spines['left'].set_visible(False) ax0.patch.set_visible(False) # Set up the categorical axis labels and draw. if orientation == 'bottom': ax0.set_xticklabels(ax0.xaxis.get_majorticklabels(), rotation=45, ha='left') elif orientation == 'top': ax0.set_xticklabels(ax0.xaxis.get_majorticklabels(), rotation=45, ha='right') if orientation == 'bottom' or orientation == 'top': ax0.tick_params(axis='y', labelsize=int(fontsize / 16 * 20)) else: ax0.tick_params(axis='x', labelsize=int(fontsize / 16 * 20)) if inline: plt.show() else: return ax0
python
def dendrogram(df, method='average', filter=None, n=0, p=0, sort=None, orientation=None, figsize=None, fontsize=16, inline=False ): """ Fits a `scipy` hierarchical clustering algorithm to the given DataFrame's variables and visualizes the results as a `scipy` dendrogram. The default vertical display will fit up to 50 columns. If more than 50 columns are specified and orientation is left unspecified the dendrogram will automatically swap to a horizontal display to fit the additional variables. :param df: The DataFrame whose completeness is being dendrogrammed. :param method: The distance measure being used for clustering. This is a parameter that is passed to `scipy.hierarchy`. :param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default). :param n: The cap on the number of columns to include in the filtered DataFrame. :param p: The cap on the percentage fill of the columns in the filtered DataFrame. :param sort: The sort to apply to the heatmap. Should be one of "ascending", "descending", or None. :param figsize: The size of the figure to display. This is a `matplotlib` parameter which defaults to `(25, 10)`. :param fontsize: The figure's font size. :param orientation: The way the dendrogram is oriented. Defaults to top-down if there are less than or equal to 50 columns and left-right if there are more. :param inline: Whether or not the figure is inline. If it's not then instead of getting plotted, this method will return its figure. :return: If `inline` is False, the underlying `matplotlib.figure` object. Else, nothing. """ if not figsize: if len(df.columns) <= 50 or orientation == 'top' or orientation == 'bottom': figsize = (25, 10) else: figsize = (25, (25 + len(df.columns) - 50)*0.5) plt.figure(figsize=figsize) gs = gridspec.GridSpec(1, 1) ax0 = plt.subplot(gs[0]) df = nullity_filter(df, filter=filter, n=n, p=p) df = nullity_sort(df, sort=sort) # Link the hierarchical output matrix, figure out orientation, construct base dendrogram. x = np.transpose(df.isnull().astype(int).values) z = hierarchy.linkage(x, method) if not orientation: if len(df.columns) > 50: orientation = 'left' else: orientation = 'bottom' hierarchy.dendrogram(z, orientation=orientation, labels=df.columns.tolist(), distance_sort='descending', link_color_func=lambda c: 'black', leaf_font_size=fontsize, ax=ax0 ) # Remove extraneous default visual elements. ax0.set_aspect('auto') ax0.grid(b=False) if orientation == 'bottom': ax0.xaxis.tick_top() ax0.xaxis.set_ticks_position('none') ax0.yaxis.set_ticks_position('none') ax0.spines['top'].set_visible(False) ax0.spines['right'].set_visible(False) ax0.spines['bottom'].set_visible(False) ax0.spines['left'].set_visible(False) ax0.patch.set_visible(False) # Set up the categorical axis labels and draw. if orientation == 'bottom': ax0.set_xticklabels(ax0.xaxis.get_majorticklabels(), rotation=45, ha='left') elif orientation == 'top': ax0.set_xticklabels(ax0.xaxis.get_majorticklabels(), rotation=45, ha='right') if orientation == 'bottom' or orientation == 'top': ax0.tick_params(axis='y', labelsize=int(fontsize / 16 * 20)) else: ax0.tick_params(axis='x', labelsize=int(fontsize / 16 * 20)) if inline: plt.show() else: return ax0
[ "def", "dendrogram", "(", "df", ",", "method", "=", "'average'", ",", "filter", "=", "None", ",", "n", "=", "0", ",", "p", "=", "0", ",", "sort", "=", "None", ",", "orientation", "=", "None", ",", "figsize", "=", "None", ",", "fontsize", "=", "16...
Fits a `scipy` hierarchical clustering algorithm to the given DataFrame's variables and visualizes the results as a `scipy` dendrogram. The default vertical display will fit up to 50 columns. If more than 50 columns are specified and orientation is left unspecified the dendrogram will automatically swap to a horizontal display to fit the additional variables. :param df: The DataFrame whose completeness is being dendrogrammed. :param method: The distance measure being used for clustering. This is a parameter that is passed to `scipy.hierarchy`. :param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default). :param n: The cap on the number of columns to include in the filtered DataFrame. :param p: The cap on the percentage fill of the columns in the filtered DataFrame. :param sort: The sort to apply to the heatmap. Should be one of "ascending", "descending", or None. :param figsize: The size of the figure to display. This is a `matplotlib` parameter which defaults to `(25, 10)`. :param fontsize: The figure's font size. :param orientation: The way the dendrogram is oriented. Defaults to top-down if there are less than or equal to 50 columns and left-right if there are more. :param inline: Whether or not the figure is inline. If it's not then instead of getting plotted, this method will return its figure. :return: If `inline` is False, the underlying `matplotlib.figure` object. Else, nothing.
[ "Fits", "a", "scipy", "hierarchical", "clustering", "algorithm", "to", "the", "given", "DataFrame", "s", "variables", "and", "visualizes", "the", "results", "as", "a", "scipy", "dendrogram", ".", "The", "default", "vertical", "display", "will", "fit", "up", "t...
1d67f91fbab0695a919c6bb72c796db57024e0ca
https://github.com/ResidentMario/missingno/blob/1d67f91fbab0695a919c6bb72c796db57024e0ca/missingno/missingno.py#L349-L434
224,542
ResidentMario/missingno
missingno/utils.py
nullity_sort
def nullity_sort(df, sort=None): """ Sorts a DataFrame according to its nullity, in either ascending or descending order. :param df: The DataFrame object being sorted. :param sort: The sorting method: either "ascending", "descending", or None (default). :return: The nullity-sorted DataFrame. """ if sort == 'ascending': return df.iloc[np.argsort(df.count(axis='columns').values), :] elif sort == 'descending': return df.iloc[np.flipud(np.argsort(df.count(axis='columns').values)), :] else: return df
python
def nullity_sort(df, sort=None): """ Sorts a DataFrame according to its nullity, in either ascending or descending order. :param df: The DataFrame object being sorted. :param sort: The sorting method: either "ascending", "descending", or None (default). :return: The nullity-sorted DataFrame. """ if sort == 'ascending': return df.iloc[np.argsort(df.count(axis='columns').values), :] elif sort == 'descending': return df.iloc[np.flipud(np.argsort(df.count(axis='columns').values)), :] else: return df
[ "def", "nullity_sort", "(", "df", ",", "sort", "=", "None", ")", ":", "if", "sort", "==", "'ascending'", ":", "return", "df", ".", "iloc", "[", "np", ".", "argsort", "(", "df", ".", "count", "(", "axis", "=", "'columns'", ")", ".", "values", ")", ...
Sorts a DataFrame according to its nullity, in either ascending or descending order. :param df: The DataFrame object being sorted. :param sort: The sorting method: either "ascending", "descending", or None (default). :return: The nullity-sorted DataFrame.
[ "Sorts", "a", "DataFrame", "according", "to", "its", "nullity", "in", "either", "ascending", "or", "descending", "order", "." ]
1d67f91fbab0695a919c6bb72c796db57024e0ca
https://github.com/ResidentMario/missingno/blob/1d67f91fbab0695a919c6bb72c796db57024e0ca/missingno/utils.py#L5-L18
224,543
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/session_entity_types_client.py
SessionEntityTypesClient.from_service_account_file
def from_service_account_file(cls, filename, *args, **kwargs): """Creates an instance of this client using the provided credentials file. Args: filename (str): The path to the service account private key json file. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: dialogflow_v2.SessionEntityTypesClient: The constructed client. """ credentials = service_account.Credentials.from_service_account_file( filename) kwargs['credentials'] = credentials return cls(*args, **kwargs)
python
def from_service_account_file(cls, filename, *args, **kwargs): """Creates an instance of this client using the provided credentials file. Args: filename (str): The path to the service account private key json file. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: dialogflow_v2.SessionEntityTypesClient: The constructed client. """ credentials = service_account.Credentials.from_service_account_file( filename) kwargs['credentials'] = credentials return cls(*args, **kwargs)
[ "def", "from_service_account_file", "(", "cls", ",", "filename", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "credentials", "=", "service_account", ".", "Credentials", ".", "from_service_account_file", "(", "filename", ")", "kwargs", "[", "'credentials'...
Creates an instance of this client using the provided credentials file. Args: filename (str): The path to the service account private key json file. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: dialogflow_v2.SessionEntityTypesClient: The constructed client.
[ "Creates", "an", "instance", "of", "this", "client", "using", "the", "provided", "credentials", "file", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/session_entity_types_client.py#L75-L91
224,544
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/session_entity_types_client.py
SessionEntityTypesClient.session_entity_type_path
def session_entity_type_path(cls, project, session, entity_type): """Return a fully-qualified session_entity_type string.""" return google.api_core.path_template.expand( 'projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}', project=project, session=session, entity_type=entity_type, )
python
def session_entity_type_path(cls, project, session, entity_type): """Return a fully-qualified session_entity_type string.""" return google.api_core.path_template.expand( 'projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}', project=project, session=session, entity_type=entity_type, )
[ "def", "session_entity_type_path", "(", "cls", ",", "project", ",", "session", ",", "entity_type", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "'projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}'", ",", "p...
Return a fully-qualified session_entity_type string.
[ "Return", "a", "fully", "-", "qualified", "session_entity_type", "string", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/session_entity_types_client.py#L105-L112
224,545
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/session_entity_types_client.py
SessionEntityTypesClient.create_session_entity_type
def create_session_entity_type( self, parent, session_entity_type, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Creates a session entity type. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.SessionEntityTypesClient() >>> >>> parent = client.session_path('[PROJECT]', '[SESSION]') >>> >>> # TODO: Initialize ``session_entity_type``: >>> session_entity_type = {} >>> >>> response = client.create_session_entity_type(parent, session_entity_type) Args: parent (str): Required. The session to create a session entity type for. Format: ``projects/<Project ID>/agent/sessions/<Session ID>``. session_entity_type (Union[dict, ~google.cloud.dialogflow_v2.types.SessionEntityType]): Required. The session entity type to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.SessionEntityType` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.SessionEntityType` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'create_session_entity_type' not in self._inner_api_calls: self._inner_api_calls[ 'create_session_entity_type'] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_session_entity_type, default_retry=self._method_configs[ 'CreateSessionEntityType'].retry, default_timeout=self._method_configs[ 'CreateSessionEntityType'].timeout, client_info=self._client_info, ) request = session_entity_type_pb2.CreateSessionEntityTypeRequest( parent=parent, session_entity_type=session_entity_type, ) return self._inner_api_calls['create_session_entity_type']( request, retry=retry, timeout=timeout, metadata=metadata)
python
def create_session_entity_type( self, parent, session_entity_type, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Creates a session entity type. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.SessionEntityTypesClient() >>> >>> parent = client.session_path('[PROJECT]', '[SESSION]') >>> >>> # TODO: Initialize ``session_entity_type``: >>> session_entity_type = {} >>> >>> response = client.create_session_entity_type(parent, session_entity_type) Args: parent (str): Required. The session to create a session entity type for. Format: ``projects/<Project ID>/agent/sessions/<Session ID>``. session_entity_type (Union[dict, ~google.cloud.dialogflow_v2.types.SessionEntityType]): Required. The session entity type to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.SessionEntityType` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.SessionEntityType` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'create_session_entity_type' not in self._inner_api_calls: self._inner_api_calls[ 'create_session_entity_type'] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_session_entity_type, default_retry=self._method_configs[ 'CreateSessionEntityType'].retry, default_timeout=self._method_configs[ 'CreateSessionEntityType'].timeout, client_info=self._client_info, ) request = session_entity_type_pb2.CreateSessionEntityTypeRequest( parent=parent, session_entity_type=session_entity_type, ) return self._inner_api_calls['create_session_entity_type']( request, retry=retry, timeout=timeout, metadata=metadata)
[ "def", "create_session_entity_type", "(", "self", ",", "parent", ",", "session_entity_type", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "...
Creates a session entity type. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.SessionEntityTypesClient() >>> >>> parent = client.session_path('[PROJECT]', '[SESSION]') >>> >>> # TODO: Initialize ``session_entity_type``: >>> session_entity_type = {} >>> >>> response = client.create_session_entity_type(parent, session_entity_type) Args: parent (str): Required. The session to create a session entity type for. Format: ``projects/<Project ID>/agent/sessions/<Session ID>``. session_entity_type (Union[dict, ~google.cloud.dialogflow_v2.types.SessionEntityType]): Required. The session entity type to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.SessionEntityType` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.SessionEntityType` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Creates", "a", "session", "entity", "type", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/session_entity_types_client.py#L351-L415
224,546
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/session_entity_types_client.py
SessionEntityTypesClient.update_session_entity_type
def update_session_entity_type( self, session_entity_type, update_mask=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Updates the specified session entity type. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.SessionEntityTypesClient() >>> >>> # TODO: Initialize ``session_entity_type``: >>> session_entity_type = {} >>> >>> response = client.update_session_entity_type(session_entity_type) Args: session_entity_type (Union[dict, ~google.cloud.dialogflow_v2.types.SessionEntityType]): Required. The entity type to update. Format: ``projects/<Project ID>/agent/sessions/<Session ID>/entityTypes/<Entity Type Display Name>``. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.SessionEntityType` update_mask (Union[dict, ~google.cloud.dialogflow_v2.types.FieldMask]): Optional. The mask to control which fields get updated. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.FieldMask` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.SessionEntityType` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'update_session_entity_type' not in self._inner_api_calls: self._inner_api_calls[ 'update_session_entity_type'] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_session_entity_type, default_retry=self._method_configs[ 'UpdateSessionEntityType'].retry, default_timeout=self._method_configs[ 'UpdateSessionEntityType'].timeout, client_info=self._client_info, ) request = session_entity_type_pb2.UpdateSessionEntityTypeRequest( session_entity_type=session_entity_type, update_mask=update_mask, ) return self._inner_api_calls['update_session_entity_type']( request, retry=retry, timeout=timeout, metadata=metadata)
python
def update_session_entity_type( self, session_entity_type, update_mask=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Updates the specified session entity type. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.SessionEntityTypesClient() >>> >>> # TODO: Initialize ``session_entity_type``: >>> session_entity_type = {} >>> >>> response = client.update_session_entity_type(session_entity_type) Args: session_entity_type (Union[dict, ~google.cloud.dialogflow_v2.types.SessionEntityType]): Required. The entity type to update. Format: ``projects/<Project ID>/agent/sessions/<Session ID>/entityTypes/<Entity Type Display Name>``. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.SessionEntityType` update_mask (Union[dict, ~google.cloud.dialogflow_v2.types.FieldMask]): Optional. The mask to control which fields get updated. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.FieldMask` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.SessionEntityType` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'update_session_entity_type' not in self._inner_api_calls: self._inner_api_calls[ 'update_session_entity_type'] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_session_entity_type, default_retry=self._method_configs[ 'UpdateSessionEntityType'].retry, default_timeout=self._method_configs[ 'UpdateSessionEntityType'].timeout, client_info=self._client_info, ) request = session_entity_type_pb2.UpdateSessionEntityTypeRequest( session_entity_type=session_entity_type, update_mask=update_mask, ) return self._inner_api_calls['update_session_entity_type']( request, retry=retry, timeout=timeout, metadata=metadata)
[ "def", "update_session_entity_type", "(", "self", ",", "session_entity_type", ",", "update_mask", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", ...
Updates the specified session entity type. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.SessionEntityTypesClient() >>> >>> # TODO: Initialize ``session_entity_type``: >>> session_entity_type = {} >>> >>> response = client.update_session_entity_type(session_entity_type) Args: session_entity_type (Union[dict, ~google.cloud.dialogflow_v2.types.SessionEntityType]): Required. The entity type to update. Format: ``projects/<Project ID>/agent/sessions/<Session ID>/entityTypes/<Entity Type Display Name>``. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.SessionEntityType` update_mask (Union[dict, ~google.cloud.dialogflow_v2.types.FieldMask]): Optional. The mask to control which fields get updated. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.FieldMask` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.SessionEntityType` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Updates", "the", "specified", "session", "entity", "type", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/session_entity_types_client.py#L417-L482
224,547
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/session_entity_types_client.py
SessionEntityTypesClient.delete_session_entity_type
def delete_session_entity_type( self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Deletes the specified session entity type. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.SessionEntityTypesClient() >>> >>> name = client.session_entity_type_path('[PROJECT]', '[SESSION]', '[ENTITY_TYPE]') >>> >>> client.delete_session_entity_type(name) Args: name (str): Required. The name of the entity type to delete. Format: ``projects/<Project ID>/agent/sessions/<Session ID>/entityTypes/<Entity Type Display Name>``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'delete_session_entity_type' not in self._inner_api_calls: self._inner_api_calls[ 'delete_session_entity_type'] = google.api_core.gapic_v1.method.wrap_method( self.transport.delete_session_entity_type, default_retry=self._method_configs[ 'DeleteSessionEntityType'].retry, default_timeout=self._method_configs[ 'DeleteSessionEntityType'].timeout, client_info=self._client_info, ) request = session_entity_type_pb2.DeleteSessionEntityTypeRequest( name=name, ) self._inner_api_calls['delete_session_entity_type']( request, retry=retry, timeout=timeout, metadata=metadata)
python
def delete_session_entity_type( self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Deletes the specified session entity type. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.SessionEntityTypesClient() >>> >>> name = client.session_entity_type_path('[PROJECT]', '[SESSION]', '[ENTITY_TYPE]') >>> >>> client.delete_session_entity_type(name) Args: name (str): Required. The name of the entity type to delete. Format: ``projects/<Project ID>/agent/sessions/<Session ID>/entityTypes/<Entity Type Display Name>``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'delete_session_entity_type' not in self._inner_api_calls: self._inner_api_calls[ 'delete_session_entity_type'] = google.api_core.gapic_v1.method.wrap_method( self.transport.delete_session_entity_type, default_retry=self._method_configs[ 'DeleteSessionEntityType'].retry, default_timeout=self._method_configs[ 'DeleteSessionEntityType'].timeout, client_info=self._client_info, ) request = session_entity_type_pb2.DeleteSessionEntityTypeRequest( name=name, ) self._inner_api_calls['delete_session_entity_type']( request, retry=retry, timeout=timeout, metadata=metadata)
[ "def", "delete_session_entity_type", "(", "self", ",", "name", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ","...
Deletes the specified session entity type. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.SessionEntityTypesClient() >>> >>> name = client.session_entity_type_path('[PROJECT]', '[SESSION]', '[ENTITY_TYPE]') >>> >>> client.delete_session_entity_type(name) Args: name (str): Required. The name of the entity type to delete. Format: ``projects/<Project ID>/agent/sessions/<Session ID>/entityTypes/<Entity Type Display Name>``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Deletes", "the", "specified", "session", "entity", "type", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/session_entity_types_client.py#L484-L537
224,548
googleapis/dialogflow-python-client-v2
samples/knowledge_base_management.py
list_knowledge_bases
def list_knowledge_bases(project_id): """Lists the Knowledge bases belonging to a project. Args: project_id: The GCP project linked with the agent.""" import dialogflow_v2beta1 as dialogflow client = dialogflow.KnowledgeBasesClient() project_path = client.project_path(project_id) print('Knowledge Bases for: {}'.format(project_id)) for knowledge_base in client.list_knowledge_bases(project_path): print(' - Display Name: {}'.format(knowledge_base.display_name)) print(' - Knowledge ID: {}\n'.format(knowledge_base.name))
python
def list_knowledge_bases(project_id): """Lists the Knowledge bases belonging to a project. Args: project_id: The GCP project linked with the agent.""" import dialogflow_v2beta1 as dialogflow client = dialogflow.KnowledgeBasesClient() project_path = client.project_path(project_id) print('Knowledge Bases for: {}'.format(project_id)) for knowledge_base in client.list_knowledge_bases(project_path): print(' - Display Name: {}'.format(knowledge_base.display_name)) print(' - Knowledge ID: {}\n'.format(knowledge_base.name))
[ "def", "list_knowledge_bases", "(", "project_id", ")", ":", "import", "dialogflow_v2beta1", "as", "dialogflow", "client", "=", "dialogflow", ".", "KnowledgeBasesClient", "(", ")", "project_path", "=", "client", ".", "project_path", "(", "project_id", ")", "print", ...
Lists the Knowledge bases belonging to a project. Args: project_id: The GCP project linked with the agent.
[ "Lists", "the", "Knowledge", "bases", "belonging", "to", "a", "project", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/knowledge_base_management.py#L35-L47
224,549
googleapis/dialogflow-python-client-v2
samples/knowledge_base_management.py
create_knowledge_base
def create_knowledge_base(project_id, display_name): """Creates a Knowledge base. Args: project_id: The GCP project linked with the agent. display_name: The display name of the Knowledge base.""" import dialogflow_v2beta1 as dialogflow client = dialogflow.KnowledgeBasesClient() project_path = client.project_path(project_id) knowledge_base = dialogflow.types.KnowledgeBase( display_name=display_name) response = client.create_knowledge_base(project_path, knowledge_base) print('Knowledge Base created:\n') print('Display Name: {}\n'.format(response.display_name)) print('Knowledge ID: {}\n'.format(response.name))
python
def create_knowledge_base(project_id, display_name): """Creates a Knowledge base. Args: project_id: The GCP project linked with the agent. display_name: The display name of the Knowledge base.""" import dialogflow_v2beta1 as dialogflow client = dialogflow.KnowledgeBasesClient() project_path = client.project_path(project_id) knowledge_base = dialogflow.types.KnowledgeBase( display_name=display_name) response = client.create_knowledge_base(project_path, knowledge_base) print('Knowledge Base created:\n') print('Display Name: {}\n'.format(response.display_name)) print('Knowledge ID: {}\n'.format(response.name))
[ "def", "create_knowledge_base", "(", "project_id", ",", "display_name", ")", ":", "import", "dialogflow_v2beta1", "as", "dialogflow", "client", "=", "dialogflow", ".", "KnowledgeBasesClient", "(", ")", "project_path", "=", "client", ".", "project_path", "(", "projec...
Creates a Knowledge base. Args: project_id: The GCP project linked with the agent. display_name: The display name of the Knowledge base.
[ "Creates", "a", "Knowledge", "base", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/knowledge_base_management.py#L52-L69
224,550
googleapis/dialogflow-python-client-v2
samples/knowledge_base_management.py
get_knowledge_base
def get_knowledge_base(project_id, knowledge_base_id): """Gets a specific Knowledge base. Args: project_id: The GCP project linked with the agent. knowledge_base_id: Id of the Knowledge base.""" import dialogflow_v2beta1 as dialogflow client = dialogflow.KnowledgeBasesClient() knowledge_base_path = client.knowledge_base_path( project_id, knowledge_base_id) response = client.get_knowledge_base(knowledge_base_path) print('Got Knowledge Base:') print(' - Display Name: {}'.format(response.display_name)) print(' - Knowledge ID: {}'.format(response.name))
python
def get_knowledge_base(project_id, knowledge_base_id): """Gets a specific Knowledge base. Args: project_id: The GCP project linked with the agent. knowledge_base_id: Id of the Knowledge base.""" import dialogflow_v2beta1 as dialogflow client = dialogflow.KnowledgeBasesClient() knowledge_base_path = client.knowledge_base_path( project_id, knowledge_base_id) response = client.get_knowledge_base(knowledge_base_path) print('Got Knowledge Base:') print(' - Display Name: {}'.format(response.display_name)) print(' - Knowledge ID: {}'.format(response.name))
[ "def", "get_knowledge_base", "(", "project_id", ",", "knowledge_base_id", ")", ":", "import", "dialogflow_v2beta1", "as", "dialogflow", "client", "=", "dialogflow", ".", "KnowledgeBasesClient", "(", ")", "knowledge_base_path", "=", "client", ".", "knowledge_base_path", ...
Gets a specific Knowledge base. Args: project_id: The GCP project linked with the agent. knowledge_base_id: Id of the Knowledge base.
[ "Gets", "a", "specific", "Knowledge", "base", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/knowledge_base_management.py#L74-L89
224,551
googleapis/dialogflow-python-client-v2
samples/knowledge_base_management.py
delete_knowledge_base
def delete_knowledge_base(project_id, knowledge_base_id): """Deletes a specific Knowledge base. Args: project_id: The GCP project linked with the agent. knowledge_base_id: Id of the Knowledge base.""" import dialogflow_v2beta1 as dialogflow client = dialogflow.KnowledgeBasesClient() knowledge_base_path = client.knowledge_base_path( project_id, knowledge_base_id) response = client.delete_knowledge_base(knowledge_base_path) print('Knowledge Base deleted.'.format(response))
python
def delete_knowledge_base(project_id, knowledge_base_id): """Deletes a specific Knowledge base. Args: project_id: The GCP project linked with the agent. knowledge_base_id: Id of the Knowledge base.""" import dialogflow_v2beta1 as dialogflow client = dialogflow.KnowledgeBasesClient() knowledge_base_path = client.knowledge_base_path( project_id, knowledge_base_id) response = client.delete_knowledge_base(knowledge_base_path) print('Knowledge Base deleted.'.format(response))
[ "def", "delete_knowledge_base", "(", "project_id", ",", "knowledge_base_id", ")", ":", "import", "dialogflow_v2beta1", "as", "dialogflow", "client", "=", "dialogflow", ".", "KnowledgeBasesClient", "(", ")", "knowledge_base_path", "=", "client", ".", "knowledge_base_path...
Deletes a specific Knowledge base. Args: project_id: The GCP project linked with the agent. knowledge_base_id: Id of the Knowledge base.
[ "Deletes", "a", "specific", "Knowledge", "base", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/knowledge_base_management.py#L94-L107
224,552
googleapis/dialogflow-python-client-v2
samples/detect_intent_with_texttospeech_response.py
detect_intent_with_texttospeech_response
def detect_intent_with_texttospeech_response(project_id, session_id, texts, language_code): """Returns the result of detect intent with texts as inputs and includes the response in an audio format. Using the same `session_id` between requests allows continuation of the conversaion.""" import dialogflow_v2beta1 as dialogflow session_client = dialogflow.SessionsClient() session_path = session_client.session_path(project_id, session_id) print('Session path: {}\n'.format(session_path)) for text in texts: text_input = dialogflow.types.TextInput( text=text, language_code=language_code) query_input = dialogflow.types.QueryInput(text=text_input) # Set the query parameters with sentiment analysis output_audio_config = dialogflow.types.OutputAudioConfig( audio_encoding=dialogflow.enums.OutputAudioEncoding .OUTPUT_AUDIO_ENCODING_LINEAR_16) response = session_client.detect_intent( session=session_path, query_input=query_input, output_audio_config=output_audio_config) print('=' * 20) print('Query text: {}'.format(response.query_result.query_text)) print('Detected intent: {} (confidence: {})\n'.format( response.query_result.intent.display_name, response.query_result.intent_detection_confidence)) print('Fulfillment text: {}\n'.format( response.query_result.fulfillment_text)) # The response's audio_content is binary. with open('output.wav', 'wb') as out: out.write(response.output_audio) print('Audio content written to file "output.wav"')
python
def detect_intent_with_texttospeech_response(project_id, session_id, texts, language_code): """Returns the result of detect intent with texts as inputs and includes the response in an audio format. Using the same `session_id` between requests allows continuation of the conversaion.""" import dialogflow_v2beta1 as dialogflow session_client = dialogflow.SessionsClient() session_path = session_client.session_path(project_id, session_id) print('Session path: {}\n'.format(session_path)) for text in texts: text_input = dialogflow.types.TextInput( text=text, language_code=language_code) query_input = dialogflow.types.QueryInput(text=text_input) # Set the query parameters with sentiment analysis output_audio_config = dialogflow.types.OutputAudioConfig( audio_encoding=dialogflow.enums.OutputAudioEncoding .OUTPUT_AUDIO_ENCODING_LINEAR_16) response = session_client.detect_intent( session=session_path, query_input=query_input, output_audio_config=output_audio_config) print('=' * 20) print('Query text: {}'.format(response.query_result.query_text)) print('Detected intent: {} (confidence: {})\n'.format( response.query_result.intent.display_name, response.query_result.intent_detection_confidence)) print('Fulfillment text: {}\n'.format( response.query_result.fulfillment_text)) # The response's audio_content is binary. with open('output.wav', 'wb') as out: out.write(response.output_audio) print('Audio content written to file "output.wav"')
[ "def", "detect_intent_with_texttospeech_response", "(", "project_id", ",", "session_id", ",", "texts", ",", "language_code", ")", ":", "import", "dialogflow_v2beta1", "as", "dialogflow", "session_client", "=", "dialogflow", ".", "SessionsClient", "(", ")", "session_path...
Returns the result of detect intent with texts as inputs and includes the response in an audio format. Using the same `session_id` between requests allows continuation of the conversaion.
[ "Returns", "the", "result", "of", "detect", "intent", "with", "texts", "as", "inputs", "and", "includes", "the", "response", "in", "an", "audio", "format", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/detect_intent_with_texttospeech_response.py#L30-L68
224,553
googleapis/dialogflow-python-client-v2
samples/detect_intent_with_model_selection.py
detect_intent_with_model_selection
def detect_intent_with_model_selection(project_id, session_id, audio_file_path, language_code): """Returns the result of detect intent with model selection on an audio file as input Using the same `session_id` between requests allows continuation of the conversaion.""" import dialogflow_v2beta1 as dialogflow session_client = dialogflow.SessionsClient() # Note: hard coding audio_encoding and sample_rate_hertz for simplicity. audio_encoding = dialogflow.enums.AudioEncoding.AUDIO_ENCODING_LINEAR_16 sample_rate_hertz = 16000 session_path = session_client.session_path(project_id, session_id) print('Session path: {}\n'.format(session_path)) with open(audio_file_path, 'rb') as audio_file: input_audio = audio_file.read() # Which Speech model to select for the given request. # Possible models: video, phone_call, command_and_search, default model = 'phone_call' audio_config = dialogflow.types.InputAudioConfig( audio_encoding=audio_encoding, language_code=language_code, sample_rate_hertz=sample_rate_hertz, model=model) query_input = dialogflow.types.QueryInput(audio_config=audio_config) response = session_client.detect_intent( session=session_path, query_input=query_input, input_audio=input_audio) print('=' * 20) print('Query text: {}'.format(response.query_result.query_text)) print('Detected intent: {} (confidence: {})\n'.format( response.query_result.intent.display_name, response.query_result.intent_detection_confidence)) print('Fulfillment text: {}\n'.format( response.query_result.fulfillment_text))
python
def detect_intent_with_model_selection(project_id, session_id, audio_file_path, language_code): """Returns the result of detect intent with model selection on an audio file as input Using the same `session_id` between requests allows continuation of the conversaion.""" import dialogflow_v2beta1 as dialogflow session_client = dialogflow.SessionsClient() # Note: hard coding audio_encoding and sample_rate_hertz for simplicity. audio_encoding = dialogflow.enums.AudioEncoding.AUDIO_ENCODING_LINEAR_16 sample_rate_hertz = 16000 session_path = session_client.session_path(project_id, session_id) print('Session path: {}\n'.format(session_path)) with open(audio_file_path, 'rb') as audio_file: input_audio = audio_file.read() # Which Speech model to select for the given request. # Possible models: video, phone_call, command_and_search, default model = 'phone_call' audio_config = dialogflow.types.InputAudioConfig( audio_encoding=audio_encoding, language_code=language_code, sample_rate_hertz=sample_rate_hertz, model=model) query_input = dialogflow.types.QueryInput(audio_config=audio_config) response = session_client.detect_intent( session=session_path, query_input=query_input, input_audio=input_audio) print('=' * 20) print('Query text: {}'.format(response.query_result.query_text)) print('Detected intent: {} (confidence: {})\n'.format( response.query_result.intent.display_name, response.query_result.intent_detection_confidence)) print('Fulfillment text: {}\n'.format( response.query_result.fulfillment_text))
[ "def", "detect_intent_with_model_selection", "(", "project_id", ",", "session_id", ",", "audio_file_path", ",", "language_code", ")", ":", "import", "dialogflow_v2beta1", "as", "dialogflow", "session_client", "=", "dialogflow", ".", "SessionsClient", "(", ")", "# Note: ...
Returns the result of detect intent with model selection on an audio file as input Using the same `session_id` between requests allows continuation of the conversaion.
[ "Returns", "the", "result", "of", "detect", "intent", "with", "model", "selection", "on", "an", "audio", "file", "as", "input" ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/detect_intent_with_model_selection.py#L30-L70
224,554
googleapis/dialogflow-python-client-v2
dialogflow_v2beta1/gapic/knowledge_bases_client.py
KnowledgeBasesClient.knowledge_base_path
def knowledge_base_path(cls, project, knowledge_base): """Return a fully-qualified knowledge_base string.""" return google.api_core.path_template.expand( 'projects/{project}/knowledgeBases/{knowledge_base}', project=project, knowledge_base=knowledge_base, )
python
def knowledge_base_path(cls, project, knowledge_base): """Return a fully-qualified knowledge_base string.""" return google.api_core.path_template.expand( 'projects/{project}/knowledgeBases/{knowledge_base}', project=project, knowledge_base=knowledge_base, )
[ "def", "knowledge_base_path", "(", "cls", ",", "project", ",", "knowledge_base", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "'projects/{project}/knowledgeBases/{knowledge_base}'", ",", "project", "=", "project", ",", "kn...
Return a fully-qualified knowledge_base string.
[ "Return", "a", "fully", "-", "qualified", "knowledge_base", "string", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2beta1/gapic/knowledge_bases_client.py#L97-L103
224,555
googleapis/dialogflow-python-client-v2
dialogflow_v2beta1/gapic/knowledge_bases_client.py
KnowledgeBasesClient.get_knowledge_base
def get_knowledge_base(self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Retrieves the specified knowledge base. Example: >>> import dialogflow_v2beta1 >>> >>> client = dialogflow_v2beta1.KnowledgeBasesClient() >>> >>> name = client.knowledge_base_path('[PROJECT]', '[KNOWLEDGE_BASE]') >>> >>> response = client.get_knowledge_base(name) Args: name (str): Required. The name of the knowledge base to retrieve. Format ``projects/<Project ID>/knowledgeBases/<Knowledge Base ID>``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2beta1.types.KnowledgeBase` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'get_knowledge_base' not in self._inner_api_calls: self._inner_api_calls[ 'get_knowledge_base'] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_knowledge_base, default_retry=self._method_configs[ 'GetKnowledgeBase'].retry, default_timeout=self._method_configs['GetKnowledgeBase'] .timeout, client_info=self._client_info, ) request = knowledge_base_pb2.GetKnowledgeBaseRequest(name=name, ) return self._inner_api_calls['get_knowledge_base']( request, retry=retry, timeout=timeout, metadata=metadata)
python
def get_knowledge_base(self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Retrieves the specified knowledge base. Example: >>> import dialogflow_v2beta1 >>> >>> client = dialogflow_v2beta1.KnowledgeBasesClient() >>> >>> name = client.knowledge_base_path('[PROJECT]', '[KNOWLEDGE_BASE]') >>> >>> response = client.get_knowledge_base(name) Args: name (str): Required. The name of the knowledge base to retrieve. Format ``projects/<Project ID>/knowledgeBases/<Knowledge Base ID>``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2beta1.types.KnowledgeBase` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'get_knowledge_base' not in self._inner_api_calls: self._inner_api_calls[ 'get_knowledge_base'] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_knowledge_base, default_retry=self._method_configs[ 'GetKnowledgeBase'].retry, default_timeout=self._method_configs['GetKnowledgeBase'] .timeout, client_info=self._client_info, ) request = knowledge_base_pb2.GetKnowledgeBaseRequest(name=name, ) return self._inner_api_calls['get_knowledge_base']( request, retry=retry, timeout=timeout, metadata=metadata)
[ "def", "get_knowledge_base", "(", "self", ",", "name", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "met...
Retrieves the specified knowledge base. Example: >>> import dialogflow_v2beta1 >>> >>> client = dialogflow_v2beta1.KnowledgeBasesClient() >>> >>> name = client.knowledge_base_path('[PROJECT]', '[KNOWLEDGE_BASE]') >>> >>> response = client.get_knowledge_base(name) Args: name (str): Required. The name of the knowledge base to retrieve. Format ``projects/<Project ID>/knowledgeBases/<Knowledge Base ID>``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2beta1.types.KnowledgeBase` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Retrieves", "the", "specified", "knowledge", "base", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2beta1/gapic/knowledge_bases_client.py#L283-L336
224,556
googleapis/dialogflow-python-client-v2
dialogflow_v2beta1/gapic/knowledge_bases_client.py
KnowledgeBasesClient.create_knowledge_base
def create_knowledge_base(self, parent, knowledge_base, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Creates a knowledge base. Example: >>> import dialogflow_v2beta1 >>> >>> client = dialogflow_v2beta1.KnowledgeBasesClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize ``knowledge_base``: >>> knowledge_base = {} >>> >>> response = client.create_knowledge_base(parent, knowledge_base) Args: parent (str): Required. The agent to create a knowledge base for. Format: ``projects/<Project ID>/agent``. knowledge_base (Union[dict, ~google.cloud.dialogflow_v2beta1.types.KnowledgeBase]): Required. The knowledge base to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2beta1.types.KnowledgeBase` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2beta1.types.KnowledgeBase` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'create_knowledge_base' not in self._inner_api_calls: self._inner_api_calls[ 'create_knowledge_base'] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_knowledge_base, default_retry=self._method_configs[ 'CreateKnowledgeBase'].retry, default_timeout=self._method_configs['CreateKnowledgeBase'] .timeout, client_info=self._client_info, ) request = knowledge_base_pb2.CreateKnowledgeBaseRequest( parent=parent, knowledge_base=knowledge_base, ) return self._inner_api_calls['create_knowledge_base']( request, retry=retry, timeout=timeout, metadata=metadata)
python
def create_knowledge_base(self, parent, knowledge_base, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Creates a knowledge base. Example: >>> import dialogflow_v2beta1 >>> >>> client = dialogflow_v2beta1.KnowledgeBasesClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize ``knowledge_base``: >>> knowledge_base = {} >>> >>> response = client.create_knowledge_base(parent, knowledge_base) Args: parent (str): Required. The agent to create a knowledge base for. Format: ``projects/<Project ID>/agent``. knowledge_base (Union[dict, ~google.cloud.dialogflow_v2beta1.types.KnowledgeBase]): Required. The knowledge base to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2beta1.types.KnowledgeBase` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2beta1.types.KnowledgeBase` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'create_knowledge_base' not in self._inner_api_calls: self._inner_api_calls[ 'create_knowledge_base'] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_knowledge_base, default_retry=self._method_configs[ 'CreateKnowledgeBase'].retry, default_timeout=self._method_configs['CreateKnowledgeBase'] .timeout, client_info=self._client_info, ) request = knowledge_base_pb2.CreateKnowledgeBaseRequest( parent=parent, knowledge_base=knowledge_base, ) return self._inner_api_calls['create_knowledge_base']( request, retry=retry, timeout=timeout, metadata=metadata)
[ "def", "create_knowledge_base", "(", "self", ",", "parent", ",", "knowledge_base", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ...
Creates a knowledge base. Example: >>> import dialogflow_v2beta1 >>> >>> client = dialogflow_v2beta1.KnowledgeBasesClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize ``knowledge_base``: >>> knowledge_base = {} >>> >>> response = client.create_knowledge_base(parent, knowledge_base) Args: parent (str): Required. The agent to create a knowledge base for. Format: ``projects/<Project ID>/agent``. knowledge_base (Union[dict, ~google.cloud.dialogflow_v2beta1.types.KnowledgeBase]): Required. The knowledge base to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2beta1.types.KnowledgeBase` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2beta1.types.KnowledgeBase` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Creates", "a", "knowledge", "base", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2beta1/gapic/knowledge_bases_client.py#L338-L401
224,557
googleapis/dialogflow-python-client-v2
dialogflow_v2beta1/gapic/session_entity_types_client.py
SessionEntityTypesClient.environment_session_path
def environment_session_path(cls, project, environment, user, session): """Return a fully-qualified environment_session string.""" return google.api_core.path_template.expand( 'projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}', project=project, environment=environment, user=user, session=session, )
python
def environment_session_path(cls, project, environment, user, session): """Return a fully-qualified environment_session string.""" return google.api_core.path_template.expand( 'projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}', project=project, environment=environment, user=user, session=session, )
[ "def", "environment_session_path", "(", "cls", ",", "project", ",", "environment", ",", "user", ",", "session", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "'projects/{project}/agent/environments/{environment}/users/{user}/se...
Return a fully-qualified environment_session string.
[ "Return", "a", "fully", "-", "qualified", "environment_session", "string", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2beta1/gapic/session_entity_types_client.py#L109-L117
224,558
googleapis/dialogflow-python-client-v2
dialogflow_v2beta1/gapic/session_entity_types_client.py
SessionEntityTypesClient.environment_session_entity_type_path
def environment_session_entity_type_path(cls, project, environment, user, session, entity_type): """Return a fully-qualified environment_session_entity_type string.""" return google.api_core.path_template.expand( 'projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}/entityTypes/{entity_type}', project=project, environment=environment, user=user, session=session, entity_type=entity_type, )
python
def environment_session_entity_type_path(cls, project, environment, user, session, entity_type): """Return a fully-qualified environment_session_entity_type string.""" return google.api_core.path_template.expand( 'projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}/entityTypes/{entity_type}', project=project, environment=environment, user=user, session=session, entity_type=entity_type, )
[ "def", "environment_session_entity_type_path", "(", "cls", ",", "project", ",", "environment", ",", "user", ",", "session", ",", "entity_type", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "'projects/{project}/agent/enviro...
Return a fully-qualified environment_session_entity_type string.
[ "Return", "a", "fully", "-", "qualified", "environment_session_entity_type", "string", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2beta1/gapic/session_entity_types_client.py#L130-L140
224,559
googleapis/dialogflow-python-client-v2
dialogflow_v2beta1/gapic/documents_client.py
DocumentsClient.document_path
def document_path(cls, project, knowledge_base, document): """Return a fully-qualified document string.""" return google.api_core.path_template.expand( 'projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}', project=project, knowledge_base=knowledge_base, document=document, )
python
def document_path(cls, project, knowledge_base, document): """Return a fully-qualified document string.""" return google.api_core.path_template.expand( 'projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}', project=project, knowledge_base=knowledge_base, document=document, )
[ "def", "document_path", "(", "cls", ",", "project", ",", "knowledge_base", ",", "document", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "'projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}'", ",", "projec...
Return a fully-qualified document string.
[ "Return", "a", "fully", "-", "qualified", "document", "string", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2beta1/gapic/documents_client.py#L90-L97
224,560
googleapis/dialogflow-python-client-v2
dialogflow_v2beta1/gapic/documents_client.py
DocumentsClient.list_documents
def list_documents(self, parent, page_size=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Returns the list of all documents of the knowledge base. Example: >>> import dialogflow_v2beta1 >>> >>> client = dialogflow_v2beta1.DocumentsClient() >>> >>> parent = client.knowledge_base_path('[PROJECT]', '[KNOWLEDGE_BASE]') >>> >>> # Iterate over all results >>> for element in client.list_documents(parent): ... # process element ... pass >>> >>> >>> # Alternatively: >>> >>> # Iterate over results one page at a time >>> for page in client.list_documents(parent, options=CallOptions(page_token=INITIAL_PAGE)): ... for element in page: ... # process element ... pass Args: parent (str): Required. The knowledge base to list all documents for. Format: ``projects/<Project ID>/knowledgeBases/<Knowledge Base ID>``. page_size (int): The maximum number of resources contained in the underlying API response. If page streaming is performed per- resource, this parameter does not affect the return value. If page streaming is performed per-page, this determines the maximum number of resources in a page. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.gax.PageIterator` instance. By default, this is an iterable of :class:`~google.cloud.dialogflow_v2beta1.types.Document` instances. This object can also be configured to iterate over the pages of the response through the `options` parameter. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'list_documents' not in self._inner_api_calls: self._inner_api_calls[ 'list_documents'] = google.api_core.gapic_v1.method.wrap_method( self.transport.list_documents, default_retry=self._method_configs['ListDocuments'].retry, default_timeout=self._method_configs['ListDocuments'] .timeout, client_info=self._client_info, ) request = document_pb2.ListDocumentsRequest( parent=parent, page_size=page_size, ) iterator = google.api_core.page_iterator.GRPCIterator( client=None, method=functools.partial( self._inner_api_calls['list_documents'], retry=retry, timeout=timeout, metadata=metadata), request=request, items_field='documents', request_token_field='page_token', response_token_field='next_page_token', ) return iterator
python
def list_documents(self, parent, page_size=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Returns the list of all documents of the knowledge base. Example: >>> import dialogflow_v2beta1 >>> >>> client = dialogflow_v2beta1.DocumentsClient() >>> >>> parent = client.knowledge_base_path('[PROJECT]', '[KNOWLEDGE_BASE]') >>> >>> # Iterate over all results >>> for element in client.list_documents(parent): ... # process element ... pass >>> >>> >>> # Alternatively: >>> >>> # Iterate over results one page at a time >>> for page in client.list_documents(parent, options=CallOptions(page_token=INITIAL_PAGE)): ... for element in page: ... # process element ... pass Args: parent (str): Required. The knowledge base to list all documents for. Format: ``projects/<Project ID>/knowledgeBases/<Knowledge Base ID>``. page_size (int): The maximum number of resources contained in the underlying API response. If page streaming is performed per- resource, this parameter does not affect the return value. If page streaming is performed per-page, this determines the maximum number of resources in a page. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.gax.PageIterator` instance. By default, this is an iterable of :class:`~google.cloud.dialogflow_v2beta1.types.Document` instances. This object can also be configured to iterate over the pages of the response through the `options` parameter. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'list_documents' not in self._inner_api_calls: self._inner_api_calls[ 'list_documents'] = google.api_core.gapic_v1.method.wrap_method( self.transport.list_documents, default_retry=self._method_configs['ListDocuments'].retry, default_timeout=self._method_configs['ListDocuments'] .timeout, client_info=self._client_info, ) request = document_pb2.ListDocumentsRequest( parent=parent, page_size=page_size, ) iterator = google.api_core.page_iterator.GRPCIterator( client=None, method=functools.partial( self._inner_api_calls['list_documents'], retry=retry, timeout=timeout, metadata=metadata), request=request, items_field='documents', request_token_field='page_token', response_token_field='next_page_token', ) return iterator
[ "def", "list_documents", "(", "self", ",", "parent", ",", "page_size", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "metho...
Returns the list of all documents of the knowledge base. Example: >>> import dialogflow_v2beta1 >>> >>> client = dialogflow_v2beta1.DocumentsClient() >>> >>> parent = client.knowledge_base_path('[PROJECT]', '[KNOWLEDGE_BASE]') >>> >>> # Iterate over all results >>> for element in client.list_documents(parent): ... # process element ... pass >>> >>> >>> # Alternatively: >>> >>> # Iterate over results one page at a time >>> for page in client.list_documents(parent, options=CallOptions(page_token=INITIAL_PAGE)): ... for element in page: ... # process element ... pass Args: parent (str): Required. The knowledge base to list all documents for. Format: ``projects/<Project ID>/knowledgeBases/<Knowledge Base ID>``. page_size (int): The maximum number of resources contained in the underlying API response. If page streaming is performed per- resource, this parameter does not affect the return value. If page streaming is performed per-page, this determines the maximum number of resources in a page. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.gax.PageIterator` instance. By default, this is an iterable of :class:`~google.cloud.dialogflow_v2beta1.types.Document` instances. This object can also be configured to iterate over the pages of the response through the `options` parameter. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Returns", "the", "list", "of", "all", "documents", "of", "the", "knowledge", "base", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2beta1/gapic/documents_client.py#L187-L274
224,561
googleapis/dialogflow-python-client-v2
dialogflow_v2beta1/gapic/documents_client.py
DocumentsClient.delete_document
def delete_document(self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Deletes the specified document. Operation <response: ``google.protobuf.Empty``, metadata: [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata]> Example: >>> import dialogflow_v2beta1 >>> >>> client = dialogflow_v2beta1.DocumentsClient() >>> >>> name = client.document_path('[PROJECT]', '[KNOWLEDGE_BASE]', '[DOCUMENT]') >>> >>> response = client.delete_document(name) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: name (str): The name of the document to delete. Format: ``projects/<Project ID>/knowledgeBases/<Knowledge Base ID>/documents/<Document ID>``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2beta1.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'delete_document' not in self._inner_api_calls: self._inner_api_calls[ 'delete_document'] = google.api_core.gapic_v1.method.wrap_method( self.transport.delete_document, default_retry=self._method_configs['DeleteDocument'].retry, default_timeout=self._method_configs['DeleteDocument'] .timeout, client_info=self._client_info, ) request = document_pb2.DeleteDocumentRequest(name=name, ) operation = self._inner_api_calls['delete_document']( request, retry=retry, timeout=timeout, metadata=metadata) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, empty_pb2.Empty, metadata_type=document_pb2.KnowledgeOperationMetadata, )
python
def delete_document(self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Deletes the specified document. Operation <response: ``google.protobuf.Empty``, metadata: [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata]> Example: >>> import dialogflow_v2beta1 >>> >>> client = dialogflow_v2beta1.DocumentsClient() >>> >>> name = client.document_path('[PROJECT]', '[KNOWLEDGE_BASE]', '[DOCUMENT]') >>> >>> response = client.delete_document(name) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: name (str): The name of the document to delete. Format: ``projects/<Project ID>/knowledgeBases/<Knowledge Base ID>/documents/<Document ID>``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2beta1.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'delete_document' not in self._inner_api_calls: self._inner_api_calls[ 'delete_document'] = google.api_core.gapic_v1.method.wrap_method( self.transport.delete_document, default_retry=self._method_configs['DeleteDocument'].retry, default_timeout=self._method_configs['DeleteDocument'] .timeout, client_info=self._client_info, ) request = document_pb2.DeleteDocumentRequest(name=name, ) operation = self._inner_api_calls['delete_document']( request, retry=retry, timeout=timeout, metadata=metadata) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, empty_pb2.Empty, metadata_type=document_pb2.KnowledgeOperationMetadata, )
[ "def", "delete_document", "(", "self", ",", "name", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "metada...
Deletes the specified document. Operation <response: ``google.protobuf.Empty``, metadata: [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata]> Example: >>> import dialogflow_v2beta1 >>> >>> client = dialogflow_v2beta1.DocumentsClient() >>> >>> name = client.document_path('[PROJECT]', '[KNOWLEDGE_BASE]', '[DOCUMENT]') >>> >>> response = client.delete_document(name) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: name (str): The name of the document to delete. Format: ``projects/<Project ID>/knowledgeBases/<Knowledge Base ID>/documents/<Document ID>``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2beta1.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Deletes", "the", "specified", "document", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2beta1/gapic/documents_client.py#L413-L484
224,562
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/contexts_client.py
ContextsClient.context_path
def context_path(cls, project, session, context): """Return a fully-qualified context string.""" return google.api_core.path_template.expand( 'projects/{project}/agent/sessions/{session}/contexts/{context}', project=project, session=session, context=context, )
python
def context_path(cls, project, session, context): """Return a fully-qualified context string.""" return google.api_core.path_template.expand( 'projects/{project}/agent/sessions/{session}/contexts/{context}', project=project, session=session, context=context, )
[ "def", "context_path", "(", "cls", ",", "project", ",", "session", ",", "context", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "'projects/{project}/agent/sessions/{session}/contexts/{context}'", ",", "project", "=", "proj...
Return a fully-qualified context string.
[ "Return", "a", "fully", "-", "qualified", "context", "string", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/contexts_client.py#L104-L111
224,563
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/contexts_client.py
ContextsClient.get_context
def get_context(self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Retrieves the specified context. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.ContextsClient() >>> >>> name = client.context_path('[PROJECT]', '[SESSION]', '[CONTEXT]') >>> >>> response = client.get_context(name) Args: name (str): Required. The name of the context. Format: ``projects/<Project ID>/agent/sessions/<Session ID>/contexts/<Context ID>``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.Context` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'get_context' not in self._inner_api_calls: self._inner_api_calls[ 'get_context'] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_context, default_retry=self._method_configs['GetContext'].retry, default_timeout=self._method_configs['GetContext'].timeout, client_info=self._client_info, ) request = context_pb2.GetContextRequest(name=name, ) return self._inner_api_calls['get_context']( request, retry=retry, timeout=timeout, metadata=metadata)
python
def get_context(self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Retrieves the specified context. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.ContextsClient() >>> >>> name = client.context_path('[PROJECT]', '[SESSION]', '[CONTEXT]') >>> >>> response = client.get_context(name) Args: name (str): Required. The name of the context. Format: ``projects/<Project ID>/agent/sessions/<Session ID>/contexts/<Context ID>``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.Context` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'get_context' not in self._inner_api_calls: self._inner_api_calls[ 'get_context'] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_context, default_retry=self._method_configs['GetContext'].retry, default_timeout=self._method_configs['GetContext'].timeout, client_info=self._client_info, ) request = context_pb2.GetContextRequest(name=name, ) return self._inner_api_calls['get_context']( request, retry=retry, timeout=timeout, metadata=metadata)
[ "def", "get_context", "(", "self", ",", "name", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "metadata",...
Retrieves the specified context. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.ContextsClient() >>> >>> name = client.context_path('[PROJECT]', '[SESSION]', '[CONTEXT]') >>> >>> response = client.get_context(name) Args: name (str): Required. The name of the context. Format: ``projects/<Project ID>/agent/sessions/<Session ID>/contexts/<Context ID>``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.Context` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Retrieves", "the", "specified", "context", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/contexts_client.py#L290-L341
224,564
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/contexts_client.py
ContextsClient.update_context
def update_context(self, context, update_mask=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Updates the specified context. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.ContextsClient() >>> >>> # TODO: Initialize ``context``: >>> context = {} >>> >>> response = client.update_context(context) Args: context (Union[dict, ~google.cloud.dialogflow_v2.types.Context]): Required. The context to update. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.Context` update_mask (Union[dict, ~google.cloud.dialogflow_v2.types.FieldMask]): Optional. The mask to control which fields get updated. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.FieldMask` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.Context` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'update_context' not in self._inner_api_calls: self._inner_api_calls[ 'update_context'] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_context, default_retry=self._method_configs['UpdateContext'].retry, default_timeout=self._method_configs['UpdateContext'] .timeout, client_info=self._client_info, ) request = context_pb2.UpdateContextRequest( context=context, update_mask=update_mask, ) return self._inner_api_calls['update_context']( request, retry=retry, timeout=timeout, metadata=metadata)
python
def update_context(self, context, update_mask=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Updates the specified context. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.ContextsClient() >>> >>> # TODO: Initialize ``context``: >>> context = {} >>> >>> response = client.update_context(context) Args: context (Union[dict, ~google.cloud.dialogflow_v2.types.Context]): Required. The context to update. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.Context` update_mask (Union[dict, ~google.cloud.dialogflow_v2.types.FieldMask]): Optional. The mask to control which fields get updated. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.FieldMask` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.Context` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'update_context' not in self._inner_api_calls: self._inner_api_calls[ 'update_context'] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_context, default_retry=self._method_configs['UpdateContext'].retry, default_timeout=self._method_configs['UpdateContext'] .timeout, client_info=self._client_info, ) request = context_pb2.UpdateContextRequest( context=context, update_mask=update_mask, ) return self._inner_api_calls['update_context']( request, retry=retry, timeout=timeout, metadata=metadata)
[ "def", "update_context", "(", "self", ",", "context", ",", "update_mask", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "me...
Updates the specified context. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.ContextsClient() >>> >>> # TODO: Initialize ``context``: >>> context = {} >>> >>> response = client.update_context(context) Args: context (Union[dict, ~google.cloud.dialogflow_v2.types.Context]): Required. The context to update. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.Context` update_mask (Union[dict, ~google.cloud.dialogflow_v2.types.FieldMask]): Optional. The mask to control which fields get updated. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.FieldMask` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.Context` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Updates", "the", "specified", "context", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/contexts_client.py#L407-L468
224,565
googleapis/dialogflow-python-client-v2
samples/session_entity_type_management.py
create_session_entity_type
def create_session_entity_type(project_id, session_id, entity_values, entity_type_display_name, entity_override_mode): """Create a session entity type with the given display name.""" import dialogflow_v2 as dialogflow session_entity_types_client = dialogflow.SessionEntityTypesClient() session_path = session_entity_types_client.session_path( project_id, session_id) session_entity_type_name = ( session_entity_types_client.session_entity_type_path( project_id, session_id, entity_type_display_name)) # Here we use the entity value as the only synonym. entities = [ dialogflow.types.EntityType.Entity(value=value, synonyms=[value]) for value in entity_values] session_entity_type = dialogflow.types.SessionEntityType( name=session_entity_type_name, entity_override_mode=entity_override_mode, entities=entities) response = session_entity_types_client.create_session_entity_type( session_path, session_entity_type) print('SessionEntityType created: \n\n{}'.format(response))
python
def create_session_entity_type(project_id, session_id, entity_values, entity_type_display_name, entity_override_mode): """Create a session entity type with the given display name.""" import dialogflow_v2 as dialogflow session_entity_types_client = dialogflow.SessionEntityTypesClient() session_path = session_entity_types_client.session_path( project_id, session_id) session_entity_type_name = ( session_entity_types_client.session_entity_type_path( project_id, session_id, entity_type_display_name)) # Here we use the entity value as the only synonym. entities = [ dialogflow.types.EntityType.Entity(value=value, synonyms=[value]) for value in entity_values] session_entity_type = dialogflow.types.SessionEntityType( name=session_entity_type_name, entity_override_mode=entity_override_mode, entities=entities) response = session_entity_types_client.create_session_entity_type( session_path, session_entity_type) print('SessionEntityType created: \n\n{}'.format(response))
[ "def", "create_session_entity_type", "(", "project_id", ",", "session_id", ",", "entity_values", ",", "entity_type_display_name", ",", "entity_override_mode", ")", ":", "import", "dialogflow_v2", "as", "dialogflow", "session_entity_types_client", "=", "dialogflow", ".", "...
Create a session entity type with the given display name.
[ "Create", "a", "session", "entity", "type", "with", "the", "given", "display", "name", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/session_entity_type_management.py#L54-L78
224,566
googleapis/dialogflow-python-client-v2
samples/session_entity_type_management.py
delete_session_entity_type
def delete_session_entity_type(project_id, session_id, entity_type_display_name): """Delete session entity type with the given entity type display name.""" import dialogflow_v2 as dialogflow session_entity_types_client = dialogflow.SessionEntityTypesClient() session_entity_type_name = ( session_entity_types_client.session_entity_type_path( project_id, session_id, entity_type_display_name)) session_entity_types_client.delete_session_entity_type( session_entity_type_name)
python
def delete_session_entity_type(project_id, session_id, entity_type_display_name): """Delete session entity type with the given entity type display name.""" import dialogflow_v2 as dialogflow session_entity_types_client = dialogflow.SessionEntityTypesClient() session_entity_type_name = ( session_entity_types_client.session_entity_type_path( project_id, session_id, entity_type_display_name)) session_entity_types_client.delete_session_entity_type( session_entity_type_name)
[ "def", "delete_session_entity_type", "(", "project_id", ",", "session_id", ",", "entity_type_display_name", ")", ":", "import", "dialogflow_v2", "as", "dialogflow", "session_entity_types_client", "=", "dialogflow", ".", "SessionEntityTypesClient", "(", ")", "session_entity_...
Delete session entity type with the given entity type display name.
[ "Delete", "session", "entity", "type", "with", "the", "given", "entity", "type", "display", "name", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/session_entity_type_management.py#L83-L94
224,567
googleapis/dialogflow-python-client-v2
samples/entity_type_management.py
create_entity_type
def create_entity_type(project_id, display_name, kind): """Create an entity type with the given display name.""" import dialogflow_v2 as dialogflow entity_types_client = dialogflow.EntityTypesClient() parent = entity_types_client.project_agent_path(project_id) entity_type = dialogflow.types.EntityType( display_name=display_name, kind=kind) response = entity_types_client.create_entity_type(parent, entity_type) print('Entity type created: \n{}'.format(response))
python
def create_entity_type(project_id, display_name, kind): """Create an entity type with the given display name.""" import dialogflow_v2 as dialogflow entity_types_client = dialogflow.EntityTypesClient() parent = entity_types_client.project_agent_path(project_id) entity_type = dialogflow.types.EntityType( display_name=display_name, kind=kind) response = entity_types_client.create_entity_type(parent, entity_type) print('Entity type created: \n{}'.format(response))
[ "def", "create_entity_type", "(", "project_id", ",", "display_name", ",", "kind", ")", ":", "import", "dialogflow_v2", "as", "dialogflow", "entity_types_client", "=", "dialogflow", ".", "EntityTypesClient", "(", ")", "parent", "=", "entity_types_client", ".", "proje...
Create an entity type with the given display name.
[ "Create", "an", "entity", "type", "with", "the", "given", "display", "name", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/entity_type_management.py#L45-L56
224,568
googleapis/dialogflow-python-client-v2
samples/entity_type_management.py
delete_entity_type
def delete_entity_type(project_id, entity_type_id): """Delete entity type with the given entity type name.""" import dialogflow_v2 as dialogflow entity_types_client = dialogflow.EntityTypesClient() entity_type_path = entity_types_client.entity_type_path( project_id, entity_type_id) entity_types_client.delete_entity_type(entity_type_path)
python
def delete_entity_type(project_id, entity_type_id): """Delete entity type with the given entity type name.""" import dialogflow_v2 as dialogflow entity_types_client = dialogflow.EntityTypesClient() entity_type_path = entity_types_client.entity_type_path( project_id, entity_type_id) entity_types_client.delete_entity_type(entity_type_path)
[ "def", "delete_entity_type", "(", "project_id", ",", "entity_type_id", ")", ":", "import", "dialogflow_v2", "as", "dialogflow", "entity_types_client", "=", "dialogflow", ".", "EntityTypesClient", "(", ")", "entity_type_path", "=", "entity_types_client", ".", "entity_typ...
Delete entity type with the given entity type name.
[ "Delete", "entity", "type", "with", "the", "given", "entity", "type", "name", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/entity_type_management.py#L61-L69
224,569
googleapis/dialogflow-python-client-v2
samples/detect_intent_texts.py
detect_intent_texts
def detect_intent_texts(project_id, session_id, texts, language_code): """Returns the result of detect intent with texts as inputs. Using the same `session_id` between requests allows continuation of the conversation.""" import dialogflow_v2 as dialogflow session_client = dialogflow.SessionsClient() session = session_client.session_path(project_id, session_id) print('Session path: {}\n'.format(session)) for text in texts: text_input = dialogflow.types.TextInput( text=text, language_code=language_code) query_input = dialogflow.types.QueryInput(text=text_input) response = session_client.detect_intent( session=session, query_input=query_input) print('=' * 20) print('Query text: {}'.format(response.query_result.query_text)) print('Detected intent: {} (confidence: {})\n'.format( response.query_result.intent.display_name, response.query_result.intent_detection_confidence)) print('Fulfillment text: {}\n'.format( response.query_result.fulfillment_text))
python
def detect_intent_texts(project_id, session_id, texts, language_code): """Returns the result of detect intent with texts as inputs. Using the same `session_id` between requests allows continuation of the conversation.""" import dialogflow_v2 as dialogflow session_client = dialogflow.SessionsClient() session = session_client.session_path(project_id, session_id) print('Session path: {}\n'.format(session)) for text in texts: text_input = dialogflow.types.TextInput( text=text, language_code=language_code) query_input = dialogflow.types.QueryInput(text=text_input) response = session_client.detect_intent( session=session, query_input=query_input) print('=' * 20) print('Query text: {}'.format(response.query_result.query_text)) print('Detected intent: {} (confidence: {})\n'.format( response.query_result.intent.display_name, response.query_result.intent_detection_confidence)) print('Fulfillment text: {}\n'.format( response.query_result.fulfillment_text))
[ "def", "detect_intent_texts", "(", "project_id", ",", "session_id", ",", "texts", ",", "language_code", ")", ":", "import", "dialogflow_v2", "as", "dialogflow", "session_client", "=", "dialogflow", ".", "SessionsClient", "(", ")", "session", "=", "session_client", ...
Returns the result of detect intent with texts as inputs. Using the same `session_id` between requests allows continuation of the conversation.
[ "Returns", "the", "result", "of", "detect", "intent", "with", "texts", "as", "inputs", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/detect_intent_texts.py#L34-L61
224,570
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/entity_types_client.py
EntityTypesClient.entity_type_path
def entity_type_path(cls, project, entity_type): """Return a fully-qualified entity_type string.""" return google.api_core.path_template.expand( 'projects/{project}/agent/entityTypes/{entity_type}', project=project, entity_type=entity_type, )
python
def entity_type_path(cls, project, entity_type): """Return a fully-qualified entity_type string.""" return google.api_core.path_template.expand( 'projects/{project}/agent/entityTypes/{entity_type}', project=project, entity_type=entity_type, )
[ "def", "entity_type_path", "(", "cls", ",", "project", ",", "entity_type", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "'projects/{project}/agent/entityTypes/{entity_type}'", ",", "project", "=", "project", ",", "entity_t...
Return a fully-qualified entity_type string.
[ "Return", "a", "fully", "-", "qualified", "entity_type", "string", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/entity_types_client.py#L118-L124
224,571
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/entity_types_client.py
EntityTypesClient.get_entity_type
def get_entity_type(self, name, language_code=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Retrieves the specified entity type. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.EntityTypesClient() >>> >>> name = client.entity_type_path('[PROJECT]', '[ENTITY_TYPE]') >>> >>> response = client.get_entity_type(name) Args: name (str): Required. The name of the entity type. Format: ``projects/<Project ID>/agent/entityTypes/<EntityType ID>``. language_code (str): Optional. The language to retrieve entity synonyms for. If not specified, the agent's default language is used. [More than a dozen languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must be enabled in the agent, before they can be used. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.EntityType` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'get_entity_type' not in self._inner_api_calls: self._inner_api_calls[ 'get_entity_type'] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_entity_type, default_retry=self._method_configs['GetEntityType'].retry, default_timeout=self._method_configs['GetEntityType'] .timeout, client_info=self._client_info, ) request = entity_type_pb2.GetEntityTypeRequest( name=name, language_code=language_code, ) return self._inner_api_calls['get_entity_type']( request, retry=retry, timeout=timeout, metadata=metadata)
python
def get_entity_type(self, name, language_code=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Retrieves the specified entity type. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.EntityTypesClient() >>> >>> name = client.entity_type_path('[PROJECT]', '[ENTITY_TYPE]') >>> >>> response = client.get_entity_type(name) Args: name (str): Required. The name of the entity type. Format: ``projects/<Project ID>/agent/entityTypes/<EntityType ID>``. language_code (str): Optional. The language to retrieve entity synonyms for. If not specified, the agent's default language is used. [More than a dozen languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must be enabled in the agent, before they can be used. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.EntityType` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'get_entity_type' not in self._inner_api_calls: self._inner_api_calls[ 'get_entity_type'] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_entity_type, default_retry=self._method_configs['GetEntityType'].retry, default_timeout=self._method_configs['GetEntityType'] .timeout, client_info=self._client_info, ) request = entity_type_pb2.GetEntityTypeRequest( name=name, language_code=language_code, ) return self._inner_api_calls['get_entity_type']( request, retry=retry, timeout=timeout, metadata=metadata)
[ "def", "get_entity_type", "(", "self", ",", "name", ",", "language_code", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "me...
Retrieves the specified entity type. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.EntityTypesClient() >>> >>> name = client.entity_type_path('[PROJECT]', '[ENTITY_TYPE]') >>> >>> response = client.get_entity_type(name) Args: name (str): Required. The name of the entity type. Format: ``projects/<Project ID>/agent/entityTypes/<EntityType ID>``. language_code (str): Optional. The language to retrieve entity synonyms for. If not specified, the agent's default language is used. [More than a dozen languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must be enabled in the agent, before they can be used. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.EntityType` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Retrieves", "the", "specified", "entity", "type", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/entity_types_client.py#L311-L372
224,572
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/entity_types_client.py
EntityTypesClient.create_entity_type
def create_entity_type(self, parent, entity_type, language_code=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Creates an entity type in the specified agent. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.EntityTypesClient() >>> >>> parent = client.project_agent_path('[PROJECT]') >>> >>> # TODO: Initialize ``entity_type``: >>> entity_type = {} >>> >>> response = client.create_entity_type(parent, entity_type) Args: parent (str): Required. The agent to create a entity type for. Format: ``projects/<Project ID>/agent``. entity_type (Union[dict, ~google.cloud.dialogflow_v2.types.EntityType]): Required. The entity type to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.EntityType` language_code (str): Optional. The language of entity synonyms defined in ``entity_type``. If not specified, the agent's default language is used. [More than a dozen languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must be enabled in the agent, before they can be used. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.EntityType` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'create_entity_type' not in self._inner_api_calls: self._inner_api_calls[ 'create_entity_type'] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_entity_type, default_retry=self._method_configs[ 'CreateEntityType'].retry, default_timeout=self._method_configs['CreateEntityType'] .timeout, client_info=self._client_info, ) request = entity_type_pb2.CreateEntityTypeRequest( parent=parent, entity_type=entity_type, language_code=language_code, ) return self._inner_api_calls['create_entity_type']( request, retry=retry, timeout=timeout, metadata=metadata)
python
def create_entity_type(self, parent, entity_type, language_code=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Creates an entity type in the specified agent. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.EntityTypesClient() >>> >>> parent = client.project_agent_path('[PROJECT]') >>> >>> # TODO: Initialize ``entity_type``: >>> entity_type = {} >>> >>> response = client.create_entity_type(parent, entity_type) Args: parent (str): Required. The agent to create a entity type for. Format: ``projects/<Project ID>/agent``. entity_type (Union[dict, ~google.cloud.dialogflow_v2.types.EntityType]): Required. The entity type to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.EntityType` language_code (str): Optional. The language of entity synonyms defined in ``entity_type``. If not specified, the agent's default language is used. [More than a dozen languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must be enabled in the agent, before they can be used. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.EntityType` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'create_entity_type' not in self._inner_api_calls: self._inner_api_calls[ 'create_entity_type'] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_entity_type, default_retry=self._method_configs[ 'CreateEntityType'].retry, default_timeout=self._method_configs['CreateEntityType'] .timeout, client_info=self._client_info, ) request = entity_type_pb2.CreateEntityTypeRequest( parent=parent, entity_type=entity_type, language_code=language_code, ) return self._inner_api_calls['create_entity_type']( request, retry=retry, timeout=timeout, metadata=metadata)
[ "def", "create_entity_type", "(", "self", ",", "parent", ",", "entity_type", ",", "language_code", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", "....
Creates an entity type in the specified agent. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.EntityTypesClient() >>> >>> parent = client.project_agent_path('[PROJECT]') >>> >>> # TODO: Initialize ``entity_type``: >>> entity_type = {} >>> >>> response = client.create_entity_type(parent, entity_type) Args: parent (str): Required. The agent to create a entity type for. Format: ``projects/<Project ID>/agent``. entity_type (Union[dict, ~google.cloud.dialogflow_v2.types.EntityType]): Required. The entity type to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.EntityType` language_code (str): Optional. The language of entity synonyms defined in ``entity_type``. If not specified, the agent's default language is used. [More than a dozen languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must be enabled in the agent, before they can be used. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.EntityType` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Creates", "an", "entity", "type", "in", "the", "specified", "agent", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/entity_types_client.py#L374-L444
224,573
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/entity_types_client.py
EntityTypesClient.update_entity_type
def update_entity_type(self, entity_type, language_code=None, update_mask=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Updates the specified entity type. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.EntityTypesClient() >>> >>> # TODO: Initialize ``entity_type``: >>> entity_type = {} >>> >>> response = client.update_entity_type(entity_type) Args: entity_type (Union[dict, ~google.cloud.dialogflow_v2.types.EntityType]): Required. The entity type to update. Format: ``projects/<Project ID>/agent/entityTypes/<EntityType ID>``. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.EntityType` language_code (str): Optional. The language of entity synonyms defined in ``entity_type``. If not specified, the agent's default language is used. [More than a dozen languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must be enabled in the agent, before they can be used. update_mask (Union[dict, ~google.cloud.dialogflow_v2.types.FieldMask]): Optional. The mask to control which fields get updated. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.FieldMask` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.EntityType` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'update_entity_type' not in self._inner_api_calls: self._inner_api_calls[ 'update_entity_type'] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_entity_type, default_retry=self._method_configs[ 'UpdateEntityType'].retry, default_timeout=self._method_configs['UpdateEntityType'] .timeout, client_info=self._client_info, ) request = entity_type_pb2.UpdateEntityTypeRequest( entity_type=entity_type, language_code=language_code, update_mask=update_mask, ) return self._inner_api_calls['update_entity_type']( request, retry=retry, timeout=timeout, metadata=metadata)
python
def update_entity_type(self, entity_type, language_code=None, update_mask=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Updates the specified entity type. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.EntityTypesClient() >>> >>> # TODO: Initialize ``entity_type``: >>> entity_type = {} >>> >>> response = client.update_entity_type(entity_type) Args: entity_type (Union[dict, ~google.cloud.dialogflow_v2.types.EntityType]): Required. The entity type to update. Format: ``projects/<Project ID>/agent/entityTypes/<EntityType ID>``. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.EntityType` language_code (str): Optional. The language of entity synonyms defined in ``entity_type``. If not specified, the agent's default language is used. [More than a dozen languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must be enabled in the agent, before they can be used. update_mask (Union[dict, ~google.cloud.dialogflow_v2.types.FieldMask]): Optional. The mask to control which fields get updated. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.FieldMask` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.EntityType` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'update_entity_type' not in self._inner_api_calls: self._inner_api_calls[ 'update_entity_type'] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_entity_type, default_retry=self._method_configs[ 'UpdateEntityType'].retry, default_timeout=self._method_configs['UpdateEntityType'] .timeout, client_info=self._client_info, ) request = entity_type_pb2.UpdateEntityTypeRequest( entity_type=entity_type, language_code=language_code, update_mask=update_mask, ) return self._inner_api_calls['update_entity_type']( request, retry=retry, timeout=timeout, metadata=metadata)
[ "def", "update_entity_type", "(", "self", ",", "entity_type", ",", "language_code", "=", "None", ",", "update_mask", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", "...
Updates the specified entity type. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.EntityTypesClient() >>> >>> # TODO: Initialize ``entity_type``: >>> entity_type = {} >>> >>> response = client.update_entity_type(entity_type) Args: entity_type (Union[dict, ~google.cloud.dialogflow_v2.types.EntityType]): Required. The entity type to update. Format: ``projects/<Project ID>/agent/entityTypes/<EntityType ID>``. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.EntityType` language_code (str): Optional. The language of entity synonyms defined in ``entity_type``. If not specified, the agent's default language is used. [More than a dozen languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must be enabled in the agent, before they can be used. update_mask (Union[dict, ~google.cloud.dialogflow_v2.types.FieldMask]): Optional. The mask to control which fields get updated. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.FieldMask` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.EntityType` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Updates", "the", "specified", "entity", "type", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/entity_types_client.py#L446-L516
224,574
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/entity_types_client.py
EntityTypesClient.batch_delete_entities
def batch_delete_entities(self, parent, entity_values, language_code=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Deletes entities in the specified entity type. Operation <response: ``google.protobuf.Empty``, metadata: [google.protobuf.Struct][google.protobuf.Struct]> Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.EntityTypesClient() >>> >>> parent = client.entity_type_path('[PROJECT]', '[ENTITY_TYPE]') >>> >>> # TODO: Initialize ``entity_values``: >>> entity_values = [] >>> >>> response = client.batch_delete_entities(parent, entity_values) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. The name of the entity type to delete entries for. Format: ``projects/<Project ID>/agent/entityTypes/<Entity Type ID>``. entity_values (list[str]): Required. The canonical ``values`` of the entities to delete. Note that these are not fully-qualified names, i.e. they don't start with ``projects/<Project ID>``. language_code (str): Optional. The language of entity synonyms defined in ``entities``. If not specified, the agent's default language is used. [More than a dozen languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must be enabled in the agent, before they can be used. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'batch_delete_entities' not in self._inner_api_calls: self._inner_api_calls[ 'batch_delete_entities'] = google.api_core.gapic_v1.method.wrap_method( self.transport.batch_delete_entities, default_retry=self._method_configs[ 'BatchDeleteEntities'].retry, default_timeout=self._method_configs['BatchDeleteEntities'] .timeout, client_info=self._client_info, ) request = entity_type_pb2.BatchDeleteEntitiesRequest( parent=parent, entity_values=entity_values, language_code=language_code, ) operation = self._inner_api_calls['batch_delete_entities']( request, retry=retry, timeout=timeout, metadata=metadata) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, empty_pb2.Empty, metadata_type=struct_pb2.Struct, )
python
def batch_delete_entities(self, parent, entity_values, language_code=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Deletes entities in the specified entity type. Operation <response: ``google.protobuf.Empty``, metadata: [google.protobuf.Struct][google.protobuf.Struct]> Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.EntityTypesClient() >>> >>> parent = client.entity_type_path('[PROJECT]', '[ENTITY_TYPE]') >>> >>> # TODO: Initialize ``entity_values``: >>> entity_values = [] >>> >>> response = client.batch_delete_entities(parent, entity_values) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. The name of the entity type to delete entries for. Format: ``projects/<Project ID>/agent/entityTypes/<Entity Type ID>``. entity_values (list[str]): Required. The canonical ``values`` of the entities to delete. Note that these are not fully-qualified names, i.e. they don't start with ``projects/<Project ID>``. language_code (str): Optional. The language of entity synonyms defined in ``entities``. If not specified, the agent's default language is used. [More than a dozen languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must be enabled in the agent, before they can be used. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'batch_delete_entities' not in self._inner_api_calls: self._inner_api_calls[ 'batch_delete_entities'] = google.api_core.gapic_v1.method.wrap_method( self.transport.batch_delete_entities, default_retry=self._method_configs[ 'BatchDeleteEntities'].retry, default_timeout=self._method_configs['BatchDeleteEntities'] .timeout, client_info=self._client_info, ) request = entity_type_pb2.BatchDeleteEntitiesRequest( parent=parent, entity_values=entity_values, language_code=language_code, ) operation = self._inner_api_calls['batch_delete_entities']( request, retry=retry, timeout=timeout, metadata=metadata) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, empty_pb2.Empty, metadata_type=struct_pb2.Struct, )
[ "def", "batch_delete_entities", "(", "self", ",", "parent", ",", "entity_values", ",", "language_code", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core",...
Deletes entities in the specified entity type. Operation <response: ``google.protobuf.Empty``, metadata: [google.protobuf.Struct][google.protobuf.Struct]> Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.EntityTypesClient() >>> >>> parent = client.entity_type_path('[PROJECT]', '[ENTITY_TYPE]') >>> >>> # TODO: Initialize ``entity_values``: >>> entity_values = [] >>> >>> response = client.batch_delete_entities(parent, entity_values) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. The name of the entity type to delete entries for. Format: ``projects/<Project ID>/agent/entityTypes/<Entity Type ID>``. entity_values (list[str]): Required. The canonical ``values`` of the entities to delete. Note that these are not fully-qualified names, i.e. they don't start with ``projects/<Project ID>``. language_code (str): Optional. The language of entity synonyms defined in ``entities``. If not specified, the agent's default language is used. [More than a dozen languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must be enabled in the agent, before they can be used. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Deletes", "entities", "in", "the", "specified", "entity", "type", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/entity_types_client.py#L945-L1033
224,575
googleapis/dialogflow-python-client-v2
samples/detect_intent_knowledge.py
detect_intent_knowledge
def detect_intent_knowledge(project_id, session_id, language_code, knowledge_base_id, texts): """Returns the result of detect intent with querying Knowledge Connector. Args: project_id: The GCP project linked with the agent you are going to query. session_id: Id of the session, using the same `session_id` between requests allows continuation of the conversation. language_code: Language of the queries. knowledge_base_id: The Knowledge base's id to query against. texts: A list of text queries to send. """ import dialogflow_v2beta1 as dialogflow session_client = dialogflow.SessionsClient() session_path = session_client.session_path(project_id, session_id) print('Session path: {}\n'.format(session_path)) for text in texts: text_input = dialogflow.types.TextInput( text=text, language_code=language_code) query_input = dialogflow.types.QueryInput(text=text_input) knowledge_base_path = dialogflow.knowledge_bases_client \ .KnowledgeBasesClient \ .knowledge_base_path(project_id, knowledge_base_id) query_params = dialogflow.types.QueryParameters( knowledge_base_names=[knowledge_base_path]) response = session_client.detect_intent( session=session_path, query_input=query_input, query_params=query_params) print('=' * 20) print('Query text: {}'.format(response.query_result.query_text)) print('Detected intent: {} (confidence: {})\n'.format( response.query_result.intent.display_name, response.query_result.intent_detection_confidence)) print('Fulfillment text: {}\n'.format( response.query_result.fulfillment_text)) print('Knowledge results:') knowledge_answers = response.query_result.knowledge_answers for answers in knowledge_answers.answers: print(' - Answer: {}'.format(answers.answer)) print(' - Confidence: {}'.format( answers.match_confidence))
python
def detect_intent_knowledge(project_id, session_id, language_code, knowledge_base_id, texts): """Returns the result of detect intent with querying Knowledge Connector. Args: project_id: The GCP project linked with the agent you are going to query. session_id: Id of the session, using the same `session_id` between requests allows continuation of the conversation. language_code: Language of the queries. knowledge_base_id: The Knowledge base's id to query against. texts: A list of text queries to send. """ import dialogflow_v2beta1 as dialogflow session_client = dialogflow.SessionsClient() session_path = session_client.session_path(project_id, session_id) print('Session path: {}\n'.format(session_path)) for text in texts: text_input = dialogflow.types.TextInput( text=text, language_code=language_code) query_input = dialogflow.types.QueryInput(text=text_input) knowledge_base_path = dialogflow.knowledge_bases_client \ .KnowledgeBasesClient \ .knowledge_base_path(project_id, knowledge_base_id) query_params = dialogflow.types.QueryParameters( knowledge_base_names=[knowledge_base_path]) response = session_client.detect_intent( session=session_path, query_input=query_input, query_params=query_params) print('=' * 20) print('Query text: {}'.format(response.query_result.query_text)) print('Detected intent: {} (confidence: {})\n'.format( response.query_result.intent.display_name, response.query_result.intent_detection_confidence)) print('Fulfillment text: {}\n'.format( response.query_result.fulfillment_text)) print('Knowledge results:') knowledge_answers = response.query_result.knowledge_answers for answers in knowledge_answers.answers: print(' - Answer: {}'.format(answers.answer)) print(' - Confidence: {}'.format( answers.match_confidence))
[ "def", "detect_intent_knowledge", "(", "project_id", ",", "session_id", ",", "language_code", ",", "knowledge_base_id", ",", "texts", ")", ":", "import", "dialogflow_v2beta1", "as", "dialogflow", "session_client", "=", "dialogflow", ".", "SessionsClient", "(", ")", ...
Returns the result of detect intent with querying Knowledge Connector. Args: project_id: The GCP project linked with the agent you are going to query. session_id: Id of the session, using the same `session_id` between requests allows continuation of the conversation. language_code: Language of the queries. knowledge_base_id: The Knowledge base's id to query against. texts: A list of text queries to send.
[ "Returns", "the", "result", "of", "detect", "intent", "with", "querying", "Knowledge", "Connector", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/detect_intent_knowledge.py#L31-L78
224,576
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/intents_client.py
IntentsClient.intent_path
def intent_path(cls, project, intent): """Return a fully-qualified intent string.""" return google.api_core.path_template.expand( 'projects/{project}/agent/intents/{intent}', project=project, intent=intent, )
python
def intent_path(cls, project, intent): """Return a fully-qualified intent string.""" return google.api_core.path_template.expand( 'projects/{project}/agent/intents/{intent}', project=project, intent=intent, )
[ "def", "intent_path", "(", "cls", ",", "project", ",", "intent", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "'projects/{project}/agent/intents/{intent}'", ",", "project", "=", "project", ",", "intent", "=", "intent",...
Return a fully-qualified intent string.
[ "Return", "a", "fully", "-", "qualified", "intent", "string", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/intents_client.py#L125-L131
224,577
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/intents_client.py
IntentsClient.agent_path
def agent_path(cls, project, agent): """Return a fully-qualified agent string.""" return google.api_core.path_template.expand( 'projects/{project}/agents/{agent}', project=project, agent=agent, )
python
def agent_path(cls, project, agent): """Return a fully-qualified agent string.""" return google.api_core.path_template.expand( 'projects/{project}/agents/{agent}', project=project, agent=agent, )
[ "def", "agent_path", "(", "cls", ",", "project", ",", "agent", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "'projects/{project}/agents/{agent}'", ",", "project", "=", "project", ",", "agent", "=", "agent", ",", ")...
Return a fully-qualified agent string.
[ "Return", "a", "fully", "-", "qualified", "agent", "string", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/intents_client.py#L134-L140
224,578
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/intents_client.py
IntentsClient.get_intent
def get_intent(self, name, language_code=None, intent_view=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Retrieves the specified intent. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.IntentsClient() >>> >>> name = client.intent_path('[PROJECT]', '[INTENT]') >>> >>> response = client.get_intent(name) Args: name (str): Required. The name of the intent. Format: ``projects/<Project ID>/agent/intents/<Intent ID>``. language_code (str): Optional. The language to retrieve training phrases, parameters and rich messages for. If not specified, the agent's default language is used. [More than a dozen languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must be enabled in the agent, before they can be used. intent_view (~google.cloud.dialogflow_v2.types.IntentView): Optional. The resource view to apply to the returned intent. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.Intent` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'get_intent' not in self._inner_api_calls: self._inner_api_calls[ 'get_intent'] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_intent, default_retry=self._method_configs['GetIntent'].retry, default_timeout=self._method_configs['GetIntent'].timeout, client_info=self._client_info, ) request = intent_pb2.GetIntentRequest( name=name, language_code=language_code, intent_view=intent_view, ) return self._inner_api_calls['get_intent']( request, retry=retry, timeout=timeout, metadata=metadata)
python
def get_intent(self, name, language_code=None, intent_view=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Retrieves the specified intent. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.IntentsClient() >>> >>> name = client.intent_path('[PROJECT]', '[INTENT]') >>> >>> response = client.get_intent(name) Args: name (str): Required. The name of the intent. Format: ``projects/<Project ID>/agent/intents/<Intent ID>``. language_code (str): Optional. The language to retrieve training phrases, parameters and rich messages for. If not specified, the agent's default language is used. [More than a dozen languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must be enabled in the agent, before they can be used. intent_view (~google.cloud.dialogflow_v2.types.IntentView): Optional. The resource view to apply to the returned intent. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.Intent` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'get_intent' not in self._inner_api_calls: self._inner_api_calls[ 'get_intent'] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_intent, default_retry=self._method_configs['GetIntent'].retry, default_timeout=self._method_configs['GetIntent'].timeout, client_info=self._client_info, ) request = intent_pb2.GetIntentRequest( name=name, language_code=language_code, intent_view=intent_view, ) return self._inner_api_calls['get_intent']( request, retry=retry, timeout=timeout, metadata=metadata)
[ "def", "get_intent", "(", "self", ",", "name", ",", "language_code", "=", "None", ",", "intent_view", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core...
Retrieves the specified intent. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.IntentsClient() >>> >>> name = client.intent_path('[PROJECT]', '[INTENT]') >>> >>> response = client.get_intent(name) Args: name (str): Required. The name of the intent. Format: ``projects/<Project ID>/agent/intents/<Intent ID>``. language_code (str): Optional. The language to retrieve training phrases, parameters and rich messages for. If not specified, the agent's default language is used. [More than a dozen languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must be enabled in the agent, before they can be used. intent_view (~google.cloud.dialogflow_v2.types.IntentView): Optional. The resource view to apply to the returned intent. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.Intent` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Retrieves", "the", "specified", "intent", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/intents_client.py#L328-L391
224,579
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/intents_client.py
IntentsClient.create_intent
def create_intent(self, parent, intent, language_code=None, intent_view=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Creates an intent in the specified agent. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.IntentsClient() >>> >>> parent = client.project_agent_path('[PROJECT]') >>> >>> # TODO: Initialize ``intent``: >>> intent = {} >>> >>> response = client.create_intent(parent, intent) Args: parent (str): Required. The agent to create a intent for. Format: ``projects/<Project ID>/agent``. intent (Union[dict, ~google.cloud.dialogflow_v2.types.Intent]): Required. The intent to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.Intent` language_code (str): Optional. The language of training phrases, parameters and rich messages defined in ``intent``. If not specified, the agent's default language is used. [More than a dozen languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must be enabled in the agent, before they can be used. intent_view (~google.cloud.dialogflow_v2.types.IntentView): Optional. The resource view to apply to the returned intent. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.Intent` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'create_intent' not in self._inner_api_calls: self._inner_api_calls[ 'create_intent'] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_intent, default_retry=self._method_configs['CreateIntent'].retry, default_timeout=self._method_configs['CreateIntent'] .timeout, client_info=self._client_info, ) request = intent_pb2.CreateIntentRequest( parent=parent, intent=intent, language_code=language_code, intent_view=intent_view, ) return self._inner_api_calls['create_intent']( request, retry=retry, timeout=timeout, metadata=metadata)
python
def create_intent(self, parent, intent, language_code=None, intent_view=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Creates an intent in the specified agent. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.IntentsClient() >>> >>> parent = client.project_agent_path('[PROJECT]') >>> >>> # TODO: Initialize ``intent``: >>> intent = {} >>> >>> response = client.create_intent(parent, intent) Args: parent (str): Required. The agent to create a intent for. Format: ``projects/<Project ID>/agent``. intent (Union[dict, ~google.cloud.dialogflow_v2.types.Intent]): Required. The intent to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.Intent` language_code (str): Optional. The language of training phrases, parameters and rich messages defined in ``intent``. If not specified, the agent's default language is used. [More than a dozen languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must be enabled in the agent, before they can be used. intent_view (~google.cloud.dialogflow_v2.types.IntentView): Optional. The resource view to apply to the returned intent. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.Intent` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'create_intent' not in self._inner_api_calls: self._inner_api_calls[ 'create_intent'] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_intent, default_retry=self._method_configs['CreateIntent'].retry, default_timeout=self._method_configs['CreateIntent'] .timeout, client_info=self._client_info, ) request = intent_pb2.CreateIntentRequest( parent=parent, intent=intent, language_code=language_code, intent_view=intent_view, ) return self._inner_api_calls['create_intent']( request, retry=retry, timeout=timeout, metadata=metadata)
[ "def", "create_intent", "(", "self", ",", "parent", ",", "intent", ",", "language_code", "=", "None", ",", "intent_view", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "goo...
Creates an intent in the specified agent. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.IntentsClient() >>> >>> parent = client.project_agent_path('[PROJECT]') >>> >>> # TODO: Initialize ``intent``: >>> intent = {} >>> >>> response = client.create_intent(parent, intent) Args: parent (str): Required. The agent to create a intent for. Format: ``projects/<Project ID>/agent``. intent (Union[dict, ~google.cloud.dialogflow_v2.types.Intent]): Required. The intent to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.Intent` language_code (str): Optional. The language of training phrases, parameters and rich messages defined in ``intent``. If not specified, the agent's default language is used. [More than a dozen languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must be enabled in the agent, before they can be used. intent_view (~google.cloud.dialogflow_v2.types.IntentView): Optional. The resource view to apply to the returned intent. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.Intent` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Creates", "an", "intent", "in", "the", "specified", "agent", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/intents_client.py#L393-L465
224,580
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/intents_client.py
IntentsClient.update_intent
def update_intent(self, intent, language_code, update_mask=None, intent_view=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Updates the specified intent. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.IntentsClient() >>> >>> # TODO: Initialize ``intent``: >>> intent = {} >>> >>> # TODO: Initialize ``language_code``: >>> language_code = '' >>> >>> response = client.update_intent(intent, language_code) Args: intent (Union[dict, ~google.cloud.dialogflow_v2.types.Intent]): Required. The intent to update. Format: ``projects/<Project ID>/agent/intents/<Intent ID>``. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.Intent` language_code (str): Optional. The language of training phrases, parameters and rich messages defined in ``intent``. If not specified, the agent's default language is used. [More than a dozen languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must be enabled in the agent, before they can be used. update_mask (Union[dict, ~google.cloud.dialogflow_v2.types.FieldMask]): Optional. The mask to control which fields get updated. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.FieldMask` intent_view (~google.cloud.dialogflow_v2.types.IntentView): Optional. The resource view to apply to the returned intent. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.Intent` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'update_intent' not in self._inner_api_calls: self._inner_api_calls[ 'update_intent'] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_intent, default_retry=self._method_configs['UpdateIntent'].retry, default_timeout=self._method_configs['UpdateIntent'] .timeout, client_info=self._client_info, ) request = intent_pb2.UpdateIntentRequest( intent=intent, language_code=language_code, update_mask=update_mask, intent_view=intent_view, ) return self._inner_api_calls['update_intent']( request, retry=retry, timeout=timeout, metadata=metadata)
python
def update_intent(self, intent, language_code, update_mask=None, intent_view=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Updates the specified intent. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.IntentsClient() >>> >>> # TODO: Initialize ``intent``: >>> intent = {} >>> >>> # TODO: Initialize ``language_code``: >>> language_code = '' >>> >>> response = client.update_intent(intent, language_code) Args: intent (Union[dict, ~google.cloud.dialogflow_v2.types.Intent]): Required. The intent to update. Format: ``projects/<Project ID>/agent/intents/<Intent ID>``. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.Intent` language_code (str): Optional. The language of training phrases, parameters and rich messages defined in ``intent``. If not specified, the agent's default language is used. [More than a dozen languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must be enabled in the agent, before they can be used. update_mask (Union[dict, ~google.cloud.dialogflow_v2.types.FieldMask]): Optional. The mask to control which fields get updated. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.FieldMask` intent_view (~google.cloud.dialogflow_v2.types.IntentView): Optional. The resource view to apply to the returned intent. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.Intent` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'update_intent' not in self._inner_api_calls: self._inner_api_calls[ 'update_intent'] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_intent, default_retry=self._method_configs['UpdateIntent'].retry, default_timeout=self._method_configs['UpdateIntent'] .timeout, client_info=self._client_info, ) request = intent_pb2.UpdateIntentRequest( intent=intent, language_code=language_code, update_mask=update_mask, intent_view=intent_view, ) return self._inner_api_calls['update_intent']( request, retry=retry, timeout=timeout, metadata=metadata)
[ "def", "update_intent", "(", "self", ",", "intent", ",", "language_code", ",", "update_mask", "=", "None", ",", "intent_view", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", ...
Updates the specified intent. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.IntentsClient() >>> >>> # TODO: Initialize ``intent``: >>> intent = {} >>> >>> # TODO: Initialize ``language_code``: >>> language_code = '' >>> >>> response = client.update_intent(intent, language_code) Args: intent (Union[dict, ~google.cloud.dialogflow_v2.types.Intent]): Required. The intent to update. Format: ``projects/<Project ID>/agent/intents/<Intent ID>``. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.Intent` language_code (str): Optional. The language of training phrases, parameters and rich messages defined in ``intent``. If not specified, the agent's default language is used. [More than a dozen languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must be enabled in the agent, before they can be used. update_mask (Union[dict, ~google.cloud.dialogflow_v2.types.FieldMask]): Optional. The mask to control which fields get updated. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.FieldMask` intent_view (~google.cloud.dialogflow_v2.types.IntentView): Optional. The resource view to apply to the returned intent. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.Intent` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Updates", "the", "specified", "intent", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/intents_client.py#L467-L542
224,581
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/intents_client.py
IntentsClient.delete_intent
def delete_intent(self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Deletes the specified intent. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.IntentsClient() >>> >>> name = client.intent_path('[PROJECT]', '[INTENT]') >>> >>> client.delete_intent(name) Args: name (str): Required. The name of the intent to delete. Format: ``projects/<Project ID>/agent/intents/<Intent ID>``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'delete_intent' not in self._inner_api_calls: self._inner_api_calls[ 'delete_intent'] = google.api_core.gapic_v1.method.wrap_method( self.transport.delete_intent, default_retry=self._method_configs['DeleteIntent'].retry, default_timeout=self._method_configs['DeleteIntent'] .timeout, client_info=self._client_info, ) request = intent_pb2.DeleteIntentRequest(name=name, ) self._inner_api_calls['delete_intent']( request, retry=retry, timeout=timeout, metadata=metadata)
python
def delete_intent(self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Deletes the specified intent. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.IntentsClient() >>> >>> name = client.intent_path('[PROJECT]', '[INTENT]') >>> >>> client.delete_intent(name) Args: name (str): Required. The name of the intent to delete. Format: ``projects/<Project ID>/agent/intents/<Intent ID>``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'delete_intent' not in self._inner_api_calls: self._inner_api_calls[ 'delete_intent'] = google.api_core.gapic_v1.method.wrap_method( self.transport.delete_intent, default_retry=self._method_configs['DeleteIntent'].retry, default_timeout=self._method_configs['DeleteIntent'] .timeout, client_info=self._client_info, ) request = intent_pb2.DeleteIntentRequest(name=name, ) self._inner_api_calls['delete_intent']( request, retry=retry, timeout=timeout, metadata=metadata)
[ "def", "delete_intent", "(", "self", ",", "name", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "metadata...
Deletes the specified intent. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.IntentsClient() >>> >>> name = client.intent_path('[PROJECT]', '[INTENT]') >>> >>> client.delete_intent(name) Args: name (str): Required. The name of the intent to delete. Format: ``projects/<Project ID>/agent/intents/<Intent ID>``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Deletes", "the", "specified", "intent", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/intents_client.py#L544-L593
224,582
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/intents_client.py
IntentsClient.batch_delete_intents
def batch_delete_intents(self, parent, intents, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Deletes intents in the specified agent. Operation <response: ``google.protobuf.Empty``> Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.IntentsClient() >>> >>> parent = client.project_agent_path('[PROJECT]') >>> >>> # TODO: Initialize ``intents``: >>> intents = [] >>> >>> response = client.batch_delete_intents(parent, intents) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. The name of the agent to delete all entities types for. Format: ``projects/<Project ID>/agent``. intents (list[Union[dict, ~google.cloud.dialogflow_v2.types.Intent]]): Required. The collection of intents to delete. Only intent ``name`` must be filled in. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.Intent` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'batch_delete_intents' not in self._inner_api_calls: self._inner_api_calls[ 'batch_delete_intents'] = google.api_core.gapic_v1.method.wrap_method( self.transport.batch_delete_intents, default_retry=self._method_configs[ 'BatchDeleteIntents'].retry, default_timeout=self._method_configs['BatchDeleteIntents'] .timeout, client_info=self._client_info, ) request = intent_pb2.BatchDeleteIntentsRequest( parent=parent, intents=intents, ) operation = self._inner_api_calls['batch_delete_intents']( request, retry=retry, timeout=timeout, metadata=metadata) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, empty_pb2.Empty, metadata_type=struct_pb2.Struct, )
python
def batch_delete_intents(self, parent, intents, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Deletes intents in the specified agent. Operation <response: ``google.protobuf.Empty``> Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.IntentsClient() >>> >>> parent = client.project_agent_path('[PROJECT]') >>> >>> # TODO: Initialize ``intents``: >>> intents = [] >>> >>> response = client.batch_delete_intents(parent, intents) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. The name of the agent to delete all entities types for. Format: ``projects/<Project ID>/agent``. intents (list[Union[dict, ~google.cloud.dialogflow_v2.types.Intent]]): Required. The collection of intents to delete. Only intent ``name`` must be filled in. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.Intent` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'batch_delete_intents' not in self._inner_api_calls: self._inner_api_calls[ 'batch_delete_intents'] = google.api_core.gapic_v1.method.wrap_method( self.transport.batch_delete_intents, default_retry=self._method_configs[ 'BatchDeleteIntents'].retry, default_timeout=self._method_configs['BatchDeleteIntents'] .timeout, client_info=self._client_info, ) request = intent_pb2.BatchDeleteIntentsRequest( parent=parent, intents=intents, ) operation = self._inner_api_calls['batch_delete_intents']( request, retry=retry, timeout=timeout, metadata=metadata) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, empty_pb2.Empty, metadata_type=struct_pb2.Struct, )
[ "def", "batch_delete_intents", "(", "self", ",", "parent", ",", "intents", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", ...
Deletes intents in the specified agent. Operation <response: ``google.protobuf.Empty``> Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.IntentsClient() >>> >>> parent = client.project_agent_path('[PROJECT]') >>> >>> # TODO: Initialize ``intents``: >>> intents = [] >>> >>> response = client.batch_delete_intents(parent, intents) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. The name of the agent to delete all entities types for. Format: ``projects/<Project ID>/agent``. intents (list[Union[dict, ~google.cloud.dialogflow_v2.types.Intent]]): Required. The collection of intents to delete. Only intent ``name`` must be filled in. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.Intent` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Deletes", "intents", "in", "the", "specified", "agent", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/intents_client.py#L704-L785
224,583
googleapis/dialogflow-python-client-v2
dialogflow_v2beta1/gapic/contexts_client.py
ContextsClient.environment_context_path
def environment_context_path(cls, project, environment, user, session, context): """Return a fully-qualified environment_context string.""" return google.api_core.path_template.expand( 'projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}/contexts/{context}', project=project, environment=environment, user=user, session=session, context=context, )
python
def environment_context_path(cls, project, environment, user, session, context): """Return a fully-qualified environment_context string.""" return google.api_core.path_template.expand( 'projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}/contexts/{context}', project=project, environment=environment, user=user, session=session, context=context, )
[ "def", "environment_context_path", "(", "cls", ",", "project", ",", "environment", ",", "user", ",", "session", ",", "context", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "'projects/{project}/agent/environments/{environm...
Return a fully-qualified environment_context string.
[ "Return", "a", "fully", "-", "qualified", "environment_context", "string", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2beta1/gapic/contexts_client.py#L125-L135
224,584
googleapis/dialogflow-python-client-v2
samples/detect_intent_with_sentiment_analysis.py
detect_intent_with_sentiment_analysis
def detect_intent_with_sentiment_analysis(project_id, session_id, texts, language_code): """Returns the result of detect intent with texts as inputs and analyzes the sentiment of the query text. Using the same `session_id` between requests allows continuation of the conversaion.""" import dialogflow_v2beta1 as dialogflow session_client = dialogflow.SessionsClient() session_path = session_client.session_path(project_id, session_id) print('Session path: {}\n'.format(session_path)) for text in texts: text_input = dialogflow.types.TextInput( text=text, language_code=language_code) query_input = dialogflow.types.QueryInput(text=text_input) # Enable sentiment analysis sentiment_config = dialogflow.types.SentimentAnalysisRequestConfig( analyze_query_text_sentiment=True) # Set the query parameters with sentiment analysis query_params = dialogflow.types.QueryParameters( sentiment_analysis_request_config=sentiment_config) response = session_client.detect_intent( session=session_path, query_input=query_input, query_params=query_params) print('=' * 20) print('Query text: {}'.format(response.query_result.query_text)) print('Detected intent: {} (confidence: {})\n'.format( response.query_result.intent.display_name, response.query_result.intent_detection_confidence)) print('Fulfillment text: {}\n'.format( response.query_result.fulfillment_text)) # Score between -1.0 (negative sentiment) and 1.0 (positive sentiment). print('Query Text Sentiment Score: {}\n'.format( response.query_result.sentiment_analysis_result .query_text_sentiment.score)) print('Query Text Sentiment Magnitude: {}\n'.format( response.query_result.sentiment_analysis_result .query_text_sentiment.magnitude))
python
def detect_intent_with_sentiment_analysis(project_id, session_id, texts, language_code): """Returns the result of detect intent with texts as inputs and analyzes the sentiment of the query text. Using the same `session_id` between requests allows continuation of the conversaion.""" import dialogflow_v2beta1 as dialogflow session_client = dialogflow.SessionsClient() session_path = session_client.session_path(project_id, session_id) print('Session path: {}\n'.format(session_path)) for text in texts: text_input = dialogflow.types.TextInput( text=text, language_code=language_code) query_input = dialogflow.types.QueryInput(text=text_input) # Enable sentiment analysis sentiment_config = dialogflow.types.SentimentAnalysisRequestConfig( analyze_query_text_sentiment=True) # Set the query parameters with sentiment analysis query_params = dialogflow.types.QueryParameters( sentiment_analysis_request_config=sentiment_config) response = session_client.detect_intent( session=session_path, query_input=query_input, query_params=query_params) print('=' * 20) print('Query text: {}'.format(response.query_result.query_text)) print('Detected intent: {} (confidence: {})\n'.format( response.query_result.intent.display_name, response.query_result.intent_detection_confidence)) print('Fulfillment text: {}\n'.format( response.query_result.fulfillment_text)) # Score between -1.0 (negative sentiment) and 1.0 (positive sentiment). print('Query Text Sentiment Score: {}\n'.format( response.query_result.sentiment_analysis_result .query_text_sentiment.score)) print('Query Text Sentiment Magnitude: {}\n'.format( response.query_result.sentiment_analysis_result .query_text_sentiment.magnitude))
[ "def", "detect_intent_with_sentiment_analysis", "(", "project_id", ",", "session_id", ",", "texts", ",", "language_code", ")", ":", "import", "dialogflow_v2beta1", "as", "dialogflow", "session_client", "=", "dialogflow", ".", "SessionsClient", "(", ")", "session_path", ...
Returns the result of detect intent with texts as inputs and analyzes the sentiment of the query text. Using the same `session_id` between requests allows continuation of the conversaion.
[ "Returns", "the", "result", "of", "detect", "intent", "with", "texts", "as", "inputs", "and", "analyzes", "the", "sentiment", "of", "the", "query", "text", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/detect_intent_with_sentiment_analysis.py#L31-L75
224,585
googleapis/dialogflow-python-client-v2
dialogflow_v2beta1/gapic/sessions_client.py
SessionsClient.detect_intent
def detect_intent(self, session, query_input, query_params=None, output_audio_config=None, input_audio=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Processes a natural language query and returns structured, actionable data as a result. This method is not idempotent, because it may cause contexts and session entity types to be updated, which in turn might affect results of future queries. Example: >>> import dialogflow_v2beta1 >>> >>> client = dialogflow_v2beta1.SessionsClient() >>> >>> session = client.session_path('[PROJECT]', '[SESSION]') >>> >>> # TODO: Initialize ``query_input``: >>> query_input = {} >>> >>> response = client.detect_intent(session, query_input) Args: session (str): Required. The name of the session this query is sent to. Format: ``projects/<Project ID>/agent/sessions/<Session ID>``, or ``projects/<Project ID>/agent/environments/<Environment ID>/users/<User ID>/sessions/<Session ID>``. If ``Environment ID`` is not specified, we assume default 'draft' environment. If ``User ID`` is not specified, we are using \"-\". It’s up to the API caller to choose an appropriate ``Session ID`` and ``User Id``. They can be a random numbers or some type of user and session identifiers (preferably hashed). The length of the ``Session ID`` and ``User ID`` must not exceed 36 characters. query_input (Union[dict, ~google.cloud.dialogflow_v2beta1.types.QueryInput]): Required. The input specification. It can be set to: 1. an audio config :: which instructs the speech recognizer how to process the speech audio, 2. a conversational query in the form of text, or 3. an event that specifies which intent to trigger. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2beta1.types.QueryInput` query_params (Union[dict, ~google.cloud.dialogflow_v2beta1.types.QueryParameters]): Optional. The parameters of this query. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2beta1.types.QueryParameters` output_audio_config (Union[dict, ~google.cloud.dialogflow_v2beta1.types.OutputAudioConfig]): Optional. Instructs the speech synthesizer how to generate the output audio. If this field is not set and agent-level speech synthesizer is not configured, no output audio is generated. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2beta1.types.OutputAudioConfig` input_audio (bytes): Optional. The natural language speech audio to be processed. This field should be populated iff ``query_input`` is set to an input audio config. A single request can contain up to 1 minute of speech audio data. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2beta1.types.DetectIntentResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'detect_intent' not in self._inner_api_calls: self._inner_api_calls[ 'detect_intent'] = google.api_core.gapic_v1.method.wrap_method( self.transport.detect_intent, default_retry=self._method_configs['DetectIntent'].retry, default_timeout=self._method_configs['DetectIntent'] .timeout, client_info=self._client_info, ) request = session_pb2.DetectIntentRequest( session=session, query_input=query_input, query_params=query_params, output_audio_config=output_audio_config, input_audio=input_audio, ) return self._inner_api_calls['detect_intent']( request, retry=retry, timeout=timeout, metadata=metadata)
python
def detect_intent(self, session, query_input, query_params=None, output_audio_config=None, input_audio=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Processes a natural language query and returns structured, actionable data as a result. This method is not idempotent, because it may cause contexts and session entity types to be updated, which in turn might affect results of future queries. Example: >>> import dialogflow_v2beta1 >>> >>> client = dialogflow_v2beta1.SessionsClient() >>> >>> session = client.session_path('[PROJECT]', '[SESSION]') >>> >>> # TODO: Initialize ``query_input``: >>> query_input = {} >>> >>> response = client.detect_intent(session, query_input) Args: session (str): Required. The name of the session this query is sent to. Format: ``projects/<Project ID>/agent/sessions/<Session ID>``, or ``projects/<Project ID>/agent/environments/<Environment ID>/users/<User ID>/sessions/<Session ID>``. If ``Environment ID`` is not specified, we assume default 'draft' environment. If ``User ID`` is not specified, we are using \"-\". It’s up to the API caller to choose an appropriate ``Session ID`` and ``User Id``. They can be a random numbers or some type of user and session identifiers (preferably hashed). The length of the ``Session ID`` and ``User ID`` must not exceed 36 characters. query_input (Union[dict, ~google.cloud.dialogflow_v2beta1.types.QueryInput]): Required. The input specification. It can be set to: 1. an audio config :: which instructs the speech recognizer how to process the speech audio, 2. a conversational query in the form of text, or 3. an event that specifies which intent to trigger. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2beta1.types.QueryInput` query_params (Union[dict, ~google.cloud.dialogflow_v2beta1.types.QueryParameters]): Optional. The parameters of this query. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2beta1.types.QueryParameters` output_audio_config (Union[dict, ~google.cloud.dialogflow_v2beta1.types.OutputAudioConfig]): Optional. Instructs the speech synthesizer how to generate the output audio. If this field is not set and agent-level speech synthesizer is not configured, no output audio is generated. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2beta1.types.OutputAudioConfig` input_audio (bytes): Optional. The natural language speech audio to be processed. This field should be populated iff ``query_input`` is set to an input audio config. A single request can contain up to 1 minute of speech audio data. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2beta1.types.DetectIntentResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'detect_intent' not in self._inner_api_calls: self._inner_api_calls[ 'detect_intent'] = google.api_core.gapic_v1.method.wrap_method( self.transport.detect_intent, default_retry=self._method_configs['DetectIntent'].retry, default_timeout=self._method_configs['DetectIntent'] .timeout, client_info=self._client_info, ) request = session_pb2.DetectIntentRequest( session=session, query_input=query_input, query_params=query_params, output_audio_config=output_audio_config, input_audio=input_audio, ) return self._inner_api_calls['detect_intent']( request, retry=retry, timeout=timeout, metadata=metadata)
[ "def", "detect_intent", "(", "self", ",", "session", ",", "query_input", ",", "query_params", "=", "None", ",", "output_audio_config", "=", "None", ",", "input_audio", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method",...
Processes a natural language query and returns structured, actionable data as a result. This method is not idempotent, because it may cause contexts and session entity types to be updated, which in turn might affect results of future queries. Example: >>> import dialogflow_v2beta1 >>> >>> client = dialogflow_v2beta1.SessionsClient() >>> >>> session = client.session_path('[PROJECT]', '[SESSION]') >>> >>> # TODO: Initialize ``query_input``: >>> query_input = {} >>> >>> response = client.detect_intent(session, query_input) Args: session (str): Required. The name of the session this query is sent to. Format: ``projects/<Project ID>/agent/sessions/<Session ID>``, or ``projects/<Project ID>/agent/environments/<Environment ID>/users/<User ID>/sessions/<Session ID>``. If ``Environment ID`` is not specified, we assume default 'draft' environment. If ``User ID`` is not specified, we are using \"-\". It’s up to the API caller to choose an appropriate ``Session ID`` and ``User Id``. They can be a random numbers or some type of user and session identifiers (preferably hashed). The length of the ``Session ID`` and ``User ID`` must not exceed 36 characters. query_input (Union[dict, ~google.cloud.dialogflow_v2beta1.types.QueryInput]): Required. The input specification. It can be set to: 1. an audio config :: which instructs the speech recognizer how to process the speech audio, 2. a conversational query in the form of text, or 3. an event that specifies which intent to trigger. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2beta1.types.QueryInput` query_params (Union[dict, ~google.cloud.dialogflow_v2beta1.types.QueryParameters]): Optional. The parameters of this query. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2beta1.types.QueryParameters` output_audio_config (Union[dict, ~google.cloud.dialogflow_v2beta1.types.OutputAudioConfig]): Optional. Instructs the speech synthesizer how to generate the output audio. If this field is not set and agent-level speech synthesizer is not configured, no output audio is generated. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2beta1.types.OutputAudioConfig` input_audio (bytes): Optional. The natural language speech audio to be processed. This field should be populated iff ``query_input`` is set to an input audio config. A single request can contain up to 1 minute of speech audio data. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2beta1.types.DetectIntentResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Processes", "a", "natural", "language", "query", "and", "returns", "structured", "actionable", "data", "as", "a", "result", ".", "This", "method", "is", "not", "idempotent", "because", "it", "may", "cause", "contexts", "and", "session", "entity", "types", "to...
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2beta1/gapic/sessions_client.py#L201-L299
224,586
googleapis/dialogflow-python-client-v2
samples/detect_intent_stream.py
detect_intent_stream
def detect_intent_stream(project_id, session_id, audio_file_path, language_code): """Returns the result of detect intent with streaming audio as input. Using the same `session_id` between requests allows continuation of the conversaion.""" import dialogflow_v2 as dialogflow session_client = dialogflow.SessionsClient() # Note: hard coding audio_encoding and sample_rate_hertz for simplicity. audio_encoding = dialogflow.enums.AudioEncoding.AUDIO_ENCODING_LINEAR_16 sample_rate_hertz = 16000 session_path = session_client.session_path(project_id, session_id) print('Session path: {}\n'.format(session_path)) def request_generator(audio_config, audio_file_path): query_input = dialogflow.types.QueryInput(audio_config=audio_config) # The first request contains the configuration. yield dialogflow.types.StreamingDetectIntentRequest( session=session_path, query_input=query_input) # Here we are reading small chunks of audio data from a local # audio file. In practice these chunks should come from # an audio input device. with open(audio_file_path, 'rb') as audio_file: while True: chunk = audio_file.read(4096) if not chunk: break # The later requests contains audio data. yield dialogflow.types.StreamingDetectIntentRequest( input_audio=chunk) audio_config = dialogflow.types.InputAudioConfig( audio_encoding=audio_encoding, language_code=language_code, sample_rate_hertz=sample_rate_hertz) requests = request_generator(audio_config, audio_file_path) responses = session_client.streaming_detect_intent(requests) print('=' * 20) for response in responses: print('Intermediate transcript: "{}".'.format( response.recognition_result.transcript)) # Note: The result from the last response is the final transcript along # with the detected content. query_result = response.query_result print('=' * 20) print('Query text: {}'.format(query_result.query_text)) print('Detected intent: {} (confidence: {})\n'.format( query_result.intent.display_name, query_result.intent_detection_confidence)) print('Fulfillment text: {}\n'.format( query_result.fulfillment_text))
python
def detect_intent_stream(project_id, session_id, audio_file_path, language_code): """Returns the result of detect intent with streaming audio as input. Using the same `session_id` between requests allows continuation of the conversaion.""" import dialogflow_v2 as dialogflow session_client = dialogflow.SessionsClient() # Note: hard coding audio_encoding and sample_rate_hertz for simplicity. audio_encoding = dialogflow.enums.AudioEncoding.AUDIO_ENCODING_LINEAR_16 sample_rate_hertz = 16000 session_path = session_client.session_path(project_id, session_id) print('Session path: {}\n'.format(session_path)) def request_generator(audio_config, audio_file_path): query_input = dialogflow.types.QueryInput(audio_config=audio_config) # The first request contains the configuration. yield dialogflow.types.StreamingDetectIntentRequest( session=session_path, query_input=query_input) # Here we are reading small chunks of audio data from a local # audio file. In practice these chunks should come from # an audio input device. with open(audio_file_path, 'rb') as audio_file: while True: chunk = audio_file.read(4096) if not chunk: break # The later requests contains audio data. yield dialogflow.types.StreamingDetectIntentRequest( input_audio=chunk) audio_config = dialogflow.types.InputAudioConfig( audio_encoding=audio_encoding, language_code=language_code, sample_rate_hertz=sample_rate_hertz) requests = request_generator(audio_config, audio_file_path) responses = session_client.streaming_detect_intent(requests) print('=' * 20) for response in responses: print('Intermediate transcript: "{}".'.format( response.recognition_result.transcript)) # Note: The result from the last response is the final transcript along # with the detected content. query_result = response.query_result print('=' * 20) print('Query text: {}'.format(query_result.query_text)) print('Detected intent: {} (confidence: {})\n'.format( query_result.intent.display_name, query_result.intent_detection_confidence)) print('Fulfillment text: {}\n'.format( query_result.fulfillment_text))
[ "def", "detect_intent_stream", "(", "project_id", ",", "session_id", ",", "audio_file_path", ",", "language_code", ")", ":", "import", "dialogflow_v2", "as", "dialogflow", "session_client", "=", "dialogflow", ".", "SessionsClient", "(", ")", "# Note: hard coding audio_e...
Returns the result of detect intent with streaming audio as input. Using the same `session_id` between requests allows continuation of the conversaion.
[ "Returns", "the", "result", "of", "detect", "intent", "with", "streaming", "audio", "as", "input", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/detect_intent_stream.py#L33-L90
224,587
googleapis/dialogflow-python-client-v2
samples/intent_management.py
create_intent
def create_intent(project_id, display_name, training_phrases_parts, message_texts): """Create an intent of the given intent type.""" import dialogflow_v2 as dialogflow intents_client = dialogflow.IntentsClient() parent = intents_client.project_agent_path(project_id) training_phrases = [] for training_phrases_part in training_phrases_parts: part = dialogflow.types.Intent.TrainingPhrase.Part( text=training_phrases_part) # Here we create a new training phrase for each provided part. training_phrase = dialogflow.types.Intent.TrainingPhrase(parts=[part]) training_phrases.append(training_phrase) text = dialogflow.types.Intent.Message.Text(text=message_texts) message = dialogflow.types.Intent.Message(text=text) intent = dialogflow.types.Intent( display_name=display_name, training_phrases=training_phrases, messages=[message]) response = intents_client.create_intent(parent, intent) print('Intent created: {}'.format(response))
python
def create_intent(project_id, display_name, training_phrases_parts, message_texts): """Create an intent of the given intent type.""" import dialogflow_v2 as dialogflow intents_client = dialogflow.IntentsClient() parent = intents_client.project_agent_path(project_id) training_phrases = [] for training_phrases_part in training_phrases_parts: part = dialogflow.types.Intent.TrainingPhrase.Part( text=training_phrases_part) # Here we create a new training phrase for each provided part. training_phrase = dialogflow.types.Intent.TrainingPhrase(parts=[part]) training_phrases.append(training_phrase) text = dialogflow.types.Intent.Message.Text(text=message_texts) message = dialogflow.types.Intent.Message(text=text) intent = dialogflow.types.Intent( display_name=display_name, training_phrases=training_phrases, messages=[message]) response = intents_client.create_intent(parent, intent) print('Intent created: {}'.format(response))
[ "def", "create_intent", "(", "project_id", ",", "display_name", ",", "training_phrases_parts", ",", "message_texts", ")", ":", "import", "dialogflow_v2", "as", "dialogflow", "intents_client", "=", "dialogflow", ".", "IntentsClient", "(", ")", "parent", "=", "intents...
Create an intent of the given intent type.
[ "Create", "an", "intent", "of", "the", "given", "intent", "type", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/intent_management.py#L63-L88
224,588
googleapis/dialogflow-python-client-v2
samples/intent_management.py
delete_intent
def delete_intent(project_id, intent_id): """Delete intent with the given intent type and intent value.""" import dialogflow_v2 as dialogflow intents_client = dialogflow.IntentsClient() intent_path = intents_client.intent_path(project_id, intent_id) intents_client.delete_intent(intent_path)
python
def delete_intent(project_id, intent_id): """Delete intent with the given intent type and intent value.""" import dialogflow_v2 as dialogflow intents_client = dialogflow.IntentsClient() intent_path = intents_client.intent_path(project_id, intent_id) intents_client.delete_intent(intent_path)
[ "def", "delete_intent", "(", "project_id", ",", "intent_id", ")", ":", "import", "dialogflow_v2", "as", "dialogflow", "intents_client", "=", "dialogflow", ".", "IntentsClient", "(", ")", "intent_path", "=", "intents_client", ".", "intent_path", "(", "project_id", ...
Delete intent with the given intent type and intent value.
[ "Delete", "intent", "with", "the", "given", "intent", "type", "and", "intent", "value", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/intent_management.py#L93-L100
224,589
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/agents_client.py
AgentsClient.get_agent
def get_agent(self, parent, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Retrieves the specified agent. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.AgentsClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> response = client.get_agent(parent) Args: parent (str): Required. The project that the agent to fetch is associated with. Format: ``projects/<Project ID>``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.Agent` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'get_agent' not in self._inner_api_calls: self._inner_api_calls[ 'get_agent'] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_agent, default_retry=self._method_configs['GetAgent'].retry, default_timeout=self._method_configs['GetAgent'].timeout, client_info=self._client_info, ) request = agent_pb2.GetAgentRequest(parent=parent, ) return self._inner_api_calls['get_agent']( request, retry=retry, timeout=timeout, metadata=metadata)
python
def get_agent(self, parent, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Retrieves the specified agent. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.AgentsClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> response = client.get_agent(parent) Args: parent (str): Required. The project that the agent to fetch is associated with. Format: ``projects/<Project ID>``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.Agent` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'get_agent' not in self._inner_api_calls: self._inner_api_calls[ 'get_agent'] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_agent, default_retry=self._method_configs['GetAgent'].retry, default_timeout=self._method_configs['GetAgent'].timeout, client_info=self._client_info, ) request = agent_pb2.GetAgentRequest(parent=parent, ) return self._inner_api_calls['get_agent']( request, retry=retry, timeout=timeout, metadata=metadata)
[ "def", "get_agent", "(", "self", ",", "parent", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "metadata",...
Retrieves the specified agent. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.AgentsClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> response = client.get_agent(parent) Args: parent (str): Required. The project that the agent to fetch is associated with. Format: ``projects/<Project ID>``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.Agent` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Retrieves", "the", "specified", "agent", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/agents_client.py#L197-L248
224,590
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/agents_client.py
AgentsClient.train_agent
def train_agent(self, parent, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Trains the specified agent. Operation <response: ``google.protobuf.Empty``, metadata: [google.protobuf.Struct][google.protobuf.Struct]> Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.AgentsClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> response = client.train_agent(parent) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. The project that the agent to train is associated with. Format: ``projects/<Project ID>``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'train_agent' not in self._inner_api_calls: self._inner_api_calls[ 'train_agent'] = google.api_core.gapic_v1.method.wrap_method( self.transport.train_agent, default_retry=self._method_configs['TrainAgent'].retry, default_timeout=self._method_configs['TrainAgent'].timeout, client_info=self._client_info, ) request = agent_pb2.TrainAgentRequest(parent=parent, ) operation = self._inner_api_calls['train_agent']( request, retry=retry, timeout=timeout, metadata=metadata) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, empty_pb2.Empty, metadata_type=struct_pb2.Struct, )
python
def train_agent(self, parent, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Trains the specified agent. Operation <response: ``google.protobuf.Empty``, metadata: [google.protobuf.Struct][google.protobuf.Struct]> Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.AgentsClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> response = client.train_agent(parent) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. The project that the agent to train is associated with. Format: ``projects/<Project ID>``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'train_agent' not in self._inner_api_calls: self._inner_api_calls[ 'train_agent'] = google.api_core.gapic_v1.method.wrap_method( self.transport.train_agent, default_retry=self._method_configs['TrainAgent'].retry, default_timeout=self._method_configs['TrainAgent'].timeout, client_info=self._client_info, ) request = agent_pb2.TrainAgentRequest(parent=parent, ) operation = self._inner_api_calls['train_agent']( request, retry=retry, timeout=timeout, metadata=metadata) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, empty_pb2.Empty, metadata_type=struct_pb2.Struct, )
[ "def", "train_agent", "(", "self", ",", "parent", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "metadata...
Trains the specified agent. Operation <response: ``google.protobuf.Empty``, metadata: [google.protobuf.Struct][google.protobuf.Struct]> Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.AgentsClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> response = client.train_agent(parent) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. The project that the agent to train is associated with. Format: ``projects/<Project ID>``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Trains", "the", "specified", "agent", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/agents_client.py#L345-L414
224,591
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/agents_client.py
AgentsClient.export_agent
def export_agent(self, parent, agent_uri=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Exports the specified agent to a ZIP file. Operation <response: ``ExportAgentResponse``, metadata: [google.protobuf.Struct][google.protobuf.Struct]> Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.AgentsClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> response = client.export_agent(parent) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. The project that the agent to export is associated with. Format: ``projects/<Project ID>``. agent_uri (str): Optional. The Google Cloud Storage URI to export the agent to. Note: The URI must start with \"gs://\". If left unspecified, the serialized agent is returned inline. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'export_agent' not in self._inner_api_calls: self._inner_api_calls[ 'export_agent'] = google.api_core.gapic_v1.method.wrap_method( self.transport.export_agent, default_retry=self._method_configs['ExportAgent'].retry, default_timeout=self._method_configs['ExportAgent'] .timeout, client_info=self._client_info, ) request = agent_pb2.ExportAgentRequest( parent=parent, agent_uri=agent_uri, ) operation = self._inner_api_calls['export_agent']( request, retry=retry, timeout=timeout, metadata=metadata) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, agent_pb2.ExportAgentResponse, metadata_type=struct_pb2.Struct, )
python
def export_agent(self, parent, agent_uri=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Exports the specified agent to a ZIP file. Operation <response: ``ExportAgentResponse``, metadata: [google.protobuf.Struct][google.protobuf.Struct]> Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.AgentsClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> response = client.export_agent(parent) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. The project that the agent to export is associated with. Format: ``projects/<Project ID>``. agent_uri (str): Optional. The Google Cloud Storage URI to export the agent to. Note: The URI must start with \"gs://\". If left unspecified, the serialized agent is returned inline. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'export_agent' not in self._inner_api_calls: self._inner_api_calls[ 'export_agent'] = google.api_core.gapic_v1.method.wrap_method( self.transport.export_agent, default_retry=self._method_configs['ExportAgent'].retry, default_timeout=self._method_configs['ExportAgent'] .timeout, client_info=self._client_info, ) request = agent_pb2.ExportAgentRequest( parent=parent, agent_uri=agent_uri, ) operation = self._inner_api_calls['export_agent']( request, retry=retry, timeout=timeout, metadata=metadata) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, agent_pb2.ExportAgentResponse, metadata_type=struct_pb2.Struct, )
[ "def", "export_agent", "(", "self", ",", "parent", ",", "agent_uri", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method"...
Exports the specified agent to a ZIP file. Operation <response: ``ExportAgentResponse``, metadata: [google.protobuf.Struct][google.protobuf.Struct]> Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.AgentsClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> response = client.export_agent(parent) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. The project that the agent to export is associated with. Format: ``projects/<Project ID>``. agent_uri (str): Optional. The Google Cloud Storage URI to export the agent to. Note: The URI must start with \"gs://\". If left unspecified, the serialized agent is returned inline. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Exports", "the", "specified", "agent", "to", "a", "ZIP", "file", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/agents_client.py#L416-L493
224,592
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/agents_client.py
AgentsClient.import_agent
def import_agent(self, parent, agent_uri=None, agent_content=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Imports the specified agent from a ZIP file. Uploads new intents and entity types without deleting the existing ones. Intents and entity types with the same name are replaced with the new versions from ImportAgentRequest. Operation <response: ``google.protobuf.Empty``, metadata: [google.protobuf.Struct][google.protobuf.Struct]> Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.AgentsClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> response = client.import_agent(parent) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. The project that the agent to import is associated with. Format: ``projects/<Project ID>``. agent_uri (str): The URI to a Google Cloud Storage file containing the agent to import. Note: The URI must start with \"gs://\". agent_content (bytes): The agent to import. Example for how to import an agent via the command line: curl \ 'https://dialogflow.googleapis.com/v2/projects/<project_name>/agent:import\ -X POST \ -H 'Authorization: Bearer '$(gcloud auth print-access-token) \ -H 'Accept: application/json' \ -H 'Content-Type: application/json' \ --compressed \ --data-binary \"{ :: 'agentContent': '$(cat <agent zip file> | base64 -w 0)' }\" retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'import_agent' not in self._inner_api_calls: self._inner_api_calls[ 'import_agent'] = google.api_core.gapic_v1.method.wrap_method( self.transport.import_agent, default_retry=self._method_configs['ImportAgent'].retry, default_timeout=self._method_configs['ImportAgent'] .timeout, client_info=self._client_info, ) # Sanity check: We have some fields which are mutually exclusive; # raise ValueError if more than one is sent. google.api_core.protobuf_helpers.check_oneof( agent_uri=agent_uri, agent_content=agent_content, ) request = agent_pb2.ImportAgentRequest( parent=parent, agent_uri=agent_uri, agent_content=agent_content, ) operation = self._inner_api_calls['import_agent']( request, retry=retry, timeout=timeout, metadata=metadata) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, empty_pb2.Empty, metadata_type=struct_pb2.Struct, )
python
def import_agent(self, parent, agent_uri=None, agent_content=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Imports the specified agent from a ZIP file. Uploads new intents and entity types without deleting the existing ones. Intents and entity types with the same name are replaced with the new versions from ImportAgentRequest. Operation <response: ``google.protobuf.Empty``, metadata: [google.protobuf.Struct][google.protobuf.Struct]> Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.AgentsClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> response = client.import_agent(parent) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. The project that the agent to import is associated with. Format: ``projects/<Project ID>``. agent_uri (str): The URI to a Google Cloud Storage file containing the agent to import. Note: The URI must start with \"gs://\". agent_content (bytes): The agent to import. Example for how to import an agent via the command line: curl \ 'https://dialogflow.googleapis.com/v2/projects/<project_name>/agent:import\ -X POST \ -H 'Authorization: Bearer '$(gcloud auth print-access-token) \ -H 'Accept: application/json' \ -H 'Content-Type: application/json' \ --compressed \ --data-binary \"{ :: 'agentContent': '$(cat <agent zip file> | base64 -w 0)' }\" retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'import_agent' not in self._inner_api_calls: self._inner_api_calls[ 'import_agent'] = google.api_core.gapic_v1.method.wrap_method( self.transport.import_agent, default_retry=self._method_configs['ImportAgent'].retry, default_timeout=self._method_configs['ImportAgent'] .timeout, client_info=self._client_info, ) # Sanity check: We have some fields which are mutually exclusive; # raise ValueError if more than one is sent. google.api_core.protobuf_helpers.check_oneof( agent_uri=agent_uri, agent_content=agent_content, ) request = agent_pb2.ImportAgentRequest( parent=parent, agent_uri=agent_uri, agent_content=agent_content, ) operation = self._inner_api_calls['import_agent']( request, retry=retry, timeout=timeout, metadata=metadata) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, empty_pb2.Empty, metadata_type=struct_pb2.Struct, )
[ "def", "import_agent", "(", "self", ",", "parent", ",", "agent_uri", "=", "None", ",", "agent_content", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_co...
Imports the specified agent from a ZIP file. Uploads new intents and entity types without deleting the existing ones. Intents and entity types with the same name are replaced with the new versions from ImportAgentRequest. Operation <response: ``google.protobuf.Empty``, metadata: [google.protobuf.Struct][google.protobuf.Struct]> Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.AgentsClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> response = client.import_agent(parent) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. The project that the agent to import is associated with. Format: ``projects/<Project ID>``. agent_uri (str): The URI to a Google Cloud Storage file containing the agent to import. Note: The URI must start with \"gs://\". agent_content (bytes): The agent to import. Example for how to import an agent via the command line: curl \ 'https://dialogflow.googleapis.com/v2/projects/<project_name>/agent:import\ -X POST \ -H 'Authorization: Bearer '$(gcloud auth print-access-token) \ -H 'Accept: application/json' \ -H 'Content-Type: application/json' \ --compressed \ --data-binary \"{ :: 'agentContent': '$(cat <agent zip file> | base64 -w 0)' }\" retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Imports", "the", "specified", "agent", "from", "a", "ZIP", "file", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/agents_client.py#L495-L600
224,593
googleapis/dialogflow-python-client-v2
samples/document_management.py
list_documents
def list_documents(project_id, knowledge_base_id): """Lists the Documents belonging to a Knowledge base. Args: project_id: The GCP project linked with the agent. knowledge_base_id: Id of the Knowledge base.""" import dialogflow_v2beta1 as dialogflow client = dialogflow.DocumentsClient() knowledge_base_path = client.knowledge_base_path(project_id, knowledge_base_id) print('Documents for Knowledge Id: {}'.format(knowledge_base_id)) for document in client.list_documents(knowledge_base_path): print(' - Display Name: {}'.format(document.display_name)) print(' - Knowledge ID: {}'.format(document.name)) print(' - MIME Type: {}'.format(document.mime_type)) print(' - Knowledge Types:') for knowledge_type in document.knowledge_types: print(' - {}'.format(KNOWLEDGE_TYPES[knowledge_type])) print(' - Source: {}\n'.format(document.content_uri))
python
def list_documents(project_id, knowledge_base_id): """Lists the Documents belonging to a Knowledge base. Args: project_id: The GCP project linked with the agent. knowledge_base_id: Id of the Knowledge base.""" import dialogflow_v2beta1 as dialogflow client = dialogflow.DocumentsClient() knowledge_base_path = client.knowledge_base_path(project_id, knowledge_base_id) print('Documents for Knowledge Id: {}'.format(knowledge_base_id)) for document in client.list_documents(knowledge_base_path): print(' - Display Name: {}'.format(document.display_name)) print(' - Knowledge ID: {}'.format(document.name)) print(' - MIME Type: {}'.format(document.mime_type)) print(' - Knowledge Types:') for knowledge_type in document.knowledge_types: print(' - {}'.format(KNOWLEDGE_TYPES[knowledge_type])) print(' - Source: {}\n'.format(document.content_uri))
[ "def", "list_documents", "(", "project_id", ",", "knowledge_base_id", ")", ":", "import", "dialogflow_v2beta1", "as", "dialogflow", "client", "=", "dialogflow", ".", "DocumentsClient", "(", ")", "knowledge_base_path", "=", "client", ".", "knowledge_base_path", "(", ...
Lists the Documents belonging to a Knowledge base. Args: project_id: The GCP project linked with the agent. knowledge_base_id: Id of the Knowledge base.
[ "Lists", "the", "Documents", "belonging", "to", "a", "Knowledge", "base", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/document_management.py#L43-L62
224,594
googleapis/dialogflow-python-client-v2
samples/document_management.py
create_document
def create_document(project_id, knowledge_base_id, display_name, mime_type, knowledge_type, content_uri): """Creates a Document. Args: project_id: The GCP project linked with the agent. knowledge_base_id: Id of the Knowledge base. display_name: The display name of the Document. mime_type: The mime_type of the Document. e.g. text/csv, text/html, text/plain, text/pdf etc. knowledge_type: The Knowledge type of the Document. e.g. FAQ, EXTRACTIVE_QA. content_uri: Uri of the document, e.g. gs://path/mydoc.csv, http://mypage.com/faq.html.""" import dialogflow_v2beta1 as dialogflow client = dialogflow.DocumentsClient() knowledge_base_path = client.knowledge_base_path(project_id, knowledge_base_id) document = dialogflow.types.Document( display_name=display_name, mime_type=mime_type, content_uri=content_uri) document.knowledge_types.append( dialogflow.types.Document.KnowledgeType.Value(knowledge_type)) response = client.create_document(knowledge_base_path, document) print('Waiting for results...') document = response.result(timeout=90) print('Created Document:') print(' - Display Name: {}'.format(document.display_name)) print(' - Knowledge ID: {}'.format(document.name)) print(' - MIME Type: {}'.format(document.mime_type)) print(' - Knowledge Types:') for knowledge_type in document.knowledge_types: print(' - {}'.format(KNOWLEDGE_TYPES[knowledge_type])) print(' - Source: {}\n'.format(document.content_uri))
python
def create_document(project_id, knowledge_base_id, display_name, mime_type, knowledge_type, content_uri): """Creates a Document. Args: project_id: The GCP project linked with the agent. knowledge_base_id: Id of the Knowledge base. display_name: The display name of the Document. mime_type: The mime_type of the Document. e.g. text/csv, text/html, text/plain, text/pdf etc. knowledge_type: The Knowledge type of the Document. e.g. FAQ, EXTRACTIVE_QA. content_uri: Uri of the document, e.g. gs://path/mydoc.csv, http://mypage.com/faq.html.""" import dialogflow_v2beta1 as dialogflow client = dialogflow.DocumentsClient() knowledge_base_path = client.knowledge_base_path(project_id, knowledge_base_id) document = dialogflow.types.Document( display_name=display_name, mime_type=mime_type, content_uri=content_uri) document.knowledge_types.append( dialogflow.types.Document.KnowledgeType.Value(knowledge_type)) response = client.create_document(knowledge_base_path, document) print('Waiting for results...') document = response.result(timeout=90) print('Created Document:') print(' - Display Name: {}'.format(document.display_name)) print(' - Knowledge ID: {}'.format(document.name)) print(' - MIME Type: {}'.format(document.mime_type)) print(' - Knowledge Types:') for knowledge_type in document.knowledge_types: print(' - {}'.format(KNOWLEDGE_TYPES[knowledge_type])) print(' - Source: {}\n'.format(document.content_uri))
[ "def", "create_document", "(", "project_id", ",", "knowledge_base_id", ",", "display_name", ",", "mime_type", ",", "knowledge_type", ",", "content_uri", ")", ":", "import", "dialogflow_v2beta1", "as", "dialogflow", "client", "=", "dialogflow", ".", "DocumentsClient", ...
Creates a Document. Args: project_id: The GCP project linked with the agent. knowledge_base_id: Id of the Knowledge base. display_name: The display name of the Document. mime_type: The mime_type of the Document. e.g. text/csv, text/html, text/plain, text/pdf etc. knowledge_type: The Knowledge type of the Document. e.g. FAQ, EXTRACTIVE_QA. content_uri: Uri of the document, e.g. gs://path/mydoc.csv, http://mypage.com/faq.html.
[ "Creates", "a", "Document", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/document_management.py#L67-L103
224,595
googleapis/dialogflow-python-client-v2
samples/document_management.py
get_document
def get_document(project_id, knowledge_base_id, document_id): """Gets a Document. Args: project_id: The GCP project linked with the agent. knowledge_base_id: Id of the Knowledge base. document_id: Id of the Document.""" import dialogflow_v2beta1 as dialogflow client = dialogflow.DocumentsClient() document_path = client.document_path(project_id, knowledge_base_id, document_id) response = client.get_document(document_path) print('Got Document:') print(' - Display Name: {}'.format(response.display_name)) print(' - Knowledge ID: {}'.format(response.name)) print(' - MIME Type: {}'.format(response.mime_type)) print(' - Knowledge Types:') for knowledge_type in response.knowledge_types: print(' - {}'.format(KNOWLEDGE_TYPES[knowledge_type])) print(' - Source: {}\n'.format(response.content_uri))
python
def get_document(project_id, knowledge_base_id, document_id): """Gets a Document. Args: project_id: The GCP project linked with the agent. knowledge_base_id: Id of the Knowledge base. document_id: Id of the Document.""" import dialogflow_v2beta1 as dialogflow client = dialogflow.DocumentsClient() document_path = client.document_path(project_id, knowledge_base_id, document_id) response = client.get_document(document_path) print('Got Document:') print(' - Display Name: {}'.format(response.display_name)) print(' - Knowledge ID: {}'.format(response.name)) print(' - MIME Type: {}'.format(response.mime_type)) print(' - Knowledge Types:') for knowledge_type in response.knowledge_types: print(' - {}'.format(KNOWLEDGE_TYPES[knowledge_type])) print(' - Source: {}\n'.format(response.content_uri))
[ "def", "get_document", "(", "project_id", ",", "knowledge_base_id", ",", "document_id", ")", ":", "import", "dialogflow_v2beta1", "as", "dialogflow", "client", "=", "dialogflow", ".", "DocumentsClient", "(", ")", "document_path", "=", "client", ".", "document_path",...
Gets a Document. Args: project_id: The GCP project linked with the agent. knowledge_base_id: Id of the Knowledge base. document_id: Id of the Document.
[ "Gets", "a", "Document", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/document_management.py#L108-L128
224,596
googleapis/dialogflow-python-client-v2
samples/document_management.py
delete_document
def delete_document(project_id, knowledge_base_id, document_id): """Deletes a Document. Args: project_id: The GCP project linked with the agent. knowledge_base_id: Id of the Knowledge base. document_id: Id of the Document.""" import dialogflow_v2beta1 as dialogflow client = dialogflow.DocumentsClient() document_path = client.document_path(project_id, knowledge_base_id, document_id) response = client.delete_document(document_path) print('operation running:\n {}'.format(response.operation)) print('Waiting for results...') print('Done.\n {}'.format(response.result()))
python
def delete_document(project_id, knowledge_base_id, document_id): """Deletes a Document. Args: project_id: The GCP project linked with the agent. knowledge_base_id: Id of the Knowledge base. document_id: Id of the Document.""" import dialogflow_v2beta1 as dialogflow client = dialogflow.DocumentsClient() document_path = client.document_path(project_id, knowledge_base_id, document_id) response = client.delete_document(document_path) print('operation running:\n {}'.format(response.operation)) print('Waiting for results...') print('Done.\n {}'.format(response.result()))
[ "def", "delete_document", "(", "project_id", ",", "knowledge_base_id", ",", "document_id", ")", ":", "import", "dialogflow_v2beta1", "as", "dialogflow", "client", "=", "dialogflow", ".", "DocumentsClient", "(", ")", "document_path", "=", "client", ".", "document_pat...
Deletes a Document. Args: project_id: The GCP project linked with the agent. knowledge_base_id: Id of the Knowledge base. document_id: Id of the Document.
[ "Deletes", "a", "Document", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/document_management.py#L133-L148
224,597
googleapis/dialogflow-python-client-v2
samples/entity_management.py
create_entity
def create_entity(project_id, entity_type_id, entity_value, synonyms): """Create an entity of the given entity type.""" import dialogflow_v2 as dialogflow entity_types_client = dialogflow.EntityTypesClient() # Note: synonyms must be exactly [entity_value] if the # entity_type's kind is KIND_LIST synonyms = synonyms or [entity_value] entity_type_path = entity_types_client.entity_type_path( project_id, entity_type_id) entity = dialogflow.types.EntityType.Entity() entity.value = entity_value entity.synonyms.extend(synonyms) response = entity_types_client.batch_create_entities( entity_type_path, [entity]) print('Entity created: {}'.format(response))
python
def create_entity(project_id, entity_type_id, entity_value, synonyms): """Create an entity of the given entity type.""" import dialogflow_v2 as dialogflow entity_types_client = dialogflow.EntityTypesClient() # Note: synonyms must be exactly [entity_value] if the # entity_type's kind is KIND_LIST synonyms = synonyms or [entity_value] entity_type_path = entity_types_client.entity_type_path( project_id, entity_type_id) entity = dialogflow.types.EntityType.Entity() entity.value = entity_value entity.synonyms.extend(synonyms) response = entity_types_client.batch_create_entities( entity_type_path, [entity]) print('Entity created: {}'.format(response))
[ "def", "create_entity", "(", "project_id", ",", "entity_type_id", ",", "entity_value", ",", "synonyms", ")", ":", "import", "dialogflow_v2", "as", "dialogflow", "entity_types_client", "=", "dialogflow", ".", "EntityTypesClient", "(", ")", "# Note: synonyms must be exact...
Create an entity of the given entity type.
[ "Create", "an", "entity", "of", "the", "given", "entity", "type", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/entity_management.py#L49-L68
224,598
googleapis/dialogflow-python-client-v2
samples/entity_management.py
delete_entity
def delete_entity(project_id, entity_type_id, entity_value): """Delete entity with the given entity type and entity value.""" import dialogflow_v2 as dialogflow entity_types_client = dialogflow.EntityTypesClient() entity_type_path = entity_types_client.entity_type_path( project_id, entity_type_id) entity_types_client.batch_delete_entities( entity_type_path, [entity_value])
python
def delete_entity(project_id, entity_type_id, entity_value): """Delete entity with the given entity type and entity value.""" import dialogflow_v2 as dialogflow entity_types_client = dialogflow.EntityTypesClient() entity_type_path = entity_types_client.entity_type_path( project_id, entity_type_id) entity_types_client.batch_delete_entities( entity_type_path, [entity_value])
[ "def", "delete_entity", "(", "project_id", ",", "entity_type_id", ",", "entity_value", ")", ":", "import", "dialogflow_v2", "as", "dialogflow", "entity_types_client", "=", "dialogflow", ".", "EntityTypesClient", "(", ")", "entity_type_path", "=", "entity_types_client", ...
Delete entity with the given entity type and entity value.
[ "Delete", "entity", "with", "the", "given", "entity", "type", "and", "entity", "value", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/entity_management.py#L73-L82
224,599
lucasb-eyer/pydensecrf
pydensecrf/utils.py
softmax_to_unary
def softmax_to_unary(sm, GT_PROB=1): """Deprecated, use `unary_from_softmax` instead.""" warning("pydensecrf.softmax_to_unary is deprecated, use unary_from_softmax instead.") scale = None if GT_PROB == 1 else GT_PROB return unary_from_softmax(sm, scale, clip=None)
python
def softmax_to_unary(sm, GT_PROB=1): """Deprecated, use `unary_from_softmax` instead.""" warning("pydensecrf.softmax_to_unary is deprecated, use unary_from_softmax instead.") scale = None if GT_PROB == 1 else GT_PROB return unary_from_softmax(sm, scale, clip=None)
[ "def", "softmax_to_unary", "(", "sm", ",", "GT_PROB", "=", "1", ")", ":", "warning", "(", "\"pydensecrf.softmax_to_unary is deprecated, use unary_from_softmax instead.\"", ")", "scale", "=", "None", "if", "GT_PROB", "==", "1", "else", "GT_PROB", "return", "unary_from_...
Deprecated, use `unary_from_softmax` instead.
[ "Deprecated", "use", "unary_from_softmax", "instead", "." ]
4d5343c398d75d7ebae34f51a47769084ba3a613
https://github.com/lucasb-eyer/pydensecrf/blob/4d5343c398d75d7ebae34f51a47769084ba3a613/pydensecrf/utils.py#L82-L86