8000 Pylint fixes for botbuilder-ai library code and tests by axelsrz · Pull Request #272 · microsoft/botbuilder-python · GitHub
[go: up one dir, main page]

Skip to content

Pylint fixes for botbuilder-ai library code and tests #272

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 22, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions libraries/botbuilder-ai/botbuilder/ai/luis/activity_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
)


class ActivityUtil(object):
class ActivityUtil:
@staticmethod
def create_trace(
turn_activity: Activity,
Expand All @@ -26,11 +26,14 @@ def create_trace(
: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: 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: 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: 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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,20 @@
from uuid import UUID, uuid4


class LuisApplication(object):
class LuisApplication:
"""
Data describing a LUIS application.
"""

def __init__(self, application_id: str, endpoint_key: str, endpoint: str):
"""Initializes a new instance of the <see cref="LuisApplication"/> class.

:param application_id: LUIS application ID.
:type application_id: str
:param endpoint_key: LUIS subscription or endpoint key.
:type endpoint_key: str
:param endpoint: LUIS endpoint to use like https://westus.api.cognitive.microsoft.com.
:type endpoint: str
:raises ValueError:
:raises ValueError:
:raises ValueError:
:raises ValueError:
"""
Expand All @@ -48,7 +47,6 @@ def __init__(self, application_id: str, endpoint_key: str, endpoint: str):
@classmethod
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:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from botbuilder.core import BotTelemetryClient, NullTelemetryClient


class LuisPredictionOptions(object):
class LuisPredictionOptions:
"""
Optional parameters for a LUIS prediction request.
"""
Expand Down
34 changes: 17 additions & 17 deletions libraries/botbuilder-ai/botbuilder/ai/luis/luis_recognizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,18 @@

from botbuilder.core import (
BotAssert,
BotTelemetryClient,
IntentScore,
NullTelemetryClient,
RecognizerResult,
TurnContext,
)
from botbuilder.schema import Activity, ActivityTypes, ChannelAccount
from botbuilder.schema import ActivityTypes

from . import LuisApplication, LuisPredictionOptions, LuisTelemetryConstants
from .activity_util import ActivityUtil
from .luis_util import LuisUtil


class LuisRecognizer(object):
class LuisRecognizer:
"""
A LUIS based implementation of <see cref="IRecognizer"/>.
"""
Expand All @@ -41,7 +39,6 @@ def __init__(
include_api_results: bool = False,
):
"""Initializes a new instance of the <see cref="LuisRecognizer"/> class.

:param application: The LUIS application to use to recognize text.
:type application: LuisApplication
:param prediction_options: The LUIS prediction options to use, defaults to None
Expand Down Expand Up @@ -77,12 +74,12 @@ 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: 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.
Expand Down Expand Up @@ -111,12 +108,13 @@ async def recognize(
luis_prediction_options: LuisPredictionOptions = 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: 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: 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
Expand All @@ -137,14 +135,15 @@ def on_recognizer_result(
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: 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: Additional metrics to be logged to telemetry with the LuisResult event, defaults to
None
:param telemetry_metrics: Dict[str, float], optional
"""

Expand All @@ -159,7 +158,7 @@ def on_recognizer_result(

@staticmethod
def _get_top_k_intent_score(
intent_names: List[str], intents: Dict[str, IntentScore], index: int
intent_names: List[str], intents: Dict[str, IntentScore], index: int # pylint: disable=unused-argument
) -> Tuple[str, str]:
intent_name = ""
intent_score = "0.00"
Expand All @@ -178,14 +177,15 @@ def fill_luis_event_properties(
) -> 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: 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.
:return: A dictionary that is sent as "Properties" to IBotTelemetryClient.TrackEvent method for the
BotMessageSend event.
:rtype: Dict[str, str]
"""

Expand Down
104 changes: 51 additions & 53 deletions libraries/botbuilder-ai/botbuilder/ai/luis/luis_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,16 @@

import platform
from collections import OrderedDict
from typing import Dict, List, Set, Union
from typing import Dict, List, Union

import azure.cognitiveservices.language.luis.runtime.models as runtime_models
from azure.cognitiveservices.language.luis.runtime.models import (
CompositeEntityModel,
EntityModel,
LuisResult,
)
from botbuilder.core import IntentScore, RecognizerResult
from msrest import Serializer
from botbuilder.core import IntentScore, RecognizerResult

from .. import __title__, __version__

Expand All @@ -35,12 +35,11 @@ def get_intents(luis_result: LuisResult) -> Dict[str, IntentScore]:
LuisUtil.normalized_intent(i.intent): IntentScore(i.score or 0)
for i in luis_result.intents
}
else:
return {
LuisUtil.normalized_intent(
luis_result.top_scoring_intent.intent
): IntentScore(luis_result.top_scoring_intent.score or 0)
}
return {
LuisUtil.normalized_intent(
luis_result.top_scoring_intent.intent
): IntentScore(luis_result.top_scoring_intent.score or 0)
}

@staticmethod
def extract_entities_and_metadata(
Expand All @@ -58,9 +57,9 @@ def extract_entities_and_metadata(
if composite_entities:
composite_entity_types = set(ce.parent_type for ce in composite_entities)
current = entities
for compositeEntity in composite_entities:
for composite_entity in composite_entities:
current = LuisUtil.populate_composite_entity_model(
compositeEntity, current, entities_and_metadata, verbose
composite_entity, current, entities_and_metadata, verbose
)
entities = current

Expand Down Expand Up @@ -90,12 +89,12 @@ def number(value: object) -> Union[int, float]:
return None

try:
s = str(value)
i = int(s)
return i
str_value = str(value)
int_value = int(str_value)
return int_value
except ValueError:
f = float(s)
return f
float_value = float(str_value)
return float_value

@staticmethod
def extract_entity_value(entity: EntityModel) -> object:
Expand All @@ -108,7 +107,7 @@ def extract_entity_value(entity: EntityModel) -> object:
resolution = entity.additional_properties["resolution"]
if entity.type.startswith("builtin.datetime."):
return resolution
elif entity.type.startswith("builtin.datetimeV2."):
if entity.type.startswith("builtin.datetimeV2."):
if not resolution["values"]:
return resolution

Expand All @@ -117,32 +116,31 @@ def extract_entity_value(entity: EntityModel) -> object:
timexes = [val["timex"] for val in resolution_values]
distinct_timexes = list(OrderedDict.fromkeys(timexes))
return {"type": val_type, "timex": distinct_timexes}
else:
if entity.type in {"builtin.number", "builtin.ordinal"}:
return LuisUtil.number(resolution["value"])
elif entity.type == "builtin.percentage":
svalue = str(resolution["value"])
if svalue.endswith("%"):
svalue = svalue[:-1]

return LuisUtil.number(svalue)
elif entity.type in {
"builtin.age",
"builtin.dimension",
"builtin.currency",
"builtin.temperature",
}:
units = resolution["unit"]
val = LuisUtil.number(resolution["value"])
obj = {}
if val is not None:
obj["number"] = val

obj["units"] = units
return obj
else:
value = resolution.get("value")
return value if value is not None else resolution.get("values")

if entity.type in {"builtin.number", "builtin.ordinal"}:
return LuisUtil.number(resolution["value"])
if entity.type == "builtin.percentage":
svalue = str(resolution["value"])
if svalue.endswith("%"):
svalue = svalue[:-1]

return LuisUtil.number(svalue)
if entity.type in {
"builtin.age",
"builtin.dimension",
"builtin.currency",
"builtin.temperature",
}:
units = resolution["unit"]
val = LuisUtil.number(resolution["value"])
obj = {}
if val is not None:
obj["number"] = val

obj["units"] = units
return obj
value = resolution.get("value")
return value if value is not None else resolution.get("values")

@staticmethod
def extract_entity_metadata(entity: EntityModel) -> Dict:
Expand Down Expand Up @@ -202,10 +200,10 @@ def populate_composite_entity_model(
# This is now implemented as O(n^2) search and can be reduced to O(2n) using a map as an optimization if n grows
composite_entity_metadata = next(
(
e
for e in entities
if e.type == composite_entity.parent_type
and e.entity == composite_entity.value
ent
for ent in entities
if ent.type == composite_entity.parent_type
and ent.entity == composite_entity.value
),
None,
)
Expand Down Expand Up @@ -310,7 +308,7 @@ def recognizer_result_as_dict(
for name, intent_score in recognizer_result.intents.items()
} if recognizer_result.intents is not None else None

d: Dict[str, object] = {
dictionary: Dict[str, object] = {
"text": recognizer_result.text,
"alteredText": recognizer_result.altered_text,
"intents": intents,
Expand All @@ -319,13 +317,13 @@ def recognizer_result_as_dict(

if recognizer_result.properties is not None:
for key, value in recognizer_result.properties.items():
if key not in d:
if key not in dictionary:
if isinstance(value, LuisResult):
d[key] = LuisUtil.luis_result_as_dict(value)
dictionary[key] = LuisUtil.luis_result_as_dict(value)
else:
d[key] = value
dictionary[key] = value

return d
return dictionary

@staticmethod
def intent_score_as_dict(intent_score: IntentScore) -> Dict[str, float]:
Expand All @@ -343,5 +341,5 @@ def luis_result_as_dict(luis_result: LuisResult) -> Dict[str, object]:
k: v for k, v in runtime_models.__dict__.items() if isinstance(v, type)
}
serializer = Serializer(client_models)
d = serializer.body(luis_result, "LuisResult")
return d
result = serializer.body(luis_result, "LuisResult")
return result
Loading
0