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 listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
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 | train | 219,400 |
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 | train | 219,401 |
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 | train | 219,402 |
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 | train | 219,403 |
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 | train | 219,404 |
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 | train | 219,405 |
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 | train | 219,406 |
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 | train | 219,407 |
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 | train | 219,408 |
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 | train | 219,409 |
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 | train | 219,410 |
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 | train | 219,411 |
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 | train | 219,412 |
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 | train | 219,413 |
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 | train | 219,414 |
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 | train | 219,415 |
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 | train | 219,416 |
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 | train | 219,417 |
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 | train | 219,418 |
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 | train | 219,419 |
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 | train | 219,420 |
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 | train | 219,421 |
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 | train | 219,422 |
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 | train | 219,423 |
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 | train | 219,424 |
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 | train | 219,425 |
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 | train | 219,426 |
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 | train | 219,427 |
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 | train | 219,428 |
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 | train | 219,429 |
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 | train | 219,430 |
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 | train | 219,431 |
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 | train | 219,432 |
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 | train | 219,433 |
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 | train | 219,434 |
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 | train | 219,435 |
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 | train | 219,436 |
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 | train | 219,437 |
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 | train | 219,438 |
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 | train | 219,439 |
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 | train | 219,440 |
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 | train | 219,441 |
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 | train | 219,442 |
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 | train | 219,443 |
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 | train | 219,444 |
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 | train | 219,445 |
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 | train | 219,446 |
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 | train | 219,447 |
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 | train | 219,448 |
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 | train | 219,449 |
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 | train | 219,450 |
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 | train | 219,451 |
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 | train | 219,452 |
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 | train | 219,453 |
lucasb-eyer/pydensecrf | pydensecrf/utils.py | create_pairwise_gaussian | def create_pairwise_gaussian(sdims, shape):
"""
Util function that create pairwise gaussian potentials. This works for all
image dimensions. For the 2D case does the same as
`DenseCRF2D.addPairwiseGaussian`.
Parameters
----------
sdims: list or tuple
The scaling factors per dimension. This is referred to `sxy` in
`DenseCRF2D.addPairwiseGaussian`.
shape: list or tuple
The shape the CRF has.
"""
# create mesh
hcord_range = [range(s) for s in shape]
mesh = np.array(np.meshgrid(*hcord_range, indexing='ij'), dtype=np.float32)
# scale mesh accordingly
for i, s in enumerate(sdims):
mesh[i] /= s
return mesh.reshape([len(sdims), -1]) | python | def create_pairwise_gaussian(sdims, shape):
"""
Util function that create pairwise gaussian potentials. This works for all
image dimensions. For the 2D case does the same as
`DenseCRF2D.addPairwiseGaussian`.
Parameters
----------
sdims: list or tuple
The scaling factors per dimension. This is referred to `sxy` in
`DenseCRF2D.addPairwiseGaussian`.
shape: list or tuple
The shape the CRF has.
"""
# create mesh
hcord_range = [range(s) for s in shape]
mesh = np.array(np.meshgrid(*hcord_range, indexing='ij'), dtype=np.float32)
# scale mesh accordingly
for i, s in enumerate(sdims):
mesh[i] /= s
return mesh.reshape([len(sdims), -1]) | [
"def",
"create_pairwise_gaussian",
"(",
"sdims",
",",
"shape",
")",
":",
"# create mesh",
"hcord_range",
"=",
"[",
"range",
"(",
"s",
")",
"for",
"s",
"in",
"shape",
"]",
"mesh",
"=",
"np",
".",
"array",
"(",
"np",
".",
"meshgrid",
"(",
"*",
"hcord_ran... | Util function that create pairwise gaussian potentials. This works for all
image dimensions. For the 2D case does the same as
`DenseCRF2D.addPairwiseGaussian`.
Parameters
----------
sdims: list or tuple
The scaling factors per dimension. This is referred to `sxy` in
`DenseCRF2D.addPairwiseGaussian`.
shape: list or tuple
The shape the CRF has. | [
"Util",
"function",
"that",
"create",
"pairwise",
"gaussian",
"potentials",
".",
"This",
"works",
"for",
"all",
"image",
"dimensions",
".",
"For",
"the",
"2D",
"case",
"does",
"the",
"same",
"as",
"DenseCRF2D",
".",
"addPairwiseGaussian",
"."
] | 4d5343c398d75d7ebae34f51a47769084ba3a613 | https://github.com/lucasb-eyer/pydensecrf/blob/4d5343c398d75d7ebae34f51a47769084ba3a613/pydensecrf/utils.py#L89-L111 | train | 219,454 |
lucasb-eyer/pydensecrf | pydensecrf/utils.py | create_pairwise_bilateral | def create_pairwise_bilateral(sdims, schan, img, chdim=-1):
"""
Util function that create pairwise bilateral potentials. This works for
all image dimensions. For the 2D case does the same as
`DenseCRF2D.addPairwiseBilateral`.
Parameters
----------
sdims: list or tuple
The scaling factors per dimension. This is referred to `sxy` in
`DenseCRF2D.addPairwiseBilateral`.
schan: list or tuple
The scaling factors per channel in the image. This is referred to
`srgb` in `DenseCRF2D.addPairwiseBilateral`.
img: numpy.array
The input image.
chdim: int, optional
This specifies where the channel dimension is in the image. For
example `chdim=2` for a RGB image of size (240, 300, 3). If the
image has no channel dimension (e.g. it has only one channel) use
`chdim=-1`.
"""
# Put channel dim in right position
if chdim == -1:
# We don't have a channel, add a new axis
im_feat = img[np.newaxis].astype(np.float32)
else:
# Put the channel dim as axis 0, all others stay relatively the same
im_feat = np.rollaxis(img, chdim).astype(np.float32)
# scale image features per channel
# Allow for a single number in `schan` to broadcast across all channels:
if isinstance(schan, Number):
im_feat /= schan
else:
for i, s in enumerate(schan):
im_feat[i] /= s
# create a mesh
cord_range = [range(s) for s in im_feat.shape[1:]]
mesh = np.array(np.meshgrid(*cord_range, indexing='ij'), dtype=np.float32)
# scale mesh accordingly
for i, s in enumerate(sdims):
mesh[i] /= s
feats = np.concatenate([mesh, im_feat])
return feats.reshape([feats.shape[0], -1]) | python | def create_pairwise_bilateral(sdims, schan, img, chdim=-1):
"""
Util function that create pairwise bilateral potentials. This works for
all image dimensions. For the 2D case does the same as
`DenseCRF2D.addPairwiseBilateral`.
Parameters
----------
sdims: list or tuple
The scaling factors per dimension. This is referred to `sxy` in
`DenseCRF2D.addPairwiseBilateral`.
schan: list or tuple
The scaling factors per channel in the image. This is referred to
`srgb` in `DenseCRF2D.addPairwiseBilateral`.
img: numpy.array
The input image.
chdim: int, optional
This specifies where the channel dimension is in the image. For
example `chdim=2` for a RGB image of size (240, 300, 3). If the
image has no channel dimension (e.g. it has only one channel) use
`chdim=-1`.
"""
# Put channel dim in right position
if chdim == -1:
# We don't have a channel, add a new axis
im_feat = img[np.newaxis].astype(np.float32)
else:
# Put the channel dim as axis 0, all others stay relatively the same
im_feat = np.rollaxis(img, chdim).astype(np.float32)
# scale image features per channel
# Allow for a single number in `schan` to broadcast across all channels:
if isinstance(schan, Number):
im_feat /= schan
else:
for i, s in enumerate(schan):
im_feat[i] /= s
# create a mesh
cord_range = [range(s) for s in im_feat.shape[1:]]
mesh = np.array(np.meshgrid(*cord_range, indexing='ij'), dtype=np.float32)
# scale mesh accordingly
for i, s in enumerate(sdims):
mesh[i] /= s
feats = np.concatenate([mesh, im_feat])
return feats.reshape([feats.shape[0], -1]) | [
"def",
"create_pairwise_bilateral",
"(",
"sdims",
",",
"schan",
",",
"img",
",",
"chdim",
"=",
"-",
"1",
")",
":",
"# Put channel dim in right position",
"if",
"chdim",
"==",
"-",
"1",
":",
"# We don't have a channel, add a new axis",
"im_feat",
"=",
"img",
"[",
... | Util function that create pairwise bilateral potentials. This works for
all image dimensions. For the 2D case does the same as
`DenseCRF2D.addPairwiseBilateral`.
Parameters
----------
sdims: list or tuple
The scaling factors per dimension. This is referred to `sxy` in
`DenseCRF2D.addPairwiseBilateral`.
schan: list or tuple
The scaling factors per channel in the image. This is referred to
`srgb` in `DenseCRF2D.addPairwiseBilateral`.
img: numpy.array
The input image.
chdim: int, optional
This specifies where the channel dimension is in the image. For
example `chdim=2` for a RGB image of size (240, 300, 3). If the
image has no channel dimension (e.g. it has only one channel) use
`chdim=-1`. | [
"Util",
"function",
"that",
"create",
"pairwise",
"bilateral",
"potentials",
".",
"This",
"works",
"for",
"all",
"image",
"dimensions",
".",
"For",
"the",
"2D",
"case",
"does",
"the",
"same",
"as",
"DenseCRF2D",
".",
"addPairwiseBilateral",
"."
] | 4d5343c398d75d7ebae34f51a47769084ba3a613 | https://github.com/lucasb-eyer/pydensecrf/blob/4d5343c398d75d7ebae34f51a47769084ba3a613/pydensecrf/utils.py#L114-L162 | train | 219,455 |
deanmalmgren/textract | textract/parsers/odt_parser.py | Parser.to_string | def to_string(self):
""" Converts the document to a string. """
buff = u""
for child in self.content.iter():
if child.tag in [self.qn('text:p'), self.qn('text:h')]:
buff += self.text_to_string(child) + "\n"
# remove last newline char
if buff:
buff = buff[:-1]
return buff | python | def to_string(self):
""" Converts the document to a string. """
buff = u""
for child in self.content.iter():
if child.tag in [self.qn('text:p'), self.qn('text:h')]:
buff += self.text_to_string(child) + "\n"
# remove last newline char
if buff:
buff = buff[:-1]
return buff | [
"def",
"to_string",
"(",
"self",
")",
":",
"buff",
"=",
"u\"\"",
"for",
"child",
"in",
"self",
".",
"content",
".",
"iter",
"(",
")",
":",
"if",
"child",
".",
"tag",
"in",
"[",
"self",
".",
"qn",
"(",
"'text:p'",
")",
",",
"self",
".",
"qn",
"(... | Converts the document to a string. | [
"Converts",
"the",
"document",
"to",
"a",
"string",
"."
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/odt_parser.py#L19-L28 | train | 219,456 |
deanmalmgren/textract | textract/parsers/odt_parser.py | Parser.qn | def qn(self, namespace):
"""Connect tag prefix to longer namespace"""
nsmap = {
'text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0',
}
spl = namespace.split(':')
return '{{{}}}{}'.format(nsmap[spl[0]], spl[1]) | python | def qn(self, namespace):
"""Connect tag prefix to longer namespace"""
nsmap = {
'text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0',
}
spl = namespace.split(':')
return '{{{}}}{}'.format(nsmap[spl[0]], spl[1]) | [
"def",
"qn",
"(",
"self",
",",
"namespace",
")",
":",
"nsmap",
"=",
"{",
"'text'",
":",
"'urn:oasis:names:tc:opendocument:xmlns:text:1.0'",
",",
"}",
"spl",
"=",
"namespace",
".",
"split",
"(",
"':'",
")",
"return",
"'{{{}}}{}'",
".",
"format",
"(",
"nsmap",... | Connect tag prefix to longer namespace | [
"Connect",
"tag",
"prefix",
"to",
"longer",
"namespace"
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/odt_parser.py#L51-L57 | train | 219,457 |
deanmalmgren/textract | textract/cli.py | get_parser | def get_parser():
"""Initialize the parser for the command line interface and bind the
autocompletion functionality"""
# initialize the parser
parser = argparse.ArgumentParser(
description=(
'Command line tool for extracting text from any document. '
) % locals(),
)
# define the command line options here
parser.add_argument(
'filename', help='Filename to extract text.',
).completer = argcomplete.completers.FilesCompleter
parser.add_argument(
'-e', '--encoding', type=str, default=DEFAULT_ENCODING,
choices=_get_available_encodings(),
help='Specify the encoding of the output.',
)
parser.add_argument(
'--extension', type=str, default=None,
choices=_get_available_extensions(),
help='Specify the extension of the file.',
)
parser.add_argument(
'-m', '--method', default='',
help='Specify a method of extraction for formats that support it',
)
parser.add_argument(
'-o', '--output', type=FileType('wb'), default='-',
help='Output raw text in this file',
)
parser.add_argument(
'-O', '--option', type=str, action=AddToNamespaceAction,
help=(
'Add arbitrary options to various parsers of the form '
'KEYWORD=VALUE. A full list of available KEYWORD options is '
'available at http://bit.ly/textract-options'
),
)
parser.add_argument(
'-v', '--version', action='version', version='%(prog)s '+VERSION,
)
# enable autocompletion with argcomplete
argcomplete.autocomplete(parser)
return parser | python | def get_parser():
"""Initialize the parser for the command line interface and bind the
autocompletion functionality"""
# initialize the parser
parser = argparse.ArgumentParser(
description=(
'Command line tool for extracting text from any document. '
) % locals(),
)
# define the command line options here
parser.add_argument(
'filename', help='Filename to extract text.',
).completer = argcomplete.completers.FilesCompleter
parser.add_argument(
'-e', '--encoding', type=str, default=DEFAULT_ENCODING,
choices=_get_available_encodings(),
help='Specify the encoding of the output.',
)
parser.add_argument(
'--extension', type=str, default=None,
choices=_get_available_extensions(),
help='Specify the extension of the file.',
)
parser.add_argument(
'-m', '--method', default='',
help='Specify a method of extraction for formats that support it',
)
parser.add_argument(
'-o', '--output', type=FileType('wb'), default='-',
help='Output raw text in this file',
)
parser.add_argument(
'-O', '--option', type=str, action=AddToNamespaceAction,
help=(
'Add arbitrary options to various parsers of the form '
'KEYWORD=VALUE. A full list of available KEYWORD options is '
'available at http://bit.ly/textract-options'
),
)
parser.add_argument(
'-v', '--version', action='version', version='%(prog)s '+VERSION,
)
# enable autocompletion with argcomplete
argcomplete.autocomplete(parser)
return parser | [
"def",
"get_parser",
"(",
")",
":",
"# initialize the parser",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"(",
"'Command line tool for extracting text from any document. '",
")",
"%",
"locals",
"(",
")",
",",
")",
"# define the command li... | Initialize the parser for the command line interface and bind the
autocompletion functionality | [
"Initialize",
"the",
"parser",
"for",
"the",
"command",
"line",
"interface",
"and",
"bind",
"the",
"autocompletion",
"functionality"
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/cli.py#L45-L93 | train | 219,458 |
deanmalmgren/textract | textract/cli.py | _get_available_encodings | def _get_available_encodings():
"""Get a list of the available encodings to make it easy to
tab-complete the command line interface.
Inspiration from http://stackoverflow.com/a/3824405/564709
"""
available_encodings = set(encodings.aliases.aliases.values())
paths = [os.path.dirname(encodings.__file__)]
for importer, modname, ispkg in pkgutil.walk_packages(path=paths):
available_encodings.add(modname)
available_encodings = list(available_encodings)
available_encodings.sort()
return available_encodings | python | def _get_available_encodings():
"""Get a list of the available encodings to make it easy to
tab-complete the command line interface.
Inspiration from http://stackoverflow.com/a/3824405/564709
"""
available_encodings = set(encodings.aliases.aliases.values())
paths = [os.path.dirname(encodings.__file__)]
for importer, modname, ispkg in pkgutil.walk_packages(path=paths):
available_encodings.add(modname)
available_encodings = list(available_encodings)
available_encodings.sort()
return available_encodings | [
"def",
"_get_available_encodings",
"(",
")",
":",
"available_encodings",
"=",
"set",
"(",
"encodings",
".",
"aliases",
".",
"aliases",
".",
"values",
"(",
")",
")",
"paths",
"=",
"[",
"os",
".",
"path",
".",
"dirname",
"(",
"encodings",
".",
"__file__",
... | Get a list of the available encodings to make it easy to
tab-complete the command line interface.
Inspiration from http://stackoverflow.com/a/3824405/564709 | [
"Get",
"a",
"list",
"of",
"the",
"available",
"encodings",
"to",
"make",
"it",
"easy",
"to",
"tab",
"-",
"complete",
"the",
"command",
"line",
"interface",
"."
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/cli.py#L96-L108 | train | 219,459 |
deanmalmgren/textract | textract/parsers/pdf_parser.py | Parser.extract_pdftotext | def extract_pdftotext(self, filename, **kwargs):
"""Extract text from pdfs using the pdftotext command line utility."""
if 'layout' in kwargs:
args = ['pdftotext', '-layout', filename, '-']
else:
args = ['pdftotext', filename, '-']
stdout, _ = self.run(args)
return stdout | python | def extract_pdftotext(self, filename, **kwargs):
"""Extract text from pdfs using the pdftotext command line utility."""
if 'layout' in kwargs:
args = ['pdftotext', '-layout', filename, '-']
else:
args = ['pdftotext', filename, '-']
stdout, _ = self.run(args)
return stdout | [
"def",
"extract_pdftotext",
"(",
"self",
",",
"filename",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'layout'",
"in",
"kwargs",
":",
"args",
"=",
"[",
"'pdftotext'",
",",
"'-layout'",
",",
"filename",
",",
"'-'",
"]",
"else",
":",
"args",
"=",
"[",
"'... | Extract text from pdfs using the pdftotext command line utility. | [
"Extract",
"text",
"from",
"pdfs",
"using",
"the",
"pdftotext",
"command",
"line",
"utility",
"."
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/pdf_parser.py#L37-L44 | train | 219,460 |
deanmalmgren/textract | textract/parsers/pdf_parser.py | Parser.extract_pdfminer | def extract_pdfminer(self, filename, **kwargs):
"""Extract text from pdfs using pdfminer."""
stdout, _ = self.run(['pdf2txt.py', filename])
return stdout | python | def extract_pdfminer(self, filename, **kwargs):
"""Extract text from pdfs using pdfminer."""
stdout, _ = self.run(['pdf2txt.py', filename])
return stdout | [
"def",
"extract_pdfminer",
"(",
"self",
",",
"filename",
",",
"*",
"*",
"kwargs",
")",
":",
"stdout",
",",
"_",
"=",
"self",
".",
"run",
"(",
"[",
"'pdf2txt.py'",
",",
"filename",
"]",
")",
"return",
"stdout"
] | Extract text from pdfs using pdfminer. | [
"Extract",
"text",
"from",
"pdfs",
"using",
"pdfminer",
"."
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/pdf_parser.py#L46-L49 | train | 219,461 |
deanmalmgren/textract | textract/parsers/audio.py | Parser.convert_to_wav | def convert_to_wav(self, filename):
"""
Uses sox cmdline tool, to convert audio file to .wav
Note: for testing, use -
http://www.text2speech.org/,
with American Male 2 for best results
"""
temp_filename = '{0}.wav'.format(self.temp_filename())
self.run(['sox', '-G', '-c', '1', filename, temp_filename])
return temp_filename | python | def convert_to_wav(self, filename):
"""
Uses sox cmdline tool, to convert audio file to .wav
Note: for testing, use -
http://www.text2speech.org/,
with American Male 2 for best results
"""
temp_filename = '{0}.wav'.format(self.temp_filename())
self.run(['sox', '-G', '-c', '1', filename, temp_filename])
return temp_filename | [
"def",
"convert_to_wav",
"(",
"self",
",",
"filename",
")",
":",
"temp_filename",
"=",
"'{0}.wav'",
".",
"format",
"(",
"self",
".",
"temp_filename",
"(",
")",
")",
"self",
".",
"run",
"(",
"[",
"'sox'",
",",
"'-G'",
",",
"'-c'",
",",
"'1'",
",",
"fi... | Uses sox cmdline tool, to convert audio file to .wav
Note: for testing, use -
http://www.text2speech.org/,
with American Male 2 for best results | [
"Uses",
"sox",
"cmdline",
"tool",
"to",
"convert",
"audio",
"file",
"to",
".",
"wav"
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/audio.py#L56-L66 | train | 219,462 |
deanmalmgren/textract | textract/parsers/html_parser.py | Parser._visible | def _visible(self, element):
"""Used to filter text elements that have invisible text on the page.
"""
if element.name in self._disallowed_names:
return False
elif re.match(u'<!--.*-->', six.text_type(element.extract())):
return False
return True | python | def _visible(self, element):
"""Used to filter text elements that have invisible text on the page.
"""
if element.name in self._disallowed_names:
return False
elif re.match(u'<!--.*-->', six.text_type(element.extract())):
return False
return True | [
"def",
"_visible",
"(",
"self",
",",
"element",
")",
":",
"if",
"element",
".",
"name",
"in",
"self",
".",
"_disallowed_names",
":",
"return",
"False",
"elif",
"re",
".",
"match",
"(",
"u'<!--.*-->'",
",",
"six",
".",
"text_type",
"(",
"element",
".",
... | Used to filter text elements that have invisible text on the page. | [
"Used",
"to",
"filter",
"text",
"elements",
"that",
"have",
"invisible",
"text",
"on",
"the",
"page",
"."
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/html_parser.py#L27-L34 | train | 219,463 |
deanmalmgren/textract | textract/parsers/html_parser.py | Parser._find_any_text | def _find_any_text(self, tag):
"""Looks for any possible text within given tag.
"""
text = ''
if tag is not None:
text = six.text_type(tag)
text = re.sub(r'(<[^>]+>)', '', text)
text = re.sub(r'\s', ' ', text)
text = text.strip()
return text | python | def _find_any_text(self, tag):
"""Looks for any possible text within given tag.
"""
text = ''
if tag is not None:
text = six.text_type(tag)
text = re.sub(r'(<[^>]+>)', '', text)
text = re.sub(r'\s', ' ', text)
text = text.strip()
return text | [
"def",
"_find_any_text",
"(",
"self",
",",
"tag",
")",
":",
"text",
"=",
"''",
"if",
"tag",
"is",
"not",
"None",
":",
"text",
"=",
"six",
".",
"text_type",
"(",
"tag",
")",
"text",
"=",
"re",
".",
"sub",
"(",
"r'(<[^>]+>)'",
",",
"''",
",",
"text... | Looks for any possible text within given tag. | [
"Looks",
"for",
"any",
"possible",
"text",
"within",
"given",
"tag",
"."
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/html_parser.py#L44-L53 | train | 219,464 |
deanmalmgren/textract | textract/parsers/html_parser.py | Parser._join_inlines | def _join_inlines(self, soup):
"""Unwraps inline elements defined in self._inline_tags.
"""
elements = soup.find_all(True)
for elem in elements:
if self._inline(elem):
elem.unwrap()
return soup | python | def _join_inlines(self, soup):
"""Unwraps inline elements defined in self._inline_tags.
"""
elements = soup.find_all(True)
for elem in elements:
if self._inline(elem):
elem.unwrap()
return soup | [
"def",
"_join_inlines",
"(",
"self",
",",
"soup",
")",
":",
"elements",
"=",
"soup",
".",
"find_all",
"(",
"True",
")",
"for",
"elem",
"in",
"elements",
":",
"if",
"self",
".",
"_inline",
"(",
"elem",
")",
":",
"elem",
".",
"unwrap",
"(",
")",
"ret... | Unwraps inline elements defined in self._inline_tags. | [
"Unwraps",
"inline",
"elements",
"defined",
"in",
"self",
".",
"_inline_tags",
"."
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/html_parser.py#L118-L125 | train | 219,465 |
deanmalmgren/textract | textract/parsers/utils.py | ShellParser.temp_filename | def temp_filename(self):
"""Return a unique tempfile name.
"""
# TODO: it would be nice to get this to behave more like a
# context so we can make sure these temporary files are
# removed, regardless of whether an error occurs or the
# program is terminated.
handle, filename = tempfile.mkstemp()
os.close(handle)
return filename | python | def temp_filename(self):
"""Return a unique tempfile name.
"""
# TODO: it would be nice to get this to behave more like a
# context so we can make sure these temporary files are
# removed, regardless of whether an error occurs or the
# program is terminated.
handle, filename = tempfile.mkstemp()
os.close(handle)
return filename | [
"def",
"temp_filename",
"(",
"self",
")",
":",
"# TODO: it would be nice to get this to behave more like a",
"# context so we can make sure these temporary files are",
"# removed, regardless of whether an error occurs or the",
"# program is terminated.",
"handle",
",",
"filename",
"=",
"... | Return a unique tempfile name. | [
"Return",
"a",
"unique",
"tempfile",
"name",
"."
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/utils.py#L106-L115 | train | 219,466 |
deanmalmgren/textract | textract/parsers/__init__.py | process | def process(filename, encoding=DEFAULT_ENCODING, extension=None, **kwargs):
"""This is the core function used for extracting text. It routes the
``filename`` to the appropriate parser and returns the extracted
text as a byte-string encoded with ``encoding``.
"""
# make sure the filename exists
if not os.path.exists(filename):
raise exceptions.MissingFileError(filename)
# get the filename extension, which is something like .docx for
# example, and import the module dynamically using importlib. This
# is a relative import so the name of the package is necessary
# normally, file extension will be extracted from the file name
# if the file name has no extension, then the user can pass the
# extension as an argument
if extension:
ext = extension
# check if the extension has the leading .
if not ext.startswith('.'):
ext = '.' + ext
ext = ext.lower()
else:
_, ext = os.path.splitext(filename)
ext = ext.lower()
# check the EXTENSION_SYNONYMS dictionary
ext = EXTENSION_SYNONYMS.get(ext, ext)
# to avoid conflicts with packages that are installed globally
# (e.g. python's json module), all extension parser modules have
# the _parser extension
rel_module = ext + _FILENAME_SUFFIX
# If we can't import the module, the file extension isn't currently
# supported
try:
filetype_module = importlib.import_module(
rel_module, 'textract.parsers'
)
except ImportError:
raise exceptions.ExtensionNotSupported(ext)
# do the extraction
parser = filetype_module.Parser()
return parser.process(filename, encoding, **kwargs) | python | def process(filename, encoding=DEFAULT_ENCODING, extension=None, **kwargs):
"""This is the core function used for extracting text. It routes the
``filename`` to the appropriate parser and returns the extracted
text as a byte-string encoded with ``encoding``.
"""
# make sure the filename exists
if not os.path.exists(filename):
raise exceptions.MissingFileError(filename)
# get the filename extension, which is something like .docx for
# example, and import the module dynamically using importlib. This
# is a relative import so the name of the package is necessary
# normally, file extension will be extracted from the file name
# if the file name has no extension, then the user can pass the
# extension as an argument
if extension:
ext = extension
# check if the extension has the leading .
if not ext.startswith('.'):
ext = '.' + ext
ext = ext.lower()
else:
_, ext = os.path.splitext(filename)
ext = ext.lower()
# check the EXTENSION_SYNONYMS dictionary
ext = EXTENSION_SYNONYMS.get(ext, ext)
# to avoid conflicts with packages that are installed globally
# (e.g. python's json module), all extension parser modules have
# the _parser extension
rel_module = ext + _FILENAME_SUFFIX
# If we can't import the module, the file extension isn't currently
# supported
try:
filetype_module = importlib.import_module(
rel_module, 'textract.parsers'
)
except ImportError:
raise exceptions.ExtensionNotSupported(ext)
# do the extraction
parser = filetype_module.Parser()
return parser.process(filename, encoding, **kwargs) | [
"def",
"process",
"(",
"filename",
",",
"encoding",
"=",
"DEFAULT_ENCODING",
",",
"extension",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# make sure the filename exists",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"rai... | This is the core function used for extracting text. It routes the
``filename`` to the appropriate parser and returns the extracted
text as a byte-string encoded with ``encoding``. | [
"This",
"is",
"the",
"core",
"function",
"used",
"for",
"extracting",
"text",
".",
"It",
"routes",
"the",
"filename",
"to",
"the",
"appropriate",
"parser",
"and",
"returns",
"the",
"extracted",
"text",
"as",
"a",
"byte",
"-",
"string",
"encoded",
"with",
"... | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/__init__.py#L31-L77 | train | 219,467 |
deanmalmgren/textract | textract/parsers/__init__.py | _get_available_extensions | def _get_available_extensions():
"""Get a list of available file extensions to make it easy for
tab-completion and exception handling.
"""
extensions = []
# from filenames
parsers_dir = os.path.join(os.path.dirname(__file__))
glob_filename = os.path.join(parsers_dir, "*" + _FILENAME_SUFFIX + ".py")
ext_re = re.compile(glob_filename.replace('*', "(?P<ext>\w+)"))
for filename in glob.glob(glob_filename):
ext_match = ext_re.match(filename)
ext = ext_match.groups()[0]
extensions.append(ext)
extensions.append('.' + ext)
# from relevant synonyms (don't use the '' synonym)
for ext in EXTENSION_SYNONYMS.keys():
if ext:
extensions.append(ext)
extensions.append(ext.replace('.', '', 1))
extensions.sort()
return extensions | python | def _get_available_extensions():
"""Get a list of available file extensions to make it easy for
tab-completion and exception handling.
"""
extensions = []
# from filenames
parsers_dir = os.path.join(os.path.dirname(__file__))
glob_filename = os.path.join(parsers_dir, "*" + _FILENAME_SUFFIX + ".py")
ext_re = re.compile(glob_filename.replace('*', "(?P<ext>\w+)"))
for filename in glob.glob(glob_filename):
ext_match = ext_re.match(filename)
ext = ext_match.groups()[0]
extensions.append(ext)
extensions.append('.' + ext)
# from relevant synonyms (don't use the '' synonym)
for ext in EXTENSION_SYNONYMS.keys():
if ext:
extensions.append(ext)
extensions.append(ext.replace('.', '', 1))
extensions.sort()
return extensions | [
"def",
"_get_available_extensions",
"(",
")",
":",
"extensions",
"=",
"[",
"]",
"# from filenames",
"parsers_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
"glob_filename",
"=",
"os",
".",
"p... | Get a list of available file extensions to make it easy for
tab-completion and exception handling. | [
"Get",
"a",
"list",
"of",
"available",
"file",
"extensions",
"to",
"make",
"it",
"easy",
"for",
"tab",
"-",
"completion",
"and",
"exception",
"handling",
"."
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/__init__.py#L80-L102 | train | 219,468 |
deanmalmgren/textract | setup.py | parse_requirements | def parse_requirements(requirements_filename):
"""read in the dependencies from the requirements files
"""
dependencies, dependency_links = [], []
requirements_dir = os.path.dirname(requirements_filename)
with open(requirements_filename, 'r') as stream:
for line in stream:
line = line.strip()
if line.startswith("-r"):
filename = os.path.join(requirements_dir, line[2:].strip())
_dependencies, _dependency_links = parse_requirements(filename)
dependencies.extend(_dependencies)
dependency_links.extend(_dependency_links)
elif line.startswith("http"):
dependency_links.append(line)
else:
package = line.split('#')[0]
if package:
dependencies.append(package)
return dependencies, dependency_links | python | def parse_requirements(requirements_filename):
"""read in the dependencies from the requirements files
"""
dependencies, dependency_links = [], []
requirements_dir = os.path.dirname(requirements_filename)
with open(requirements_filename, 'r') as stream:
for line in stream:
line = line.strip()
if line.startswith("-r"):
filename = os.path.join(requirements_dir, line[2:].strip())
_dependencies, _dependency_links = parse_requirements(filename)
dependencies.extend(_dependencies)
dependency_links.extend(_dependency_links)
elif line.startswith("http"):
dependency_links.append(line)
else:
package = line.split('#')[0]
if package:
dependencies.append(package)
return dependencies, dependency_links | [
"def",
"parse_requirements",
"(",
"requirements_filename",
")",
":",
"dependencies",
",",
"dependency_links",
"=",
"[",
"]",
",",
"[",
"]",
"requirements_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"requirements_filename",
")",
"with",
"open",
"(",
"req... | read in the dependencies from the requirements files | [
"read",
"in",
"the",
"dependencies",
"from",
"the",
"requirements",
"files"
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/setup.py#L18-L37 | train | 219,469 |
lyst/lightfm | lightfm/data.py | Dataset.build_interactions | def build_interactions(self, data):
"""
Build an interaction matrix.
Two matrices will be returned: a (num_users, num_items)
COO matrix with interactions, and a (num_users, num_items)
matrix with the corresponding interaction weights.
Parameters
----------
data: iterable of (user_id, item_id) or (user_id, item_id, weight)
An iterable of interactions. The user and item ids will be
translated to internal model indices using the mappings
constructed during the fit call. If weights are not provided
they will be assumed to be 1.0.
Returns
-------
(interactions, weights): COO matrix, COO matrix
Two COO matrices: the interactions matrix
and the corresponding weights matrix.
"""
interactions = _IncrementalCOOMatrix(self.interactions_shape(), np.int32)
weights = _IncrementalCOOMatrix(self.interactions_shape(), np.float32)
for datum in data:
user_idx, item_idx, weight = self._unpack_datum(datum)
interactions.append(user_idx, item_idx, 1)
weights.append(user_idx, item_idx, weight)
return (interactions.tocoo(), weights.tocoo()) | python | def build_interactions(self, data):
"""
Build an interaction matrix.
Two matrices will be returned: a (num_users, num_items)
COO matrix with interactions, and a (num_users, num_items)
matrix with the corresponding interaction weights.
Parameters
----------
data: iterable of (user_id, item_id) or (user_id, item_id, weight)
An iterable of interactions. The user and item ids will be
translated to internal model indices using the mappings
constructed during the fit call. If weights are not provided
they will be assumed to be 1.0.
Returns
-------
(interactions, weights): COO matrix, COO matrix
Two COO matrices: the interactions matrix
and the corresponding weights matrix.
"""
interactions = _IncrementalCOOMatrix(self.interactions_shape(), np.int32)
weights = _IncrementalCOOMatrix(self.interactions_shape(), np.float32)
for datum in data:
user_idx, item_idx, weight = self._unpack_datum(datum)
interactions.append(user_idx, item_idx, 1)
weights.append(user_idx, item_idx, weight)
return (interactions.tocoo(), weights.tocoo()) | [
"def",
"build_interactions",
"(",
"self",
",",
"data",
")",
":",
"interactions",
"=",
"_IncrementalCOOMatrix",
"(",
"self",
".",
"interactions_shape",
"(",
")",
",",
"np",
".",
"int32",
")",
"weights",
"=",
"_IncrementalCOOMatrix",
"(",
"self",
".",
"interacti... | Build an interaction matrix.
Two matrices will be returned: a (num_users, num_items)
COO matrix with interactions, and a (num_users, num_items)
matrix with the corresponding interaction weights.
Parameters
----------
data: iterable of (user_id, item_id) or (user_id, item_id, weight)
An iterable of interactions. The user and item ids will be
translated to internal model indices using the mappings
constructed during the fit call. If weights are not provided
they will be assumed to be 1.0.
Returns
-------
(interactions, weights): COO matrix, COO matrix
Two COO matrices: the interactions matrix
and the corresponding weights matrix. | [
"Build",
"an",
"interaction",
"matrix",
"."
] | 87b942f87759b8336f9066a25e4762ae7d95455e | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/lightfm/data.py#L292-L326 | train | 219,470 |
lyst/lightfm | lightfm/data.py | Dataset.mapping | def mapping(self):
"""
Return the constructed mappings.
Invert these to map internal indices to external ids.
Returns
-------
(user id map, user feature map, item id map, item id map): tuple of dictionaries
"""
return (
self._user_id_mapping,
self._user_feature_mapping,
self._item_id_mapping,
self._item_feature_mapping,
) | python | def mapping(self):
"""
Return the constructed mappings.
Invert these to map internal indices to external ids.
Returns
-------
(user id map, user feature map, item id map, item id map): tuple of dictionaries
"""
return (
self._user_id_mapping,
self._user_feature_mapping,
self._item_id_mapping,
self._item_feature_mapping,
) | [
"def",
"mapping",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"_user_id_mapping",
",",
"self",
".",
"_user_feature_mapping",
",",
"self",
".",
"_item_id_mapping",
",",
"self",
".",
"_item_feature_mapping",
",",
")"
] | Return the constructed mappings.
Invert these to map internal indices to external ids.
Returns
-------
(user id map, user feature map, item id map, item id map): tuple of dictionaries | [
"Return",
"the",
"constructed",
"mappings",
"."
] | 87b942f87759b8336f9066a25e4762ae7d95455e | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/lightfm/data.py#L428-L445 | train | 219,471 |
lyst/lightfm | examples/movielens/data.py | _get_movielens_path | def _get_movielens_path():
"""
Get path to the movielens dataset file.
"""
return os.path.join(os.path.dirname(os.path.abspath(__file__)),
'movielens.zip') | python | def _get_movielens_path():
"""
Get path to the movielens dataset file.
"""
return os.path.join(os.path.dirname(os.path.abspath(__file__)),
'movielens.zip') | [
"def",
"_get_movielens_path",
"(",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
")",
",",
"'movielens.zip'",
")"
] | Get path to the movielens dataset file. | [
"Get",
"path",
"to",
"the",
"movielens",
"dataset",
"file",
"."
] | 87b942f87759b8336f9066a25e4762ae7d95455e | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/examples/movielens/data.py#L12-L18 | train | 219,472 |
lyst/lightfm | examples/movielens/data.py | _download_movielens | def _download_movielens(dest_path):
"""
Download the dataset.
"""
url = 'http://files.grouplens.org/datasets/movielens/ml-100k.zip'
req = requests.get(url, stream=True)
with open(dest_path, 'wb') as fd:
for chunk in req.iter_content():
fd.write(chunk) | python | def _download_movielens(dest_path):
"""
Download the dataset.
"""
url = 'http://files.grouplens.org/datasets/movielens/ml-100k.zip'
req = requests.get(url, stream=True)
with open(dest_path, 'wb') as fd:
for chunk in req.iter_content():
fd.write(chunk) | [
"def",
"_download_movielens",
"(",
"dest_path",
")",
":",
"url",
"=",
"'http://files.grouplens.org/datasets/movielens/ml-100k.zip'",
"req",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"stream",
"=",
"True",
")",
"with",
"open",
"(",
"dest_path",
",",
"'wb'",
"... | Download the dataset. | [
"Download",
"the",
"dataset",
"."
] | 87b942f87759b8336f9066a25e4762ae7d95455e | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/examples/movielens/data.py#L21-L31 | train | 219,473 |
lyst/lightfm | examples/movielens/data.py | _get_movie_raw_metadata | def _get_movie_raw_metadata():
"""
Get raw lines of the genre file.
"""
path = _get_movielens_path()
if not os.path.isfile(path):
_download_movielens(path)
with zipfile.ZipFile(path) as datafile:
return datafile.read('ml-100k/u.item').decode(errors='ignore').split('\n') | python | def _get_movie_raw_metadata():
"""
Get raw lines of the genre file.
"""
path = _get_movielens_path()
if not os.path.isfile(path):
_download_movielens(path)
with zipfile.ZipFile(path) as datafile:
return datafile.read('ml-100k/u.item').decode(errors='ignore').split('\n') | [
"def",
"_get_movie_raw_metadata",
"(",
")",
":",
"path",
"=",
"_get_movielens_path",
"(",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"_download_movielens",
"(",
"path",
")",
"with",
"zipfile",
".",
"ZipFile",
"(",
"path",
... | Get raw lines of the genre file. | [
"Get",
"raw",
"lines",
"of",
"the",
"genre",
"file",
"."
] | 87b942f87759b8336f9066a25e4762ae7d95455e | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/examples/movielens/data.py#L82-L93 | train | 219,474 |
lyst/lightfm | lightfm/lightfm.py | LightFM._initialize | def _initialize(self, no_components, no_item_features, no_user_features):
"""
Initialise internal latent representations.
"""
# Initialise item features.
self.item_embeddings = (
(self.random_state.rand(no_item_features, no_components) - 0.5)
/ no_components
).astype(np.float32)
self.item_embedding_gradients = np.zeros_like(self.item_embeddings)
self.item_embedding_momentum = np.zeros_like(self.item_embeddings)
self.item_biases = np.zeros(no_item_features, dtype=np.float32)
self.item_bias_gradients = np.zeros_like(self.item_biases)
self.item_bias_momentum = np.zeros_like(self.item_biases)
# Initialise user features.
self.user_embeddings = (
(self.random_state.rand(no_user_features, no_components) - 0.5)
/ no_components
).astype(np.float32)
self.user_embedding_gradients = np.zeros_like(self.user_embeddings)
self.user_embedding_momentum = np.zeros_like(self.user_embeddings)
self.user_biases = np.zeros(no_user_features, dtype=np.float32)
self.user_bias_gradients = np.zeros_like(self.user_biases)
self.user_bias_momentum = np.zeros_like(self.user_biases)
if self.learning_schedule == "adagrad":
self.item_embedding_gradients += 1
self.item_bias_gradients += 1
self.user_embedding_gradients += 1
self.user_bias_gradients += 1 | python | def _initialize(self, no_components, no_item_features, no_user_features):
"""
Initialise internal latent representations.
"""
# Initialise item features.
self.item_embeddings = (
(self.random_state.rand(no_item_features, no_components) - 0.5)
/ no_components
).astype(np.float32)
self.item_embedding_gradients = np.zeros_like(self.item_embeddings)
self.item_embedding_momentum = np.zeros_like(self.item_embeddings)
self.item_biases = np.zeros(no_item_features, dtype=np.float32)
self.item_bias_gradients = np.zeros_like(self.item_biases)
self.item_bias_momentum = np.zeros_like(self.item_biases)
# Initialise user features.
self.user_embeddings = (
(self.random_state.rand(no_user_features, no_components) - 0.5)
/ no_components
).astype(np.float32)
self.user_embedding_gradients = np.zeros_like(self.user_embeddings)
self.user_embedding_momentum = np.zeros_like(self.user_embeddings)
self.user_biases = np.zeros(no_user_features, dtype=np.float32)
self.user_bias_gradients = np.zeros_like(self.user_biases)
self.user_bias_momentum = np.zeros_like(self.user_biases)
if self.learning_schedule == "adagrad":
self.item_embedding_gradients += 1
self.item_bias_gradients += 1
self.user_embedding_gradients += 1
self.user_bias_gradients += 1 | [
"def",
"_initialize",
"(",
"self",
",",
"no_components",
",",
"no_item_features",
",",
"no_user_features",
")",
":",
"# Initialise item features.",
"self",
".",
"item_embeddings",
"=",
"(",
"(",
"self",
".",
"random_state",
".",
"rand",
"(",
"no_item_features",
",... | Initialise internal latent representations. | [
"Initialise",
"internal",
"latent",
"representations",
"."
] | 87b942f87759b8336f9066a25e4762ae7d95455e | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/lightfm/lightfm.py#L264-L295 | train | 219,475 |
lyst/lightfm | lightfm/lightfm.py | LightFM._run_epoch | def _run_epoch(
self,
item_features,
user_features,
interactions,
sample_weight,
num_threads,
loss,
):
"""
Run an individual epoch.
"""
if loss in ("warp", "bpr", "warp-kos"):
# The CSR conversion needs to happen before shuffle indices are created.
# Calling .tocsr may result in a change in the data arrays of the COO matrix,
positives_lookup = CSRMatrix(
self._get_positives_lookup_matrix(interactions)
)
# Create shuffle indexes.
shuffle_indices = np.arange(len(interactions.data), dtype=np.int32)
self.random_state.shuffle(shuffle_indices)
lightfm_data = self._get_lightfm_data()
# Call the estimation routines.
if loss == "warp":
fit_warp(
CSRMatrix(item_features),
CSRMatrix(user_features),
positives_lookup,
interactions.row,
interactions.col,
interactions.data,
sample_weight,
shuffle_indices,
lightfm_data,
self.learning_rate,
self.item_alpha,
self.user_alpha,
num_threads,
self.random_state,
)
elif loss == "bpr":
fit_bpr(
CSRMatrix(item_features),
CSRMatrix(user_features),
positives_lookup,
interactions.row,
interactions.col,
interactions.data,
sample_weight,
shuffle_indices,
lightfm_data,
self.learning_rate,
self.item_alpha,
self.user_alpha,
num_threads,
self.random_state,
)
elif loss == "warp-kos":
fit_warp_kos(
CSRMatrix(item_features),
CSRMatrix(user_features),
positives_lookup,
interactions.row,
shuffle_indices,
lightfm_data,
self.learning_rate,
self.item_alpha,
self.user_alpha,
self.k,
self.n,
num_threads,
self.random_state,
)
else:
fit_logistic(
CSRMatrix(item_features),
CSRMatrix(user_features),
interactions.row,
interactions.col,
interactions.data,
sample_weight,
shuffle_indices,
lightfm_data,
self.learning_rate,
self.item_alpha,
self.user_alpha,
num_threads,
) | python | def _run_epoch(
self,
item_features,
user_features,
interactions,
sample_weight,
num_threads,
loss,
):
"""
Run an individual epoch.
"""
if loss in ("warp", "bpr", "warp-kos"):
# The CSR conversion needs to happen before shuffle indices are created.
# Calling .tocsr may result in a change in the data arrays of the COO matrix,
positives_lookup = CSRMatrix(
self._get_positives_lookup_matrix(interactions)
)
# Create shuffle indexes.
shuffle_indices = np.arange(len(interactions.data), dtype=np.int32)
self.random_state.shuffle(shuffle_indices)
lightfm_data = self._get_lightfm_data()
# Call the estimation routines.
if loss == "warp":
fit_warp(
CSRMatrix(item_features),
CSRMatrix(user_features),
positives_lookup,
interactions.row,
interactions.col,
interactions.data,
sample_weight,
shuffle_indices,
lightfm_data,
self.learning_rate,
self.item_alpha,
self.user_alpha,
num_threads,
self.random_state,
)
elif loss == "bpr":
fit_bpr(
CSRMatrix(item_features),
CSRMatrix(user_features),
positives_lookup,
interactions.row,
interactions.col,
interactions.data,
sample_weight,
shuffle_indices,
lightfm_data,
self.learning_rate,
self.item_alpha,
self.user_alpha,
num_threads,
self.random_state,
)
elif loss == "warp-kos":
fit_warp_kos(
CSRMatrix(item_features),
CSRMatrix(user_features),
positives_lookup,
interactions.row,
shuffle_indices,
lightfm_data,
self.learning_rate,
self.item_alpha,
self.user_alpha,
self.k,
self.n,
num_threads,
self.random_state,
)
else:
fit_logistic(
CSRMatrix(item_features),
CSRMatrix(user_features),
interactions.row,
interactions.col,
interactions.data,
sample_weight,
shuffle_indices,
lightfm_data,
self.learning_rate,
self.item_alpha,
self.user_alpha,
num_threads,
) | [
"def",
"_run_epoch",
"(",
"self",
",",
"item_features",
",",
"user_features",
",",
"interactions",
",",
"sample_weight",
",",
"num_threads",
",",
"loss",
",",
")",
":",
"if",
"loss",
"in",
"(",
"\"warp\"",
",",
"\"bpr\"",
",",
"\"warp-kos\"",
")",
":",
"# ... | Run an individual epoch. | [
"Run",
"an",
"individual",
"epoch",
"."
] | 87b942f87759b8336f9066a25e4762ae7d95455e | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/lightfm/lightfm.py#L651-L742 | train | 219,476 |
lyst/lightfm | lightfm/lightfm.py | LightFM.predict | def predict(
self, user_ids, item_ids, item_features=None, user_features=None, num_threads=1
):
"""
Compute the recommendation score for user-item pairs.
For details on how to use feature matrices, see the documentation
on the :class:`lightfm.LightFM` class.
Arguments
---------
user_ids: integer or np.int32 array of shape [n_pairs,]
single user id or an array containing the user ids for the
user-item pairs for which a prediction is to be computed. Note
that these are LightFM's internal id's, i.e. the index of the
user in the interaction matrix used for fitting the model.
item_ids: np.int32 array of shape [n_pairs,]
an array containing the item ids for the user-item pairs for which
a prediction is to be computed. Note that these are LightFM's
internal id's, i.e. the index of the item in the interaction
matrix used for fitting the model.
user_features: np.float32 csr_matrix of shape [n_users, n_user_features], optional
Each row contains that user's weights over features.
item_features: np.float32 csr_matrix of shape [n_items, n_item_features], optional
Each row contains that item's weights over features.
num_threads: int, optional
Number of parallel computation threads to use. Should
not be higher than the number of physical cores.
Returns
-------
np.float32 array of shape [n_pairs,]
Numpy array containing the recommendation scores for pairs defined
by the inputs.
"""
self._check_initialized()
if not isinstance(user_ids, np.ndarray):
user_ids = np.repeat(np.int32(user_ids), len(item_ids))
if isinstance(item_ids, (list, tuple)):
item_ids = np.array(item_ids, dtype=np.int32)
assert len(user_ids) == len(item_ids)
if user_ids.dtype != np.int32:
user_ids = user_ids.astype(np.int32)
if item_ids.dtype != np.int32:
item_ids = item_ids.astype(np.int32)
if num_threads < 1:
raise ValueError("Number of threads must be 1 or larger.")
if user_ids.min() < 0 or item_ids.min() < 0:
raise ValueError(
"User or item ids cannot be negative. "
"Check your inputs for negative numbers "
"or very large numbers that can overflow."
)
n_users = user_ids.max() + 1
n_items = item_ids.max() + 1
(user_features, item_features) = self._construct_feature_matrices(
n_users, n_items, user_features, item_features
)
lightfm_data = self._get_lightfm_data()
predictions = np.empty(len(user_ids), dtype=np.float64)
predict_lightfm(
CSRMatrix(item_features),
CSRMatrix(user_features),
user_ids,
item_ids,
predictions,
lightfm_data,
num_threads,
)
return predictions | python | def predict(
self, user_ids, item_ids, item_features=None, user_features=None, num_threads=1
):
"""
Compute the recommendation score for user-item pairs.
For details on how to use feature matrices, see the documentation
on the :class:`lightfm.LightFM` class.
Arguments
---------
user_ids: integer or np.int32 array of shape [n_pairs,]
single user id or an array containing the user ids for the
user-item pairs for which a prediction is to be computed. Note
that these are LightFM's internal id's, i.e. the index of the
user in the interaction matrix used for fitting the model.
item_ids: np.int32 array of shape [n_pairs,]
an array containing the item ids for the user-item pairs for which
a prediction is to be computed. Note that these are LightFM's
internal id's, i.e. the index of the item in the interaction
matrix used for fitting the model.
user_features: np.float32 csr_matrix of shape [n_users, n_user_features], optional
Each row contains that user's weights over features.
item_features: np.float32 csr_matrix of shape [n_items, n_item_features], optional
Each row contains that item's weights over features.
num_threads: int, optional
Number of parallel computation threads to use. Should
not be higher than the number of physical cores.
Returns
-------
np.float32 array of shape [n_pairs,]
Numpy array containing the recommendation scores for pairs defined
by the inputs.
"""
self._check_initialized()
if not isinstance(user_ids, np.ndarray):
user_ids = np.repeat(np.int32(user_ids), len(item_ids))
if isinstance(item_ids, (list, tuple)):
item_ids = np.array(item_ids, dtype=np.int32)
assert len(user_ids) == len(item_ids)
if user_ids.dtype != np.int32:
user_ids = user_ids.astype(np.int32)
if item_ids.dtype != np.int32:
item_ids = item_ids.astype(np.int32)
if num_threads < 1:
raise ValueError("Number of threads must be 1 or larger.")
if user_ids.min() < 0 or item_ids.min() < 0:
raise ValueError(
"User or item ids cannot be negative. "
"Check your inputs for negative numbers "
"or very large numbers that can overflow."
)
n_users = user_ids.max() + 1
n_items = item_ids.max() + 1
(user_features, item_features) = self._construct_feature_matrices(
n_users, n_items, user_features, item_features
)
lightfm_data = self._get_lightfm_data()
predictions = np.empty(len(user_ids), dtype=np.float64)
predict_lightfm(
CSRMatrix(item_features),
CSRMatrix(user_features),
user_ids,
item_ids,
predictions,
lightfm_data,
num_threads,
)
return predictions | [
"def",
"predict",
"(",
"self",
",",
"user_ids",
",",
"item_ids",
",",
"item_features",
"=",
"None",
",",
"user_features",
"=",
"None",
",",
"num_threads",
"=",
"1",
")",
":",
"self",
".",
"_check_initialized",
"(",
")",
"if",
"not",
"isinstance",
"(",
"u... | Compute the recommendation score for user-item pairs.
For details on how to use feature matrices, see the documentation
on the :class:`lightfm.LightFM` class.
Arguments
---------
user_ids: integer or np.int32 array of shape [n_pairs,]
single user id or an array containing the user ids for the
user-item pairs for which a prediction is to be computed. Note
that these are LightFM's internal id's, i.e. the index of the
user in the interaction matrix used for fitting the model.
item_ids: np.int32 array of shape [n_pairs,]
an array containing the item ids for the user-item pairs for which
a prediction is to be computed. Note that these are LightFM's
internal id's, i.e. the index of the item in the interaction
matrix used for fitting the model.
user_features: np.float32 csr_matrix of shape [n_users, n_user_features], optional
Each row contains that user's weights over features.
item_features: np.float32 csr_matrix of shape [n_items, n_item_features], optional
Each row contains that item's weights over features.
num_threads: int, optional
Number of parallel computation threads to use. Should
not be higher than the number of physical cores.
Returns
-------
np.float32 array of shape [n_pairs,]
Numpy array containing the recommendation scores for pairs defined
by the inputs. | [
"Compute",
"the",
"recommendation",
"score",
"for",
"user",
"-",
"item",
"pairs",
"."
] | 87b942f87759b8336f9066a25e4762ae7d95455e | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/lightfm/lightfm.py#L744-L828 | train | 219,477 |
lyst/lightfm | lightfm/lightfm.py | LightFM.get_item_representations | def get_item_representations(self, features=None):
"""
Get the latent representations for items given model and features.
Arguments
---------
features: np.float32 csr_matrix of shape [n_items, n_item_features], optional
Each row contains that item's weights over features.
An identity matrix will be used if not supplied.
Returns
-------
(item_biases, item_embeddings):
(np.float32 array of shape n_items,
np.float32 array of shape [n_items, num_components]
Biases and latent representations for items.
"""
self._check_initialized()
if features is None:
return self.item_biases, self.item_embeddings
features = sp.csr_matrix(features, dtype=CYTHON_DTYPE)
return features * self.item_biases, features * self.item_embeddings | python | def get_item_representations(self, features=None):
"""
Get the latent representations for items given model and features.
Arguments
---------
features: np.float32 csr_matrix of shape [n_items, n_item_features], optional
Each row contains that item's weights over features.
An identity matrix will be used if not supplied.
Returns
-------
(item_biases, item_embeddings):
(np.float32 array of shape n_items,
np.float32 array of shape [n_items, num_components]
Biases and latent representations for items.
"""
self._check_initialized()
if features is None:
return self.item_biases, self.item_embeddings
features = sp.csr_matrix(features, dtype=CYTHON_DTYPE)
return features * self.item_biases, features * self.item_embeddings | [
"def",
"get_item_representations",
"(",
"self",
",",
"features",
"=",
"None",
")",
":",
"self",
".",
"_check_initialized",
"(",
")",
"if",
"features",
"is",
"None",
":",
"return",
"self",
".",
"item_biases",
",",
"self",
".",
"item_embeddings",
"features",
"... | Get the latent representations for items given model and features.
Arguments
---------
features: np.float32 csr_matrix of shape [n_items, n_item_features], optional
Each row contains that item's weights over features.
An identity matrix will be used if not supplied.
Returns
-------
(item_biases, item_embeddings):
(np.float32 array of shape n_items,
np.float32 array of shape [n_items, num_components]
Biases and latent representations for items. | [
"Get",
"the",
"latent",
"representations",
"for",
"items",
"given",
"model",
"and",
"features",
"."
] | 87b942f87759b8336f9066a25e4762ae7d95455e | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/lightfm/lightfm.py#L947-L974 | train | 219,478 |
lyst/lightfm | lightfm/lightfm.py | LightFM.get_user_representations | def get_user_representations(self, features=None):
"""
Get the latent representations for users given model and features.
Arguments
---------
features: np.float32 csr_matrix of shape [n_users, n_user_features], optional
Each row contains that user's weights over features.
An identity matrix will be used if not supplied.
Returns
-------
(user_biases, user_embeddings):
(np.float32 array of shape n_users
np.float32 array of shape [n_users, num_components]
Biases and latent representations for users.
"""
self._check_initialized()
if features is None:
return self.user_biases, self.user_embeddings
features = sp.csr_matrix(features, dtype=CYTHON_DTYPE)
return features * self.user_biases, features * self.user_embeddings | python | def get_user_representations(self, features=None):
"""
Get the latent representations for users given model and features.
Arguments
---------
features: np.float32 csr_matrix of shape [n_users, n_user_features], optional
Each row contains that user's weights over features.
An identity matrix will be used if not supplied.
Returns
-------
(user_biases, user_embeddings):
(np.float32 array of shape n_users
np.float32 array of shape [n_users, num_components]
Biases and latent representations for users.
"""
self._check_initialized()
if features is None:
return self.user_biases, self.user_embeddings
features = sp.csr_matrix(features, dtype=CYTHON_DTYPE)
return features * self.user_biases, features * self.user_embeddings | [
"def",
"get_user_representations",
"(",
"self",
",",
"features",
"=",
"None",
")",
":",
"self",
".",
"_check_initialized",
"(",
")",
"if",
"features",
"is",
"None",
":",
"return",
"self",
".",
"user_biases",
",",
"self",
".",
"user_embeddings",
"features",
"... | Get the latent representations for users given model and features.
Arguments
---------
features: np.float32 csr_matrix of shape [n_users, n_user_features], optional
Each row contains that user's weights over features.
An identity matrix will be used if not supplied.
Returns
-------
(user_biases, user_embeddings):
(np.float32 array of shape n_users
np.float32 array of shape [n_users, num_components]
Biases and latent representations for users. | [
"Get",
"the",
"latent",
"representations",
"for",
"users",
"given",
"model",
"and",
"features",
"."
] | 87b942f87759b8336f9066a25e4762ae7d95455e | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/lightfm/lightfm.py#L976-L1003 | train | 219,479 |
quantopian/empyrical | empyrical/stats.py | _adjust_returns | def _adjust_returns(returns, adjustment_factor):
"""
Returns the returns series adjusted by adjustment_factor. Optimizes for the
case of adjustment_factor being 0 by returning returns itself, not a copy!
Parameters
----------
returns : pd.Series or np.ndarray
adjustment_factor : pd.Series or np.ndarray or float or int
Returns
-------
adjusted_returns : array-like
"""
if isinstance(adjustment_factor, (float, int)) and adjustment_factor == 0:
return returns
return returns - adjustment_factor | python | def _adjust_returns(returns, adjustment_factor):
"""
Returns the returns series adjusted by adjustment_factor. Optimizes for the
case of adjustment_factor being 0 by returning returns itself, not a copy!
Parameters
----------
returns : pd.Series or np.ndarray
adjustment_factor : pd.Series or np.ndarray or float or int
Returns
-------
adjusted_returns : array-like
"""
if isinstance(adjustment_factor, (float, int)) and adjustment_factor == 0:
return returns
return returns - adjustment_factor | [
"def",
"_adjust_returns",
"(",
"returns",
",",
"adjustment_factor",
")",
":",
"if",
"isinstance",
"(",
"adjustment_factor",
",",
"(",
"float",
",",
"int",
")",
")",
"and",
"adjustment_factor",
"==",
"0",
":",
"return",
"returns",
"return",
"returns",
"-",
"a... | Returns the returns series adjusted by adjustment_factor. Optimizes for the
case of adjustment_factor being 0 by returning returns itself, not a copy!
Parameters
----------
returns : pd.Series or np.ndarray
adjustment_factor : pd.Series or np.ndarray or float or int
Returns
-------
adjusted_returns : array-like | [
"Returns",
"the",
"returns",
"series",
"adjusted",
"by",
"adjustment_factor",
".",
"Optimizes",
"for",
"the",
"case",
"of",
"adjustment_factor",
"being",
"0",
"by",
"returning",
"returns",
"itself",
"not",
"a",
"copy!"
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L127-L143 | train | 219,480 |
quantopian/empyrical | empyrical/stats.py | annualization_factor | def annualization_factor(period, annualization):
"""
Return annualization factor from period entered or if a custom
value is passed in.
Parameters
----------
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
Returns
-------
annualization_factor : float
"""
if annualization is None:
try:
factor = ANNUALIZATION_FACTORS[period]
except KeyError:
raise ValueError(
"Period cannot be '{}'. "
"Can be '{}'.".format(
period, "', '".join(ANNUALIZATION_FACTORS.keys())
)
)
else:
factor = annualization
return factor | python | def annualization_factor(period, annualization):
"""
Return annualization factor from period entered or if a custom
value is passed in.
Parameters
----------
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
Returns
-------
annualization_factor : float
"""
if annualization is None:
try:
factor = ANNUALIZATION_FACTORS[period]
except KeyError:
raise ValueError(
"Period cannot be '{}'. "
"Can be '{}'.".format(
period, "', '".join(ANNUALIZATION_FACTORS.keys())
)
)
else:
factor = annualization
return factor | [
"def",
"annualization_factor",
"(",
"period",
",",
"annualization",
")",
":",
"if",
"annualization",
"is",
"None",
":",
"try",
":",
"factor",
"=",
"ANNUALIZATION_FACTORS",
"[",
"period",
"]",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",
"\"Period canno... | Return annualization factor from period entered or if a custom
value is passed in.
Parameters
----------
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
Returns
-------
annualization_factor : float | [
"Return",
"annualization",
"factor",
"from",
"period",
"entered",
"or",
"if",
"a",
"custom",
"value",
"is",
"passed",
"in",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L146-L183 | train | 219,481 |
quantopian/empyrical | empyrical/stats.py | simple_returns | def simple_returns(prices):
"""
Compute simple returns from a timeseries of prices.
Parameters
----------
prices : pd.Series, pd.DataFrame or np.ndarray
Prices of assets in wide-format, with assets as columns,
and indexed by datetimes.
Returns
-------
returns : array-like
Returns of assets in wide-format, with assets as columns,
and index coerced to be tz-aware.
"""
if isinstance(prices, (pd.DataFrame, pd.Series)):
out = prices.pct_change().iloc[1:]
else:
# Assume np.ndarray
out = np.diff(prices, axis=0)
np.divide(out, prices[:-1], out=out)
return out | python | def simple_returns(prices):
"""
Compute simple returns from a timeseries of prices.
Parameters
----------
prices : pd.Series, pd.DataFrame or np.ndarray
Prices of assets in wide-format, with assets as columns,
and indexed by datetimes.
Returns
-------
returns : array-like
Returns of assets in wide-format, with assets as columns,
and index coerced to be tz-aware.
"""
if isinstance(prices, (pd.DataFrame, pd.Series)):
out = prices.pct_change().iloc[1:]
else:
# Assume np.ndarray
out = np.diff(prices, axis=0)
np.divide(out, prices[:-1], out=out)
return out | [
"def",
"simple_returns",
"(",
"prices",
")",
":",
"if",
"isinstance",
"(",
"prices",
",",
"(",
"pd",
".",
"DataFrame",
",",
"pd",
".",
"Series",
")",
")",
":",
"out",
"=",
"prices",
".",
"pct_change",
"(",
")",
".",
"iloc",
"[",
"1",
":",
"]",
"e... | Compute simple returns from a timeseries of prices.
Parameters
----------
prices : pd.Series, pd.DataFrame or np.ndarray
Prices of assets in wide-format, with assets as columns,
and indexed by datetimes.
Returns
-------
returns : array-like
Returns of assets in wide-format, with assets as columns,
and index coerced to be tz-aware. | [
"Compute",
"simple",
"returns",
"from",
"a",
"timeseries",
"of",
"prices",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L186-L209 | train | 219,482 |
quantopian/empyrical | empyrical/stats.py | cum_returns | def cum_returns(returns, starting_value=0, out=None):
"""
Compute cumulative returns from simple returns.
Parameters
----------
returns : pd.Series, np.ndarray, or pd.DataFrame
Returns of the strategy as a percentage, noncumulative.
- Time series with decimal returns.
- Example::
2015-07-16 -0.012143
2015-07-17 0.045350
2015-07-20 0.030957
2015-07-21 0.004902
- Also accepts two dimensional data. In this case, each column is
cumulated.
starting_value : float, optional
The starting returns.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
cumulative_returns : array-like
Series of cumulative returns.
"""
if len(returns) < 1:
return returns.copy()
nanmask = np.isnan(returns)
if np.any(nanmask):
returns = returns.copy()
returns[nanmask] = 0
allocated_output = out is None
if allocated_output:
out = np.empty_like(returns)
np.add(returns, 1, out=out)
out.cumprod(axis=0, out=out)
if starting_value == 0:
np.subtract(out, 1, out=out)
else:
np.multiply(out, starting_value, out=out)
if allocated_output:
if returns.ndim == 1 and isinstance(returns, pd.Series):
out = pd.Series(out, index=returns.index)
elif isinstance(returns, pd.DataFrame):
out = pd.DataFrame(
out, index=returns.index, columns=returns.columns,
)
return out | python | def cum_returns(returns, starting_value=0, out=None):
"""
Compute cumulative returns from simple returns.
Parameters
----------
returns : pd.Series, np.ndarray, or pd.DataFrame
Returns of the strategy as a percentage, noncumulative.
- Time series with decimal returns.
- Example::
2015-07-16 -0.012143
2015-07-17 0.045350
2015-07-20 0.030957
2015-07-21 0.004902
- Also accepts two dimensional data. In this case, each column is
cumulated.
starting_value : float, optional
The starting returns.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
cumulative_returns : array-like
Series of cumulative returns.
"""
if len(returns) < 1:
return returns.copy()
nanmask = np.isnan(returns)
if np.any(nanmask):
returns = returns.copy()
returns[nanmask] = 0
allocated_output = out is None
if allocated_output:
out = np.empty_like(returns)
np.add(returns, 1, out=out)
out.cumprod(axis=0, out=out)
if starting_value == 0:
np.subtract(out, 1, out=out)
else:
np.multiply(out, starting_value, out=out)
if allocated_output:
if returns.ndim == 1 and isinstance(returns, pd.Series):
out = pd.Series(out, index=returns.index)
elif isinstance(returns, pd.DataFrame):
out = pd.DataFrame(
out, index=returns.index, columns=returns.columns,
)
return out | [
"def",
"cum_returns",
"(",
"returns",
",",
"starting_value",
"=",
"0",
",",
"out",
"=",
"None",
")",
":",
"if",
"len",
"(",
"returns",
")",
"<",
"1",
":",
"return",
"returns",
".",
"copy",
"(",
")",
"nanmask",
"=",
"np",
".",
"isnan",
"(",
"returns... | Compute cumulative returns from simple returns.
Parameters
----------
returns : pd.Series, np.ndarray, or pd.DataFrame
Returns of the strategy as a percentage, noncumulative.
- Time series with decimal returns.
- Example::
2015-07-16 -0.012143
2015-07-17 0.045350
2015-07-20 0.030957
2015-07-21 0.004902
- Also accepts two dimensional data. In this case, each column is
cumulated.
starting_value : float, optional
The starting returns.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
cumulative_returns : array-like
Series of cumulative returns. | [
"Compute",
"cumulative",
"returns",
"from",
"simple",
"returns",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L212-L270 | train | 219,483 |
quantopian/empyrical | empyrical/stats.py | cum_returns_final | def cum_returns_final(returns, starting_value=0):
"""
Compute total returns from simple returns.
Parameters
----------
returns : pd.DataFrame, pd.Series, or np.ndarray
Noncumulative simple returns of one or more timeseries.
starting_value : float, optional
The starting returns.
Returns
-------
total_returns : pd.Series, np.ndarray, or float
If input is 1-dimensional (a Series or 1D numpy array), the result is a
scalar.
If input is 2-dimensional (a DataFrame or 2D numpy array), the result
is a 1D array containing cumulative returns for each column of input.
"""
if len(returns) == 0:
return np.nan
if isinstance(returns, pd.DataFrame):
result = (returns + 1).prod()
else:
result = np.nanprod(returns + 1, axis=0)
if starting_value == 0:
result -= 1
else:
result *= starting_value
return result | python | def cum_returns_final(returns, starting_value=0):
"""
Compute total returns from simple returns.
Parameters
----------
returns : pd.DataFrame, pd.Series, or np.ndarray
Noncumulative simple returns of one or more timeseries.
starting_value : float, optional
The starting returns.
Returns
-------
total_returns : pd.Series, np.ndarray, or float
If input is 1-dimensional (a Series or 1D numpy array), the result is a
scalar.
If input is 2-dimensional (a DataFrame or 2D numpy array), the result
is a 1D array containing cumulative returns for each column of input.
"""
if len(returns) == 0:
return np.nan
if isinstance(returns, pd.DataFrame):
result = (returns + 1).prod()
else:
result = np.nanprod(returns + 1, axis=0)
if starting_value == 0:
result -= 1
else:
result *= starting_value
return result | [
"def",
"cum_returns_final",
"(",
"returns",
",",
"starting_value",
"=",
"0",
")",
":",
"if",
"len",
"(",
"returns",
")",
"==",
"0",
":",
"return",
"np",
".",
"nan",
"if",
"isinstance",
"(",
"returns",
",",
"pd",
".",
"DataFrame",
")",
":",
"result",
... | Compute total returns from simple returns.
Parameters
----------
returns : pd.DataFrame, pd.Series, or np.ndarray
Noncumulative simple returns of one or more timeseries.
starting_value : float, optional
The starting returns.
Returns
-------
total_returns : pd.Series, np.ndarray, or float
If input is 1-dimensional (a Series or 1D numpy array), the result is a
scalar.
If input is 2-dimensional (a DataFrame or 2D numpy array), the result
is a 1D array containing cumulative returns for each column of input. | [
"Compute",
"total",
"returns",
"from",
"simple",
"returns",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L273-L306 | train | 219,484 |
quantopian/empyrical | empyrical/stats.py | aggregate_returns | def aggregate_returns(returns, convert_to):
"""
Aggregates returns by week, month, or year.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
convert_to : str
Can be 'weekly', 'monthly', or 'yearly'.
Returns
-------
aggregated_returns : pd.Series
"""
def cumulate_returns(x):
return cum_returns(x).iloc[-1]
if convert_to == WEEKLY:
grouping = [lambda x: x.year, lambda x: x.isocalendar()[1]]
elif convert_to == MONTHLY:
grouping = [lambda x: x.year, lambda x: x.month]
elif convert_to == YEARLY:
grouping = [lambda x: x.year]
else:
raise ValueError(
'convert_to must be {}, {} or {}'.format(WEEKLY, MONTHLY, YEARLY)
)
return returns.groupby(grouping).apply(cumulate_returns) | python | def aggregate_returns(returns, convert_to):
"""
Aggregates returns by week, month, or year.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
convert_to : str
Can be 'weekly', 'monthly', or 'yearly'.
Returns
-------
aggregated_returns : pd.Series
"""
def cumulate_returns(x):
return cum_returns(x).iloc[-1]
if convert_to == WEEKLY:
grouping = [lambda x: x.year, lambda x: x.isocalendar()[1]]
elif convert_to == MONTHLY:
grouping = [lambda x: x.year, lambda x: x.month]
elif convert_to == YEARLY:
grouping = [lambda x: x.year]
else:
raise ValueError(
'convert_to must be {}, {} or {}'.format(WEEKLY, MONTHLY, YEARLY)
)
return returns.groupby(grouping).apply(cumulate_returns) | [
"def",
"aggregate_returns",
"(",
"returns",
",",
"convert_to",
")",
":",
"def",
"cumulate_returns",
"(",
"x",
")",
":",
"return",
"cum_returns",
"(",
"x",
")",
".",
"iloc",
"[",
"-",
"1",
"]",
"if",
"convert_to",
"==",
"WEEKLY",
":",
"grouping",
"=",
"... | Aggregates returns by week, month, or year.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
convert_to : str
Can be 'weekly', 'monthly', or 'yearly'.
Returns
-------
aggregated_returns : pd.Series | [
"Aggregates",
"returns",
"by",
"week",
"month",
"or",
"year",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L309-L340 | train | 219,485 |
quantopian/empyrical | empyrical/stats.py | max_drawdown | def max_drawdown(returns, out=None):
"""
Determines the maximum drawdown of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
max_drawdown : float
Note
-----
See https://en.wikipedia.org/wiki/Drawdown_(economics) for more details.
"""
allocated_output = out is None
if allocated_output:
out = np.empty(returns.shape[1:])
returns_1d = returns.ndim == 1
if len(returns) < 1:
out[()] = np.nan
if returns_1d:
out = out.item()
return out
returns_array = np.asanyarray(returns)
cumulative = np.empty(
(returns.shape[0] + 1,) + returns.shape[1:],
dtype='float64',
)
cumulative[0] = start = 100
cum_returns(returns_array, starting_value=start, out=cumulative[1:])
max_return = np.fmax.accumulate(cumulative, axis=0)
nanmin((cumulative - max_return) / max_return, axis=0, out=out)
if returns_1d:
out = out.item()
elif allocated_output and isinstance(returns, pd.DataFrame):
out = pd.Series(out)
return out | python | def max_drawdown(returns, out=None):
"""
Determines the maximum drawdown of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
max_drawdown : float
Note
-----
See https://en.wikipedia.org/wiki/Drawdown_(economics) for more details.
"""
allocated_output = out is None
if allocated_output:
out = np.empty(returns.shape[1:])
returns_1d = returns.ndim == 1
if len(returns) < 1:
out[()] = np.nan
if returns_1d:
out = out.item()
return out
returns_array = np.asanyarray(returns)
cumulative = np.empty(
(returns.shape[0] + 1,) + returns.shape[1:],
dtype='float64',
)
cumulative[0] = start = 100
cum_returns(returns_array, starting_value=start, out=cumulative[1:])
max_return = np.fmax.accumulate(cumulative, axis=0)
nanmin((cumulative - max_return) / max_return, axis=0, out=out)
if returns_1d:
out = out.item()
elif allocated_output and isinstance(returns, pd.DataFrame):
out = pd.Series(out)
return out | [
"def",
"max_drawdown",
"(",
"returns",
",",
"out",
"=",
"None",
")",
":",
"allocated_output",
"=",
"out",
"is",
"None",
"if",
"allocated_output",
":",
"out",
"=",
"np",
".",
"empty",
"(",
"returns",
".",
"shape",
"[",
"1",
":",
"]",
")",
"returns_1d",
... | Determines the maximum drawdown of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
max_drawdown : float
Note
-----
See https://en.wikipedia.org/wiki/Drawdown_(economics) for more details. | [
"Determines",
"the",
"maximum",
"drawdown",
"of",
"a",
"strategy",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L343-L393 | train | 219,486 |
quantopian/empyrical | empyrical/stats.py | annual_return | def annual_return(returns, period=DAILY, annualization=None):
"""
Determines the mean annual growth rate of returns. This is equivilent
to the compound annual growth rate.
Parameters
----------
returns : pd.Series or np.ndarray
Periodic returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
Returns
-------
annual_return : float
Annual Return as CAGR (Compounded Annual Growth Rate).
"""
if len(returns) < 1:
return np.nan
ann_factor = annualization_factor(period, annualization)
num_years = len(returns) / ann_factor
# Pass array to ensure index -1 looks up successfully.
ending_value = cum_returns_final(returns, starting_value=1)
return ending_value ** (1 / num_years) - 1 | python | def annual_return(returns, period=DAILY, annualization=None):
"""
Determines the mean annual growth rate of returns. This is equivilent
to the compound annual growth rate.
Parameters
----------
returns : pd.Series or np.ndarray
Periodic returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
Returns
-------
annual_return : float
Annual Return as CAGR (Compounded Annual Growth Rate).
"""
if len(returns) < 1:
return np.nan
ann_factor = annualization_factor(period, annualization)
num_years = len(returns) / ann_factor
# Pass array to ensure index -1 looks up successfully.
ending_value = cum_returns_final(returns, starting_value=1)
return ending_value ** (1 / num_years) - 1 | [
"def",
"annual_return",
"(",
"returns",
",",
"period",
"=",
"DAILY",
",",
"annualization",
"=",
"None",
")",
":",
"if",
"len",
"(",
"returns",
")",
"<",
"1",
":",
"return",
"np",
".",
"nan",
"ann_factor",
"=",
"annualization_factor",
"(",
"period",
",",
... | Determines the mean annual growth rate of returns. This is equivilent
to the compound annual growth rate.
Parameters
----------
returns : pd.Series or np.ndarray
Periodic returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
Returns
-------
annual_return : float
Annual Return as CAGR (Compounded Annual Growth Rate). | [
"Determines",
"the",
"mean",
"annual",
"growth",
"rate",
"of",
"returns",
".",
"This",
"is",
"equivilent",
"to",
"the",
"compound",
"annual",
"growth",
"rate",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L399-L438 | train | 219,487 |
quantopian/empyrical | empyrical/stats.py | annual_volatility | def annual_volatility(returns,
period=DAILY,
alpha=2.0,
annualization=None,
out=None):
"""
Determines the annual volatility of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Periodic returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
alpha : float, optional
Scaling relation (Levy stability exponent).
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
annual_volatility : float
"""
allocated_output = out is None
if allocated_output:
out = np.empty(returns.shape[1:])
returns_1d = returns.ndim == 1
if len(returns) < 2:
out[()] = np.nan
if returns_1d:
out = out.item()
return out
ann_factor = annualization_factor(period, annualization)
nanstd(returns, ddof=1, axis=0, out=out)
out = np.multiply(out, ann_factor ** (1.0 / alpha), out=out)
if returns_1d:
out = out.item()
return out | python | def annual_volatility(returns,
period=DAILY,
alpha=2.0,
annualization=None,
out=None):
"""
Determines the annual volatility of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Periodic returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
alpha : float, optional
Scaling relation (Levy stability exponent).
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
annual_volatility : float
"""
allocated_output = out is None
if allocated_output:
out = np.empty(returns.shape[1:])
returns_1d = returns.ndim == 1
if len(returns) < 2:
out[()] = np.nan
if returns_1d:
out = out.item()
return out
ann_factor = annualization_factor(period, annualization)
nanstd(returns, ddof=1, axis=0, out=out)
out = np.multiply(out, ann_factor ** (1.0 / alpha), out=out)
if returns_1d:
out = out.item()
return out | [
"def",
"annual_volatility",
"(",
"returns",
",",
"period",
"=",
"DAILY",
",",
"alpha",
"=",
"2.0",
",",
"annualization",
"=",
"None",
",",
"out",
"=",
"None",
")",
":",
"allocated_output",
"=",
"out",
"is",
"None",
"if",
"allocated_output",
":",
"out",
"... | Determines the annual volatility of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Periodic returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
alpha : float, optional
Scaling relation (Levy stability exponent).
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
annual_volatility : float | [
"Determines",
"the",
"annual",
"volatility",
"of",
"a",
"strategy",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L478-L531 | train | 219,488 |
quantopian/empyrical | empyrical/stats.py | calmar_ratio | def calmar_ratio(returns, period=DAILY, annualization=None):
"""
Determines the Calmar ratio, or drawdown ratio, of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
Returns
-------
calmar_ratio : float
Calmar ratio (drawdown ratio) as float. Returns np.nan if there is no
calmar ratio.
Note
-----
See https://en.wikipedia.org/wiki/Calmar_ratio for more details.
"""
max_dd = max_drawdown(returns=returns)
if max_dd < 0:
temp = annual_return(
returns=returns,
period=period,
annualization=annualization
) / abs(max_dd)
else:
return np.nan
if np.isinf(temp):
return np.nan
return temp | python | def calmar_ratio(returns, period=DAILY, annualization=None):
"""
Determines the Calmar ratio, or drawdown ratio, of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
Returns
-------
calmar_ratio : float
Calmar ratio (drawdown ratio) as float. Returns np.nan if there is no
calmar ratio.
Note
-----
See https://en.wikipedia.org/wiki/Calmar_ratio for more details.
"""
max_dd = max_drawdown(returns=returns)
if max_dd < 0:
temp = annual_return(
returns=returns,
period=period,
annualization=annualization
) / abs(max_dd)
else:
return np.nan
if np.isinf(temp):
return np.nan
return temp | [
"def",
"calmar_ratio",
"(",
"returns",
",",
"period",
"=",
"DAILY",
",",
"annualization",
"=",
"None",
")",
":",
"max_dd",
"=",
"max_drawdown",
"(",
"returns",
"=",
"returns",
")",
"if",
"max_dd",
"<",
"0",
":",
"temp",
"=",
"annual_return",
"(",
"return... | Determines the Calmar ratio, or drawdown ratio, of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
Returns
-------
calmar_ratio : float
Calmar ratio (drawdown ratio) as float. Returns np.nan if there is no
calmar ratio.
Note
-----
See https://en.wikipedia.org/wiki/Calmar_ratio for more details. | [
"Determines",
"the",
"Calmar",
"ratio",
"or",
"drawdown",
"ratio",
"of",
"a",
"strategy",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L539-L587 | train | 219,489 |
quantopian/empyrical | empyrical/stats.py | omega_ratio | def omega_ratio(returns, risk_free=0.0, required_return=0.0,
annualization=APPROX_BDAYS_PER_YEAR):
"""Determines the Omega ratio of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
risk_free : int, float
Constant risk-free return throughout the period
required_return : float, optional
Minimum acceptance return of the investor. Threshold over which to
consider positive vs negative returns. It will be converted to a
value appropriate for the period of the returns. E.g. An annual minimum
acceptable return of 100 will translate to a minimum acceptable
return of 0.018.
annualization : int, optional
Factor used to convert the required_return into a daily
value. Enter 1 if no time period conversion is necessary.
Returns
-------
omega_ratio : float
Note
-----
See https://en.wikipedia.org/wiki/Omega_ratio for more details.
"""
if len(returns) < 2:
return np.nan
if annualization == 1:
return_threshold = required_return
elif required_return <= -1:
return np.nan
else:
return_threshold = (1 + required_return) ** \
(1. / annualization) - 1
returns_less_thresh = returns - risk_free - return_threshold
numer = sum(returns_less_thresh[returns_less_thresh > 0.0])
denom = -1.0 * sum(returns_less_thresh[returns_less_thresh < 0.0])
if denom > 0.0:
return numer / denom
else:
return np.nan | python | def omega_ratio(returns, risk_free=0.0, required_return=0.0,
annualization=APPROX_BDAYS_PER_YEAR):
"""Determines the Omega ratio of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
risk_free : int, float
Constant risk-free return throughout the period
required_return : float, optional
Minimum acceptance return of the investor. Threshold over which to
consider positive vs negative returns. It will be converted to a
value appropriate for the period of the returns. E.g. An annual minimum
acceptable return of 100 will translate to a minimum acceptable
return of 0.018.
annualization : int, optional
Factor used to convert the required_return into a daily
value. Enter 1 if no time period conversion is necessary.
Returns
-------
omega_ratio : float
Note
-----
See https://en.wikipedia.org/wiki/Omega_ratio for more details.
"""
if len(returns) < 2:
return np.nan
if annualization == 1:
return_threshold = required_return
elif required_return <= -1:
return np.nan
else:
return_threshold = (1 + required_return) ** \
(1. / annualization) - 1
returns_less_thresh = returns - risk_free - return_threshold
numer = sum(returns_less_thresh[returns_less_thresh > 0.0])
denom = -1.0 * sum(returns_less_thresh[returns_less_thresh < 0.0])
if denom > 0.0:
return numer / denom
else:
return np.nan | [
"def",
"omega_ratio",
"(",
"returns",
",",
"risk_free",
"=",
"0.0",
",",
"required_return",
"=",
"0.0",
",",
"annualization",
"=",
"APPROX_BDAYS_PER_YEAR",
")",
":",
"if",
"len",
"(",
"returns",
")",
"<",
"2",
":",
"return",
"np",
".",
"nan",
"if",
"annu... | Determines the Omega ratio of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
risk_free : int, float
Constant risk-free return throughout the period
required_return : float, optional
Minimum acceptance return of the investor. Threshold over which to
consider positive vs negative returns. It will be converted to a
value appropriate for the period of the returns. E.g. An annual minimum
acceptable return of 100 will translate to a minimum acceptable
return of 0.018.
annualization : int, optional
Factor used to convert the required_return into a daily
value. Enter 1 if no time period conversion is necessary.
Returns
-------
omega_ratio : float
Note
-----
See https://en.wikipedia.org/wiki/Omega_ratio for more details. | [
"Determines",
"the",
"Omega",
"ratio",
"of",
"a",
"strategy",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L590-L640 | train | 219,490 |
quantopian/empyrical | empyrical/stats.py | sharpe_ratio | def sharpe_ratio(returns,
risk_free=0,
period=DAILY,
annualization=None,
out=None):
"""
Determines the Sharpe ratio of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
risk_free : int, float
Constant risk-free return throughout the period.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
sharpe_ratio : float
nan if insufficient length of returns or if if adjusted returns are 0.
Note
-----
See https://en.wikipedia.org/wiki/Sharpe_ratio for more details.
"""
allocated_output = out is None
if allocated_output:
out = np.empty(returns.shape[1:])
return_1d = returns.ndim == 1
if len(returns) < 2:
out[()] = np.nan
if return_1d:
out = out.item()
return out
returns_risk_adj = np.asanyarray(_adjust_returns(returns, risk_free))
ann_factor = annualization_factor(period, annualization)
np.multiply(
np.divide(
nanmean(returns_risk_adj, axis=0),
nanstd(returns_risk_adj, ddof=1, axis=0),
out=out,
),
np.sqrt(ann_factor),
out=out,
)
if return_1d:
out = out.item()
return out | python | def sharpe_ratio(returns,
risk_free=0,
period=DAILY,
annualization=None,
out=None):
"""
Determines the Sharpe ratio of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
risk_free : int, float
Constant risk-free return throughout the period.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
sharpe_ratio : float
nan if insufficient length of returns or if if adjusted returns are 0.
Note
-----
See https://en.wikipedia.org/wiki/Sharpe_ratio for more details.
"""
allocated_output = out is None
if allocated_output:
out = np.empty(returns.shape[1:])
return_1d = returns.ndim == 1
if len(returns) < 2:
out[()] = np.nan
if return_1d:
out = out.item()
return out
returns_risk_adj = np.asanyarray(_adjust_returns(returns, risk_free))
ann_factor = annualization_factor(period, annualization)
np.multiply(
np.divide(
nanmean(returns_risk_adj, axis=0),
nanstd(returns_risk_adj, ddof=1, axis=0),
out=out,
),
np.sqrt(ann_factor),
out=out,
)
if return_1d:
out = out.item()
return out | [
"def",
"sharpe_ratio",
"(",
"returns",
",",
"risk_free",
"=",
"0",
",",
"period",
"=",
"DAILY",
",",
"annualization",
"=",
"None",
",",
"out",
"=",
"None",
")",
":",
"allocated_output",
"=",
"out",
"is",
"None",
"if",
"allocated_output",
":",
"out",
"=",... | Determines the Sharpe ratio of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
risk_free : int, float
Constant risk-free return throughout the period.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
sharpe_ratio : float
nan if insufficient length of returns or if if adjusted returns are 0.
Note
-----
See https://en.wikipedia.org/wiki/Sharpe_ratio for more details. | [
"Determines",
"the",
"Sharpe",
"ratio",
"of",
"a",
"strategy",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L643-L712 | train | 219,491 |
quantopian/empyrical | empyrical/stats.py | sortino_ratio | def sortino_ratio(returns,
required_return=0,
period=DAILY,
annualization=None,
out=None,
_downside_risk=None):
"""
Determines the Sortino ratio of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray or pd.DataFrame
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
required_return: float / series
minimum acceptable return
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
_downside_risk : float, optional
The downside risk of the given inputs, if known. Will be calculated if
not provided.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
sortino_ratio : float or pd.Series
depends on input type
series ==> float
DataFrame ==> pd.Series
Note
-----
See `<https://www.sunrisecapital.com/wp-content/uploads/2014/06/Futures_
Mag_Sortino_0213.pdf>`__ for more details.
"""
allocated_output = out is None
if allocated_output:
out = np.empty(returns.shape[1:])
return_1d = returns.ndim == 1
if len(returns) < 2:
out[()] = np.nan
if return_1d:
out = out.item()
return out
adj_returns = np.asanyarray(_adjust_returns(returns, required_return))
ann_factor = annualization_factor(period, annualization)
average_annual_return = nanmean(adj_returns, axis=0) * ann_factor
annualized_downside_risk = (
_downside_risk
if _downside_risk is not None else
downside_risk(returns, required_return, period, annualization)
)
np.divide(average_annual_return, annualized_downside_risk, out=out)
if return_1d:
out = out.item()
elif isinstance(returns, pd.DataFrame):
out = pd.Series(out)
return out | python | def sortino_ratio(returns,
required_return=0,
period=DAILY,
annualization=None,
out=None,
_downside_risk=None):
"""
Determines the Sortino ratio of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray or pd.DataFrame
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
required_return: float / series
minimum acceptable return
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
_downside_risk : float, optional
The downside risk of the given inputs, if known. Will be calculated if
not provided.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
sortino_ratio : float or pd.Series
depends on input type
series ==> float
DataFrame ==> pd.Series
Note
-----
See `<https://www.sunrisecapital.com/wp-content/uploads/2014/06/Futures_
Mag_Sortino_0213.pdf>`__ for more details.
"""
allocated_output = out is None
if allocated_output:
out = np.empty(returns.shape[1:])
return_1d = returns.ndim == 1
if len(returns) < 2:
out[()] = np.nan
if return_1d:
out = out.item()
return out
adj_returns = np.asanyarray(_adjust_returns(returns, required_return))
ann_factor = annualization_factor(period, annualization)
average_annual_return = nanmean(adj_returns, axis=0) * ann_factor
annualized_downside_risk = (
_downside_risk
if _downside_risk is not None else
downside_risk(returns, required_return, period, annualization)
)
np.divide(average_annual_return, annualized_downside_risk, out=out)
if return_1d:
out = out.item()
elif isinstance(returns, pd.DataFrame):
out = pd.Series(out)
return out | [
"def",
"sortino_ratio",
"(",
"returns",
",",
"required_return",
"=",
"0",
",",
"period",
"=",
"DAILY",
",",
"annualization",
"=",
"None",
",",
"out",
"=",
"None",
",",
"_downside_risk",
"=",
"None",
")",
":",
"allocated_output",
"=",
"out",
"is",
"None",
... | Determines the Sortino ratio of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray or pd.DataFrame
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
required_return: float / series
minimum acceptable return
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
_downside_risk : float, optional
The downside risk of the given inputs, if known. Will be calculated if
not provided.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
sortino_ratio : float or pd.Series
depends on input type
series ==> float
DataFrame ==> pd.Series
Note
-----
See `<https://www.sunrisecapital.com/wp-content/uploads/2014/06/Futures_
Mag_Sortino_0213.pdf>`__ for more details. | [
"Determines",
"the",
"Sortino",
"ratio",
"of",
"a",
"strategy",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L718-L796 | train | 219,492 |
quantopian/empyrical | empyrical/stats.py | downside_risk | def downside_risk(returns,
required_return=0,
period=DAILY,
annualization=None,
out=None):
"""
Determines the downside deviation below a threshold
Parameters
----------
returns : pd.Series or np.ndarray or pd.DataFrame
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
required_return: float / series
minimum acceptable return
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
downside_deviation : float or pd.Series
depends on input type
series ==> float
DataFrame ==> pd.Series
Note
-----
See `<https://www.sunrisecapital.com/wp-content/uploads/2014/06/Futures_
Mag_Sortino_0213.pdf>`__ for more details, specifically why using the
standard deviation of the negative returns is not correct.
"""
allocated_output = out is None
if allocated_output:
out = np.empty(returns.shape[1:])
returns_1d = returns.ndim == 1
if len(returns) < 1:
out[()] = np.nan
if returns_1d:
out = out.item()
return out
ann_factor = annualization_factor(period, annualization)
downside_diff = np.clip(
_adjust_returns(
np.asanyarray(returns),
np.asanyarray(required_return),
),
np.NINF,
0,
)
np.square(downside_diff, out=downside_diff)
nanmean(downside_diff, axis=0, out=out)
np.sqrt(out, out=out)
np.multiply(out, np.sqrt(ann_factor), out=out)
if returns_1d:
out = out.item()
elif isinstance(returns, pd.DataFrame):
out = pd.Series(out, index=returns.columns)
return out | python | def downside_risk(returns,
required_return=0,
period=DAILY,
annualization=None,
out=None):
"""
Determines the downside deviation below a threshold
Parameters
----------
returns : pd.Series or np.ndarray or pd.DataFrame
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
required_return: float / series
minimum acceptable return
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
downside_deviation : float or pd.Series
depends on input type
series ==> float
DataFrame ==> pd.Series
Note
-----
See `<https://www.sunrisecapital.com/wp-content/uploads/2014/06/Futures_
Mag_Sortino_0213.pdf>`__ for more details, specifically why using the
standard deviation of the negative returns is not correct.
"""
allocated_output = out is None
if allocated_output:
out = np.empty(returns.shape[1:])
returns_1d = returns.ndim == 1
if len(returns) < 1:
out[()] = np.nan
if returns_1d:
out = out.item()
return out
ann_factor = annualization_factor(period, annualization)
downside_diff = np.clip(
_adjust_returns(
np.asanyarray(returns),
np.asanyarray(required_return),
),
np.NINF,
0,
)
np.square(downside_diff, out=downside_diff)
nanmean(downside_diff, axis=0, out=out)
np.sqrt(out, out=out)
np.multiply(out, np.sqrt(ann_factor), out=out)
if returns_1d:
out = out.item()
elif isinstance(returns, pd.DataFrame):
out = pd.Series(out, index=returns.columns)
return out | [
"def",
"downside_risk",
"(",
"returns",
",",
"required_return",
"=",
"0",
",",
"period",
"=",
"DAILY",
",",
"annualization",
"=",
"None",
",",
"out",
"=",
"None",
")",
":",
"allocated_output",
"=",
"out",
"is",
"None",
"if",
"allocated_output",
":",
"out",... | Determines the downside deviation below a threshold
Parameters
----------
returns : pd.Series or np.ndarray or pd.DataFrame
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
required_return: float / series
minimum acceptable return
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
downside_deviation : float or pd.Series
depends on input type
series ==> float
DataFrame ==> pd.Series
Note
-----
See `<https://www.sunrisecapital.com/wp-content/uploads/2014/06/Futures_
Mag_Sortino_0213.pdf>`__ for more details, specifically why using the
standard deviation of the negative returns is not correct. | [
"Determines",
"the",
"downside",
"deviation",
"below",
"a",
"threshold"
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L802-L879 | train | 219,493 |
quantopian/empyrical | empyrical/stats.py | excess_sharpe | def excess_sharpe(returns, factor_returns, out=None):
"""
Determines the Excess Sharpe of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns: float / series
Benchmark return to compare returns against.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
excess_sharpe : float
Note
-----
The excess Sharpe is a simplified Information Ratio that uses
tracking error rather than "active risk" as the denominator.
"""
allocated_output = out is None
if allocated_output:
out = np.empty(returns.shape[1:])
returns_1d = returns.ndim == 1
if len(returns) < 2:
out[()] = np.nan
if returns_1d:
out = out.item()
return out
active_return = _adjust_returns(returns, factor_returns)
tracking_error = np.nan_to_num(nanstd(active_return, ddof=1, axis=0))
out = np.divide(
nanmean(active_return, axis=0, out=out),
tracking_error,
out=out,
)
if returns_1d:
out = out.item()
return out | python | def excess_sharpe(returns, factor_returns, out=None):
"""
Determines the Excess Sharpe of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns: float / series
Benchmark return to compare returns against.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
excess_sharpe : float
Note
-----
The excess Sharpe is a simplified Information Ratio that uses
tracking error rather than "active risk" as the denominator.
"""
allocated_output = out is None
if allocated_output:
out = np.empty(returns.shape[1:])
returns_1d = returns.ndim == 1
if len(returns) < 2:
out[()] = np.nan
if returns_1d:
out = out.item()
return out
active_return = _adjust_returns(returns, factor_returns)
tracking_error = np.nan_to_num(nanstd(active_return, ddof=1, axis=0))
out = np.divide(
nanmean(active_return, axis=0, out=out),
tracking_error,
out=out,
)
if returns_1d:
out = out.item()
return out | [
"def",
"excess_sharpe",
"(",
"returns",
",",
"factor_returns",
",",
"out",
"=",
"None",
")",
":",
"allocated_output",
"=",
"out",
"is",
"None",
"if",
"allocated_output",
":",
"out",
"=",
"np",
".",
"empty",
"(",
"returns",
".",
"shape",
"[",
"1",
":",
... | Determines the Excess Sharpe of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns: float / series
Benchmark return to compare returns against.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
excess_sharpe : float
Note
-----
The excess Sharpe is a simplified Information Ratio that uses
tracking error rather than "active risk" as the denominator. | [
"Determines",
"the",
"Excess",
"Sharpe",
"of",
"a",
"strategy",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L885-L931 | train | 219,494 |
quantopian/empyrical | empyrical/stats.py | _to_pandas | def _to_pandas(ob):
"""Convert an array-like to a pandas object.
Parameters
----------
ob : array-like
The object to convert.
Returns
-------
pandas_structure : pd.Series or pd.DataFrame
The correct structure based on the dimensionality of the data.
"""
if isinstance(ob, (pd.Series, pd.DataFrame)):
return ob
if ob.ndim == 1:
return pd.Series(ob)
elif ob.ndim == 2:
return pd.DataFrame(ob)
else:
raise ValueError(
'cannot convert array of dim > 2 to a pandas structure',
) | python | def _to_pandas(ob):
"""Convert an array-like to a pandas object.
Parameters
----------
ob : array-like
The object to convert.
Returns
-------
pandas_structure : pd.Series or pd.DataFrame
The correct structure based on the dimensionality of the data.
"""
if isinstance(ob, (pd.Series, pd.DataFrame)):
return ob
if ob.ndim == 1:
return pd.Series(ob)
elif ob.ndim == 2:
return pd.DataFrame(ob)
else:
raise ValueError(
'cannot convert array of dim > 2 to a pandas structure',
) | [
"def",
"_to_pandas",
"(",
"ob",
")",
":",
"if",
"isinstance",
"(",
"ob",
",",
"(",
"pd",
".",
"Series",
",",
"pd",
".",
"DataFrame",
")",
")",
":",
"return",
"ob",
"if",
"ob",
".",
"ndim",
"==",
"1",
":",
"return",
"pd",
".",
"Series",
"(",
"ob... | Convert an array-like to a pandas object.
Parameters
----------
ob : array-like
The object to convert.
Returns
-------
pandas_structure : pd.Series or pd.DataFrame
The correct structure based on the dimensionality of the data. | [
"Convert",
"an",
"array",
"-",
"like",
"to",
"a",
"pandas",
"object",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L937-L960 | train | 219,495 |
quantopian/empyrical | empyrical/stats.py | _aligned_series | def _aligned_series(*many_series):
"""
Return a new list of series containing the data in the input series, but
with their indices aligned. NaNs will be filled in for missing values.
Parameters
----------
*many_series
The series to align.
Returns
-------
aligned_series : iterable[array-like]
A new list of series containing the data in the input series, but
with their indices aligned. NaNs will be filled in for missing values.
"""
head = many_series[0]
tail = many_series[1:]
n = len(head)
if (isinstance(head, np.ndarray) and
all(len(s) == n and isinstance(s, np.ndarray) for s in tail)):
# optimization: ndarrays of the same length are already aligned
return many_series
# dataframe has no ``itervalues``
return (
v
for _, v in iteritems(pd.concat(map(_to_pandas, many_series), axis=1))
) | python | def _aligned_series(*many_series):
"""
Return a new list of series containing the data in the input series, but
with their indices aligned. NaNs will be filled in for missing values.
Parameters
----------
*many_series
The series to align.
Returns
-------
aligned_series : iterable[array-like]
A new list of series containing the data in the input series, but
with their indices aligned. NaNs will be filled in for missing values.
"""
head = many_series[0]
tail = many_series[1:]
n = len(head)
if (isinstance(head, np.ndarray) and
all(len(s) == n and isinstance(s, np.ndarray) for s in tail)):
# optimization: ndarrays of the same length are already aligned
return many_series
# dataframe has no ``itervalues``
return (
v
for _, v in iteritems(pd.concat(map(_to_pandas, many_series), axis=1))
) | [
"def",
"_aligned_series",
"(",
"*",
"many_series",
")",
":",
"head",
"=",
"many_series",
"[",
"0",
"]",
"tail",
"=",
"many_series",
"[",
"1",
":",
"]",
"n",
"=",
"len",
"(",
"head",
")",
"if",
"(",
"isinstance",
"(",
"head",
",",
"np",
".",
"ndarra... | Return a new list of series containing the data in the input series, but
with their indices aligned. NaNs will be filled in for missing values.
Parameters
----------
*many_series
The series to align.
Returns
-------
aligned_series : iterable[array-like]
A new list of series containing the data in the input series, but
with their indices aligned. NaNs will be filled in for missing values. | [
"Return",
"a",
"new",
"list",
"of",
"series",
"containing",
"the",
"data",
"in",
"the",
"input",
"series",
"but",
"with",
"their",
"indices",
"aligned",
".",
"NaNs",
"will",
"be",
"filled",
"in",
"for",
"missing",
"values",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L963-L992 | train | 219,496 |
quantopian/empyrical | empyrical/stats.py | roll_alpha_beta | def roll_alpha_beta(returns, factor_returns, window=10, **kwargs):
"""
Computes alpha and beta over a rolling window.
Parameters
----------
lhs : array-like
The first array to pass to the rolling alpha-beta.
rhs : array-like
The second array to pass to the rolling alpha-beta.
window : int
Size of the rolling window in terms of the periodicity of the data.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
**kwargs
Forwarded to :func:`~empyrical.alpha_beta`.
"""
returns, factor_returns = _aligned_series(returns, factor_returns)
return roll_alpha_beta_aligned(
returns,
factor_returns,
window=window,
**kwargs
) | python | def roll_alpha_beta(returns, factor_returns, window=10, **kwargs):
"""
Computes alpha and beta over a rolling window.
Parameters
----------
lhs : array-like
The first array to pass to the rolling alpha-beta.
rhs : array-like
The second array to pass to the rolling alpha-beta.
window : int
Size of the rolling window in terms of the periodicity of the data.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
**kwargs
Forwarded to :func:`~empyrical.alpha_beta`.
"""
returns, factor_returns = _aligned_series(returns, factor_returns)
return roll_alpha_beta_aligned(
returns,
factor_returns,
window=window,
**kwargs
) | [
"def",
"roll_alpha_beta",
"(",
"returns",
",",
"factor_returns",
",",
"window",
"=",
"10",
",",
"*",
"*",
"kwargs",
")",
":",
"returns",
",",
"factor_returns",
"=",
"_aligned_series",
"(",
"returns",
",",
"factor_returns",
")",
"return",
"roll_alpha_beta_aligned... | Computes alpha and beta over a rolling window.
Parameters
----------
lhs : array-like
The first array to pass to the rolling alpha-beta.
rhs : array-like
The second array to pass to the rolling alpha-beta.
window : int
Size of the rolling window in terms of the periodicity of the data.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
**kwargs
Forwarded to :func:`~empyrical.alpha_beta`. | [
"Computes",
"alpha",
"and",
"beta",
"over",
"a",
"rolling",
"window",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L1049-L1074 | train | 219,497 |
quantopian/empyrical | empyrical/stats.py | stability_of_timeseries | def stability_of_timeseries(returns):
"""Determines R-squared of a linear fit to the cumulative
log returns. Computes an ordinary least squares linear fit,
and returns R-squared.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
Returns
-------
float
R-squared.
"""
if len(returns) < 2:
return np.nan
returns = np.asanyarray(returns)
returns = returns[~np.isnan(returns)]
cum_log_returns = np.log1p(returns).cumsum()
rhat = stats.linregress(np.arange(len(cum_log_returns)),
cum_log_returns)[2]
return rhat ** 2 | python | def stability_of_timeseries(returns):
"""Determines R-squared of a linear fit to the cumulative
log returns. Computes an ordinary least squares linear fit,
and returns R-squared.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
Returns
-------
float
R-squared.
"""
if len(returns) < 2:
return np.nan
returns = np.asanyarray(returns)
returns = returns[~np.isnan(returns)]
cum_log_returns = np.log1p(returns).cumsum()
rhat = stats.linregress(np.arange(len(cum_log_returns)),
cum_log_returns)[2]
return rhat ** 2 | [
"def",
"stability_of_timeseries",
"(",
"returns",
")",
":",
"if",
"len",
"(",
"returns",
")",
"<",
"2",
":",
"return",
"np",
".",
"nan",
"returns",
"=",
"np",
".",
"asanyarray",
"(",
"returns",
")",
"returns",
"=",
"returns",
"[",
"~",
"np",
".",
"is... | Determines R-squared of a linear fit to the cumulative
log returns. Computes an ordinary least squares linear fit,
and returns R-squared.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
Returns
-------
float
R-squared. | [
"Determines",
"R",
"-",
"squared",
"of",
"a",
"linear",
"fit",
"to",
"the",
"cumulative",
"log",
"returns",
".",
"Computes",
"an",
"ordinary",
"least",
"squares",
"linear",
"fit",
"and",
"returns",
"R",
"-",
"squared",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L1454-L1481 | train | 219,498 |
quantopian/empyrical | empyrical/stats.py | capture | def capture(returns, factor_returns, period=DAILY):
"""
Compute capture ratio.
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns : pd.Series or np.ndarray
Noncumulative returns of the factor to which beta is
computed. Usually a benchmark such as the market.
- This is in the same style as returns.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
Returns
-------
capture_ratio : float
Note
----
See http://www.investopedia.com/terms/u/up-market-capture-ratio.asp for
details.
"""
return (annual_return(returns, period=period) /
annual_return(factor_returns, period=period)) | python | def capture(returns, factor_returns, period=DAILY):
"""
Compute capture ratio.
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns : pd.Series or np.ndarray
Noncumulative returns of the factor to which beta is
computed. Usually a benchmark such as the market.
- This is in the same style as returns.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
Returns
-------
capture_ratio : float
Note
----
See http://www.investopedia.com/terms/u/up-market-capture-ratio.asp for
details.
"""
return (annual_return(returns, period=period) /
annual_return(factor_returns, period=period)) | [
"def",
"capture",
"(",
"returns",
",",
"factor_returns",
",",
"period",
"=",
"DAILY",
")",
":",
"return",
"(",
"annual_return",
"(",
"returns",
",",
"period",
"=",
"period",
")",
"/",
"annual_return",
"(",
"factor_returns",
",",
"period",
"=",
"period",
")... | Compute capture ratio.
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns : pd.Series or np.ndarray
Noncumulative returns of the factor to which beta is
computed. Usually a benchmark such as the market.
- This is in the same style as returns.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
Returns
-------
capture_ratio : float
Note
----
See http://www.investopedia.com/terms/u/up-market-capture-ratio.asp for
details. | [
"Compute",
"capture",
"ratio",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L1514-L1546 | train | 219,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.