INSTRUCTION
stringlengths 1
8.43k
| RESPONSE
stringlengths 75
104k
|
|---|---|
Add additional requirements from setup. cfg to file metadata_path
|
def add_requirements(self, metadata_path):
"""Add additional requirements from setup.cfg to file metadata_path"""
additional = list(self.setupcfg_requirements())
if not additional: return
pkg_info = read_pkg_info(metadata_path)
if 'Provides-Extra' in pkg_info or 'Requires-Dist' in pkg_info:
warnings.warn('setup.cfg requirements overwrite values from setup.py')
del pkg_info['Provides-Extra']
del pkg_info['Requires-Dist']
for k, v in additional:
pkg_info[k] = v
write_pkg_info(metadata_path, pkg_info)
|
Convert an. egg - info directory into a. dist - info directory
|
def egg2dist(self, egginfo_path, distinfo_path):
"""Convert an .egg-info directory into a .dist-info directory"""
def adios(p):
"""Appropriately delete directory, file or link."""
if os.path.exists(p) and not os.path.islink(p) and os.path.isdir(p):
shutil.rmtree(p)
elif os.path.exists(p):
os.unlink(p)
adios(distinfo_path)
if not os.path.exists(egginfo_path):
# There is no egg-info. This is probably because the egg-info
# file/directory is not named matching the distribution name used
# to name the archive file. Check for this case and report
# accordingly.
import glob
pat = os.path.join(os.path.dirname(egginfo_path), '*.egg-info')
possible = glob.glob(pat)
err = "Egg metadata expected at %s but not found" % (egginfo_path,)
if possible:
alt = os.path.basename(possible[0])
err += " (%s found - possible misnamed archive file?)" % (alt,)
raise ValueError(err)
if os.path.isfile(egginfo_path):
# .egg-info is a single file
pkginfo_path = egginfo_path
pkg_info = self._pkginfo_to_metadata(egginfo_path, egginfo_path)
os.mkdir(distinfo_path)
else:
# .egg-info is a directory
pkginfo_path = os.path.join(egginfo_path, 'PKG-INFO')
pkg_info = self._pkginfo_to_metadata(egginfo_path, pkginfo_path)
# ignore common egg metadata that is useless to wheel
shutil.copytree(egginfo_path, distinfo_path,
ignore=lambda x, y: set(('PKG-INFO',
'requires.txt',
'SOURCES.txt',
'not-zip-safe',)))
# delete dependency_links if it is only whitespace
dependency_links_path = os.path.join(distinfo_path, 'dependency_links.txt')
with open(dependency_links_path, 'r') as dependency_links_file:
dependency_links = dependency_links_file.read().strip()
if not dependency_links:
adios(dependency_links_path)
write_pkg_info(os.path.join(distinfo_path, 'METADATA'), pkg_info)
# XXX deprecated. Still useful for current distribute/setuptools.
metadata_path = os.path.join(distinfo_path, 'METADATA')
self.add_requirements(metadata_path)
# XXX intentionally a different path than the PEP.
metadata_json_path = os.path.join(distinfo_path, 'metadata.json')
pymeta = pkginfo_to_dict(metadata_path,
distribution=self.distribution)
if 'description' in pymeta:
description_filename = 'DESCRIPTION.rst'
description_text = pymeta.pop('description')
description_path = os.path.join(distinfo_path,
description_filename)
with open(description_path, "wb") as description_file:
description_file.write(description_text.encode('utf-8'))
pymeta['extensions']['python.details']['document_names']['description'] = description_filename
# XXX heuristically copy any LICENSE/LICENSE.txt?
license = self.license_file()
if license:
license_filename = 'LICENSE.txt'
shutil.copy(license, os.path.join(self.distinfo_dir, license_filename))
pymeta['extensions']['python.details']['document_names']['license'] = license_filename
with open(metadata_json_path, "w") as metadata_json:
json.dump(pymeta, metadata_json, sort_keys=True)
adios(egginfo_path)
|
GetConversations.
|
def get_conversations(
self, continuation_token=None, custom_headers=None, raw=False, **operation_config):
"""GetConversations.
List the Conversations in which this bot has participated.
GET from this method with a skip token
The return value is a ConversationsResult, which contains an array of
ConversationMembers and a skip token. If the skip token is not empty,
then
there are further values to be returned. Call this method again with
the returned token to get more values.
Each ConversationMembers object contains the ID of the conversation and
an array of ChannelAccounts that describe the members of the
conversation.
:param continuation_token: skip or continuation token
:type continuation_token: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ConversationsResult or ClientRawResponse if raw=true
:rtype: ~botframework.connector.models.ConversationsResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`ErrorResponseException<botframework.connector.models.ErrorResponseException>`
"""
# Construct URL
url = self.get_conversations.metadata['url']
# Construct parameters
query_parameters = {}
if continuation_token is not None:
query_parameters['continuationToken'] = self._serialize.query("continuation_token", continuation_token, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise models.ErrorResponseException(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ConversationsResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
|
CreateConversation.
|
def create_conversation(
self, parameters, custom_headers=None, raw=False, **operation_config):
"""CreateConversation.
Create a new Conversation.
POST to this method with a
* Bot being the bot creating the conversation
* IsGroup set to true if this is not a direct message (default is
false)
* Array containing the members to include in the conversation
The return value is a ResourceResponse which contains a conversation id
which is suitable for use
in the message payload and REST API uris.
Most channels only support the semantics of bots initiating a direct
message conversation. An example of how to do that would be:
```
var resource = await connector.conversations.CreateConversation(new
ConversationParameters(){ Bot = bot, members = new ChannelAccount[] {
new ChannelAccount("user1") } );
await connect.Conversations.SendToConversationAsync(resource.Id, new
Activity() ... ) ;
```.
:param parameters: Parameters to create the conversation from
:type parameters:
~botframework.connector.models.ConversationParameters
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ConversationResourceResponse or ClientRawResponse if raw=true
:rtype: ~botframework.connector.models.ConversationResourceResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`ErrorResponseException<botframework.connector.models.ErrorResponseException>`
"""
# Construct URL
url = self.create_conversation.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
body_content = self._serialize.body(parameters, 'ConversationParameters')
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 201, 202]:
raise models.ErrorResponseException(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ConversationResourceResponse', response)
if response.status_code == 201:
deserialized = self._deserialize('ConversationResourceResponse', response)
if response.status_code == 202:
deserialized = self._deserialize('ConversationResourceResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
|
GetConversationPagedMembers.
|
def get_conversation_paged_members(
self, conversation_id, page_size=None, continuation_token=None, custom_headers=None, raw=False, **operation_config):
"""GetConversationPagedMembers.
Enumerate the members of a conversation one page at a time.
This REST API takes a ConversationId. Optionally a pageSize and/or
continuationToken can be provided. It returns a PagedMembersResult,
which contains an array
of ChannelAccounts representing the members of the conversation and a
continuation token that can be used to get more values.
One page of ChannelAccounts records are returned with each call. The
number of records in a page may vary between channels and calls. The
pageSize parameter can be used as
a suggestion. If there are no additional results the response will not
contain a continuation token. If there are no members in the
conversation the Members will be empty or not present in the response.
A response to a request that has a continuation token from a prior
request may rarely return members from a previous request.
:param conversation_id: Conversation ID
:type conversation_id: str
:param page_size: Suggested page size
:type page_size: int
:param continuation_token: Continuation Token
:type continuation_token: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: PagedMembersResult or ClientRawResponse if raw=true
:rtype: ~botframework.connector.models.PagedMembersResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_conversation_paged_members.metadata['url']
path_format_arguments = {
'conversationId': self._serialize.url("conversation_id", conversation_id, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if continuation_token is not None:
query_parameters['continuationToken'] = self._serialize.query("continuation_token", continuation_token, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('PagedMembersResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
|
Send information about the page viewed in the application ( a web page for instance ).: param name: the name of the page that was viewed.: param url: the URL of the page that was viewed.: param duration: the duration of the page view in milliseconds. ( defaults to: 0 ): param properties: the set of custom properties the client wants attached to this data item. ( defaults to: None ): param measurements: the set of custom measurements the client wants to attach to this data item. ( defaults to: None )
|
def track_pageview(self, name: str, url, duration: int = 0, properties : Dict[str, object]=None,
measurements: Dict[str, object]=None) -> None:
"""
Send information about the page viewed in the application (a web page for instance).
:param name: the name of the page that was viewed.
:param url: the URL of the page that was viewed.
:param duration: the duration of the page view in milliseconds. (defaults to: 0)
:param properties: the set of custom properties the client wants attached to this data item. (defaults to: None)
:param measurements: the set of custom measurements the client wants to attach to this data item. (defaults to: None)
"""
raise NotImplementedError('BotTelemetryClient.track_request(): is not implemented.')
|
Send information about a single exception that occurred in the application.: param type: the type of the exception that was thrown.: param value: the exception that the client wants to send.: param tb: the traceback information as returned by: func: sys. exc_info.: param properties: the set of custom properties the client wants attached to this data item. ( defaults to: None ): param measurements: the set of custom measurements the client wants to attach to this data item. ( defaults to: None )
|
def track_exception(self, type: type = None, value : Exception =None, tb : traceback =None,
properties: Dict[str, object]=None, measurements: Dict[str, object]=None) -> None:
"""
Send information about a single exception that occurred in the application.
:param type: the type of the exception that was thrown.
:param value: the exception that the client wants to send.
:param tb: the traceback information as returned by :func:`sys.exc_info`.
:param properties: the set of custom properties the client wants attached to this data item. (defaults to: None)
:param measurements: the set of custom measurements the client wants to attach to this data item. (defaults to: None)
"""
raise NotImplementedError('BotTelemetryClient.track_request(): is not implemented.')
|
Send information about a single metric data point that was captured for the application.: param name: The name of the metric that was captured.: param value: The value of the metric that was captured.: param type: The type of the metric. ( defaults to: TelemetryDataPointType. aggregation ): param count: the number of metrics that were aggregated into this data point. ( defaults to: None ): param min: the minimum of all metrics collected that were aggregated into this data point. ( defaults to: None ): param max: the maximum of all metrics collected that were aggregated into this data point. ( defaults to: None ): param std_dev: the standard deviation of all metrics collected that were aggregated into this data point. ( defaults to: None ): param properties: the set of custom properties the client wants attached to this data item. ( defaults to: None )
|
def track_metric(self, name: str, value: float, type: TelemetryDataPointType =None,
count: int =None, min: float=None, max: float=None, std_dev: float=None,
properties: Dict[str, object]=None) -> NotImplemented:
"""
Send information about a single metric data point that was captured for the application.
:param name: The name of the metric that was captured.
:param value: The value of the metric that was captured.
:param type: The type of the metric. (defaults to: TelemetryDataPointType.aggregation`)
:param count: the number of metrics that were aggregated into this data point. (defaults to: None)
:param min: the minimum of all metrics collected that were aggregated into this data point. (defaults to: None)
:param max: the maximum of all metrics collected that were aggregated into this data point. (defaults to: None)
:param std_dev: the standard deviation of all metrics collected that were aggregated into this data point. (defaults to: None)
:param properties: the set of custom properties the client wants attached to this data item. (defaults to: None)
"""
raise NotImplementedError('BotTelemetryClient.track_metric(): is not implemented.')
|
Sends a single request that was captured for the application.: param name: The name for this request. All requests with the same name will be grouped together.: param url: The actual URL for this request ( to show in individual request instances ).: param success: True if the request ended in success False otherwise.: param start_time: the start time of the request. The value should look the same as the one returned by: func: datetime. isoformat () ( defaults to: None ): param duration: the number of milliseconds that this request lasted. ( defaults to: None ): param response_code: the response code that this request returned. ( defaults to: None ): param http_method: the HTTP method that triggered this request. ( defaults to: None ): param properties: the set of custom properties the client wants attached to this data item. ( defaults to: None ): param measurements: the set of custom measurements the client wants to attach to this data item. ( defaults to: None ): param request_id: the id for this request. If None a new uuid will be generated. ( defaults to: None )
|
def track_request(self, name: str, url: str, success: bool, start_time: str=None,
duration: int=None, response_code: str =None, http_method: str=None,
properties: Dict[str, object]=None, measurements: Dict[str, object]=None,
request_id: str=None):
"""
Sends a single request that was captured for the application.
:param name: The name for this request. All requests with the same name will be grouped together.
:param url: The actual URL for this request (to show in individual request instances).
:param success: True if the request ended in success, False otherwise.
:param start_time: the start time of the request. The value should look the same as the one returned by :func:`datetime.isoformat()` (defaults to: None)
:param duration: the number of milliseconds that this request lasted. (defaults to: None)
:param response_code: the response code that this request returned. (defaults to: None)
:param http_method: the HTTP method that triggered this request. (defaults to: None)
:param properties: the set of custom properties the client wants attached to this data item. (defaults to: None)
:param measurements: the set of custom measurements the client wants to attach to this data item. (defaults to: None)
:param request_id: the id for this request. If None, a new uuid will be generated. (defaults to: None)
"""
raise NotImplementedError('BotTelemetryClient.track_request(): is not implemented.')
|
Sends a single dependency telemetry that was captured for the application.: param name: the name of the command initiated with this dependency call. Low cardinality value. Examples are stored procedure name and URL path template.: param data: the command initiated by this dependency call. Examples are SQL statement and HTTP URL with all query parameters.: param type: the dependency type name. Low cardinality value for logical grouping of dependencies and interpretation of other fields like commandName and resultCode. Examples are SQL Azure table and HTTP. ( default to: None ): param target: the target site of a dependency call. Examples are server name host address. ( default to: None ): param duration: the number of milliseconds that this dependency call lasted. ( defaults to: None ): param success: true if the dependency call ended in success false otherwise. ( defaults to: None ): param result_code: the result code of a dependency call. Examples are SQL error code and HTTP status code. ( defaults to: None ): param properties: the set of custom properties the client wants attached to this data item. ( defaults to: None ): param measurements: the set of custom measurements the client wants to attach to this data item. ( defaults to: None ): param id: the id for this dependency call. If None a new uuid will be generated. ( defaults to: None )
|
def track_dependency(self, name:str, data:str, type:str=None, target:str=None, duration:int=None,
success:bool=None, result_code:str=None, properties:Dict[str, object]=None,
measurements:Dict[str, object]=None, dependency_id:str=None):
"""
Sends a single dependency telemetry that was captured for the application.
:param name: the name of the command initiated with this dependency call. Low cardinality value. Examples are stored procedure name and URL path template.
:param data: the command initiated by this dependency call. Examples are SQL statement and HTTP URL with all query parameters.
:param type: the dependency type name. Low cardinality value for logical grouping of dependencies and interpretation of other fields like commandName and resultCode. Examples are SQL, Azure table, and HTTP. (default to: None)
:param target: the target site of a dependency call. Examples are server name, host address. (default to: None)
:param duration: the number of milliseconds that this dependency call lasted. (defaults to: None)
:param success: true if the dependency call ended in success, false otherwise. (defaults to: None)
:param result_code: the result code of a dependency call. Examples are SQL error code and HTTP status code. (defaults to: None)
:param properties: the set of custom properties the client wants attached to this data item. (defaults to: None)
:param measurements: the set of custom measurements the client wants to attach to this data item. (defaults to: None)
:param id: the id for this dependency call. If None, a new uuid will be generated. (defaults to: None)
"""
raise NotImplementedError('BotTelemetryClient.track_dependency(): is not implemented.')
|
Returns a simple text message.
|
def text(text: str, speak: str = None, input_hint: Union[InputHints, str] = InputHints.accepting_input) -> Activity:
"""
Returns a simple text message.
:Example:
message = MessageFactory.text('Greetings from example message')
await context.send_activity(message)
:param text:
:param speak:
:param input_hint:
:return:
"""
message = Activity(type=ActivityTypes.message, text=text, input_hint=input_hint)
if speak:
message.speak = speak
return message
|
Returns a message that includes a set of suggested actions and optional text.
|
def suggested_actions(actions: List[CardAction], text: str = None, speak: str = None,
input_hint: Union[InputHints, str] = InputHints.accepting_input) -> Activity:
"""
Returns a message that includes a set of suggested actions and optional text.
:Example:
message = MessageFactory.suggested_actions([CardAction(title='a', type=ActionTypes.im_back, value='a'),
CardAction(title='b', type=ActionTypes.im_back, value='b'),
CardAction(title='c', type=ActionTypes.im_back, value='c')], 'Choose a color')
await context.send_activity(message)
:param actions:
:param text:
:param speak:
:param input_hint:
:return:
"""
actions = SuggestedActions(actions=actions)
message = Activity(type=ActivityTypes.message, input_hint=input_hint, suggested_actions=actions)
if text:
message.text = text
if speak:
message.speak = speak
return message
|
Returns a single message activity containing an attachment.
|
def attachment(attachment: Attachment, text: str = None, speak: str = None,
input_hint: Union[InputHints, str] = None):
"""
Returns a single message activity containing an attachment.
:Example:
message = MessageFactory.attachment(CardFactory.hero_card(HeroCard(title='White T-Shirt',
images=[CardImage(url='https://example.com/whiteShirt.jpg')],
buttons=[CardAction(title='buy')])))
await context.send_activity(message)
:param attachment:
:param text:
:param speak:
:param input_hint:
:return:
"""
return attachment_activity(AttachmentLayoutTypes.list, [attachment], text, speak, input_hint)
|
Returns a message that will display a set of attachments in list form.
|
def list(attachments: List[Attachment], text: str = None, speak: str = None,
input_hint: Union[InputHints, str] = None) -> Activity:
"""
Returns a message that will display a set of attachments in list form.
:Example:
message = MessageFactory.list([CardFactory.hero_card(HeroCard(title='title1',
images=[CardImage(url='imageUrl1')],
buttons=[CardAction(title='button1')])),
CardFactory.hero_card(HeroCard(title='title2',
images=[CardImage(url='imageUrl2')],
buttons=[CardAction(title='button2')])),
CardFactory.hero_card(HeroCard(title='title3',
images=[CardImage(url='imageUrl3')],
buttons=[CardAction(title='button3')]))])
await context.send_activity(message)
:param attachments:
:param text:
:param speak:
:param input_hint:
:return:
"""
return attachment_activity(AttachmentLayoutTypes.list, attachments, text, speak, input_hint)
|
Returns a message that will display a single image or video to a user.
|
def content_url(url: str, content_type: str, name: str = None, text: str = None, speak: str = None,
input_hint: Union[InputHints, str] = None):
"""
Returns a message that will display a single image or video to a user.
:Example:
message = MessageFactory.content_url('https://example.com/hawaii.jpg', 'image/jpeg',
'Hawaii Trip', 'A photo from our family vacation.')
await context.send_activity(message)
:param url:
:param content_type:
:param name:
:param text:
:param speak:
:param input_hint:
:return:
"""
attachment = Attachment(content_type=content_type, content_url=url)
if name:
attachment.name = name
return attachment_activity(AttachmentLayoutTypes.list, [attachment], text, speak, input_hint)
|
Validate the incoming Auth Header
|
async def authenticate_token_service_url(auth_header: str, credentials: CredentialProvider, service_url: str, channel_id: str) -> ClaimsIdentity:
""" Validate the incoming Auth Header
Validate the incoming Auth Header as a token sent from the Bot Framework Service.
A token issued by the Bot Framework emulator will FAIL this check.
:param auth_header: The raw HTTP header in the format: 'Bearer [longString]'
:type auth_header: str
:param credentials: The user defined set of valid credentials, such as the AppId.
:type credentials: CredentialProvider
:param service_url: Claim value that must match in the identity.
:type service_url: str
:return: A valid ClaimsIdentity.
:raises Exception:
"""
identity = await asyncio.ensure_future(
ChannelValidation.authenticate_token(auth_header, credentials, channel_id))
service_url_claim = identity.get_claim_value(ChannelValidation.SERVICE_URL_CLAIM)
if service_url_claim != service_url:
# Claim must match. Not Authorized.
raise Exception('Unauthorized. service_url claim do not match.')
return identity
|
Validate the incoming Auth Header
|
async def authenticate_token(auth_header: str, credentials: CredentialProvider, channel_id: str) -> ClaimsIdentity:
""" Validate the incoming Auth Header
Validate the incoming Auth Header as a token sent from the Bot Framework Service.
A token issued by the Bot Framework emulator will FAIL this check.
:param auth_header: The raw HTTP header in the format: 'Bearer [longString]'
:type auth_header: str
:param credentials: The user defined set of valid credentials, such as the AppId.
:type credentials: CredentialProvider
:return: A valid ClaimsIdentity.
:raises Exception:
"""
token_extractor = JwtTokenExtractor(
ChannelValidation.TO_BOT_FROM_CHANNEL_TOKEN_VALIDATION_PARAMETERS,
Constants.TO_BOT_FROM_CHANNEL_OPEN_ID_METADATA_URL,
Constants.ALLOWED_SIGNING_ALGORITHMS)
identity = await asyncio.ensure_future(
token_extractor.get_identity_from_auth_header(auth_header, channel_id))
if not identity:
# No valid identity. Not Authorized.
raise Exception('Unauthorized. No valid identity.')
if not identity.isAuthenticated:
# The token is in some way invalid. Not Authorized.
raise Exception('Unauthorized. Is not authenticated')
# Now check that the AppID in the claimset matches
# what we're looking for. Note that in a multi-tenant bot, this value
# comes from developer code that may be reaching out to a service, hence the
# Async validation.
# Look for the "aud" claim, but only if issued from the Bot Framework
if identity.get_claim_value(Constants.ISSUER_CLAIM) != Constants.TO_BOT_FROM_CHANNEL_TOKEN_ISSUER:
# The relevant Audience Claim MUST be present. Not Authorized.
raise Exception('Unauthorized. Audience Claim MUST be present.')
# The AppId from the claim in the token must match the AppId specified by the developer.
# Note that the Bot Framework uses the Audience claim ("aud") to pass the AppID.
aud_claim = identity.get_claim_value(Constants.AUDIENCE_CLAIM)
is_valid_app_id = await asyncio.ensure_future(credentials.is_valid_appid(aud_claim or ""))
if not is_valid_app_id:
# The AppId is not valid or not present. Not Authorized.
raise Exception('Unauthorized. Invalid AppId passed on token: ', aud_claim)
return identity
|
Creates a trace activity based on this activity.
|
def create_trace(
turn_activity: Activity,
name: str,
value: object = None,
value_type: str = None,
label: str = None,
) -> Activity:
"""Creates a trace activity based on this activity.
:param turn_activity:
:type turn_activity: Activity
:param name: The value to assign to the trace activity's <see cref="Activity.name"/> property.
:type name: str
:param value: The value to assign to the trace activity's <see cref="Activity.value"/> property., defaults to None
:param value: object, optional
:param value_type: The value to assign to the trace activity's <see cref="Activity.value_type"/> property, defaults to None
:param value_type: str, optional
:param label: The value to assign to the trace activity's <see cref="Activity.label"/> property, defaults to None
:param label: str, optional
:return: The created trace activity.
:rtype: Activity
"""
from_property = (
ChannelAccount(
id=turn_activity.recipient.id, name=turn_activity.recipient.name
)
if turn_activity.recipient is not None
else ChannelAccount()
)
if value_type is None and value is not None:
value_type = type(value).__name__
reply = Activity(
type=ActivityTypes.trace,
timestamp=datetime.utcnow(),
from_property=from_property,
recipient=ChannelAccount(
id=turn_activity.from_property.id, name=turn_activity.from_property.name
),
reply_to_id=turn_activity.id,
service_url=turn_activity.service_url,
channel_id=turn_activity.channel_id,
conversation=ConversationAccount(
is_group=turn_activity.conversation.is_group,
id=turn_activity.conversation.id,
name=turn_activity.conversation.name,
),
name=name,
label=label,
value_type=value_type,
value=value,
)
return reply
|
Adds a new dialog to the set and returns the added dialog.: param dialog: The dialog to add.
|
async def add(self, dialog: Dialog):
"""
Adds a new dialog to the set and returns the added dialog.
:param dialog: The dialog to add.
"""
if dialog is None or not isinstance(dialog, Dialog):
raise TypeError('DialogSet.add(): dialog cannot be None and must be a Dialog or derived class.')
if dialog.id in self._dialogs:
raise TypeError("DialogSet.add(): A dialog with an id of '%s' already added." % dialog.id)
# dialog.telemetry_client = this._telemetry_client;
self._dialogs[dialog.id] = dialog
return self
|
Finds a dialog that was previously added to the set using add ( dialog ): param dialog_id: ID of the dialog/ prompt to look up.: return: The dialog if found otherwise null.
|
async def find(self, dialog_id: str) -> Dialog:
"""
Finds a dialog that was previously added to the set using add(dialog)
:param dialog_id: ID of the dialog/prompt to look up.
:return: The dialog if found, otherwise null.
"""
if (not dialog_id):
raise TypeError('DialogContext.find(): dialog_id cannot be None.')
if dialog_id in self._dialogs:
return self._dialogs[dialog_id]
return None
|
Returns the storage key for the current user state.: param context:: return:
|
def get_storage_key(self, context: TurnContext) -> str:
"""
Returns the storage key for the current user state.
:param context:
:return:
"""
activity = context.activity
channel_id = getattr(activity, 'channel_id', None)
user_id = getattr(activity.from_property, 'id', None) if hasattr(activity, 'from_property') else None
storage_key = None
if channel_id and user_id:
storage_key = "%s/users/%s" % (channel_id, user_id)
return storage_key
|
Return the top scoring intent and its score.: return: Intent and score.: rtype: TopIntent
|
def get_top_scoring_intent(self) -> TopIntent:
"""Return the top scoring intent and its score.
:return: Intent and score.
:rtype: TopIntent
"""
if self.intents is None:
raise TypeError("result.intents can't be None")
top_intent = TopIntent(intent="", score=0.0)
for intent_name, intent_score in self.intents.items():
score = intent_score.score
if score > top_intent[1]:
top_intent = TopIntent(intent_name, score)
return top_intent
|
Sets the telemetry client for logging events.
|
def telemetry_client(self, value: BotTelemetryClient) -> None:
"""
Sets the telemetry client for logging events.
"""
if value is None:
self._telemetry_client = NullTelemetryClient()
else:
self._telemetry_client = value
|
Method called when an instance of the dialog is being returned to from another dialog that was started by the current instance using begin_dialog (). If this method is NOT implemented then the dialog will be automatically ended with a call to end_dialog (). Any result passed from the called dialog will be passed to the current dialog s parent.: param dc: The dialog context for the current turn of conversation.: param reason: Reason why the dialog resumed.: param result: ( Optional ) value returned from the dialog that was called. The type of the value returned is dependent on the dialog that was called.: return:
|
async def resume_dialog(self, dc, reason: DialogReason, result: object):
"""
Method called when an instance of the dialog is being returned to from another
dialog that was started by the current instance using `begin_dialog()`.
If this method is NOT implemented then the dialog will be automatically ended with a call
to `end_dialog()`. Any result passed from the called dialog will be passed
to the current dialog's parent.
:param dc: The dialog context for the current turn of conversation.
:param reason: Reason why the dialog resumed.
:param result: (Optional) value returned from the dialog that was called. The type of the value returned is dependent on the dialog that was called.
:return:
"""
# By default just end the current dialog.
return await dc.EndDialog(result)
|
Initializes a new instance of the <see cref = LuisApplication/ > class.: param application_endpoint: LUIS application endpoint.: type application_endpoint: str: return:: rtype: LuisApplication
|
def from_application_endpoint(cls, application_endpoint: str):
"""Initializes a new instance of the <see cref="LuisApplication"/> class.
:param application_endpoint: LUIS application endpoint.
:type application_endpoint: str
:return:
:rtype: LuisApplication
"""
(application_id, endpoint_key, endpoint) = LuisApplication._parse(
application_endpoint
)
return cls(application_id, endpoint_key, endpoint)
|
Returns the name of the top scoring intent from a set of LUIS results.: param results: Result set to be searched.: type results: RecognizerResult: param default_intent: Intent name to return should a top intent be found defaults to None: param default_intent: str optional: param min_score: Minimum score needed for an intent to be considered as a top intent. If all intents in the set are below this threshold then the defaultIntent will be returned defaults to 0. 0: param min_score: float optional: raises TypeError:: return: The top scoring intent name.: rtype: str
|
def top_intent(
results: RecognizerResult, default_intent: str = "None", min_score: float = 0.0
) -> str:
"""Returns the name of the top scoring intent from a set of LUIS results.
:param results: Result set to be searched.
:type results: RecognizerResult
:param default_intent: Intent name to return should a top intent be found, defaults to "None"
:param default_intent: str, optional
:param min_score: Minimum score needed for an intent to be considered as a top intent. If all intents in the set are below this threshold then the `defaultIntent` will be returned, defaults to 0.0
:param min_score: float, optional
:raises TypeError:
:return: The top scoring intent name.
:rtype: str
"""
if results is None:
raise TypeError("LuisRecognizer.top_intent(): results cannot be None.")
top_intent: str = None
top_score: float = -1.0
if results.intents:
for intent_name, intent_score in results.intents.items():
score = intent_score.score
if score > top_score and score >= min_score:
top_intent = intent_name
top_score = score
return top_intent or default_intent
|
Return results of the analysis ( Suggested actions and intents ).: param turn_context: Context object containing information for a single turn of conversation with a user.: type turn_context: TurnContext: param telemetry_properties: Additional properties to be logged to telemetry with the LuisResult event defaults to None: param telemetry_properties: Dict [ str str ] optional: param telemetry_metrics: Additional metrics to be logged to telemetry with the LuisResult event defaults to None: param telemetry_metrics: Dict [ str float ] optional: return: The LUIS results of the analysis of the current message text in the current turn s context activity.: rtype: RecognizerResult
|
async def recognize(
self,
turn_context: TurnContext,
telemetry_properties: Dict[str, str] = None,
telemetry_metrics: Dict[str, float] = None,
) -> RecognizerResult:
"""Return results of the analysis (Suggested actions and intents).
:param turn_context: Context object containing information for a single turn of conversation with a user.
:type turn_context: TurnContext
:param telemetry_properties: Additional properties to be logged to telemetry with the LuisResult event, defaults to None
:param telemetry_properties: Dict[str, str], optional
:param telemetry_metrics: Additional metrics to be logged to telemetry with the LuisResult event, defaults to None
:param telemetry_metrics: Dict[str, float], optional
:return: The LUIS results of the analysis of the current message text in the current turn's context activity.
:rtype: RecognizerResult
"""
return await self._recognize_internal(
turn_context, telemetry_properties, telemetry_metrics
)
|
Invoked prior to a LuisResult being logged.: param recognizer_result: The Luis Results for the call.: type recognizer_result: RecognizerResult: param turn_context: Context object containing information for a single turn of conversation with a user.: type turn_context: TurnContext: param telemetry_properties: Additional properties to be logged to telemetry with the LuisResult event defaults to None: param telemetry_properties: Dict [ str str ] optional: param telemetry_metrics: Additional metrics to be logged to telemetry with the LuisResult event defaults to None: param telemetry_metrics: Dict [ str float ] optional
|
def on_recognizer_result(
self,
recognizer_result: RecognizerResult,
turn_context: TurnContext,
telemetry_properties: Dict[str, str] = None,
telemetry_metrics: Dict[str, float] = None,
):
"""Invoked prior to a LuisResult being logged.
:param recognizer_result: The Luis Results for the call.
:type recognizer_result: RecognizerResult
:param turn_context: Context object containing information for a single turn of conversation with a user.
:type turn_context: TurnContext
:param telemetry_properties: Additional properties to be logged to telemetry with the LuisResult event, defaults to None
:param telemetry_properties: Dict[str, str], optional
:param telemetry_metrics: Additional metrics to be logged to telemetry with the LuisResult event, defaults to None
:param telemetry_metrics: Dict[str, float], optional
"""
properties = self.fill_luis_event_properties(
recognizer_result, turn_context, telemetry_properties
)
# Track the event
self.telemetry_client.track_event(
LuisTelemetryConstants.luis_result, properties, telemetry_metrics
)
|
Fills the event properties for LuisResult event for telemetry. These properties are logged when the recognizer is called.: param recognizer_result: Last activity sent from user.: type recognizer_result: RecognizerResult: param turn_context: Context object containing information for a single turn of conversation with a user.: type turn_context: TurnContext: param telemetry_properties: Additional properties to be logged to telemetry with the LuisResult event defaults to None: param telemetry_properties: Dict [ str str ] optional: return: A dictionary that is sent as Properties to IBotTelemetryClient. TrackEvent method for the BotMessageSend event.: rtype: Dict [ str str ]
|
def fill_luis_event_properties(
self,
recognizer_result: RecognizerResult,
turn_context: TurnContext,
telemetry_properties: Dict[str, str] = None,
) -> Dict[str, str]:
"""Fills the event properties for LuisResult event for telemetry.
These properties are logged when the recognizer is called.
:param recognizer_result: Last activity sent from user.
:type recognizer_result: RecognizerResult
:param turn_context: Context object containing information for a single turn of conversation with a user.
:type turn_context: TurnContext
:param telemetry_properties: Additional properties to be logged to telemetry with the LuisResult event, defaults to None
:param telemetry_properties: Dict[str, str], optional
:return: A dictionary that is sent as "Properties" to IBotTelemetryClient.TrackEvent method for the BotMessageSend event.
:rtype: Dict[str, str]
"""
intents = recognizer_result.intents
top_two_intents = (
sorted(intents.keys(), key=lambda k: intents[k].score, reverse=True)[:2]
if intents
else []
)
intent_name, intent_score = LuisRecognizer._get_top_k_intent_score(
top_two_intents, intents, index=0
)
intent2_name, intent2_score = LuisRecognizer._get_top_k_intent_score(
top_two_intents, intents, index=1
)
# Add the intent score and conversation id properties
properties: Dict[str, str] = {
LuisTelemetryConstants.application_id_property: self._application.application_id,
LuisTelemetryConstants.intent_property: intent_name,
LuisTelemetryConstants.intent_score_property: intent_score,
LuisTelemetryConstants.intent2_property: intent2_name,
LuisTelemetryConstants.intent_score2_property: intent2_score,
LuisTelemetryConstants.from_id_property: turn_context.activity.from_property.id,
}
sentiment = recognizer_result.properties.get("sentiment")
if sentiment is not None and isinstance(sentiment, Dict):
label = sentiment.get("label")
if label is not None:
properties[LuisTelemetryConstants.sentiment_label_property] = str(label)
score = sentiment.get("score")
if score is not None:
properties[LuisTelemetryConstants.sentiment_score_property] = str(score)
entities = None
if recognizer_result.entities is not None:
entities = json.dumps(recognizer_result.entities)
properties[LuisTelemetryConstants.entities_property] = entities
# Use the LogPersonalInformation flag to toggle logging PII data, text is a common example
if self.log_personal_information and turn_context.activity.text:
properties[
LuisTelemetryConstants.question_property
] = turn_context.activity.text
# Additional Properties can override "stock" properties.
if telemetry_properties is not None:
for key in telemetry_properties:
properties[key] = telemetry_properties[key]
return properties
|
Send data as a multipart form - data request. We only deal with file - like objects or strings at this point. The requests is not yet streamed.: param ClientRequest request: The request object to be sent.: param dict headers: Any headers to add to the request.: param dict content: Dictionary of the fields of the formdata.: param config: Any specific config overrides.
|
async def async_send_formdata(self, request, headers=None, content=None, **config):
"""Send data as a multipart form-data request.
We only deal with file-like objects or strings at this point.
The requests is not yet streamed.
:param ClientRequest request: The request object to be sent.
:param dict headers: Any headers to add to the request.
:param dict content: Dictionary of the fields of the formdata.
:param config: Any specific config overrides.
"""
files = self._prepare_send_formdata(request, headers, content)
return await self.async_send(request, headers, files=files, **config)
|
Prepare and send request object according to configuration.: param ClientRequest request: The request object to be sent.: param dict headers: Any headers to add to the request.: param content: Any body data to add to the request.: param config: Any specific config overrides
|
async def async_send(self, request, headers=None, content=None, **config):
"""Prepare and send request object according to configuration.
:param ClientRequest request: The request object to be sent.
:param dict headers: Any headers to add to the request.
:param content: Any body data to add to the request.
:param config: Any specific config overrides
"""
loop = asyncio.get_event_loop()
if self.config.keep_alive and self._session is None:
self._session = requests.Session()
try:
session = self.creds.signed_session(self._session)
except TypeError: # Credentials does not support session injection
session = self.creds.signed_session()
if self._session is not None:
_LOGGER.warning(
"Your credentials class does not support session injection. Performance will not be at the maximum.")
kwargs = self._configure_session(session, **config)
if headers:
request.headers.update(headers)
if not kwargs.get('files'):
request.add_content(content)
if request.data:
kwargs['data'] = request.data
kwargs['headers'].update(request.headers)
response = None
try:
try:
future = loop.run_in_executor(
None,
functools.partial(
session.request,
request.method,
request.url,
**kwargs
)
)
return await future
except (oauth2.rfc6749.errors.InvalidGrantError,
oauth2.rfc6749.errors.TokenExpiredError) as err:
error = "Token expired or is invalid. Attempting to refresh."
_LOGGER.warning(error)
try:
session = self.creds.refresh_session()
kwargs = self._configure_session(session)
if request.data:
kwargs['data'] = request.data
kwargs['headers'].update(request.headers)
future = loop.run_in_executor(
None,
functools.partial(
session.request,
request.method,
request.url,
**kwargs
)
)
return await future
except (oauth2.rfc6749.errors.InvalidGrantError,
oauth2.rfc6749.errors.TokenExpiredError) as err:
msg = "Token expired or is invalid."
raise_with_traceback(TokenExpiredError, msg, err)
except (requests.RequestException,
oauth2.rfc6749.errors.OAuth2Error) as err:
msg = "Error occurred in request."
raise_with_traceback(ClientRequestError, msg, err)
finally:
self._close_local_session_if_necessary(response, session, kwargs['stream'])
|
Async Generator for streaming request body data.: param response: The initial response: param user_callback: Custom callback for monitoring progress.
|
def stream_download_async(self, response, user_callback):
"""Async Generator for streaming request body data.
:param response: The initial response
:param user_callback: Custom callback for monitoring progress.
"""
block = self.config.connection.data_block_size
return StreamDownloadGenerator(response, user_callback, block)
|
Read storeitems from storage.
|
async def read(self, keys: List[str]) -> dict:
"""Read storeitems from storage.
:param keys:
:return dict:
"""
try:
# check if the database and container exists and if not create
if not self.__container_exists:
self.__create_db_and_container()
if len(keys) > 0:
# create the parameters object
parameters = [
{'name': f'@id{i}', 'value': f'{self.__sanitize_key(key)}'}
for i, key in enumerate(keys)
]
# get the names of the params
parameter_sequence = ','.join(param.get('name')
for param in parameters)
# create the query
query = {
"query":
f"SELECT c.id, c.realId, c.document, c._etag \
FROM c WHERE c.id in ({parameter_sequence})",
"parameters": parameters
}
options = {'enableCrossPartitionQuery': True}
# run the query and store the results as a list
results = list(
self.client.QueryItems(
self.__container_link, query, options)
)
# return a dict with a key and a StoreItem
return {
r.get('realId'): self.__create_si(r) for r in results
}
else:
raise Exception('cosmosdb_storage.read(): \
provide at least one key')
except TypeError as e:
raise e
|
Save storeitems to storage.
|
async def write(self, changes: Dict[str, StoreItem]):
"""Save storeitems to storage.
:param changes:
:return:
"""
try:
# check if the database and container exists and if not create
if not self.__container_exists:
self.__create_db_and_container()
# iterate over the changes
for (key, change) in changes.items():
# store the e_tag
e_tag = change.e_tag
# create the new document
doc = {'id': self.__sanitize_key(key),
'realId': key,
'document': self.__create_dict(change)
}
# the e_tag will be * for new docs so do an insert
if (e_tag == '*' or not e_tag):
self.client.UpsertItem(
database_or_Container_link=self.__container_link,
document=doc,
options={'disableAutomaticIdGeneration': True}
)
# if we have an etag, do opt. concurrency replace
elif(len(e_tag) > 0):
access_condition = {'type': 'IfMatch', 'condition': e_tag}
self.client.ReplaceItem(
document_link=self.__item_link(
self.__sanitize_key(key)),
new_document=doc,
options={'accessCondition': access_condition}
)
# error when there is no e_tag
else:
raise Exception('cosmosdb_storage.write(): etag missing')
except Exception as e:
raise e
|
Remove storeitems from storage.
|
async def delete(self, keys: List[str]):
"""Remove storeitems from storage.
:param keys:
:return:
"""
try:
# check if the database and container exists and if not create
if not self.__container_exists:
self.__create_db_and_container()
# call the function for each key
for k in keys:
self.client.DeleteItem(
document_link=self.__item_link(self.__sanitize_key(k)))
# print(res)
except cosmos_errors.HTTPFailure as h:
# print(h.status_code)
if h.status_code != 404:
raise h
except TypeError as e:
raise e
|
Create a StoreItem from a result out of CosmosDB.
|
def __create_si(self, result) -> StoreItem:
"""Create a StoreItem from a result out of CosmosDB.
:param result:
:return StoreItem:
"""
# get the document item from the result and turn into a dict
doc = result.get('document')
# readd the e_tag from Cosmos
doc['e_tag'] = result.get('_etag')
# create and return the StoreItem
return StoreItem(**doc)
|
Return the dict of a StoreItem.
|
def __create_dict(self, si: StoreItem) -> Dict:
"""Return the dict of a StoreItem.
This eliminates non_magic attributes and the e_tag.
:param si:
:return dict:
"""
# read the content
non_magic_attr = ([attr for attr in dir(si)
if not attr.startswith('_') or attr.__eq__('e_tag')])
# loop through attributes and write and return a dict
return ({attr: getattr(si, attr)
for attr in non_magic_attr})
|
Return the sanitized key.
|
def __sanitize_key(self, key) -> str:
"""Return the sanitized key.
Replace characters that are not allowed in keys in Cosmos.
:param key:
:return str:
"""
# forbidden characters
bad_chars = ['\\', '?', '/', '#', '\t', '\n', '\r']
# replace those with with '*' and the
# Unicode code point of the character and return the new string
return ''.join(
map(
lambda x: '*'+str(ord(x)) if x in bad_chars else x, key
)
)
|
Call the get or create methods.
|
def __create_db_and_container(self):
"""Call the get or create methods."""
db_id = self.config.database
container_name = self.config.container
self.db = self.__get_or_create_database(self.client, db_id)
self.container = self.__get_or_create_container(
self.client, container_name
)
|
Return the database link.
|
def __get_or_create_database(self, doc_client, id) -> str:
"""Return the database link.
Check if the database exists or create the db.
:param doc_client:
:param id:
:return str:
"""
# query CosmosDB for a database with that name/id
dbs = list(doc_client.QueryDatabases({
"query": "SELECT * FROM r WHERE r.id=@id",
"parameters": [
{"name": "@id", "value": id}
]
}))
# if there are results, return the first (db names are unique)
if len(dbs) > 0:
return dbs[0]['id']
else:
# create the database if it didn't exist
res = doc_client.CreateDatabase({'id': id})
return res['id']
|
Return the container link.
|
def __get_or_create_container(self, doc_client, container) -> str:
"""Return the container link.
Check if the container exists or create the container.
:param doc_client:
:param container:
:return str:
"""
# query CosmosDB for a container in the database with that name
containers = list(doc_client.QueryContainers(
self.__database_link,
{
"query": "SELECT * FROM r WHERE r.id=@id",
"parameters": [
{"name": "@id", "value": container}
]
}
))
# if there are results, return the first (container names are unique)
if len(containers) > 0:
return containers[0]['id']
else:
# Create a container if it didn't exist
res = doc_client.CreateContainer(
self.__database_link, {'id': container})
return res['id']
|
Fills the event properties and metrics for the QnaMessage event for telemetry.
|
def fill_qna_event(
self,
query_results: [QueryResult],
turn_context: TurnContext,
telemetry_properties: Dict[str,str] = None,
telemetry_metrics: Dict[str,float] = None
) -> EventData:
"""
Fills the event properties and metrics for the QnaMessage event for telemetry.
:return: A tuple of event data properties and metrics that will be sent to the BotTelemetryClient.track_event() method for the QnAMessage event. The properties and metrics returned the standard properties logged with any properties passed from the get_answers() method.
:rtype: EventData
"""
properties: Dict[str,str] = dict()
metrics: Dict[str, float] = dict()
properties[QnATelemetryConstants.knowledge_base_id_property] = self._endpoint.knowledge_base_id
text: str = turn_context.activity.text
userName: str = turn_context.activity.from_property.name
# Use the LogPersonalInformation flag to toggle logging PII data; text and username are common examples.
if self.log_personal_information:
if text:
properties[QnATelemetryConstants.question_property] = text
if userName:
properties[QnATelemetryConstants.username_property] = userName
# Fill in Qna Results (found or not).
if len(query_results) > 0:
query_result = query_results[0]
result_properties = {
QnATelemetryConstants.matched_question_property: json.dumps(query_result.questions),
QnATelemetryConstants.question_id_property: str(query_result.id),
QnATelemetryConstants.answer_property: query_result.answer,
QnATelemetryConstants.score_metric: query_result.score,
QnATelemetryConstants.article_found_property: 'true'
}
properties.update(result_properties)
else:
no_match_properties = {
QnATelemetryConstants.matched_question_property : 'No Qna Question matched',
QnATelemetryConstants.question_id_property : 'No Qna Question Id matched',
QnATelemetryConstants.answer_property : 'No Qna Answer matched',
QnATelemetryConstants.article_found_property : 'false'
}
properties.update(no_match_properties)
# Additional Properties can override "stock" properties.
if telemetry_properties:
properties.update(telemetry_properties)
# Additional Metrics can override "stock" metrics.
if telemetry_metrics:
metrics.update(telemetry_metrics)
return EventData(properties=properties, metrics=metrics)
|
Generates answers from the knowledge base.: return: A list of answers for the user s query sorted in decreasing order of ranking score.: rtype: [ QueryResult ]
|
async def get_answers(
self,
context: TurnContext,
options: QnAMakerOptions = None,
telemetry_properties: Dict[str,str] = None,
telemetry_metrics: Dict[str,int] = None
) -> [QueryResult]:
"""
Generates answers from the knowledge base.
:return: A list of answers for the user's query, sorted in decreasing order of ranking score.
:rtype: [QueryResult]
"""
hydrated_options = self._hydrate_options(options)
self._validate_options(hydrated_options)
result = self._query_qna_service(context.activity, hydrated_options)
await self._emit_trace_info(context, result, hydrated_options)
return result
|
Combines QnAMakerOptions passed into the QnAMaker constructor with the options passed as arguments into get_answers ().: return: QnAMakerOptions with options passed into constructor overwritten by new options passed into get_answers ()
|
def _hydrate_options(self, query_options: QnAMakerOptions) -> QnAMakerOptions:
"""
Combines QnAMakerOptions passed into the QnAMaker constructor with the options passed as arguments into get_answers().
:return: QnAMakerOptions with options passed into constructor overwritten by new options passed into get_answers()
:rtype: QnAMakerOptions
"""
hydrated_options = copy(self._options)
if query_options:
if (
query_options.score_threshold != hydrated_options.score_threshold
and query_options.score_threshold
):
hydrated_options.score_threshold = query_options.score_threshold
if (query_options.top != hydrated_options.top and query_options.top != 0):
hydrated_options.top = query_options.top
if (len(query_options.strict_filters) > 0):
hydrated_options.strict_filters = query_options.strict_filters
return hydrated_options
|
Called when this TurnContext instance is passed into the constructor of a new TurnContext instance. Can be overridden in derived classes.: param context:: return:
|
def copy_to(self, context: 'TurnContext') -> None:
"""
Called when this TurnContext instance is passed into the constructor of a new TurnContext
instance. Can be overridden in derived classes.
:param context:
:return:
"""
for attribute in ['adapter', 'activity', '_responded', '_services',
'_on_send_activities', '_on_update_activity', '_on_delete_activity']:
setattr(context, attribute, getattr(self, attribute))
|
Used to set TurnContext. _activity when a context object is created. Only takes instances of Activities.: param value:: return:
|
def activity(self, value):
"""
Used to set TurnContext._activity when a context object is created. Only takes instances of Activities.
:param value:
:return:
"""
if not isinstance(value, Activity):
raise TypeError('TurnContext: cannot set `activity` to a type other than Activity.')
else:
self._activity = value
|
Returns True is set () has been called for a key. The cached value may be of type None.: param key:: return:
|
def has(self, key: str) -> bool:
"""
Returns True is set() has been called for a key. The cached value may be of type 'None'.
:param key:
:return:
"""
if key in self._services:
return True
return False
|
Caches a value for the lifetime of the current turn.: param key:: param value:: return:
|
def set(self, key: str, value: object) -> None:
"""
Caches a value for the lifetime of the current turn.
:param key:
:param value:
:return:
"""
if not key or not isinstance(key, str):
raise KeyError('"key" must be a valid string.')
self._services[key] = value
|
Sends a single activity or message to the user.: param activity_or_text:: return:
|
async def send_activity(self, *activity_or_text: Union[Activity, str]) -> ResourceResponse:
"""
Sends a single activity or message to the user.
:param activity_or_text:
:return:
"""
reference = TurnContext.get_conversation_reference(self.activity)
output = [TurnContext.apply_conversation_reference(
Activity(text=a, type='message') if isinstance(a, str) else a, reference)
for a in activity_or_text]
for activity in output:
activity.input_hint = 'acceptingInput'
async def callback(context: 'TurnContext', output):
responses = await context.adapter.send_activities(context, output)
context._responded = True
return responses
await self._emit(self._on_send_activities, output, callback(self, output))
|
Replaces an existing activity.: param activity:: return:
|
async def update_activity(self, activity: Activity):
"""
Replaces an existing activity.
:param activity:
:return:
"""
return await self._emit(self._on_update_activity, activity, self.adapter.update_activity(self, activity))
|
Deletes an existing activity.: param id_or_reference:: return:
|
async def delete_activity(self, id_or_reference: Union[str, ConversationReference]):
"""
Deletes an existing activity.
:param id_or_reference:
:return:
"""
if type(id_or_reference) == str:
reference = TurnContext.get_conversation_reference(self.activity)
reference.activity_id = id_or_reference
else:
reference = id_or_reference
return await self._emit(self._on_delete_activity, reference, self.adapter.delete_activity(self, reference))
|
Returns the conversation reference for an activity. This can be saved as a plain old JSON object and then later used to message the user proactively.
|
def get_conversation_reference(activity: Activity) -> ConversationReference:
"""
Returns the conversation reference for an activity. This can be saved as a plain old JSON
object and then later used to message the user proactively.
Usage Example:
reference = TurnContext.get_conversation_reference(context.request)
:param activity:
:return:
"""
return ConversationReference(activity_id=activity.id,
user=copy(activity.from_property),
bot=copy(activity.recipient),
conversation=copy(activity.conversation),
channel_id=activity.channel_id,
service_url=activity.service_url)
|
Updates an activity with the delivery information from a conversation reference. Calling this after get_conversation_reference on an incoming activity will properly address the reply to a received activity.: param activity:: param reference:: param is_incoming:: return:
|
def apply_conversation_reference(activity: Activity,
reference: ConversationReference,
is_incoming: bool=False) -> Activity:
"""
Updates an activity with the delivery information from a conversation reference. Calling
this after get_conversation_reference on an incoming activity
will properly address the reply to a received activity.
:param activity:
:param reference:
:param is_incoming:
:return:
"""
activity.channel_id = reference.channel_id
activity.service_url = reference.service_url
activity.conversation = reference.conversation
if is_incoming:
activity.from_property = reference.user
activity.recipient = reference.bot
if reference.activity_id:
activity.id = reference.activity_id
else:
activity.from_property = reference.bot
activity.recipient = reference.user
if reference.activity_id:
activity.reply_to_id = reference.activity_id
return activity
|
Adds a new step to the waterfall.: param step: Step to add: return: Waterfall dialog for fluent calls to add_step ().
|
def add_step(self, step):
"""
Adds a new step to the waterfall.
:param step: Step to add
:return: Waterfall dialog for fluent calls to `add_step()`.
"""
if not step:
raise TypeError('WaterfallDialog.add_step(): step cannot be None.')
self._steps.append(step)
return self
|
Give the waterfall step a unique name
|
def get_step_name(self, index: int) -> str:
"""
Give the waterfall step a unique name
"""
step_name = self._steps[index].__qualname__
if not step_name or ">" in step_name :
step_name = f"Step{index + 1}of{len(self._steps)}"
return step_name
|
Send information about a single event that has occurred in the context of the application.: param name: the data to associate to this event.: param properties: the set of custom properties the client wants attached to this data item. ( defaults to: None ): param measurements: the set of custom measurements the client wants to attach to this data item. ( defaults to: None )
|
def track_event(self, name: str, properties: Dict[str, object] = None,
measurements: Dict[str, object] = None) -> None:
"""
Send information about a single event that has occurred in the context of the application.
:param name: the data to associate to this event.
:param properties: the set of custom properties the client wants attached to this data item. (defaults to: None)
:param measurements: the set of custom measurements the client wants to attach to this data item. (defaults to: None)
"""
pass
|
Utility function to calculate a change hash for a StoreItem.: param item:: return:
|
def calculate_change_hash(item: StoreItem) -> str:
"""
Utility function to calculate a change hash for a `StoreItem`.
:param item:
:return:
"""
cpy = copy(item)
if cpy.e_tag is not None:
del cpy.e_tag
return str(cpy)
|
Pushes a new dialog onto the dialog stack.: param dialog_id: ID of the dialog to start..: param options: ( Optional ) additional argument ( s ) to pass to the dialog being started.
|
async def begin_dialog(self, dialog_id: str, options: object = None):
"""
Pushes a new dialog onto the dialog stack.
:param dialog_id: ID of the dialog to start..
:param options: (Optional) additional argument(s) to pass to the dialog being started.
"""
if (not dialog_id):
raise TypeError('Dialog(): dialogId cannot be None.')
# Look up dialog
dialog = await self.find_dialog(dialog_id)
if dialog is None:
raise Exception("'DialogContext.begin_dialog(): A dialog with an id of '%s' wasn't found."
" The dialog must be included in the current or parent DialogSet."
" For example, if subclassing a ComponentDialog you can call add_dialog() within your constructor." % dialog_id)
# Push new instance onto stack
instance = DialogInstance()
instance.id = dialog_id
instance.state = {}
self._stack.append(instance)
# Call dialog's begin_dialog() method
return await dialog.begin_dialog(self, options)
|
Helper function to simplify formatting the options for calling a prompt dialog. This helper will take a PromptOptions argument and then call.: param dialog_id: ID of the prompt to start.: param options: Contains a Prompt potentially a RetryPrompt and if using ChoicePrompt Choices.: return:
|
async def prompt(self, dialog_id: str, options) -> DialogTurnResult:
"""
Helper function to simplify formatting the options for calling a prompt dialog. This helper will
take a `PromptOptions` argument and then call.
:param dialog_id: ID of the prompt to start.
:param options: Contains a Prompt, potentially a RetryPrompt and if using ChoicePrompt, Choices.
:return:
"""
if (not dialog_id):
raise TypeError('DialogContext.prompt(): dialogId cannot be None.')
if (not options):
raise TypeError('DialogContext.prompt(): options cannot be None.')
return await self.begin_dialog(dialog_id, options)
|
Continues execution of the active dialog if there is one by passing the context object to its Dialog. continue_dialog () method. You can check turn_context. responded after the call completes to determine if a dialog was run and a reply was sent to the user.: return:
|
async def continue_dialog(self):
"""
Continues execution of the active dialog, if there is one, by passing the context object to
its `Dialog.continue_dialog()` method. You can check `turn_context.responded` after the call completes
to determine if a dialog was run and a reply was sent to the user.
:return:
"""
# Check for a dialog on the stack
if self.active_dialog != None:
# Look up dialog
dialog = await self.find_dialog(self.active_dialog.id)
if not dialog:
raise Exception("DialogContext.continue_dialog(): Can't continue dialog. A dialog with an id of '%s' wasn't found." % active_dialog.id)
# Continue execution of dialog
return await dialog.continue_dialog(self)
else:
return DialogTurnResult(DialogTurnStatus.Empty)
|
Ends a dialog by popping it off the stack and returns an optional result to the dialog s parent. The parent dialog is the dialog that started the dialog being ended via a call to either begin_dialog or prompt. The parent dialog will have its Dialog. resume_dialog () method invoked with any returned result. If the parent dialog hasn t implemented a resume_dialog () method then it will be automatically ended as well and the result passed to its parent. If there are no more parent dialogs on the stack then processing of the turn will end.: param result: ( Optional ) result to pass to the parent dialogs.: return:
|
async def end_dialog(self, result: object = None):
"""
Ends a dialog by popping it off the stack and returns an optional result to the dialog's
parent. The parent dialog is the dialog that started the dialog being ended via a call to
either "begin_dialog" or "prompt".
The parent dialog will have its `Dialog.resume_dialog()` method invoked with any returned
result. If the parent dialog hasn't implemented a `resume_dialog()` method then it will be
automatically ended as well and the result passed to its parent. If there are no more
parent dialogs on the stack then processing of the turn will end.
:param result: (Optional) result to pass to the parent dialogs.
:return:
"""
await self.end_active_dialog(DialogReason.EndCalled)
# Resume previous dialog
if self.active_dialog != None:
# Look up dialog
dialog = await self.find_dialog(self.active_dialog.id)
if not dialog:
raise Exception("DialogContext.EndDialogAsync(): Can't resume previous dialog. A dialog with an id of '%s' wasn't found." % self.active_dialog.id)
# Return result to previous dialog
return await dialog.resume_dialog(self, DialogReason.EndCalled, result)
else:
return DialogTurnResult(DialogTurnStatus.Complete, result)
|
Deletes any existing dialog stack thus cancelling all dialogs on the stack.: param result: ( Optional ) result to pass to the parent dialogs.: return:
|
async def cancel_all_dialogs(self):
"""
Deletes any existing dialog stack thus cancelling all dialogs on the stack.
:param result: (Optional) result to pass to the parent dialogs.
:return:
"""
if (len(self.stack) > 0):
while (len(self.stack) > 0):
await self.end_active_dialog(DialogReason.CancelCalled)
return DialogTurnResult(DialogTurnStatus.Cancelled)
else:
return DialogTurnResult(DialogTurnStatus.Empty)
|
If the dialog cannot be found within the current DialogSet the parent DialogContext will be searched if there is one.: param dialog_id: ID of the dialog to search for.: return:
|
async def find_dialog(self, dialog_id: str) -> Dialog:
"""
If the dialog cannot be found within the current `DialogSet`, the parent `DialogContext`
will be searched if there is one.
:param dialog_id: ID of the dialog to search for.
:return:
"""
dialog = await self.dialogs.find(dialog_id)
if (dialog == None and self.parent != None):
dialog = self.parent.find_dialog(dialog_id)
return dialog
|
Ends the active dialog and starts a new dialog in its place. This is particularly useful for creating loops or redirecting to another dialog.: param dialog_id: ID of the dialog to search for.: param options: ( Optional ) additional argument ( s ) to pass to the new dialog.: return:
|
async def replace_dialog(self, dialog_id: str, options: object = None) -> DialogTurnResult:
"""
Ends the active dialog and starts a new dialog in its place. This is particularly useful
for creating loops or redirecting to another dialog.
:param dialog_id: ID of the dialog to search for.
:param options: (Optional) additional argument(s) to pass to the new dialog.
:return:
"""
# End the current dialog and giving the reason.
await self.end_active_dialog(DialogReason.ReplaceCalled)
# Start replacement dialog
return await self.begin_dialog(dialog_id, options)
|
Calls reprompt on the currently active dialog if there is one. Used with Prompts that have a reprompt behavior.: return:
|
async def reprompt_dialog(self):
"""
Calls reprompt on the currently active dialog, if there is one. Used with Prompts that have a reprompt behavior.
:return:
"""
# Check for a dialog on the stack
if self.active_dialog != None:
# Look up dialog
dialog = await self.find_dialog(self.active_dialog.id)
if not dialog:
raise Exception("DialogSet.reprompt_dialog(): Can't find A dialog with an id of '%s'." % self.active_dialog.id)
# Ask dialog to re-prompt if supported
await dialog.reprompt_dialog(self.context, self.active_dialog)
|
Determine if a number of Suggested Actions are supported by a Channel.
|
def supports_suggested_actions(channel_id: str, button_cnt: int = 100) -> bool:
"""Determine if a number of Suggested Actions are supported by a Channel.
Args:
channel_id (str): The Channel to check the if Suggested Actions are supported in.
button_cnt (int, optional): Defaults to 100. The number of Suggested Actions to check for the Channel.
Returns:
bool: True if the Channel supports the button_cnt total Suggested Actions, False if the Channel does not support that number of Suggested Actions.
"""
max_actions = {
# https://developers.facebook.com/docs/messenger-platform/send-messages/quick-replies
Channels.facebook: 10,
Channels.skype: 10,
# https://developers.line.biz/en/reference/messaging-api/#items-object
Channels.line: 13,
# https://dev.kik.com/#/docs/messaging#text-response-object
Channels.kik: 20,
Channels.telegram: 100,
Channels.slack: 100,
Channels.emulator: 100,
Channels.direct_line: 100,
Channels.webchat: 100,
}
return button_cnt <= max_actions[channel_id] if channel_id in max_actions else False
|
Determine if a number of Card Actions are supported by a Channel.
|
def supports_card_actions(channel_id: str, button_cnt: int = 100) -> bool:
"""Determine if a number of Card Actions are supported by a Channel.
Args:
channel_id (str): The Channel to check if the Card Actions are supported in.
button_cnt (int, optional): Defaults to 100. The number of Card Actions to check for the Channel.
Returns:
bool: True if the Channel supports the button_cnt total Card Actions, False if the Channel does not support that number of Card Actions.
"""
max_actions = {
Channels.facebook: 3,
Channels.skype: 3,
Channels.ms_teams: 3,
Channels.line: 99,
Channels.slack: 100,
Channels.emulator: 100,
Channels.direct_line: 100,
Channels.webchat: 100,
Channels.cortana: 100,
}
return button_cnt <= max_actions[channel_id] if channel_id in max_actions else False
|
Get the Channel Id from the current Activity on the Turn Context.
|
def get_channel_id(turn_context: TurnContext) -> str:
"""Get the Channel Id from the current Activity on the Turn Context.
Args:
turn_context (TurnContext): The Turn Context to retrieve the Activity's Channel Id from.
Returns:
str: The Channel Id from the Turn Context's Activity.
"""
if turn_context.activity.channel_id is None:
return ""
else:
return turn_context.activity.channel_id
|
Begins listening to console input.: param logic:: return:
|
async def process_activity(self, logic: Callable):
"""
Begins listening to console input.
:param logic:
:return:
"""
while True:
msg = input()
if msg is None:
pass
else:
self._next_id += 1
activity = Activity(text=msg,
channel_id='console',
from_property=ChannelAccount(id='user', name='User1'),
recipient=ChannelAccount(id='bot', name='Bot'),
conversation=ConversationAccount(id='Convo1'),
type=ActivityTypes.message,
timestamp=datetime.datetime.now(),
id=str(self._next_id))
activity = TurnContext.apply_conversation_reference(activity, self.reference, True)
context = TurnContext(self, activity)
await self.run_middleware(context, logic)
|
Logs a series of activities to the console.: param context:: param activities:: return:
|
async def send_activities(self, context: TurnContext, activities: List[Activity]):
"""
Logs a series of activities to the console.
:param context:
:param activities:
:return:
"""
if context is None:
raise TypeError('ConsoleAdapter.send_activities(): `context` argument cannot be None.')
if type(activities) != list:
raise TypeError('ConsoleAdapter.send_activities(): `activities` argument must be a list.')
if len(activities) == 0:
raise ValueError('ConsoleAdapter.send_activities(): `activities` argument cannot have a length of 0.')
async def next_activity(i: int):
responses = []
if i < len(activities):
responses.append(ResourceResponse())
a = activities[i]
if a.type == 'delay':
await asyncio.sleep(a.delay)
await next_activity(i + 1)
elif a.type == ActivityTypes.message:
if a.attachments is not None and len(a.attachments) > 0:
append = '(1 attachment)' if len(a.attachments) == 1 else f'({len(a.attachments)} attachments)'
print(f'{a.text} {append}')
else:
print(a.text)
await next_activity(i + 1)
else:
print(f'[{a.type}]')
await next_activity(i + 1)
else:
return responses
await next_activity(0)
|
Determines if a given Auth header is from the Bot Framework Emulator
|
def is_token_from_emulator(auth_header: str) -> bool:
""" Determines if a given Auth header is from the Bot Framework Emulator
:param auth_header: Bearer Token, in the 'Bearer [Long String]' Format.
:type auth_header: str
:return: True, if the token was issued by the Emulator. Otherwise, false.
"""
# The Auth Header generally looks like this:
# "Bearer eyJ0e[...Big Long String...]XAiO"
if not auth_header:
# No token. Can't be an emulator token.
return False
parts = auth_header.split(' ')
if len(parts) != 2:
# Emulator tokens MUST have exactly 2 parts.
# If we don't have 2 parts, it's not an emulator token
return False
auth_scheme = parts[0]
bearer_token = parts[1]
# We now have an array that should be:
# [0] = "Bearer"
# [1] = "[Big Long String]"
if auth_scheme != 'Bearer':
# The scheme from the emulator MUST be "Bearer"
return False
# Parse the Big Long String into an actual token.
token = jwt.decode(bearer_token, verify=False)
if not token:
return False
# Is there an Issuer?
issuer = token['iss']
if not issuer:
# No Issuer, means it's not from the Emulator.
return False
# Is the token issues by a source we consider to be the emulator?
issuer_list = EmulatorValidation.TO_BOT_FROM_EMULATOR_TOKEN_VALIDATION_PARAMETERS.issuer
if issuer_list and not issuer in issuer_list:
# Not a Valid Issuer. This is NOT a Bot Framework Emulator Token.
return False
# The Token is from the Bot Framework Emulator. Success!
return True
|
Validate the incoming Auth Header
|
async def authenticate_emulator_token(auth_header: str, credentials: CredentialProvider, channel_id: str) -> ClaimsIdentity:
""" Validate the incoming Auth Header
Validate the incoming Auth Header as a token sent from the Bot Framework Service.
A token issued by the Bot Framework emulator will FAIL this check.
:param auth_header: The raw HTTP header in the format: 'Bearer [longString]'
:type auth_header: str
:param credentials: The user defined set of valid credentials, such as the AppId.
:type credentials: CredentialProvider
:return: A valid ClaimsIdentity.
:raises Exception:
"""
token_extractor = JwtTokenExtractor(
EmulatorValidation.TO_BOT_FROM_EMULATOR_TOKEN_VALIDATION_PARAMETERS,
Constants.TO_BOT_FROM_EMULATOR_OPEN_ID_METADATA_URL,
Constants.ALLOWED_SIGNING_ALGORITHMS)
identity = await asyncio.ensure_future(
token_extractor.get_identity_from_auth_header(auth_header, channel_id))
if not identity:
# No valid identity. Not Authorized.
raise Exception('Unauthorized. No valid identity.')
if not identity.isAuthenticated:
# The token is in some way invalid. Not Authorized.
raise Exception('Unauthorized. Is not authenticated')
# Now check that the AppID in the claimset matches
# what we're looking for. Note that in a multi-tenant bot, this value
# comes from developer code that may be reaching out to a service, hence the
# Async validation.
version_claim = identity.get_claim_value(EmulatorValidation.VERSION_CLAIM)
if version_claim is None:
raise Exception('Unauthorized. "ver" claim is required on Emulator Tokens.')
app_id = ''
# The Emulator, depending on Version, sends the AppId via either the
# appid claim (Version 1) or the Authorized Party claim (Version 2).
if not version_claim or version_claim == '1.0':
# either no Version or a version of "1.0" means we should look for
# the claim in the "appid" claim.
app_id_claim = identity.get_claim_value(EmulatorValidation.APP_ID_CLAIM)
if not app_id_claim:
# No claim around AppID. Not Authorized.
raise Exception('Unauthorized. '
'"appid" claim is required on Emulator Token version "1.0".')
app_id = app_id_claim
elif version_claim == '2.0':
# Emulator, "2.0" puts the AppId in the "azp" claim.
app_authz_claim = identity.get_claim_value(Constants.AUTHORIZED_PARTY)
if not app_authz_claim:
# No claim around AppID. Not Authorized.
raise Exception('Unauthorized. '
'"azp" claim is required on Emulator Token version "2.0".')
app_id = app_authz_claim
else:
# Unknown Version. Not Authorized.
raise Exception('Unauthorized. Unknown Emulator Token version ', version_claim, '.')
is_valid_app_id = await asyncio.ensure_future(credentials.is_valid_appid(app_id))
if not is_valid_app_id:
raise Exception('Unauthorized. Invalid AppId passed on token: ', app_id)
return identity
|
Returns an attachment for an adaptive card. The attachment will contain the card and the appropriate contentType. Will raise a TypeError if the card argument is not an dict.: param card:: return:
|
def adaptive_card(card: dict) -> Attachment:
"""
Returns an attachment for an adaptive card. The attachment will contain the card and the
appropriate 'contentType'. Will raise a TypeError if the 'card' argument is not an
dict.
:param card:
:return:
"""
if not type(card) == dict:
raise TypeError('CardFactory.adaptive_card(): `card` argument is not of type dict, unable to prepare '
'attachment.')
return Attachment(content_type=CardFactory.content_types.adaptive_card,
content=card)
|
Returns an attachment for an animation card. Will raise a TypeError if the card argument is not an AnimationCard.: param card:: return:
|
def animation_card(card: AnimationCard) -> Attachment:
"""
Returns an attachment for an animation card. Will raise a TypeError if the 'card' argument is not an
AnimationCard.
:param card:
:return:
"""
if not isinstance(card, AnimationCard):
raise TypeError('CardFactory.animation_card(): `card` argument is not an instance of an AnimationCard, '
'unable to prepare attachment.')
return Attachment(content_type=CardFactory.content_types.animation_card,
content=card)
|
Returns an attachment for an audio card. Will raise a TypeError if card argument is not an AudioCard.: param card:: return:
|
def audio_card(card: AudioCard) -> Attachment:
"""
Returns an attachment for an audio card. Will raise a TypeError if 'card' argument is not an AudioCard.
:param card:
:return:
"""
if not isinstance(card, AudioCard):
raise TypeError('CardFactory.audio_card(): `card` argument is not an instance of an AudioCard, '
'unable to prepare attachment.')
return Attachment(content_type=CardFactory.content_types.audio_card,
content=card)
|
Returns an attachment for a hero card. Will raise a TypeError if card argument is not a HeroCard.
|
def hero_card(card: HeroCard) -> Attachment:
"""
Returns an attachment for a hero card. Will raise a TypeError if 'card' argument is not a HeroCard.
Hero cards tend to have one dominant full width image and the cards text & buttons can
usually be found below the image.
:return:
"""
if not isinstance(card, HeroCard):
raise TypeError('CardFactory.hero_card(): `card` argument is not an instance of an HeroCard, '
'unable to prepare attachment.')
return Attachment(content_type=CardFactory.content_types.hero_card,
content=card)
|
Returns an attachment for an OAuth card used by the Bot Frameworks Single Sign On ( SSO ) service. Will raise a TypeError if card argument is not a OAuthCard.: param card:: return:
|
def oauth_card(card: OAuthCard) -> Attachment:
"""
Returns an attachment for an OAuth card used by the Bot Frameworks Single Sign On (SSO) service. Will raise a
TypeError if 'card' argument is not a OAuthCard.
:param card:
:return:
"""
if not isinstance(card, OAuthCard):
raise TypeError('CardFactory.oauth_card(): `card` argument is not an instance of an OAuthCard, '
'unable to prepare attachment.')
return Attachment(content_type=CardFactory.content_types.oauth_card,
content=card)
|
Returns an attachment for a receipt card. Will raise a TypeError if card argument is not a ReceiptCard.: param card:: return:
|
def receipt_card(card: ReceiptCard) -> Attachment:
"""
Returns an attachment for a receipt card. Will raise a TypeError if 'card' argument is not a ReceiptCard.
:param card:
:return:
"""
if not isinstance(card, ReceiptCard):
raise TypeError('CardFactory.receipt_card(): `card` argument is not an instance of an ReceiptCard, '
'unable to prepare attachment.')
return Attachment(content_type=CardFactory.content_types.receipt_card,
content=card)
|
Returns an attachment for a signin card. For channels that don t natively support signin cards an alternative message will be rendered. Will raise a TypeError if card argument is not a SigninCard.: param card:: return:
|
def signin_card(card: SigninCard) -> Attachment:
"""
Returns an attachment for a signin card. For channels that don't natively support signin cards an alternative
message will be rendered. Will raise a TypeError if 'card' argument is not a SigninCard.
:param card:
:return:
"""
if not isinstance(card, SigninCard):
raise TypeError('CardFactory.signin_card(): `card` argument is not an instance of an SigninCard, '
'unable to prepare attachment.')
return Attachment(content_type=CardFactory.content_types.signin_card,
content=card)
|
Returns an attachment for a thumbnail card. Thumbnail cards are similar to but instead of a full width image they re typically rendered with a smaller thumbnail version of the image on either side and the text will be rendered in column next to the image. Any buttons will typically show up under the card. Will raise a TypeError if card argument is not a ThumbnailCard.: param card:: return:
|
def thumbnail_card(card: ThumbnailCard) -> Attachment:
"""
Returns an attachment for a thumbnail card. Thumbnail cards are similar to
but instead of a full width image, they're typically rendered with a smaller thumbnail version of
the image on either side and the text will be rendered in column next to the image. Any buttons
will typically show up under the card. Will raise a TypeError if 'card' argument is not a ThumbnailCard.
:param card:
:return:
"""
if not isinstance(card, ThumbnailCard):
raise TypeError('CardFactory.thumbnail_card(): `card` argument is not an instance of an ThumbnailCard, '
'unable to prepare attachment.')
return Attachment(content_type=CardFactory.content_types.thumbnail_card,
content=card)
|
Returns an attachment for a video card. Will raise a TypeError if card argument is not a VideoCard.: param card:: return:
|
def video_card(card: VideoCard) -> Attachment:
"""
Returns an attachment for a video card. Will raise a TypeError if 'card' argument is not a VideoCard.
:param card:
:return:
"""
if not isinstance(card, VideoCard):
raise TypeError('CardFactory.video_card(): `card` argument is not an instance of an VideoCard, '
'unable to prepare attachment.')
return Attachment(content_type=CardFactory.content_types.video_card,
content=card)
|
return instruction params
|
def params(self):
"""return instruction params"""
# if params already defined don't attempt to get them from definition
if self._definition and not self._params:
self._params = []
for sub_instr, _, _ in self._definition:
self._params.extend(sub_instr.params) # recursive call
return self._params
else:
return self._params
|
Assemble a QasmQobjInstruction
|
def assemble(self):
"""Assemble a QasmQobjInstruction"""
instruction = QasmQobjInstruction(name=self.name)
# Evaluate parameters
if self.params:
params = [
x.evalf() if hasattr(x, 'evalf') else x for x in self.params
]
params = [
sympy.matrix2numpy(x, dtype=complex) if isinstance(
x, sympy.Matrix) else x for x in params
]
instruction.params = params
# Add placeholder for qarg and carg params
if self.num_qubits:
instruction.qubits = list(range(self.num_qubits))
if self.num_clbits:
instruction.memory = list(range(self.num_clbits))
# Add control parameters for assembler. This is needed to convert
# to a qobj conditional instruction at assemble time and after
# conversion will be deleted by the assembler.
if self.control:
instruction._control = self.control
return instruction
|
For a composite instruction reverse the order of sub - gates.
|
def mirror(self):
"""For a composite instruction, reverse the order of sub-gates.
This is done by recursively mirroring all sub-instructions.
It does not invert any gate.
Returns:
Instruction: a fresh gate with sub-gates reversed
"""
if not self._definition:
return self.copy()
reverse_inst = self.copy(name=self.name + '_mirror')
reverse_inst.definition = []
for inst, qargs, cargs in reversed(self._definition):
reverse_inst._definition.append((inst.mirror(), qargs, cargs))
return reverse_inst
|
Invert this instruction.
|
def inverse(self):
"""Invert this instruction.
If the instruction is composite (i.e. has a definition),
then its definition will be recursively inverted.
Special instructions inheriting from Instruction can
implement their own inverse (e.g. T and Tdg, Barrier, etc.)
Returns:
Instruction: a fresh instruction for the inverse
Raises:
QiskitError: if the instruction is not composite
and an inverse has not been implemented for it.
"""
if not self.definition:
raise QiskitError("inverse() not implemented for %s." % self.name)
inverse_gate = self.copy(name=self.name + '_dg')
inverse_gate._definition = []
for inst, qargs, cargs in reversed(self._definition):
inverse_gate._definition.append((inst.inverse(), qargs, cargs))
return inverse_gate
|
Add classical control on register classical and value val.
|
def c_if(self, classical, val):
"""Add classical control on register classical and value val."""
if not isinstance(classical, ClassicalRegister):
raise QiskitError("c_if must be used with a classical register")
if val < 0:
raise QiskitError("control value should be non-negative")
self.control = (classical, val)
return self
|
shallow copy of the instruction.
|
def copy(self, name=None):
"""
shallow copy of the instruction.
Args:
name (str): name to be given to the copied circuit,
if None then the name stays the same
Returns:
Instruction: a shallow copy of the current instruction, with the name
updated if it was provided
"""
cpy = copy.copy(self)
if name:
cpy.name = name
return cpy
|
Print an if statement if needed.
|
def _qasmif(self, string):
"""Print an if statement if needed."""
if self.control is None:
return string
return "if(%s==%d) " % (self.control[0].name, self.control[1]) + string
|
Return a default OpenQASM string for the instruction.
|
def qasm(self):
"""Return a default OpenQASM string for the instruction.
Derived instructions may override this to print in a
different format (e.g. measure q[0] -> c[0];).
"""
name_param = self.name
if self.params:
name_param = "%s(%s)" % (name_param, ",".join(
[str(i) for i in self.params]))
return self._qasmif(name_param)
|
Set the options of each passset based on precedence rules: passset options ( set via PassManager. append () ) override passmanager options ( set via PassManager. __init__ () ) which override Default..
|
def _join_options(self, passset_options):
"""Set the options of each passset, based on precedence rules:
passset options (set via ``PassManager.append()``) override
passmanager options (set via ``PassManager.__init__()``), which override Default.
.
"""
default = {'ignore_preserves': False, # Ignore preserves for this pass
'ignore_requires': False, # Ignore requires for this pass
'max_iteration': 1000} # Maximum allowed iteration on this pass
passmanager_level = {k: v for k, v in self.passmanager_options.items() if v is not None}
passset_level = {k: v for k, v in passset_options.items() if v is not None}
return {**default, **passmanager_level, **passset_level}
|
Args: passes ( list [ BasePass ] or BasePass ): pass ( es ) to be added to schedule ignore_preserves ( bool ): ignore the preserves claim of passes. Default: False ignore_requires ( bool ): ignore the requires need of passes. Default: False max_iteration ( int ): max number of iterations of passes. Default: 1000 flow_controller_conditions ( kwargs ): See add_flow_controller (): Dictionary of control flow plugins. Default:
|
def append(self, passes, ignore_requires=None, ignore_preserves=None, max_iteration=None,
**flow_controller_conditions):
"""
Args:
passes (list[BasePass] or BasePass): pass(es) to be added to schedule
ignore_preserves (bool): ignore the preserves claim of passes. Default: False
ignore_requires (bool): ignore the requires need of passes. Default: False
max_iteration (int): max number of iterations of passes. Default: 1000
flow_controller_conditions (kwargs): See add_flow_controller(): Dictionary of
control flow plugins. Default:
* do_while (callable property_set -> boolean): The passes repeat until the
callable returns False.
Default: `lambda x: False # i.e. passes run once`
* condition (callable property_set -> boolean): The passes run only if the
callable returns True.
Default: `lambda x: True # i.e. passes run`
Raises:
TranspilerError: if a pass in passes is not a proper pass.
"""
passset_options = {'ignore_requires': ignore_requires,
'ignore_preserves': ignore_preserves,
'max_iteration': max_iteration}
options = self._join_options(passset_options)
if isinstance(passes, BasePass):
passes = [passes]
for pass_ in passes:
if not isinstance(pass_, BasePass):
raise TranspilerError('%s is not a pass instance' % pass_.__class__)
for name, param in flow_controller_conditions.items():
if callable(param):
flow_controller_conditions[name] = partial(param, self.fenced_property_set)
else:
raise TranspilerError('The flow controller parameter %s is not callable' % name)
self.working_list.append(
FlowController.controller_factory(passes, options, **flow_controller_conditions))
|
Run all the passes on a QuantumCircuit
|
def run(self, circuit):
"""Run all the passes on a QuantumCircuit
Args:
circuit (QuantumCircuit): circuit to transform via all the registered passes
Returns:
QuantumCircuit: Transformed circuit.
"""
name = circuit.name
dag = circuit_to_dag(circuit)
del circuit
for passset in self.working_list:
for pass_ in passset:
dag = self._do_pass(pass_, dag, passset.options)
circuit = dag_to_circuit(dag)
circuit.name = name
return circuit
|
Do a pass and its requires.
|
def _do_pass(self, pass_, dag, options):
"""Do a pass and its "requires".
Args:
pass_ (BasePass): Pass to do.
dag (DAGCircuit): The dag on which the pass is ran.
options (dict): PassManager options.
Returns:
DAGCircuit: The transformed dag in case of a transformation pass.
The same input dag in case of an analysis pass.
Raises:
TranspilerError: If the pass is not a proper pass instance.
"""
# First, do the requires of pass_
if not options["ignore_requires"]:
for required_pass in pass_.requires:
dag = self._do_pass(required_pass, dag, options)
# Run the pass itself, if not already run
if pass_ not in self.valid_passes:
if pass_.is_transformation_pass:
pass_.property_set = self.fenced_property_set
new_dag = pass_.run(dag)
if not isinstance(new_dag, DAGCircuit):
raise TranspilerError("Transformation passes should return a transformed dag."
"The pass %s is returning a %s" % (type(pass_).__name__,
type(new_dag)))
dag = new_dag
elif pass_.is_analysis_pass:
pass_.property_set = self.property_set
pass_.run(FencedDAGCircuit(dag))
else:
raise TranspilerError("I dont know how to handle this type of pass")
# update the valid_passes property
self._update_valid_passes(pass_, options['ignore_preserves'])
return dag
|
Returns a list structure of the appended passes and its options.
|
def passes(self):
"""
Returns a list structure of the appended passes and its options.
Returns (list): The appended passes.
"""
ret = []
for pass_ in self.working_list:
ret.append(pass_.dump_passes())
return ret
|
Fetches the passes added to this flow controller.
|
def dump_passes(self):
"""
Fetches the passes added to this flow controller.
Returns (dict): {'options': self.options, 'passes': [passes], 'type': type(self)}
"""
ret = {'options': self.options, 'passes': [], 'type': type(self)}
for pass_ in self._passes:
if isinstance(pass_, FlowController):
ret['passes'].append(pass_.dump_passes())
else:
ret['passes'].append(pass_)
return ret
|
Removes a flow controller. Args: name ( string ): Name of the controller to remove. Raises: KeyError: If the controller to remove was not registered.
|
def remove_flow_controller(cls, name):
"""
Removes a flow controller.
Args:
name (string): Name of the controller to remove.
Raises:
KeyError: If the controller to remove was not registered.
"""
if name not in cls.registered_controllers:
raise KeyError("Flow controller not found: %s" % name)
del cls.registered_controllers[name]
|
Constructs a flow controller based on the partially evaluated controller arguments.
|
def controller_factory(cls, passes, options, **partial_controller):
"""
Constructs a flow controller based on the partially evaluated controller arguments.
Args:
passes (list[BasePass]): passes to add to the flow controller.
options (dict): PassManager options.
**partial_controller (dict): Partially evaluated controller arguments in the form
`{name:partial}`
Raises:
TranspilerError: When partial_controller is not well-formed.
Returns:
FlowController: A FlowController instance.
"""
if None in partial_controller.values():
raise TranspilerError('The controller needs a condition.')
if partial_controller:
for registered_controller in cls.registered_controllers.keys():
if registered_controller in partial_controller:
return cls.registered_controllers[registered_controller](passes, options,
**partial_controller)
raise TranspilerError("The controllers for %s are not registered" % partial_controller)
else:
return FlowControllerLinear(passes, options)
|
Apply U to q.
|
def u_base(self, theta, phi, lam, q):
"""Apply U to q."""
return self.append(UBase(theta, phi, lam), [q], [])
|
Return a Numpy. array for the U3 gate.
|
def to_matrix(self):
"""Return a Numpy.array for the U3 gate."""
theta, phi, lam = self.params
return numpy.array(
[[
numpy.cos(theta / 2),
-numpy.exp(1j * lam) * numpy.sin(theta / 2)
],
[
numpy.exp(1j * phi) * numpy.sin(theta / 2),
numpy.exp(1j * (phi + lam)) * numpy.cos(theta / 2)
]],
dtype=complex)
|
Apply a single qubit gate to the qubit.
|
def single_gate_params(gate, params=None):
"""Apply a single qubit gate to the qubit.
Args:
gate(str): the single qubit gate name
params(list): the operation parameters op['params']
Returns:
tuple: a tuple of U gate parameters (theta, phi, lam)
Raises:
QiskitError: if the gate name is not valid
"""
if gate in ('U', 'u3'):
return params[0], params[1], params[2]
elif gate == 'u2':
return np.pi / 2, params[0], params[1]
elif gate == 'u1':
return 0, 0, params[0]
elif gate == 'id':
return 0, 0, 0
raise QiskitError('Gate is not among the valid types: %s' % gate)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.